Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
- *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
Expand Down
25 changes: 23 additions & 2 deletions src/rememberstack/core/file_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -82,19 +101,21 @@ 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",
f"the file is larger than the {limit:,}-byte reading limit "
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:
Expand Down
22 changes: 18 additions & 4 deletions src/rememberstack/workers/e0.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
20 changes: 20 additions & 0 deletions src/tests/adapters/test_text_and_card_converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
63 changes: 63 additions & 0 deletions src/tests/workers/test_ingest_stored_pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
)
Loading