From d882e013056225914c05ef3f0da9bb6a17644137 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 12:12:07 +0100 Subject: [PATCH 1/2] fix(D147): card an oversized file without reading it The card of a file over its family's reading limit holds only metadata, but the convert stage read the whole object to build it (len(content)). CardConverter.convert_unread builds the identical card from the size and MIME, and the convert stage uses it for every oversized file, so an oversized object is never read, whatever route or store. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 5 +- src/rememberstack/core/file_card.py | 25 +++++++- src/rememberstack/workers/e0.py | 22 +++++-- .../adapters/test_text_and_card_converters.py | 20 ++++++ src/tests/workers/test_ingest_stored_pg.py | 63 +++++++++++++++++++ 5 files changed, 128 insertions(+), 7 deletions(-) diff --git a/decisions.md b/decisions.md index d6b1ba1ce..15813fd37 100644 --- a/decisions.md +++ b/decisions.md @@ -7414,7 +7414,10 @@ 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. + for any route; the size and pre-OCR limits are checked before the URL is signed. A + 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. - *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/src/rememberstack/core/file_card.py b/src/rememberstack/core/file_card.py index 6ed341d4d..15ca7f5af 100644 --- a/src/rememberstack/core/file_card.py +++ b/src/rememberstack/core/file_card.py @@ -26,6 +26,7 @@ from PIL import Image from PIL import UnidentifiedImageError +from rememberstack.core.format_registry import exceeds_reading_limit from rememberstack.core.format_registry import family_for_mime from rememberstack.core.format_registry import FORMAT_MIMES from rememberstack.model import ConversionCoverage @@ -74,6 +75,24 @@ def convert( self, *, content: bytes, mime: str, hints: FileHints | None = None ) -> ConversionResult: """Build the card; its facts come from headers and directories only.""" + return self._card(size=len(content), content=content, mime=mime, hints=hints) + + def convert_unread( + self, *, size: int, mime: str, hints: FileHints | None = None + ) -> ConversionResult: + """The card of a file over its reading limit, built without its bytes. + + Such a card holds only metadata, so the convert stage never reads an + oversized object (D147); the result equals :meth:`convert`'s. + """ + if not exceeds_reading_limit(mime=mime, byte_size=size): + raise ValueError("only a file over its reading limit is carded unread") + return self._card(size=size, content=None, mime=mime, hints=hints) + + def _card( + self, *, size: int, content: bytes | None, mime: str, hints: FileHints | None + ) -> ConversionResult: + """Build the card from the size, the format and (within limits) bytes.""" family = family_for_mime(mime=mime) file_name = _one_line(value=hints.file_name if hints is not None else None) source_path = _one_line(value=hints.source_path if hints is not None else None) @@ -82,12 +101,12 @@ def convert( ("Source path", source_path or "unknown"), ("Family", family.name), ("Format", mime), - ("Byte size", f"{len(content):,} bytes"), + ("Byte size", f"{size:,} bytes"), ] sections: list[str] = [] warnings: list[str] = [] limit = family.reading_limit_bytes - if limit is not None and len(content) > limit: + if limit is not None and size > limit: fields.append( ( "Not read", @@ -95,6 +114,8 @@ def convert( f"for {family.name} files", ) ) + elif content is None: + raise ValueError("a card within the reading limit reads the bytes") elif family.name == "image": fields.append(_image_field(content=content, mime=mime, warnings=warnings)) elif mime == _ZIP_MIME: diff --git a/src/rememberstack/workers/e0.py b/src/rememberstack/workers/e0.py index 95de9abb8..c0eb8f984 100644 --- a/src/rememberstack/workers/e0.py +++ b/src/rememberstack/workers/e0.py @@ -707,16 +707,30 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: ) lane_meter = _ConvertLaneMeter(meter=meter, converter_name=converter.name) hints = FileHints(file_name=source.file_name, source_path=source.source_path) + # D138/D147: an oversized file's card is metadata only, so its bytes + # are never read, whatever the store. + unread = ( + isinstance(converter, CardConverter) + and source.byte_size is not None + and exceeds_reading_limit(mime=source.mime, byte_size=source.byte_size) + ) by_url = ( - isinstance(converter, UrlConverter) + not unread + and isinstance(converter, UrlConverter) and isinstance(self._raw_store, PresignedReadPort) and source.byte_size is not None ) - uses_lane_checkpoints = not by_url and isinstance( - converter, LaneCheckpointConverter + uses_lane_checkpoints = ( + not by_url and not unread and isinstance(converter, LaneCheckpointConverter) ) try: - if by_url: + if unread: + assert isinstance(converter, CardConverter) + assert source.byte_size is not None + result = converter.convert_unread( + size=source.byte_size, mime=source.mime, hints=hints + ) + elif by_url: # D147: the route reads the object itself; the bytes never # pass through this worker. assert isinstance(converter, UrlConverter) diff --git a/src/tests/adapters/test_text_and_card_converters.py b/src/tests/adapters/test_text_and_card_converters.py index 240924257..d030dca5d 100644 --- a/src/tests/adapters/test_text_and_card_converters.py +++ b/src/tests/adapters/test_text_and_card_converters.py @@ -328,3 +328,23 @@ def test_oversized_file_card_states_the_reason(monkeypatch: pytest.MonkeyPatch) "- Not read: the file is larger than the 10-byte reading limit for pdf files" in result.document_md ) + + +def test_an_oversized_card_needs_no_bytes(monkeypatch: pytest.MonkeyPatch) -> None: + """D147: the card of a file over its limit is built from its size alone.""" + from rememberstack.core import format_registry + + 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(card_module, "family_for_mime", small) + hints = FileHints(file_name="scan.pdf", source_path="archive") + content = b"%PDF-1.7 more than ten bytes" + assert CardConverter().convert_unread( + size=len(content), mime="application/pdf", hints=hints + ) == CardConverter().convert(content=content, mime="application/pdf", hints=hints) + with pytest.raises(ValueError, match="reading limit"): + CardConverter().convert_unread(size=5, mime="application/pdf", hints=hints) diff --git a/src/tests/workers/test_ingest_stored_pg.py b/src/tests/workers/test_ingest_stored_pg.py index 1e4231729..726003ff6 100644 --- a/src/tests/workers/test_ingest_stored_pg.py +++ b/src/tests/workers/test_ingest_stored_pg.py @@ -265,3 +265,66 @@ def stored_keys() -> set[str]: assert connection.execute( text("SELECT raw_uri FROM content_objects") ).one() == (first.root,) + + +def test_an_oversized_file_is_carded_without_reading_it( + database_engine: Engine, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """D147: the convert stage never reads an object it only cards.""" + import dataclasses + + from rememberstack.core import file_card + from rememberstack.core import format_registry + + 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 _CountingStore(LocalFSObjectStore): + reads = 0 + + def read_bytes(self, *, key: ObjectKey) -> bytes: + type(self).reads += 1 + return super().read_bytes(key=key) + + raw = _CountingStore(root=tmp_path / "raw") + artifacts = LocalFSObjectStore(root=tmp_path / "artifacts") + ingestor = _ingestor(engine=database_engine, raw=raw) + ingestor.ingest_stored( + deployment_id=_DEPLOYMENT_ID, + key=_put(raw, "uploads/cccccccccccccccc", _BODY), + size=len(_BODY), + mime="text/markdown", + filename="notes.md", + ) + registry = HandlerRegistry() + registry.register( + stage=PipelineStage.CONVERT, + handler=ConvertHandler( + catalog=DocumentCatalog(engine=database_engine), + raw_store=raw, + artifact_store=artifacts, + router=ConversionRouter( + routes={"text/markdown": MarkdownPassthroughConverter()} + ), + ), + ) + 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 _CountingStore.reads == 0 + (card,) = (tmp_path / "artifacts").rglob("document.md") + assert "- Not read: the file is larger than the 10-byte reading limit" in ( + card.read_text(encoding="utf-8") + ) From 879977e365d1502aba889c9323d31e587fb63a1c Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sat, 7 Nov 2026 12:17:36 +0100 Subject: [PATCH 2/2] docs(D147): only a non-PDF oversized file is carded (PDFs fail before OCR) Codex round 1 minor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F9cMsQBqiW2qU2ow4zeNCm --- decisions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/decisions.md b/decisions.md index 15813fd37..d2cae63e2 100644 --- a/decisions.md +++ b/decisions.md @@ -7414,7 +7414,7 @@ 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 + 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.