LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-2646 [FIX] Image mode: fail oversized documents early (upload and indexing); fix re-extraction of names with [ ] (#2324)
Praveen Kumar0ecc36d04beb
diff --git a/backend/prompt_studio/prompt_studio_core_v2/exceptions.py b/backend/prompt_studio/prompt_studio_core_v2/exceptions.pyindex d387d762a..0caab8f14 100644--- a/backend/prompt_studio/prompt_studio_core_v2/exceptions.py+++ b/backend/prompt_studio/prompt_studio_core_v2/exceptions.py@@ -23,6 +23,13 @@ class IndexingAPIError(APIException):self.status_code = status_code+class ImageModePageLimitExceeded(APIException):+ """An upload has more pages than image output mode can answer."""++ status_code = 400+ default_detail = "This document has too many pages for image output mode."++class ExtractionAPIError(APIException):status_code = 500default_detail = "Error while extracting file"diff --git a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.pyindex 5a6fafa4b..04fd0540e 100644--- a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py+++ b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py@@ -8,6 +8,7 @@ from typing import Anyfrom account_v2.constants import Commonfrom account_v2.models import User+from adapter_processor_v2.image_output_gating import LLMWHISPERER_ADAPTER_PREFIXfrom adapter_processor_v2.models import AdapterInstance, UserDefaultAdapterfrom django.conf import settingsfrom django.db import transaction@@ -54,6 +55,7 @@ from prompt_studio.prompt_studio_core_v2.exceptions import (DefaultProfileError,EmptyPromptError,ExtractionAPIError,+ ImageModePageLimitExceeded,IndexingAPIError,NoPromptsFound,OperationNotSupported,@@ -79,6 +81,10 @@ from prompt_studio.prompt_studio_v2.models import ToolStudioPromptfrom prompt_studio.vlm_utils import invalidate_vlm_answers_on_reextractionfrom unstract.core.pubsub_helper import LogPublisherfrom unstract.sdk1.adapters.x2text.constants import ImageOutputConstants+from unstract.sdk1.adapters.x2text.llm_whisperer_v2.src.helper import (+ LLMWhispererHelper,+)+from unstract.sdk1.adapters.x2text.page_image_loader import configured_page_capfrom unstract.sdk1.constants import LogLevelfrom unstract.sdk1.exceptions import IndexingError, SdkErrorfrom unstract.sdk1.execution.context import ExecutionContext@@ -1428,7 +1434,7 @@ class PromptStudioHelper:returntry:adapter_id = str(getattr(x2text, "adapter_id", "") or "")- if not adapter_id.startswith("llmwhisperer|"):+ if not adapter_id.startswith(LLMWHISPERER_ADAPTER_PREFIX):returnmetadata = x2text.metadata or {}output[TSPKeys.X2TEXT_OUTPUT_MODE] = metadata.get(@@ -1437,6 +1443,73 @@ class PromptStudioHelper:except Exception:logger.exception("Could not stamp x2text output mode; will resolve live")+ @staticmethod+ def _is_image_output_mode(profile_manager: ProfileManager | None) -> bool:+ """True when the profile's x2text adapter is LLMWhisperer in image mode.++ Gated on BOTH the LLMWhisperer adapter id and ``output_mode == image``:+ ``output_mode`` is user-editable adapter metadata, so keying on it alone+ would make any future x2text adapter that adopts the same key inherit+ image-mode rules it never asked for.+ """+ x2text = getattr(profile_manager, "x2text", None)+ if x2text is None:+ return False+ adapter_id = str(getattr(x2text, "adapter_id", "") or "")+ if not adapter_id.startswith(LLMWHISPERER_ADAPTER_PREFIX):+ return False+ return (x2text.metadata or {}).get(+ ImageOutputConstants.OUTPUT_MODE+ ) == ImageOutputConstants.IMAGE_MODE++ @staticmethod+ def uploads_use_image_output_mode(profile_manager: ProfileManager | None) -> bool:+ """Whether uploads to a project are checked against image-mode limits.++ True when the project's default profile is LLMWhisperer in image mode:+ an upload isn't tied to an output mode, and the same document is fine+ in a text mode. Fails open — an unreadable adapter config (e.g. metadata+ encrypted with an old key) must not block uploads; extraction still+ enforces the limits.+ """+ try:+ return PromptStudioHelper._is_image_output_mode(profile_manager)+ except Exception:+ logger.exception("Could not read the default profile's output mode")+ return False++ @staticmethod+ def validate_upload_page_count_for_image_mode(file_data: Any, file_type: str) -> None:+ """Reject, at upload, a PDF with more pages than image mode can answer.++ Call only when ``uploads_use_image_output_mode`` is True. Image mode+ sends every page to the LLM in one request, so a document over the+ page cap can never be answered — and converting it would be billed.+ Catching it at upload means the user never builds prompts around a+ document that will fail at indexing.++ Uses the SDK's own page counter and cap, so a document accepted here+ also passes the extraction-time pre-check. The file is read in place,+ not copied into memory. A PDF whose page count can't be read is let+ through; extraction re-checks it.+ """+ if file_type != "application/pdf":+ return+ page_cap = configured_page_cap()+ page_count = LLMWhispererHelper.pdf_page_count(file_data)+ file_data.seek(0)+ if page_count is None or page_count <= page_cap:+ return+ raise ImageModePageLimitExceeded(+ detail=(+ "This document has too many pages for image output mode. It "+ f"has {page_count} pages, and the limit is {page_cap} because "+ "every page is sent to the LLM in one request. Split the "+ "document into smaller files, or switch the project's default "+ "profile to a text output mode."+ )+ )+@staticmethoddef _validate_image_output_pdf_only(profile_manager: ProfileManager, file_name: str@@ -1450,26 +1523,13 @@ class PromptStudioHelper:PDF-only message early. The message + PDF test come from the shared``ImageOutputConstants`` so the two layers cannot drift.- Gated on BOTH the LLMWhisperer adapter id and ``output_mode == image``:- ``output_mode`` is user-editable adapter metadata, so keying on it alone- would make any future x2text adapter that adopts the same key inherit a- PDF-only rejection it never asked for.+ Gated by ``_is_image_output_mode`` (adapter id AND output mode).Also rejects image-mode extraction outright when the cloud pluginpackage is present but its backend hooks are broken(``vlm_utils.VLM_HOOKS_BROKEN``) — see the inline comment below."""- x2text = profile_manager.x2text- if x2text is None:- return- adapter_id = getattr(x2text, "adapter_id", "") or ""- if not adapter_id.startswith("llmwhisperer|"):- return- metadata = x2text.metadata or {}- if (- metadata.get(ImageOutputConstants.OUTPUT_MODE)- != ImageOutputConstants.IMAGE_MODE- ):+ if not PromptStudioHelper._is_image_output_mode(profile_manager):return# Fail-closed on a half-broken cloud install: with the plugin package# present but its backend hooks unimportable, a re-extraction would@@ -2732,7 +2792,7 @@ class PromptStudioHelper:EnvHelper.get_storage(storage_type=StorageType.PERMANENT,env_name=FileStorageKeys.PERMANENT_REMOTE_STORAGE,- ).rm(extract_file_path, recursive=False)+ ).rm_exact(extract_file_path)except Exception:logger.exception(f"Failed to remove {extract_file_path}; a retry may "diff --git a/backend/prompt_studio/prompt_studio_core_v2/tests/test_upload_page_cap_image_mode.py b/backend/prompt_studio/prompt_studio_core_v2/tests/test_upload_page_cap_image_mode.pynew file mode 100644index 000000000..8609a8699--- /dev/null+++ b/backend/prompt_studio/prompt_studio_core_v2/tests/test_upload_page_cap_image_mode.py@@ -0,0 +1,125 @@+"""Unit tests for the upload-time page-cap check in image output mode.++Image mode sends every page to the LLM in one request, so a PDF over the page+cap can never be answered. The check rejects it at upload, before anything is+stored, but only when the project's default profile is LLMWhisperer in image+mode — the same document is fine in a text mode.++Unit tests: the profile is a lightweight mock and the PDFs are generated in+memory, so no database or storage is touched.+"""++from __future__ import annotations++import inspect+import io+from unittest.mock import MagicMock++import pypdfium2 as pdfium+import pytest++from prompt_studio.prompt_studio_core_v2 import prompt_studio_helper as _psh_mod+from prompt_studio.prompt_studio_core_v2 import views as _views_mod+from prompt_studio.prompt_studio_core_v2.exceptions import ImageModePageLimitExceeded++PromptStudioHelper = _psh_mod.PromptStudioHelper+check = PromptStudioHelper.validate_upload_page_count_for_image_mode+gated = PromptStudioHelper.uploads_use_image_output_mode++_LLMW_ADAPTER_ID = "llmwhisperer|a5e6b8af-3e1f-4a80-b006-d017e8e67f93"+_PDF = "application/pdf"+++def _profile(metadata: dict | None, adapter_id: str = _LLMW_ADAPTER_ID) -> MagicMock:+ profile = MagicMock(name="ProfileManager")+ profile.x2text.adapter_id = adapter_id+ profile.x2text.metadata = metadata+ return profile+++def _pdf(pages: int) -> io.BytesIO:+ doc = pdfium.PdfDocument.new()+ for _ in range(pages):+ doc.new_page(612, 792)+ buf = io.BytesIO()+ doc.save(buf)+ buf.seek(0)+ return buf++[email protected](autouse=True)+def _cap_of_five(monkeypatch: pytest.MonkeyPatch) -> None:+ # The real cap (90) via its env override, so small PDFs exercise it.+ monkeypatch.setenv("VLM_IMAGE_ANSWER_PAGE_CAP", "5")+++class TestRejectsOverCapInImageMode:+ def test_over_cap_pdf_is_rejected_with_a_clear_message(self) -> None:+ with pytest.raises(ImageModePageLimitExceeded) as excinfo:+ check(_pdf(6), _PDF)+ err = excinfo.value+ assert err.status_code == 400+ msg = str(err.detail)+ assert msg.startswith("This document has too many pages for image output mode.")+ assert "It has 6 pages, and the limit is 5" in msg+ assert "VLM_IMAGE_ANSWER_PAGE_CAP" not in msg++ def test_pdf_at_the_cap_is_accepted(self) -> None:+ check(_pdf(5), _PDF)++ def test_stream_is_rewound_for_storage(self) -> None:+ data = _pdf(3)+ check(data, _PDF)+ assert data.tell() == 0+ assert not data.closed+++class TestGate:+ def test_image_mode_default_profile_is_gated(self) -> None:+ assert gated(_profile({"output_mode": "image"})) is True++ @pytest.mark.parametrize(+ "metadata", [{"output_mode": "text"}, {"output_mode": "layout_preserving"}, {}]+ )+ def test_text_modes_are_not_gated(self, metadata: dict) -> None:+ assert gated(_profile(metadata)) is False++ def test_other_x2text_adapter_is_not_gated(self) -> None:+ assert gated(_profile({"output_mode": "image"}, adapter_id="other|1")) is False++ def test_no_default_profile_is_not_gated(self) -> None:+ assert gated(None) is False++ def test_profile_without_x2text_is_not_gated(self) -> None:+ profile = MagicMock(name="ProfileManager")+ profile.x2text = None+ assert gated(profile) is False++ def test_unreadable_adapter_metadata_fails_open(self) -> None:+ # e.g. metadata encrypted with a rotated key: uploads must still work.+ profile = MagicMock(name="ProfileManager")+ profile.x2text.adapter_id = _LLMW_ADAPTER_ID+ type(profile.x2text).metadata = property(+ lambda _self: (_ for _ in ()).throw(ValueError("InvalidEncryptionKey"))+ )+ assert gated(profile) is False+++class TestPassesThrough:+ def test_non_pdf_is_left_to_the_pdf_only_guard(self) -> None:+ check(io.BytesIO(b"a,b\n"), "text/csv")++ def test_unreadable_pdf_is_left_to_extraction(self) -> None:+ # Extraction re-checks it; a parse failure must not block the upload.+ check(io.BytesIO(b"%PDF-1.7 junk"), _PDF)+++class TestCheckIsWiredIntoUpload:+ def test_upload_for_ide_validates_before_storing(self) -> None:+ # Pins the call site and its order: deleting the call, or moving it+ # after the store, fails this test.+ source = inspect.getsource(_views_mod.PromptStudioCoreView.upload_for_ide)+ gate_at = source.index("uploads_use_image_output_mode")+ validate_at = source.index("validate_upload_page_count_for_image_mode")+ store_at = source.index("PromptStudioFileHelper.upload_for_ide")+ assert gate_at < validate_at < store_atdiff --git a/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_image_output_pdf_only.py b/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_image_output_pdf_only.pyindex 2fd2751c8..613f82c4e 100644--- a/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_image_output_pdf_only.py+++ b/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_image_output_pdf_only.py@@ -183,7 +183,7 @@ class TestInvalidationFailureClearsMarker:kwargs = index_helper.mark_extraction_status.call_args.kwargsassert kwargs["extracted"] is Falseassert "boom" in kwargs["error_message"]- storage.rm.assert_not_called()+ storage.rm_exact.assert_not_called()def test_failed_marker_write_removes_extracted_text(self,@@ -194,4 +194,4 @@ class TestInvalidationFailureClearsMarker:_, storage = self._run_with_failing_hook(monkeypatch, _psh_mod.ExtractionStatusResult.WRITE_FAILED)- storage.rm.assert_called_once_with("/data/extract/statement.txt", recursive=False)+ storage.rm_exact.assert_called_once_with("/data/extract/statement.txt")diff --git a/backend/prompt_studio/prompt_studio_core_v2/views.py b/backend/prompt_studio/prompt_studio_core_v2/views.pyindex 2179253ec..6da770a06 100644--- a/backend/prompt_studio/prompt_studio_core_v2/views.py+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py@@ -53,6 +53,7 @@ from prompt_studio.prompt_studio_core_v2.document_indexing_service import (DocumentIndexingService,)from prompt_studio.prompt_studio_core_v2.exceptions import (+ DefaultProfileError,DeploymentUsageCheckError,MaxProfilesReachedError,OperationNotSupported,@@ -1064,14 +1065,30 @@ class PromptStudioCoreView(tool__in=CustomTool.objects.all()).count()- documents = []+ # Detect MIME from file content (not browser-supplied header)+ file_types = []for uploaded_file in uploaded_files:+ file_types.append(magic.from_buffer(uploaded_file.read(2048), mime=True))+ uploaded_file.seek(0)++ # Image mode can't answer a PDF over the page cap: reject it here,+ # rather than at indexing. Every file is checked before any is stored,+ # so a page-cap rejection never leaves part of the upload behind.+ try:+ default_profile = ProfileManager.get_default_llm_profile(custom_tool)+ except DefaultProfileError:+ default_profile = None+ if PromptStudioHelper.uploads_use_image_output_mode(default_profile):+ for uploaded_file, file_type in zip(uploaded_files, file_types, strict=True):+ PromptStudioHelper.validate_upload_page_count_for_image_mode(+ uploaded_file, file_type+ )++ documents = []+ for uploaded_file, file_type in zip(uploaded_files, file_types, strict=True):# Store filefile_name = uploaded_file.namefile_data = uploaded_file- # Detect MIME from file content (not browser-supplied header)- file_type = magic.from_buffer(uploaded_file.read(2048), mime=True)- uploaded_file.seek(0)if file_converter_plugin and file_type != "application/pdf":file_converter_service = file_converter_plugin["service_class"]()diff --git a/backend/utils/file_storage/helpers/prompt_studio_file_helper.py b/backend/utils/file_storage/helpers/prompt_studio_file_helper.pyindex c5e9cfebd..ee7ea311d 100644--- a/backend/utils/file_storage/helpers/prompt_studio_file_helper.py+++ b/backend/utils/file_storage/helpers/prompt_studio_file_helper.py@@ -1,4 +1,5 @@import base64+import globimport loggingimport osfrom pathlib import Path@@ -218,9 +219,12 @@ class PromptStudioFileHelper:# path that is no longer there, and a bare rm() raises FileNotFoundError# on the usual fsspec backends. That turned the retry into a permanent# 400 and left the row undeletable through the endpoint.+ # rm_exact, not rm: these paths carry the uploaded document's name, and+ # rm expands it as a glob on GCS/S3 — "Report [Final].pdf" would miss+ # itself and delete "Report F.pdf" (another document) instead.source_file = str(Path(file_system_path) / file_name)if fs_instance.exists(source_file):- fs_instance.rm(source_file)+ fs_instance.rm_exact(source_file)# Delete all related files for cascade deletedirectories = ["extract/", "extract/metadata/", "summarize/", "converted/"]base_file_name, _ = os.path.splitext(file_name)@@ -232,7 +236,7 @@ class PromptStudioFileHelper:directories=directories,)for file_path in file_paths:- fs_instance.rm(file_path)+ fs_instance.rm_exact(file_path)return True@staticmethod@@ -245,7 +249,8 @@ class PromptStudioFileHelper:for a specific prompt studio project."""file_paths = []- pattern = f"{base_file_name}.*"+ # Escape the document's name so only the extension is a wildcard.+ pattern = f"{glob.escape(base_file_name)}.*"for directory in directories:directory_path = str(Path(base_path) / directory)for file in fs.glob(f"{directory_path}/{pattern}"):diff --git a/backend/utils/file_storage/helpers/streaming_writer.py b/backend/utils/file_storage/helpers/streaming_writer.pyindex f63fce49a..feaadb40b 100644--- a/backend/utils/file_storage/helpers/streaming_writer.py+++ b/backend/utils/file_storage/helpers/streaming_writer.py@@ -49,8 +49,12 @@ def write_streaming(fs_instance: Any, file_path: str, file_data: Any) -> None:def _remove_file(fs_instance: Any, file_path: str) -> None:+ # rm_file, not rm: the path carries the uploaded document's name, and rm+ # expands it as a glob on GCS/S3 — "Report [Final].pdf" would miss itself+ # (leaving the partial object) or delete "Report F.pdf" instead. rm_file+ # deletes the one exact key on every fsspec backend.try:- fs_instance.fs.rm(file_path)+ fs_instance.fs.rm_file(file_path)except FileNotFoundError:passexcept Exception as e:diff --git a/backend/utils/tests/test_prompt_studio_file_helper.py b/backend/utils/tests/test_prompt_studio_file_helper.pyindex 69f08180e..0709ac706 100644--- a/backend/utils/tests/test_prompt_studio_file_helper.py+++ b/backend/utils/tests/test_prompt_studio_file_helper.py@@ -3,7 +3,8 @@from __future__ import annotationsimport io-from typing import Any, Callable+from collections.abc import Callable+from typing import Anyimport pytest@@ -15,7 +16,8 @@ from utils.file_storage.helpers.streaming_writer import (class FakeHandle:"""Stand-in for an fsspec file handle. Records writes; lets tests- inject failures via ``write_side_effect`` / ``close_side_effect``."""+ inject failures via ``write_side_effect`` / ``close_side_effect``.+ """def __init__(self,@@ -39,7 +41,7 @@ class FakeHandle:class FakeFs:- """Stand-in for ``fs_instance.fs`` — supports ``open`` and ``rm``."""+ """Stand-in for ``fs_instance.fs`` — supports ``open`` and ``rm_file``."""def __init__(self,@@ -55,11 +57,15 @@ class FakeFs:self.open_calls.append({"path": path, "mode": mode, "block_size": block_size})return self._handle- def rm(self, path: str) -> None:+ def rm_file(self, path: str) -> None:self.rm_calls.append(path)if self._rm_side_effect is not None:self._rm_side_effect(path)+ def rm(self, path: str, recursive: bool = False) -> None:+ # The path carries the document's name; rm() would glob it on GCS/S3.+ raise AssertionError(f"cleanup must use rm_file, not rm: {path}")+class FakeStorage:"""Stand-in for the ``FileStorage`` wrapper passed to the helper."""@@ -109,9 +115,7 @@ def storage(handle: FakeHandle) -> FakeStorage:def test_bytes_input_uses_single_shot_write(storage: FakeStorage) -> None:write_streaming(storage, "/p/file.pdf", b"abc")- assert storage.write_calls == [- {"path": "/p/file.pdf", "mode": "wb", "data": b"abc"}- ]+ assert storage.write_calls == [{"path": "/p/file.pdf", "mode": "wb", "data": b"abc"}]assert storage.fs.open_calls == []@@ -210,9 +214,7 @@ def test_rm_failure_does_not_mask_original_error(failing = FakeHandle(write_side_effect=write_boom)storage.fs = FakeFs(failing, rm_side_effect=rm_boom)- with caplog.at_level(- "WARNING", logger="utils.file_storage.helpers.streaming_writer"- ):+ with caplog.at_level("WARNING", logger="utils.file_storage.helpers.streaming_writer"):with pytest.raises(RuntimeError, match="primary failure"):write_streaming(storage, "/p/file.pdf", UploadedFileLike(b"X" * 8, 4))@@ -335,17 +337,21 @@ class _DeleteFs:def exists(self, path: str) -> bool:return path in self.existing- def rm(self, path: str) -> None:+ def rm_exact(self, path: str) -> None:if path not in self.existing:raise FileNotFoundError(path)self.existing.remove(path)self.removed.append(path)+ def rm(self, path: str, recursive: bool = True) -> None:+ # Paths here carry the document's name; rm() would glob it on GCS/S3.+ raise AssertionError(f"delete_for_ide must use rm_exact, not rm: {path}")+def glob(self, pattern: str) -> list[str]:return []-def _delete_with(fs: _DeleteFs):+def _delete_with(fs: _DeleteFs, file_name: str = "invoice.pdf", base: str = "/base"):from unittest.mock import patchfrom utils.file_storage.helpers.prompt_studio_file_helper import (@@ -358,11 +364,11 @@ def _delete_with(fs: _DeleteFs):patch.object(PromptStudioFileHelper,"get_or_create_prompt_studio_subdirectory",- return_value="/base",+ return_value=base,),):return PromptStudioFileHelper.delete_for_ide(- org_id="org", user_id="user", tool_id="tool", file_name="invoice.pdf"+ org_id="org", user_id="user", tool_id="tool", file_name=file_name)@@ -380,3 +386,60 @@ def test_delete_for_ide_is_idempotent_when_the_source_is_already_gone() -> None:assert _delete_with(fs) is Trueassert fs.removed == []+++def test_cleanup_deletes_only_the_partial_file_for_a_glob_name(tmp_path) -> None: # noqa: ANN001+ """A failed write of "Report [Final].pdf" removes that file only.++ Real fsspec LocalFileSystem; its rm_file is an exact delete, as on gcsfs+ and s3fs. "Report F.pdf" is what "[Final]" matches as a glob.+ """+ from unstract.sdk1.file_storage import FileStorage, FileStorageProvider++ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ (tmp_path / "Report F.pdf").write_bytes(b"other document")+ target = str(tmp_path / "Report [Final].pdf")++ class _Boom:+ def read(self, _n: int) -> bytes:+ (tmp_path / "Report [Final].pdf").write_bytes(b"partial")+ raise RuntimeError("upload interrupted")++ with pytest.raises(RuntimeError, match="upload interrupted"):+ write_streaming(storage, target, _Boom())++ assert not (tmp_path / "Report [Final].pdf").exists()+ assert (tmp_path / "Report F.pdf").read_bytes() == b"other document"+++# --- delete_for_ide: names with glob characters ---------------------------+#+# The document's name is part of every path deleted here. fsspec reads+# "[Final]" as a character class: on GCS/S3 rm("Report [Final].pdf") misses+# itself and deletes "Report F.pdf" instead (seen on MinIO), and the related+# files glob matched the wrong document's extract files the same way.+++def test_delete_for_ide_leaves_a_glob_matching_document_alone(tmp_path) -> None: # noqa: ANN001+ from unstract.sdk1.file_storage import FileStorage, FileStorageProvider++ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ for rel in (+ "Report [Final].pdf",+ "extract/Report [Final].txt",+ "extract/metadata/Report [Final].json",+ "Report F.pdf", # what "[Final]" matches as a glob+ "extract/Report F.txt",+ "extract/metadata/Report F.json",+ ):+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_bytes(b"x")++ assert _delete_with(storage, "Report [Final].pdf", str(tmp_path)) is True++ left = sorted(str(p.relative_to(tmp_path)) for p in tmp_path.rglob("*.*"))+ assert left == [+ "Report F.pdf",+ "extract/Report F.txt",+ "extract/metadata/Report F.json",+ ]diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.pyindex 92245b703..a7701094f 100644--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/llm_whisperer_v2/src/helper.py@@ -6,7 +6,7 @@ import zipfileimport zlibfrom io import BytesIOfrom pathlib import Path-from typing import Any+from typing import Any, BinaryIOimport requestsfrom requests import Response@@ -38,7 +38,10 @@ from unstract.sdk1.adapters.x2text.llm_whisperer_v2.src.constants import (from unstract.sdk1.adapters.x2text.llm_whisperer_v2.src.dto import (WhispererRequestParams,)-from unstract.sdk1.adapters.x2text.page_image_loader import configured_page_cap+from unstract.sdk1.adapters.x2text.page_image_loader import (+ configured_max_total_bytes,+ configured_page_cap,+)from unstract.sdk1.constants import MimeTypefrom unstract.sdk1.exceptions import FileOperationErrorfrom unstract.sdk1.file_storage import FileStorage, FileStorageProvider@@ -693,8 +696,13 @@ class LLMWhispererHelper:return pages@staticmethod- def _safe_pdf_page_count(pdf_bytes: bytes) -> int | None:- """Page count of the input PDF, or None if it cannot be read.+ def pdf_page_count(source: bytes | BinaryIO) -> int | None:+ """Page count of a PDF, or None if it cannot be read.++ ``source`` is the PDF's bytes or a seekable binary stream; a stream is+ read in place rather than copied into memory. This is the counter the+ image-mode page-cap checks use, so callers outside the SDK (e.g. an+ upload-time check) agree with the extraction-time pre-check.Best-effort: the extraction must not fail just because the count couldnot be derived locally, so any error returns None (and the caller@@ -703,12 +711,17 @@ class LLMWhispererHelper:try:import pdfplumber # noqa: PLC0415 - lazy: only image mode needs it- with pdfplumber.open(BytesIO(pdf_bytes)) as pdf:+ stream = BytesIO(source) if isinstance(source, bytes | bytearray) else source+ with pdfplumber.open(stream) as pdf:return len(pdf.pages)except Exception as e:logger.warning("Image mode: unable to read input PDF page count: %s", e)return None+ @staticmethod+ def _safe_pdf_page_count(pdf_bytes: bytes) -> int | None:+ return LLMWhispererHelper.pdf_page_count(pdf_bytes)+@staticmethoddef verify_page_count(pages: list[tuple[int, bytes]], expected_page_count: int | None@@ -738,6 +751,29 @@ class LLMWhispererHelper:status_code=502,)+ @staticmethod+ def verify_page_bytes(pages: list[tuple[int, bytes]]) -> None:+ """Reject a page set too large to send to an LLM in one request.++ Same budget, from the same accessor, as the answer-time check in+ ``page_image_loader`` — so a document that passes here passes there.+ Raises before anything is persisted.+ """+ budget = configured_max_total_bytes()+ total = sum(len(data) for _, data in pages)+ if total <= budget:+ return+ mb = 1024 * 1024+ raise ExtractorError(+ "This document is too large for image output mode. Its "+ f"{len(pages)} page images total {total / mb:.1f} MB, over the "+ f"{budget // mb} MB limit for one LLM request. Split the document "+ "into smaller files, or use a text output mode instead. The page "+ "conversion has already been charged, because image sizes are "+ "only known after the pages are rendered.",+ status_code=400,+ )+# Single canonical derivation of ``{extract_dir}/{stem}/pages`` shared# by writer and reader alike (see unstract.sdk1.adapters.x2text.constants).build_page_store_dir = staticmethod(_shared_build_page_store_dir)@@ -763,7 +799,8 @@ class LLMWhispererHelper:extraction error is what the caller must see."""try:- fs.rm(page_store_dir, recursive=True)+ # Named after the uploaded document: never a glob (rm_exact).+ fs.rm_exact(page_store_dir)except Exception as e:logger.warning("Image mode: could not clean up partial page dir %s: %s",@@ -807,7 +844,8 @@ class LLMWhispererHelper:"""try:if fs.exists(page_store_dir):- fs.rm(page_store_dir, recursive=True)+ # Named after the uploaded document: never a glob (rm_exact).+ fs.rm_exact(page_store_dir)except Exception as e:raise ExtractorError("Failed to clear previous page images before writing the new "@@ -815,10 +853,10 @@ class LLMWhispererHelper:status_code=500,actual_err=e,) from e- # ``fs.rm`` is not enough on its own: its S3-compatibility fallback- # (MissingContentMD5 → per-object deletes) only WARNS on individual- # failures, so a "successful" rm can leave survivors behind — which- # would silently join the new set as stale trailing pages. Verify the+ # The delete is not trusted on its own: it works from a listing, and+ # fsspec's dircache can serve a stale one that omits objects, so a+ # "successful" delete can leave survivors behind — which would+ # silently join the new set as stale trailing pages. Verify the# prefix is actually gone (through a fresh listing, not fsspec's# dircache) and fail loudly otherwise.invalidate = getattr(getattr(fs, "fs", None), "invalidate_cache", None)@@ -919,12 +957,12 @@ class LLMWhispererHelper:page_cap = configured_page_cap()if expected_page_count is not None and expected_page_count > page_cap:raise ExtractorError(- f"Document exceeds the {page_cap}-page limit for image output "- f"mode ({expected_page_count} pages). Image mode answers a "- "prompt in one request containing every page image, so a "- "larger document cannot be answered. Split the document, or "- "select a text output mode instead. Nothing was converted or "- "billed.",+ "This document has too many pages for image output mode. It "+ f"has {expected_page_count} pages, and the limit is {page_cap} "+ "because every page is sent to the LLM in one request. Split "+ "the document into smaller files, or use a text output mode "+ "instead. No pages were converted or charged. (The 'Pages to "+ "extract' setting does not apply in image output mode.)",status_code=400,)@@ -945,6 +983,15 @@ class LLMWhispererHelper:# nothing is written on a truncated/over-produced archive.LLMWhispererHelper.verify_page_count(pages, expected_page_count)+ # Enforce the byte budget HERE, at extraction, not only when a prompt+ # runs. The page images are only measurable after conversion, so the+ # conversion itself cannot be saved — but without this check the+ # document indexed successfully and failed only when the user ran a+ # prompt, after they had built their prompts around it. Failing at+ # indexing is the earliest point the size is known. The answer-time+ # check in page_image_loader stays as the backstop.+ LLMWhispererHelper.verify_page_bytes(pages)+page_store_dir = LLMWhispererHelper.build_page_store_dir(output_file_path=output_file_path,input_file_path=input_file_path,diff --git a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/page_image_loader.py b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/page_image_loader.pyindex 49873ba0b..8d40a90e4 100644--- a/unstract/sdk1/src/unstract/sdk1/adapters/x2text/page_image_loader.py+++ b/unstract/sdk1/src/unstract/sdk1/adapters/x2text/page_image_loader.py@@ -106,36 +106,52 @@ DEFAULT_MAX_TOTAL_BYTES = 14 * 1024 * 1024_PAGE_NAME_RE = re.compile(ImageOutputConstants.PAGE_NUMBER_REGEX)-# Platform override for the page cap. Defined here — next to the default and-# the enforcement — so the two sites that need it agree: the extraction-time-# pre-check (adapter, before the per-page-billed conversion is submitted) and-# the answer-time enforcement (cloud consumer plugin).+# Platform overrides for the two limits. Defined here — next to the defaults+# and the enforcement — so every site that needs them agrees: the+# extraction-time checks (adapter: the page-count pre-check before the+# per-page-billed conversion is submitted, and the byte check right after+# it) and the answer-time enforcement (cloud consumer plugin). Emergency+# overrides only; see DEFAULT_PAGE_CAP for why the values live in this file.PAGE_CAP_ENV = "VLM_IMAGE_ANSWER_PAGE_CAP"+MAX_TOTAL_MB_ENV = "VLM_IMAGE_ANSWER_MAX_TOTAL_MB"-def configured_page_cap() -> int:- """The effective page cap: ``PAGE_CAP_ENV`` or ``DEFAULT_PAGE_CAP``.+def _positive_int_env(name: str, default: int, *, scale: int = 1) -> int:+ """Parse a positive-integer env override, logging and defaulting otherwise.- An absent variable is the normal case and returns the default silently.+ An absent variable is the normal case and returns ``default`` silently.A present-but-unusable value is an operator mistake: log it and fall back- rather than failing extraction over a malformed env var.+ rather than failing extraction over a malformed env var. ``scale``+ converts the parsed value into the unit of ``default`` (e.g. MB → bytes)."""- raw = os.getenv(PAGE_CAP_ENV)+ raw = os.getenv(name)if raw is None:- return DEFAULT_PAGE_CAP+ return defaulttry:value = int(raw)if value <= 0:raise ValueError("must be positive")except (TypeError, ValueError):- logger.warning(- "Invalid %s value %r; using default %d",- PAGE_CAP_ENV,- raw,- DEFAULT_PAGE_CAP,- )- return DEFAULT_PAGE_CAP- return value+ logger.warning("Invalid %s value %r; using default %d", name, raw, default)+ return default+ return value * scale+++def configured_page_cap() -> int:+ """The effective page cap: ``PAGE_CAP_ENV`` or ``DEFAULT_PAGE_CAP``."""+ return _positive_int_env(PAGE_CAP_ENV, DEFAULT_PAGE_CAP)+++def configured_max_total_bytes() -> int:+ """The effective byte budget: ``MAX_TOTAL_MB_ENV`` (in MB) or the default."""+ return _positive_int_env(MAX_TOTAL_MB_ENV, DEFAULT_MAX_TOTAL_BYTES, scale=1024 * 1024)+++class _UseConfigured:+ """Sentinel type: read the limit from the environment at call time."""+++USE_CONFIGURED = _UseConfigured()class PageImageLoadError(Exception):@@ -298,8 +314,8 @@ def load_page_images(fs: FileStorage,page_store_dir: str,*,- page_cap: int | None = DEFAULT_PAGE_CAP,- max_total_bytes: int | None = DEFAULT_MAX_TOTAL_BYTES,+ page_cap: int | None | _UseConfigured = USE_CONFIGURED,+ max_total_bytes: int | None | _UseConfigured = USE_CONFIGURED,) -> list[LoadedPageImage]:"""Discover, cap-check, read, and base64-encode all page images.@@ -309,23 +325,29 @@ def load_page_images(remaining budget plus one byte, so no read — not even of a singlepathological object — can ever allocate more than the budget inworker memory, regardless of the object's actual size or whether the- backend exposes size metadata. ``None`` disables either limit.+ backend exposes size metadata. ``None`` disables either limit. Left+ unset, each limit is read from ``configured_page_cap()`` /+ ``configured_max_total_bytes()`` — the same values the extraction-time+ checks use, so a document that passed indexing is not rejected here.Raises:PageCapExceededError: more pages than ``page_cap`` allows.PageImageSetTooLargeError: pages total more than ``max_total_bytes``.(plus the discovery errors from ``discover_page_images``)"""+ if isinstance(page_cap, _UseConfigured):+ page_cap = configured_page_cap()+ if isinstance(max_total_bytes, _UseConfigured):+ max_total_bytes = configured_max_total_bytes()discovered = discover_page_images(fs, page_store_dir)if page_cap is not None and len(discovered) > page_cap:raise PageCapExceededError(- f"Document exceeds the {page_cap}-page limit for image output "- f"mode ({len(discovered)} pages found). Image mode answers a "- "prompt in one request containing every page image, so a larger "- "document cannot be answered. Split the document, or extract it "- "in a text output mode instead. (This limit is set by the "- "platform via VLM_IMAGE_ANSWER_PAGE_CAP — it is not the "- "adapter's 'pages to extract' setting.)",+ "This document has too many pages for image output mode. It "+ f"has {len(discovered)} pages, and the limit is {page_cap} "+ "because every page is sent to the LLM in one request. Split "+ "the document into smaller files, or use a text output mode "+ "instead. (The 'Pages to extract' setting does not apply in "+ "image output mode.)",page_store_dir=page_store_dir,page_count=len(discovered),page_cap=page_cap,@@ -360,13 +382,13 @@ def load_page_images(# Stop before encoding/retaining more — the page cap bounds the# count, this bounds the payload.raise PageImageSetTooLargeError(- f"Page images total more than "- f"{max_total_bytes // (1024 * 1024)}MB by page {page_number} "- f"of {len(discovered)} — larger than an LLM provider accepts "- "in one request, so this document cannot be answered in "- "image mode however many pages it has. Split the document, "- "or extract it in a text output mode instead. (This budget "- "is set by the platform via VLM_IMAGE_ANSWER_MAX_TOTAL_MB.)",+ "This document is too large for image output mode. Its "+ "page images go over the "+ f"{max_total_bytes // (1024 * 1024)} MB limit at page "+ f"{page_number} of {len(discovered)}, and image mode has to "+ "send every page to the LLM in one request. Split the "+ "document into smaller files, or use a text output mode "+ "instead.",page_store_dir=page_store_dir,total_bytes=total_bytes,max_total_bytes=max_total_bytes,diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py b/unstract/sdk1/src/unstract/sdk1/file_storage/impl.pyindex 198e838f8..3bcc89e63 100644--- a/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/impl.py@@ -181,6 +181,54 @@ class FileStorage(FileStorageInterface):else:raise+ def rm_exact(self, path: str) -> None:+ """Remove a file or directory tree by its EXACT path.++ Use this instead of ``rm`` whenever ``path`` contains a name you don't+ control (e.g. derived from an uploaded document's filename). ``rm``+ hands its argument to fsspec, which expands it as a GLOB on every+ backend that takes fsspec's generic delete path (gcsfs, s3fs, adlfs —+ but not LocalFileSystem, which uses a plain rmtree). So a path+ containing ``[``, ``]``, ``*`` or ``?`` — ``Report [Final].pdf`` — is+ read as a pattern: ``[Final]`` becomes a character class, matches+ nothing, and ``rm`` raises ``FileNotFoundError`` on GCS/S3 while+ working fine on LOCAL storage.++ ``find`` walks the tree and ``rm_file`` deletes one named object;+ neither expands glob characters on any backend. Files are deleted+ first, then directories deepest-first (needed on LOCAL and on GCS+ HNS buckets). On flat object storage a prefix disappears with its+ last object, so ``rmdir`` there raises ``FileNotFoundError`` (s3fs)+ or does nothing (gcsfs) — only that error is tolerated. Any other+ failure, a failed file delete or a directory that can't be removed+ (permissions, not empty), raises, unlike the ``MissingContentMD5``+ fallback below, so callers learn about it.++ Slower than ``rm`` on object storage — one request per object rather+ than a bulk delete — so prefer ``rm`` where the path is known not to+ contain glob characters.+ """+ invalidate = getattr(self.fs, "invalidate_cache", None)+ if callable(invalidate):+ invalidate(path) # a stale listing would make find() miss objects+ entries = self.fs.find(path, withdirs=True, detail=True)+ files = [n for n, info in entries.items() if info.get("type") != "directory"]+ dirs = sorted(+ (n for n, info in entries.items() if info.get("type") == "directory"),+ key=len,+ reverse=True,+ )+ for file_path in files:+ try:+ self.fs.rm_file(file_path)+ except FileNotFoundError:+ pass # already gone (concurrent delete, stale listing)+ for dir_path in [*dirs, path]:+ try:+ self.fs.rmdir(dir_path)+ except FileNotFoundError:+ pass # prefix already gone with its last object+def _rm_files_individually(self, path: str) -> None:"""Fallback deletion: delete files one at a time.diff --git a/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py b/unstract/sdk1/src/unstract/sdk1/file_storage/interface.pyindex d053f149f..d4012b47b 100644--- a/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py+++ b/unstract/sdk1/src/unstract/sdk1/file_storage/interface.py@@ -54,6 +54,11 @@ class FileStorageInterface(ABC):def rm(self, path: str, recursive: bool = True) -> None:pass+ @abstractmethod+ def rm_exact(self, path: str) -> None:+ """Remove a file or directory tree, treating glob characters literally."""+ pass+@abstractmethoddef cp(self,diff --git a/unstract/sdk1/tests/llmw_image_fixtures.py b/unstract/sdk1/tests/llmw_image_fixtures.pyindex e10d8d434..ebaad4e8d 100644--- a/unstract/sdk1/tests/llmw_image_fixtures.py+++ b/unstract/sdk1/tests/llmw_image_fixtures.py@@ -24,6 +24,7 @@ import structimport zipfileimport zlib+from fsspec.implementations.memory import MemoryFileSystemfrom unstract.sdk1.exceptions import FileOperationErrorfrom unstract.sdk1.file_storage import FileStorageProvider@@ -75,7 +76,7 @@ class InMemoryFileStorage:"""Minimal in-memory FileStorage double (S3-like), no network/credentials.Implements only the surface the image-mode helper uses: ``provider``,- ``mkdir``, ``write``, ``read``, ``exists``.+ ``mkdir``, ``write``, ``read``, ``exists``, ``ls``, ``rm``, ``rm_exact``."""def __init__(self, provider: FileStorageProvider = FileStorageProvider.S3) -> None:@@ -88,6 +89,16 @@ class InMemoryFileStorage:def rm(self, path: str, recursive: bool = True) -> None:self.rm_calls.append(str(path))+ self._delete_prefix(path)++ def rm_exact(self, path: str) -> None:+ # This double never globs, so rm and rm_exact only differ on real+ # fsspec backends (see FileStorage.rm_exact). Kept as its own entry+ # point so tests can fault-inject the method production calls.+ self.rm_calls.append(str(path))+ self._delete_prefix(path)++ def _delete_prefix(self, path: str) -> None:prefix = str(path).rstrip("/") + "/"for key in list(self._files):if key == str(path) or key.startswith(prefix):@@ -203,3 +214,32 @@ class FlakyFileStorage(InMemoryFileStorage):def attempts_for(self, path: str) -> int:return self._attempts.get(str(path), 0)+++class ObjectStoreLikeMemoryFS(MemoryFileSystem):+ """In-memory filesystem with gcsfs / s3fs delete semantics.++ * ``rm(path, recursive=True)`` takes fsspec's generic path, which expands+ its argument as a GLOB — exactly what gcsfs and s3fs do for directory+ deletes. LocalFileSystem overrides ``rm`` with a plain rmtree and never+ globs, which is why the bracket bug was invisible on LOCAL storage.+ * ``rm_file(path)`` deletes ONE exact key, mirroring gcsfs ``_rm_file``+ (a single object DELETE by key) and s3fs ``_rm_file`` (``delete_object``+ by key). Plain MemoryFileSystem does not override ``rm_file``, so it+ inherits a globbing version that production backends don't have; using+ it unmodified would model the wrong backend.+ * ``ls(path)`` defaults to plain path strings, as on gcsfs / s3fs / local.+ """++ def ls(self, path: str, detail: bool = False, **kwargs: object) -> list:+ # gcsfs, s3fs and LocalFileSystem all default to detail=False (plain+ # path strings); MemoryFileSystem defaults to True (dicts). FileStorage+ # calls ls() without detail, so match the production default.+ return super().ls(path, detail=detail, **kwargs)++ def rm_file(self, path: str) -> None:+ path = self._strip_protocol(path)+ try:+ del self.store[path]+ except KeyError as e:+ raise FileNotFoundError(path) from ediff --git a/unstract/sdk1/tests/test_file_storage_rm_exact.py b/unstract/sdk1/tests/test_file_storage_rm_exact.pynew file mode 100644index 000000000..ae7edadb3--- /dev/null+++ b/unstract/sdk1/tests/test_file_storage_rm_exact.py@@ -0,0 +1,150 @@+"""FileStorage.rm_exact: delete by exact path, never as a glob.++``FileStorage.rm`` hands its path to fsspec, which expands it as a glob on+every backend that takes the generic delete path (gcsfs, s3fs, adlfs). A+path containing ``[``, ``]``, ``*`` or ``?`` — derived from an uploaded+document's name — is then read as a pattern and the delete fails on GCS/S3+while working on LOCAL. ``rm_exact`` must remove such paths on both.+"""++import uuid+from pathlib import Path++import pytest+from unstract.sdk1.file_storage import FileStorage, FileStorageProvider++from tests.llmw_image_fixtures import ObjectStoreLikeMemoryFS++GLOB_NAMES = [+ "Report [CDIC] Final",+ "Invoice *copy*",+ "Scan ? 2",+ "plain name",+]+++def _object_store_like() -> FileStorage:+ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ storage.fs = ObjectStoreLikeMemoryFS()+ return storage++[email protected]("name", GLOB_NAMES)+def test_removes_tree_on_object_store_semantics(name: str) -> None:+ storage = _object_store_like()+ root = f"/{uuid.uuid4().hex}/{name}"+ for rel in ("pages/page_001.png", "pages/page_002.png", "meta.json"):+ storage.fs.pipe(f"{root}/{rel}", b"x")++ storage.rm_exact(root)++ assert storage.fs.find(root) == []++[email protected]("name", GLOB_NAMES)+def test_removes_nested_tree_on_local(name: str, tmp_path: Path) -> None:+ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ root = tmp_path / name+ (root / "pages" / "sub").mkdir(parents=True)+ for rel in ("pages/page_001.png", "pages/sub/page_002.png", "meta.json"):+ (root / rel).write_bytes(b"x")++ storage.rm_exact(str(root))++ # Files and every directory, deepest first, including the root.+ assert not root.exists()+++def test_removes_a_single_file(tmp_path: Path) -> None:+ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ target = tmp_path / "Report [CDIC].png"+ target.write_bytes(b"x")+ sibling = tmp_path / "Report C.png" # what "[CDIC]" would match as a glob+ sibling.write_bytes(b"y")++ storage.rm_exact(str(target))++ assert not target.exists()+ assert sibling.exists() # literal match only — never the glob's matches+++def test_glob_rm_is_the_failure_this_replaces() -> None:+ # Pins the premise: on object-store semantics plain rm() fails for these+ # names. If fsspec ever stops globbing, this flags that rm_exact may no+ # longer be needed — rather than silently testing nothing.+ storage = _object_store_like()+ root = f"/{uuid.uuid4().hex}/Report [CDIC] Final"+ storage.fs.pipe(f"{root}/page_001.png", b"x")+ with pytest.raises(FileNotFoundError):+ storage.rm(root, recursive=True)+++def test_directory_delete_error_reaches_the_caller(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # Only "prefix already gone" is tolerated. A directory that can't be+ # removed (here: permission denied on LOCAL) must not be reported as+ # a successful delete.+ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ root = tmp_path / "Report [CDIC]"+ (root / "pages").mkdir(parents=True)+ (root / "pages" / "page_001.png").write_bytes(b"x")++ def deny(path: str) -> None:+ raise PermissionError(13, "Permission denied", path)++ monkeypatch.setattr(storage.fs, "rmdir", deny)+ with pytest.raises(PermissionError):+ storage.rm_exact(str(root))+++def test_directory_already_gone_is_tolerated(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ # On s3fs a prefix vanishes with its last object, so rmdir raises+ # FileNotFoundError for it; that is success, not a failure.+ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ root = tmp_path / "Report [CDIC]"+ (root / "pages").mkdir(parents=True)+ (root / "pages" / "page_001.png").write_bytes(b"x")++ def gone(path: str) -> None:+ raise FileNotFoundError(path)++ monkeypatch.setattr(storage.fs, "rmdir", gone)+ storage.rm_exact(str(root))++ assert not (root / "pages" / "page_001.png").exists()+++def test_glob_matching_sibling_is_left_alone_on_object_store_semantics() -> None:+ # Seen on MinIO and a GCS emulator: when another document's folder+ # matches the name as a glob ("TOBE-065 C Venkat" for "[CDIC]"), plain+ # rm() deletes THAT folder silently and leaves the target in place.+ storage = _object_store_like()+ base = f"/{uuid.uuid4().hex}/extract"+ target = f"{base}/TOBE-065 [CDIC] Venkat/pages"+ sibling = f"{base}/TOBE-065 C Venkat/pages/page_001.png"+ storage.fs.pipe(f"{target}/page_001.png", b"x")+ storage.fs.pipe(sibling, b"other document")++ storage.rm_exact(target)++ assert storage.fs.find(target) == []+ assert storage.fs.cat_file(sibling) == b"other document"+++def test_glob_rm_deletes_the_wrong_folder_when_a_sibling_matches() -> None:+ # Pins the second failure mode of plain rm(), alongside the+ # FileNotFoundError premise above.+ storage = _object_store_like()+ base = f"/{uuid.uuid4().hex}/extract"+ target = f"{base}/TOBE-065 [CDIC] Venkat/pages"+ sibling = f"{base}/TOBE-065 C Venkat/pages/page_001.png"+ storage.fs.pipe(f"{target}/page_001.png", b"x")+ storage.fs.pipe(sibling, b"other document")++ storage.rm(target, recursive=True)++ assert storage.fs.find(target) != []+ assert not storage.fs.exists(sibling)diff --git a/unstract/sdk1/tests/test_llmw_image_helper.py b/unstract/sdk1/tests/test_llmw_image_helper.pyindex 559ef8369..892bb5db2 100644--- a/unstract/sdk1/tests/test_llmw_image_helper.py+++ b/unstract/sdk1/tests/test_llmw_image_helper.py@@ -8,6 +8,7 @@ All tests are pure in-memory / temp-dir units: no network, no live service."""import io+import uuidfrom unittest.mock import MagicMockimport pytest@@ -25,6 +26,7 @@ from tests.llmw_image_fixtures import (CORRUPT_ZIP,FlakyFileStorage,InMemoryFileStorage,+ ObjectStoreLikeMemoryFS,make_page_zip,minimal_png,)@@ -199,30 +201,30 @@ class TestPersistence:fs = InMemoryFileStorage(provider=FileStorageProvider.S3)H.persist_page_images(fs, "doc/pages", [(1, b"a")])- def _rm_fails(path: str, recursive: bool = True) -> None:+ def _rm_fails(path: str) -> None:raise OSError("permission denied")- fs.rm = _rm_fails # type: ignore[method-assign]+ fs.rm_exact = _rm_fails # type: ignore[method-assign]with pytest.raises(ExtractorError, match="clear previous page images"):H.persist_page_images(fs, "doc/pages", [(1, b"x")])def test_silently_partial_delete_raises_instead_of_serving_stale_pages(self,) -> None:- # FileStorage.rm's S3-compatibility fallback deletes objects one at a- # time and only WARNS on per-object failures — so rm can "succeed"- # while files survive. The writer must detect survivors and refuse to- # write, else the stale page joins the new set as a trailing page.+ # The delete works from a listing, and a stale listing can omit+ # objects — so it can "succeed" while files survive. The writer must+ # detect survivors and refuse to write, else the stale page joins the+ # new set as a trailing page.fs = InMemoryFileStorage(provider=FileStorageProvider.S3)H.persist_page_images(fs, "doc/pages", [(1, b"a"), (2, b"b"), (3, b"c")])- real_rm = type(fs).rm+ real_rm_exact = type(fs).rm_exact- def _rm_leaves_survivor(path: str, recursive: bool = True) -> None:- real_rm(fs, path, recursive)+ def _rm_leaves_survivor(path: str) -> None:+ real_rm_exact(fs, path)fs._files["doc/pages/page_003.png"] = b"c" # survived the delete- fs.rm = _rm_leaves_survivor # type: ignore[method-assign]+ fs.rm_exact = _rm_leaves_survivor # type: ignore[method-assign]with pytest.raises(ExtractorError, match="survived the pre-write cleanup"):H.persist_page_images(fs, "doc/pages", [(1, b"x"), (2, b"y")])@@ -233,7 +235,7 @@ class TestPersistence:fs = InMemoryFileStorage(provider=FileStorageProvider.S3)H.persist_page_images(fs, "doc/pages", [(1, b"a"), (2, b"b")])- fs.rm = lambda path, recursive=True: None # type: ignore[method-assign]+ fs.rm_exact = lambda path: None # type: ignore[method-assign]with pytest.raises(ExtractorError, match="survived the pre-write cleanup"):H.persist_page_images(fs, "doc/pages", [(1, b"x")])assert fs.read(path="doc/pages/page_001.png", mode="rb") == b"a" # untouched@@ -434,9 +436,10 @@ class TestPreSubmitPageCap:H.get_page_images({}, "/in/doc.pdf", "/out/doc.txt", fs=fs)msg = str(excinfo.value)- assert "exceeds the 20-page limit" in msg- assert "164 pages" in msg- assert "Nothing was converted or billed" in msg+ assert "too many pages for image output mode" in msg+ assert "It has 164 pages, and the limit is 20" in msg+ assert "No pages were converted or charged" in msg+ assert "VLM_IMAGE_ANSWER_PAGE_CAP" not in msg# The billed call never happened.submit.assert_not_called()@@ -471,3 +474,169 @@ class TestPreSubmitPageCap:H.get_page_images({}, "/in/doc.pdf", "/out/doc.txt", fs=fs)submit.assert_called_once()+++def _glob_expanding_storage() -> FileStorage:+ """A FileStorage on the delete semantics of GCS / S3 (see above)."""+ storage = FileStorage(provider=FileStorageProvider.LOCAL)+ storage.fs = ObjectStoreLikeMemoryFS()+ return storage+++def _bracketed_page_dir() -> str:+ # Mirrors the failing staging path: the directory is named after the+ # uploaded document, here "... [CDIC] ...". Unique per test because the+ # in-memory filesystem is process-global.+ return f"/{uuid.uuid4().hex}/extract/Crystal Ball [CDIC] Feasibility/pages"+++class TestPageStoreWithGlobCharacters:+ """Re-extraction must work when the document name contains [ ] * ?.++ Regression: on GCS, re-extracting a document named with "[CDIC]" failed+ with "Failed to clear previous page images" — fs.rm() read "[CDIC]" as a+ glob character class, matched nothing, and raised FileNotFoundError.+ """++ def test_fixture_reproduces_the_globbing_delete(self) -> None:+ # Guards the two tests below: if fsspec ever stops globbing here,+ # they would pass without exercising the bug at all.+ storage = _glob_expanding_storage()+ page_dir = _bracketed_page_dir()+ storage.fs.pipe(f"{page_dir}/page_001.png", b"old")+ with pytest.raises(FileNotFoundError):+ storage.fs.rm(page_dir, recursive=True)+ # ...while a single exact-key delete works, as on gcsfs / s3fs.+ storage.fs.rm_file(f"{page_dir}/page_001.png")+ assert storage.fs.find(page_dir) == []++ def test_reextraction_replaces_the_previous_page_set(self) -> None:+ storage = _glob_expanding_storage()+ page_dir = _bracketed_page_dir()+ for n in (1, 2, 3):+ storage.fs.pipe(f"{page_dir}/page_{n:03d}.png", b"old")++ refs = H.persist_page_images(+ storage, page_dir, [(1, minimal_png()), (2, minimal_png())]+ )++ assert [r.page_number for r in refs] == [1, 2]+ names = sorted(p.rsplit("/", 1)[-1] for p in storage.fs.find(page_dir))+ # The stale third page from the previous, longer run is gone.+ assert names == ["page_001.png", "page_002.png"]+ assert storage.fs.cat_file(f"{page_dir}/page_001.png") == minimal_png()++ def test_answer_time_loader_reads_the_bracketed_set(self) -> None:+ # Round trip: what extraction writes, the vision-answer path must be+ # able to read back. Discovery uses ls() and reads use open(), neither+ # of which globs — pinned so a future change to either can't quietly+ # break documents with these names at prompt time instead.+ from unstract.sdk1.adapters.x2text.page_image_loader import load_page_images++ storage = _glob_expanding_storage()+ page_dir = _bracketed_page_dir()+ H.persist_page_images(storage, page_dir, [(1, minimal_png()), (2, minimal_png())])++ loaded = load_page_images(storage, page_dir)++ assert [p.page_number for p in loaded] == [1, 2]++ def test_failed_write_cleans_up_partial_pages(self, monkeypatch: MonkeyPatch) -> None:+ # The best-effort cleanup used the same globbing rm and only logged+ # its failure — so for these names it silently left partial pages.+ monkeypatch.setattr(helper_mod.WhispererDefaults, "RETRY_MIN_WAIT", 0.0)+ monkeypatch.setattr(helper_mod.WhispererDefaults, "PAGE_STORE_MAX_RETRIES", 1)+ storage = _glob_expanding_storage()+ page_dir = _bracketed_page_dir()+ real_write = H._write_single_page++ def fail_on_page_two(fs, path, data): # noqa: ANN001, ANN202+ if path.endswith("page_002.png"):+ raise OSError("simulated storage failure")+ return real_write(fs=fs, path=path, data=data)++ monkeypatch.setattr(H, "_write_single_page", staticmethod(fail_on_page_two))++ pages = [(1, minimal_png()), (2, minimal_png())]++ with pytest.raises(ExtractorError):+ H.persist_page_images(storage, page_dir, pages)++ assert storage.fs.find(page_dir) == []+++class TestExtractionTimeByteBudget:+ """The byte budget is enforced at extraction, before anything is stored.++ Previously only the answer-time check enforced it: a document indexed+ successfully, then failed when the user ran a prompt — after they had+ built their prompts around it.+ """++ def test_within_budget_passes(self, monkeypatch: MonkeyPatch) -> None:+ monkeypatch.setenv("VLM_IMAGE_ANSWER_MAX_TOTAL_MB", "1")+ H.verify_page_bytes([(1, b"x" * 400_000), (2, b"x" * 400_000)])++ def test_over_budget_raises_a_clear_error(self, monkeypatch: MonkeyPatch) -> None:+ monkeypatch.setenv("VLM_IMAGE_ANSWER_MAX_TOTAL_MB", "1")+ with pytest.raises(ExtractorError) as excinfo:+ H.verify_page_bytes([(1, b"x" * 700_000), (2, b"x" * 700_000)])+ msg = str(excinfo.value)+ assert msg.startswith("This document is too large for image output mode.")+ assert "Its 2 page images total 1.3 MB, over the 1 MB limit" in msg+ # Honest about cost: sizes are only known after the charged conversion.+ assert "already been charged" in msg+ assert "however many pages" not in msg++ def test_extraction_fails_before_persisting(self, monkeypatch: MonkeyPatch) -> None:+ monkeypatch.setenv("VLM_IMAGE_ANSWER_MAX_TOTAL_MB", "1")+ monkeypatch.setattr(H, "_safe_pdf_page_count", staticmethod(lambda _b: 2))+ monkeypatch.setattr(+ H, "submit_pdf_to_images", staticmethod(MagicMock(return_value="h1"))+ )+ monkeypatch.setattr(H, "poll_pdf_to_images_status", staticmethod(MagicMock()))+ big_pages = [(1, b"x" * 700_000), (2, b"x" * 700_000)]+ monkeypatch.setattr(+ H, "_download_and_extract", staticmethod(lambda **_k: big_pages)+ )+ persist = MagicMock(name="persist_page_images")+ monkeypatch.setattr(H, "persist_page_images", staticmethod(persist))+ fs = MagicMock(name="FileStorage")+ fs.read.return_value = b"%PDF-1.7 fake"++ with pytest.raises(ExtractorError):+ H.get_page_images({}, "/in/doc.pdf", "/out/doc.txt", fs=fs)++ persist.assert_not_called()++ @pytest.mark.parametrize("budget_mb", ["1", "2"])+ def test_extraction_and_answer_time_checks_agree(+ self, budget_mb: str, monkeypatch: MonkeyPatch+ ) -> None:+ # Both checks must read the same override. A ~1.4 MB page set fails+ # both under 1 MB and passes both under 2 MB; it must never pass+ # indexing and then fail when a prompt runs.+ from unstract.sdk1.adapters.x2text.page_image_loader import (+ PageImageSetTooLargeError,+ load_page_images,+ )++ monkeypatch.setenv("VLM_IMAGE_ANSWER_MAX_TOTAL_MB", budget_mb)+ pages = [(1, b"x" * 700_000), (2, b"x" * 700_000)]+ storage = InMemoryFileStorage()+ page_dir = "/data/extract/doc/pages"+ for number, data in pages:+ storage.write(path=f"{page_dir}/page_{number:03d}.png", mode="wb", data=data)++ try:+ H.verify_page_bytes(pages)+ indexing_ok = True+ except ExtractorError:+ indexing_ok = False+ try:+ load_page_images(storage, page_dir) # no explicit budget+ answer_ok = True+ except PageImageSetTooLargeError:+ answer_ok = False++ assert indexing_ok == answer_ok == (budget_mb == "2")diff --git a/unstract/sdk1/tests/test_page_image_loader.py b/unstract/sdk1/tests/test_page_image_loader.pyindex d8242d11f..f6857cb22 100644--- a/unstract/sdk1/tests/test_page_image_loader.py+++ b/unstract/sdk1/tests/test_page_image_loader.py@@ -114,13 +114,14 @@ class TestPageCap:err = excinfo.valueassert err.page_count == 5assert err.page_cap == 4- assert "exceeds the 4-page limit" in str(err)- # Names the platform knob, and explicitly rules out the adapter's- # "pages to extract" setting — pointing at that one sent a tester- # hunting through a field they had never set (UN-2646 follow-up).- assert "VLM_IMAGE_ANSWER_PAGE_CAP" in str(err)- assert "not the adapter's 'pages to extract' setting" in str(err)- assert "Reduce the page range" not in str(err)+ msg = str(err)+ assert "too many pages for image output mode" in msg+ assert "It has 5 pages, and the limit is 4" in msg+ # Rules out the adapter's "Pages to extract" setting — pointing at it+ # sent a tester hunting through a field they had never set (UN-2646+ # follow-up). The operator-only env var is not shown to users.+ assert "'Pages to extract' setting does not apply" in msg+ assert "VLM_IMAGE_ANSWER_PAGE_CAP" not in msgdef test_cap_check_precedes_reads(self) -> None:# Fail-fast: no image bytes are read for an oversized document.@@ -271,8 +272,7 @@ class TestByteBudget:# the recorded total is budget + 1, and page 3 was never touched.assert err.total_bytes == 51assert err.max_total_bytes == 50- assert "VLM_IMAGE_ANSWER_MAX_TOTAL_MB" in str(err)- assert "pages to extract" not in str(err)+ assert "too large for image output mode" in str(err)def test_single_oversized_page_reads_are_bounded(self) -> None:# A single pathological object must never be fully allocated: each@@ -350,14 +350,39 @@ class TestConfiguredPageCap:assert configured_page_cap() == DEFAULT_PAGE_CAP+class TestLoaderReadsConfiguredLimits:+ """Left unset, the loader's limits come from the env, not fixed defaults."""++ def test_default_page_cap_follows_env(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(PAGE_CAP_ENV, "2")+ fs = _store({1: b"a", 2: b"b", 3: b"c"})+ with pytest.raises(PageCapExceededError):+ load_page_images(fs, _DIR)++ def test_explicit_none_still_disables(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(PAGE_CAP_ENV, "2")+ monkeypatch.setenv("VLM_IMAGE_ANSWER_MAX_TOTAL_MB", "1")+ fs = _store({1: b"a", 2: b"b", 3: b"c" * (2 * 1024 * 1024)})+ assert len(load_page_images(fs, _DIR, page_cap=None, max_total_bytes=None)) == 3++ def test_explicit_value_wins_over_env(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(PAGE_CAP_ENV, "2")+ fs = _store({1: b"a", 2: b"b", 3: b"c"})+ assert len(load_page_images(fs, _DIR, page_cap=3)) == 3++class TestByteBudgetMessage:- def test_over_budget_names_the_platform_knob(self) -> None:- fs = _store({1: b"x" * 2048, 2: b"y" * 2048})+ def test_over_budget_message_is_user_facing(self) -> None:+ fs = _store({1: b"x" * 700_000, 2: b"y" * 700_000, 3: b"z"})with pytest.raises(PageImageSetTooLargeError) as excinfo:- load_page_images(fs, _DIR, page_cap=None, max_total_bytes=1024)+ load_page_images(fs, _DIR, page_cap=None, max_total_bytes=1024 * 1024)msg = str(excinfo.value)- assert "VLM_IMAGE_ANSWER_MAX_TOTAL_MB" in msg- assert "pages to extract" not in msg+ assert msg.startswith("This document is too large for image output mode.")+ assert "go over the 1 MB limit at page 2 of 3" in msg+ assert "Split the document into smaller files" in msg+ # Operator-only knob and the confusing phrasing are gone.+ assert "VLM_IMAGE_ANSWER_MAX_TOTAL_MB" not in msg+ assert "however many pages" not in msgclass TestCapMatchesBudget: