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
14 changes: 12 additions & 2 deletions decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -7403,8 +7403,18 @@ deployment's values into another's work.
- *Replaceable conversion.* `conversion_routes` (MIME type to `Converter`) on the
profile and `from_settings` replace the routes `SelfHostSettings.conversion_routes`
names, in both the `convert` stage and the upload admission check. Example: a host
whose converter forwards the bytes to an isolated conversion service, while claim,
lease, artifacts and completion stay with the trusted worker.
whose converter calls an isolated conversion service, while claim, lease, artifacts
and completion stay with the trusted worker.
- *Conversion by reference (2026-11-07, owner: no transport-driven upload caps).* A
route that implements `UrlConverter` (`accepts_url`, `url_ttl_s`,
`convert_from_url(url, size, mime, hints)`) is handed a pre-signed `GET` URL for the
raw object, its size and MIME type instead of the bytes, whenever the raw store
implements `PresignedReadPort.presign_get(key, ttl_s)` (the S3 adapter does) and the
version's size is known; the worker never reads the object. Every other route or store
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.
- *No deployment state on local disk.* `SelfHostSettings.forget_manifest_bucket_name`
keeps D74 hard-forget manifests as immutable objects in that dedicated bucket
(`ObjectStoreForgetManifestStore`, same contract as the local root) instead of
Expand Down
16 changes: 16 additions & 0 deletions src/rememberstack/adapters/selfhost/minio.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ def list_objects_v2(
"""List one page beneath a key prefix."""
...

def generate_presigned_url(
self, ClientMethod: str, Params: dict[str, str], ExpiresIn: int
) -> str:
"""Sign one request locally; nothing is sent."""
...


class MinIOObjectStore:
"""Immutable objects in one explicitly selected S3 bucket."""
Expand Down Expand Up @@ -233,6 +239,16 @@ def verify_objects_purged(
f"object purge verification found: {sorted(remaining)!r}"
)

def presign_get(self, *, key: ObjectKey, ttl_s: int) -> str:
"""A SigV4 query-signed ``GET`` URL for one object, valid ``ttl_s`` seconds."""
if ttl_s <= 0:
raise ValueError("a pre-signed URL needs a positive lifetime")
return self._client.generate_presigned_url(
ClientMethod="get_object",
Params={"Bucket": self._bucket, "Key": _validated_key(key=key)},
ExpiresIn=ttl_s,
)

def keys_under(self, *, prefix: ObjectKey) -> tuple[str, ...]:
"""Every key at or below ``prefix`` (prefix-boundary safe)."""
return self._keys_under(prefix=_validated_key(key=prefix))
Expand Down
2 changes: 2 additions & 0 deletions src/rememberstack/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from rememberstack.core.conversion import MarkdownPassthroughConverter
from rememberstack.core.conversion import PASSTHROUGH_CONVERTER_VERSION
from rememberstack.core.conversion import STOCK_CONVERSION_ROUTE_NAMES
from rememberstack.core.conversion import UrlConverter
from rememberstack.core.core_manifest import CORE_MANIFEST
from rememberstack.core.core_manifest import CoreManifest
from rememberstack.core.core_manifest import EntityTypeDefinition
Expand Down Expand Up @@ -122,6 +123,7 @@
"CONSUMPTION_SKILL_VERSION",
"Converter",
"LaneCheckpointConverter",
"UrlConverter",
"LaneCheckpointStore",
"LaneUsageRecorder",
"CoreManifest",
Expand Down
33 changes: 33 additions & 0 deletions src/rememberstack/core/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,39 @@ def convert(
...


@runtime_checkable
class UrlConverter(Protocol):
"""A converter that reads its input itself, from a short-lived URL (D147).

When the raw store can lend objects by pre-signed URL, the convert worker
hands such a route the URL, the size and the MIME type instead of
reading the bytes; it still writes the artifacts and records the result.
Every other route, and every store that cannot presign, keeps the bytes
path. Usage the route incurs travels in ``ConversionResult.usage_events``.
"""

accepts_url: bool
#: Lifetime of the URL the worker signs for this route, in seconds; long
#: enough for the route's whole call.
url_ttl_s: int

@property
def name(self) -> str:
"""The route name recorded on representations."""
...

@property
def version(self) -> str:
"""The converter version (D38): a bump creates new representations."""
...

def convert_from_url(
self, *, url: str, size: int, mime: str, hints: FileHints
) -> ConversionResult:
"""Produce the Markdown reading of the object behind ``url``."""
...


class ConversionRouter:
"""Route an input MIME type to its configured converter (D38 routing table)."""

Expand Down
2 changes: 2 additions & 0 deletions src/rememberstack/ports/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from rememberstack.ports.model_provider import ModelProviderPort
from rememberstack.ports.mounts import MountPublisherPort
from rememberstack.ports.object_store import ObjectStorePort
from rememberstack.ports.object_store import PresignedReadPort
from rememberstack.ports.postgres_read import PostgresReadPoolPort
from rememberstack.ports.purge import KGitPurgePort
from rememberstack.ports.purge import ObjectPurgePort
Expand All @@ -24,6 +25,7 @@
"MeterReceiptPort",
"MountPublisherPort",
"ObjectStorePort",
"PresignedReadPort",
"PostgresReadPoolPort",
"ObjectPurgePort",
"ProjectionPurgePort",
Expand Down
14 changes: 14 additions & 0 deletions src/rememberstack/ports/object_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,17 @@ def write_bytes(
that do not record it, so the routing is observable either way.
"""
...


@runtime_checkable
class PresignedReadPort(Protocol):
"""An object store that can lend one object by a short-lived URL (D147).

Lets a caller hand a reader (a conversion service, an OCR provider) a
reference instead of the bytes, so an object's size is never bounded by
a request body on the way.
"""

def presign_get(self, *, key: ObjectKey, ttl_s: int) -> str:
"""A URL that reads ``key`` with a plain ``GET`` for ``ttl_s`` seconds."""
...
52 changes: 37 additions & 15 deletions src/rememberstack/workers/e0.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
from rememberstack.core import SKELETON_STATS_VERSION
from rememberstack.core import SkeletonAnalysis
from rememberstack.core import storage_class_for
from rememberstack.core import UrlConverter
from rememberstack.core import with_content_hashes
from rememberstack.core.content_detection import detect_content_mime
from rememberstack.core.extraction_eligibility import block_eligibility
Expand Down Expand Up @@ -112,6 +113,7 @@
from rememberstack.ports.cost_meter import CostMeterPort
from rememberstack.ports.model_provider import ModelProviderPort
from rememberstack.ports.object_store import ObjectStorePort
from rememberstack.ports.object_store import PresignedReadPort
from rememberstack.spine.document_catalog import DocumentCatalog
from rememberstack.workers.base import HandlerOutcome
from rememberstack.workers.base import NoRouteHandlerError
Expand Down Expand Up @@ -535,23 +537,43 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome:
return self._structure_follow_up(
work=work, version_id=source.version_id, representation_id=existing
)
content = self._raw_store.read_bytes(key=ObjectKey(source.raw_uri))
lane_meter = _ConvertLaneMeter(meter=meter, converter_name=converter.name)
uses_lane_checkpoints = isinstance(converter, LaneCheckpointConverter)
hints = FileHints(file_name=source.file_name, source_path=source.source_path)
by_url = (
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
)
try:
result = _convert_with_lane_checkpoints(
converter=converter,
content=content,
mime=source.mime,
hints=FileHints(
file_name=source.file_name, source_path=source.source_path
),
checkpoint_store=self._artifact_store,
checkpoint_prefix=(
f"{source.doc_id}/{source.content_hash}/conversion-checkpoints"
),
record_usage=lane_meter,
)
if by_url:
# D147: the route reads the object itself; the bytes never
# pass through this worker.
assert isinstance(converter, UrlConverter)
assert isinstance(self._raw_store, PresignedReadPort)
assert source.byte_size is not None
result = converter.convert_from_url(
url=self._raw_store.presign_get(
key=ObjectKey(source.raw_uri), ttl_s=converter.url_ttl_s
),
size=source.byte_size,
mime=source.mime,
hints=hints,
)
else:
result = _convert_with_lane_checkpoints(
converter=converter,
content=self._raw_store.read_bytes(key=ObjectKey(source.raw_uri)),
mime=source.mime,
hints=hints,
checkpoint_store=self._artifact_store,
checkpoint_prefix=(
f"{source.doc_id}/{source.content_hash}/conversion-checkpoints"
),
record_usage=lane_meter,
)
if not uses_lane_checkpoints:
for event in result.usage_events:
# billed before coherence: the spend is real even if the
Expand Down
37 changes: 37 additions & 0 deletions src/tests/adapters/test_minio_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ def delete_object(self, *, Bucket: str, Key: str) -> object:
self.objects.pop((Bucket, Key), None)
return {}

def generate_presigned_url(
self, ClientMethod: str, Params: dict[str, str], ExpiresIn: int
) -> str:
"""Sign nothing; name what would be signed."""
return f"memory://{Params['Bucket']}/{Params['Key']}?{ClientMethod}&{ExpiresIn}"

def list_objects_v2(
self, *, Bucket: str, Prefix: str, ContinuationToken: str = ""
) -> _ListObjectsOutput:
Expand Down Expand Up @@ -197,3 +203,34 @@ def _client_error(*, code: str, operation: str) -> ClientError:
error_response={"Error": {"Code": code, "Message": code}},
operation_name=operation,
)


def test_presigned_get_is_signed_locally_for_one_object() -> None:
"""D147: a real S3 client signs a GET URL for the key without any request."""
from urllib.parse import parse_qs
from urllib.parse import urlparse

from pydantic import SecretStr

from rememberstack.adapters.selfhost import MinIOSettings
from rememberstack.ports import PresignedReadPort

store = MinIOObjectStore(
bucket="fs-raw",
settings=MinIOSettings(
endpoint_url="https://s3.example.invalid",
access_key=SecretStr("AKIDEXAMPLE"),
secret_key=SecretStr("secret"),
),
)
assert isinstance(store, PresignedReadPort)
url = urlparse(store.presign_get(key=ObjectKey("doc/hash/original.pdf"), ttl_s=900))
query = parse_qs(url.query)
assert (url.netloc, url.path) == (
"s3.example.invalid",
"/fs-raw/doc/hash/original.pdf",
)
assert query["X-Amz-Expires"] == ["900"]
assert query["X-Amz-Signature"]
with pytest.raises(ValueError, match="positive"):
store.presign_get(key=ObjectKey("doc/hash/original.pdf"), ttl_s=0)
59 changes: 55 additions & 4 deletions src/tests/profiles/test_two_deployment_contexts_pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from dataclasses import replace
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import url2pathname
from uuid import UUID
from uuid import uuid4

Expand All @@ -30,6 +32,8 @@
from rememberstack.core import MarkdownPassthroughConverter
from rememberstack.model import ConversionResult
from rememberstack.model import DeploymentBootstrapInput
from rememberstack.model import FileHints
from rememberstack.model import ObjectKey
from rememberstack.model import PipelineStage
from rememberstack.model import QueueRoute
from rememberstack.model import RunResultOutcome
Expand Down Expand Up @@ -63,13 +67,41 @@ def announce(
self.announced.append((processing_id, route_snapshot))


class _PresigningStore(LocalFSObjectStore):
"""A raw store that lends objects by URL and counts direct reads."""

def __init__(self, *, root: Path) -> None:
super().__init__(root=root)
self.reads = 0

def read_bytes(self, *, key: ObjectKey) -> bytes:
self.reads += 1
return super().read_bytes(key=key)

def presign_get(self, *, key: ObjectKey, ttl_s: int) -> str:
return f"{self._path_for(key=key).as_uri()}#ttl={ttl_s}" # noqa: SLF001


class _DelegatingConverter:
"""Stands in for a host's remote conversion call (D147)."""
"""Stands in for a host's remote conversion call by URL (D147)."""

accepts_url = True
url_ttl_s = 600

def __init__(self) -> None:
self.calls: list[str] = []
self.url_calls: list[tuple[int, str, str | None]] = []
self._inner = MarkdownPassthroughConverter()

def convert_from_url(
self, *, url: str, size: int, mime: str, hints: FileHints
) -> ConversionResult:
assert url.endswith("#ttl=600")
content = Path(url2pathname(urlparse(url).path)).read_bytes()
assert len(content) == size
self.url_calls.append((size, mime, hints.file_name))
return self._inner.convert(content=content, mime=mime)

@property
def name(self) -> str:
return self._inner.name
Expand Down Expand Up @@ -161,12 +193,19 @@ def converter() -> _DelegatingConverter:
return _DelegatingConverter()


@pytest.fixture
def raw_stores() -> dict[UUID, _PresigningStore]:
"""The presigning raw stores the profiles use, by deployment."""
return {}


@pytest.fixture
def profiles(
engines: dict[UUID, Engine],
tmp_path: Path,
queues: dict[UUID, _RecordingQueue],
converter: _DelegatingConverter,
raw_stores: dict[UUID, _PresigningStore],
) -> Iterator[dict[UUID, SelfHostProfile]]:
"""One context per deployment, each with its own database and stores."""
built: dict[UUID, SelfHostProfile] = {}
Expand All @@ -183,7 +222,13 @@ def profiles(
projection_work_root=root / "projection",
),
engine=engine,
raw_store=LocalFSObjectStore(root=root / "raw"), # type: ignore[arg-type]
raw_store=( # type: ignore[arg-type]
raw_stores.setdefault(
deployment_id, _PresigningStore(root=root / "raw")
)
if deployment_id == _DEPLOYMENT_B
else LocalFSObjectStore(root=root / "raw")
),
artifact_store=LocalFSObjectStore(root=root / "artifacts"), # type: ignore[arg-type]
corpusfs_store=LocalFSObjectStore(root=root / "corpusfs"), # type: ignore[arg-type]
model_provider=_NoModels(), # type: ignore[arg-type]
Expand All @@ -208,6 +253,7 @@ def test_two_contexts_keep_requests_and_tasks_in_their_own_database(
profiles: dict[UUID, SelfHostProfile],
queues: dict[UUID, _RecordingQueue],
converter: _DelegatingConverter,
raw_stores: dict[UUID, _PresigningStore],
) -> None:
"""Requests and tasks for A and B, interleaved, never touch the other's rows."""
contexts: dict[str, ApiDeployment] = {
Expand Down Expand Up @@ -308,8 +354,13 @@ def per_request(request: Request) -> ApiDeployment:
result = run_task(profiles[deployment_id], task)
assert result.processing_id == task
assert result.outcome is RunResultOutcome.SUCCEEDED
# B converted through its replaced route; A through the in-process one.
assert converter.calls == ["text/markdown"]
# B converted through its replaced route, by URL: the worker never read
# B's raw bytes. A converted through the in-process bytes route.
assert converter.url_calls == [
(len(b"# Bravo\n\nOnly B holds this.\n"), "text/markdown", "note.md")
]
assert converter.calls == []
assert raw_stores[_DEPLOYMENT_B].reads == 0
# Each task's successor was announced through its own deployment's queue.
for deployment_id, engine in engines.items():
structure = _rows(
Expand Down
Loading
Loading