diff --git a/decisions.md b/decisions.md index 38e63c128..93c9f5d47 100644 --- a/decisions.md +++ b/decisions.md @@ -7414,10 +7414,15 @@ deployment's values into another's work. keeps the in-process bytes path, the self-host default. The same capability lets an OCR or vision route have its provider fetch the input by URL instead of receiving uploaded bytes. Usage the route incurs is returned in `usage_events` and metered as - for any route; the size and pre-OCR limits are checked before the URL is signed. A non-PDF - file over its family's reading limit is carded from its size and MIME alone - (`CardConverter.convert_unread`), so the convert stage never reads an oversized - object, whichever route or store the deployment has. + for any route; the route's provider limit is checked before the URL is signed. On the + bytes path, a non-PDF file over its family's reading limit is carded from its size + and MIME alone (`CardConverter.convert_unread`), so the convert stage never reads an + oversized object. The reading limits + (100 MB for office and PDF, 200 MB for spreadsheets; D138, D139) guard this process, + which would read the file, so they apply only on the bytes path (owner, + 2026-11-07): a file over its limit whose route fetches it by URL from a presigning + store goes to that route instead of being refused (PDF) or carded. A route's own + declared `provider_limit_bytes` still applies. - *Register a stored object (2026-11-07).* `UploadIngestor.ingest_stored(deployment_id, key, size, mime, filename, title=None, source_path=None, ingested_by=None)` ingests a file a client wrote to the raw store itself (direct multipart upload by pre-signed diff --git a/plan/designs/format_conversion_design.md b/plan/designs/format_conversion_design.md index 6f5de2795..95f406d9c 100644 --- a/plan/designs/format_conversion_design.md +++ b/plan/designs/format_conversion_design.md @@ -73,7 +73,7 @@ setting one route never removes the others. Every file is stored. Outcomes: |---|---| | Bytes a declaration contradicts (D132) | Refused with a typed error | | Bytes not recognized as any family | Stored; a `binary` card (D138 §6) | -| Over the family's reading limit | Stored; the head/tail profile for text, otherwise a card stating the reason (D138 §3, §5.2), except PDF: its effective pre-OCR limit is the lower of the family limit and provider input ceiling, and exceeding it fails the version with a typed reason, no card and no `document.md` reading | +| Over the family's reading limit | Stored; the head/tail profile for text, otherwise a card stating the reason (D138 §3, §5.2), except PDF: its effective pre-OCR limit is the lower of the family limit and provider input ceiling, and exceeding it fails the version with a typed reason, no card and no `document.md` reading. The reading limit guards the engine process, which would read the file: when the file's route fetches it by URL from a presigning store (D147), the file goes to that route instead, and only the route's own provider ceiling applies | | Family recognized but its converter not built | Stored; conversion parks with `no_route` (D117) until it is | | Family on, converter needs an unconfigured provider | Stored; conversion parks with `no_route` (D117); `resume-no-route` releases it after configuration | | Family on and ready | Stored and converted | diff --git a/src/rememberstack/adapters/selfhost/control_plane_spend_lease.py b/src/rememberstack/adapters/selfhost/control_plane_spend_lease.py index 0d279ddb4..c84d9d9de 100644 --- a/src/rememberstack/adapters/selfhost/control_plane_spend_lease.py +++ b/src/rememberstack/adapters/selfhost/control_plane_spend_lease.py @@ -95,7 +95,9 @@ def _post( raise SpendLeaseUnavailable("spend lease timed out") from error except httpx.HTTPError as error: raise SpendLeaseUnavailable("spend lease unreachable") from error - if response.status_code in {401, 403, 423}: + # 413: the control plane refuses a hold for an over-size request; + # the caller gets that answer, not "unavailable". + if response.status_code in {401, 403, 413, 423}: raise SpendLeaseRefused( status_code=response.status_code, detail=_detail_from_response(response=response), diff --git a/src/rememberstack/workers/e0.py b/src/rememberstack/workers/e0.py index c8a76c2b8..8bdb6a132 100644 --- a/src/rememberstack/workers/e0.py +++ b/src/rememberstack/workers/e0.py @@ -24,6 +24,7 @@ import re import tempfile from typing import Final +from typing import NoReturn from typing import Protocol from uuid import NAMESPACE_URL from uuid import UUID @@ -690,22 +691,26 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: source = self._catalog.convert_source( version_id=_payload_uuid(work=work, field="version_id") ) - if ( - source.mime == "application/pdf" - and source.byte_size is not None - and exceeds_reading_limit(mime=source.mime, byte_size=source.byte_size) - ): - limit = family_for_mime(mime=source.mime).reading_limit_bytes - error = f"PDF exceeds the pre-OCR reading limit of {limit} bytes" - self._catalog.mark_version_failed(version_id=source.version_id, error=error) - raise NonRetryableHandlerError(error) + oversized = source.byte_size is not None and exceeds_reading_limit( + mime=source.mime, byte_size=source.byte_size + ) try: converter = self._converter_for(source=source) except UnroutableMimeError as err: + if source.mime == "application/pdf" and oversized: + self._fail_oversized_pdf(source=source) # Configuration can differ from the ingestor or resume command. # This runs before reading bytes or making a provider call, so the # runner may park and return the unused attempt (D117). raise NoRouteHandlerError(str(err), mime=source.mime) from err + if ( + source.mime == "application/pdf" + and oversized + and not self._reads_by_url(converter) + ): + # The reading limit guards this process, which would read the PDF; + # a route that fetches it by URL is not bound by it (D147). + self._fail_oversized_pdf(source=source) provider_limit = getattr(converter, "provider_limit_bytes", None) if ( source.mime == "application/pdf" @@ -949,17 +954,36 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: def _converter_for(self, *, source: ConvertSource) -> Converter: """The routed converter, or a card for an oversized non-PDF file. - D138 §3: an oversized file is always carded, whatever the deployment's - route table maps; the card states the limit it exceeded. + D138 §3: an oversized file is carded, and the card states the limit it + exceeded, because converting it would read it into this process. A + route that fetches its input by URL from a presigning store reads + nothing here, so an oversized file goes to that route (D147). """ if ( source.mime != "application/pdf" and source.byte_size is not None and exceeds_reading_limit(mime=source.mime, byte_size=source.byte_size) ): - return CardConverter() + try: + routed = self._router.converter_for(mime=source.mime) + except UnroutableMimeError: + return CardConverter() + return routed if self._reads_by_url(routed) else CardConverter() return self._router.converter_for(mime=source.mime) + def _reads_by_url(self, converter: Converter) -> bool: + """Whether this route would fetch its input by URL instead of bytes.""" + return isinstance(converter, UrlConverter) and isinstance( + self._raw_store, PresignedReadPort + ) + + def _fail_oversized_pdf(self, *, source: ConvertSource) -> NoReturn: + """Refuse a PDF this process would have to read beyond its limit.""" + limit = family_for_mime(mime=source.mime).reading_limit_bytes + error = f"PDF exceeds the pre-OCR reading limit of {limit} bytes" + self._catalog.mark_version_failed(version_id=source.version_id, error=error) + raise NonRetryableHandlerError(error) + def finalize_terminal_failure(self, *, work: ClaimedWork, error: str) -> None: """A convert whose retries exhausted must not leave the version in-flight.""" self._catalog.mark_version_failed( diff --git a/src/tests/adapters/test_control_plane_spend_lease.py b/src/tests/adapters/test_control_plane_spend_lease.py index 29233f232..9d544fc2d 100644 --- a/src/tests/adapters/test_control_plane_spend_lease.py +++ b/src/tests/adapters/test_control_plane_spend_lease.py @@ -392,6 +392,23 @@ def handler(request: httpx.Request) -> httpx.Response: assert error.value.detail == "dispatch_refused:x" +def test_adapter_passes_an_oversize_refusal_through() -> None: + """CP 413 becomes SpendLeaseRefused, so the caller sees 413, not 503.""" + + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(413, json={"detail": "hold_too_large"}) + + lease = ControlPlaneSpendLease( + base_url="https://example.test/v1/spend", transport=httpx.MockTransport(handler) + ) + with pytest.raises(SpendLeaseRefused) as error: + lease.reserve( + authorization="Bearer x", path_id="ingest", content_length=1 << 40 + ) + assert error.value.status_code == 413 + assert error.value.detail == "hold_too_large" + + def test_lease_200_open_query_sql_commits() -> None: """D109: POST /query/sql reserves under path_id='search' and commits on 200.""" lease = _FakeLease() diff --git a/src/tests/workers/test_ingest_stored_pg.py b/src/tests/workers/test_ingest_stored_pg.py index 726003ff6..887ecdff8 100644 --- a/src/tests/workers/test_ingest_stored_pg.py +++ b/src/tests/workers/test_ingest_stored_pg.py @@ -328,3 +328,107 @@ def read_bytes(self, *, key: ObjectKey) -> bytes: assert "- Not read: the file is larger than the 10-byte reading limit" in ( card.read_text(encoding="utf-8") ) + + +@pytest.mark.parametrize( + ("mime", "filename", "body"), + [ + ("text/markdown", "notes.md", _BODY), + ("application/pdf", "scan.pdf", b"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n"), + ], +) +def test_an_oversized_file_reaches_a_url_route( + database_engine: Engine, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mime: str, + filename: str, + body: bytes, +) -> None: + """D147: no size refusal or card when the route fetches the file by URL.""" + import dataclasses + + from rememberstack.core import file_card + from rememberstack.core import format_registry + from rememberstack.model import ConversionResult + from rememberstack.model import FileHints + + original = format_registry.family_for_mime + + def small(*, mime: str): # noqa: ANN202 + return dataclasses.replace(original(mime=mime), reading_limit_bytes=10) + + monkeypatch.setattr(format_registry, "family_for_mime", small) + monkeypatch.setattr(file_card, "family_for_mime", small) + + class _PresigningStore(LocalFSObjectStore): + reads = 0 + + def read_bytes(self, *, key: ObjectKey) -> bytes: + type(self).reads += 1 + return super().read_bytes(key=key) + + def presign_get(self, *, key: ObjectKey, ttl_s: int) -> str: + return f"memory://{key.root}?ttl={ttl_s}" + + class _UrlRoute: + accepts_url = True + url_ttl_s = 60 + calls: list[tuple[int, str]] = [] + + @property + def name(self) -> str: + return "remote" + + @property + def version(self) -> str: + return "remote-1" + + def convert(self, *, content: bytes, mime: str) -> ConversionResult: + raise AssertionError("the bytes path must not run") + + def convert_from_url( + self, *, url: str, size: int, mime: str, hints: FileHints + ) -> ConversionResult: + type(self).calls.append((size, mime)) + return MarkdownPassthroughConverter().convert( + content=b"# Remote\n", mime="text/markdown" + ) + + raw = _PresigningStore(root=tmp_path / "raw") + artifacts = LocalFSObjectStore(root=tmp_path / "artifacts") + ingestor = UploadIngestor( + catalog=DocumentCatalog(engine=database_engine), + raw_store=raw, + admission=ForgetCatalog(engine=database_engine), + routable_mimes=frozenset({mime}), + ) + ingestor.ingest_stored( + deployment_id=_DEPLOYMENT_ID, + key=_put(raw, "uploads/dddddddddddddddd", body), + size=len(body), + mime=mime, + filename=filename, + ) + registry = HandlerRegistry() + registry.register( + stage=PipelineStage.CONVERT, + handler=ConvertHandler( + catalog=DocumentCatalog(engine=database_engine), + raw_store=raw, + artifact_store=artifacts, + router=ConversionRouter(routes={mime: _UrlRoute()}), + ), + ) + worker = Worker( + ledger=WorkLedger(engine=database_engine, settings=WorkLedgerSettings()), + registry=registry, + ) + result = worker.run_one( + deployment_id=_DEPLOYMENT_ID, + stage=PipelineStage.CONVERT, + lane=ProcessingLane.STEADY, + ) + assert result.outcome is RunResultOutcome.SUCCEEDED + assert _UrlRoute.calls == [(len(body), mime)] + assert _PresigningStore.reads == 0 diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index 4f4560c9e..6d8de9c6f 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -3356,6 +3356,11 @@ from its sheet list and dimensions only. A text file over 1 MB is described by its size, line count, first 50 and last 20 lines instead of read in full. +The 100 MB and 200 MB limits protect the engine process, which reads the +file itself. A deployment whose converter fetches files by a signed URL +from S3 storage reads nothing in the engine, so it sends these files to +that converter instead; only the converter's own input limit applies. + ## Formats and converters A new self-hosted deployment reads the formats above locally, with no API diff --git a/website/src/app/docs/guides/file-types/page.mdx b/website/src/app/docs/guides/file-types/page.mdx index 04d85de53..62326f375 100644 --- a/website/src/app/docs/guides/file-types/page.mdx +++ b/website/src/app/docs/guides/file-types/page.mdx @@ -42,6 +42,11 @@ from its sheet list and dimensions only. A text file over 1 MB is described by its size, line count, first 50 and last 20 lines instead of read in full. +The 100 MB and 200 MB limits protect the engine process, which reads the +file itself. A deployment whose converter fetches files by a signed URL +from S3 storage reads nothing in the engine, so it sends these files to +that converter instead; only the converter's own input limit applies. + ## Formats and converters A new self-hosted deployment reads the formats above locally, with no API