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
12 changes: 11 additions & 1 deletion decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -7463,7 +7463,17 @@ deployment's values into another's work.
first one recorded, and only that one is purged by hard forget; so when identical
bytes are already stored under another key, that version answers and every ingest
path (`ingest`, `ingest_observed`, `ingest_stored`) deletes the copy it wrote or was
given. Callers never delete registered objects. The declared size must
given. Callers never delete registered objects. A refusal (declared size, content type,
managed metering, a forgotten identity, invalid metadata) raises
`StoredObjectRefusedError(refusal, raw_object_deleted)`: the engine deletes the refused
object unless a content keeps the key as its raw object (only the engine knows; a
refused re-registration of a registered key keeps it), so refused uploads do not stay
in storage unbilled. Storage and database failures delete nothing, so a retry can
succeed. `UploadIngestor.discard_unregistered(deployment_id, key) -> bool` applies the
same rule on its own, for a host sweeping uploads that were abandoned before
registration (unregistered bytes would escape hard forget): it deletes the object
unless a content keeps the key and returns whether it did. The caller serializes
registration and discard per key. The declared size must
match, and the uploader chooses the storage class (D51 routing is not applied). A
deployment with managed text metering measures the object exactly as `ingest` does;
that profile accepts only native text up to 10 MB, so a larger object is refused
Expand Down
2 changes: 2 additions & 0 deletions src/rememberstack/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
from rememberstack.model.documents import RepresentationNotFoundError
from rememberstack.model.documents import RepresentationRecord
from rememberstack.model.documents import SourceItem
from rememberstack.model.documents import StoredObjectRefusedError
from rememberstack.model.documents import StructureSource
from rememberstack.model.documents import SyncCycleSummary
from rememberstack.model.documents import SyntheticRootRecord
Expand Down Expand Up @@ -766,6 +767,7 @@
"UnroutableMimeError",
"VideoRegionLocator",
"UploadRecord",
"StoredObjectRefusedError",
"VersionKeyConflictError",
"Validity",
"VersionPipelineReadiness",
Expand Down
17 changes: 17 additions & 0 deletions src/rememberstack/model/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,23 @@ def __init__(self, *, version_key: str, version_id: UUID) -> None:
self.detail = str(self)


class StoredObjectRefusedError(ValueError):
"""``ingest_stored`` refused an object and says whether it deleted it (D147).

``refusal`` is the original refusal (a size mismatch, a content-type or
metering refusal, a forgotten identity). ``raw_object_deleted`` is
``True`` when the engine deleted the object because no content keeps
it, and ``False`` when the key is some content's raw object, which is
never deleted.
"""

def __init__(self, *, refusal: Exception, raw_object_deleted: bool) -> None:
"""Record the refusal and what happened to the object."""
super().__init__(str(refusal))
self.refusal = refusal
self.raw_object_deleted = raw_object_deleted


class EffectivePeriodConflictError(Exception):
"""A declared start equals a live declaration of another version (D140)."""

Expand Down
13 changes: 13 additions & 0 deletions src/rememberstack/spine/document_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,19 @@ def raw_object_key(self, *, deployment_id: UUID, content_hash: str) -> str | Non
{"deployment_id": deployment_id, "content_hash": content_hash},
).scalar_one_or_none()

def raw_object_registered(self, *, deployment_id: UUID, key: str) -> bool:
"""Whether any content keeps ``key`` as its raw object."""
with self._engine.connect() as connection:
return bool(
connection.execute(
text(
"SELECT EXISTS (SELECT 1 FROM content_objects"
" WHERE deployment_id = :deployment_id AND raw_uri = :key)"
),
{"deployment_id": deployment_id, "key": key},
).scalar_one()
)

def convert_source(self, *, version_id: UUID) -> ConvertSource:
"""Load what the convert stage needs about one document version."""
with self._engine.connect() as connection:
Expand Down
180 changes: 124 additions & 56 deletions src/rememberstack/workers/e0.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
from rememberstack.model import EnqueueWork
from rememberstack.model import FallbackStructureResponse
from rememberstack.model import FileHints
from rememberstack.model import ForgottenSourceError
from rememberstack.model import IngestedVersion
from rememberstack.model import IngestPrincipal
from rememberstack.model import ModelRequest
Expand All @@ -106,6 +107,7 @@
from rememberstack.model import SkeletonCheckResponse
from rememberstack.model import SnappedSection
from rememberstack.model import SourceLocator
from rememberstack.model import StoredObjectRefusedError
from rememberstack.model import StructureRouteTag
from rememberstack.model import StructureSource
from rememberstack.model import UnroutableMimeError
Expand Down Expand Up @@ -186,6 +188,11 @@
disjoint from the engine's own keys (``<doc_id>/…``, ``forgotten/…``)."""


_STORED_REFUSALS: Final = (ValueError, ForgottenSourceError)
"""What refuses a stored object for good (size, content type, metering,
metadata, a forgotten identity); anything else may succeed on retry."""


class IngestAdmission(Protocol):
"""The one D74 check required before an ingest writes any bytes."""

Expand Down Expand Up @@ -340,6 +347,18 @@ def ingest_stored(
forget). A repeated registration of the same key changes nothing.
Callers never delete registered objects; hard forget removes them.

A refusal (declared size, content type, managed metering, a forgotten
identity, invalid metadata) raises :class:`StoredObjectRefusedError`
carrying the original refusal. The engine deletes the refused object
unless a content keeps ``key`` as its raw object (a refused
re-registration of a registered key keeps it), and the error's
``raw_object_deleted`` says which. Other failures (storage or
database errors, admission paused for a forget in progress) raise
unchanged and delete nothing, so a retry can succeed;
:meth:`discard_unregistered` removes an object abandoned after such
a failure. The caller must not register or discard the same key
concurrently.

``key`` must be ``uploads/<id>`` with an opaque ``id`` of 16–128
characters from ``[A-Za-z0-9_-]``: hard forget purges a version's raw
key in every store, so a key outside this namespace could name
Expand Down Expand Up @@ -367,84 +386,133 @@ def ingest_stored(
digest = hashlib.sha256()
with tempfile.TemporaryFile() as spool:
received = 0
# Storage failures while streaming are not refusals: they raise
# unchanged and delete nothing, so a retry can succeed.
for chunk in self._raw_store.iter_bytes(
key=key, chunk_size=_STORED_CHUNK_BYTES
):
digest.update(chunk)
spool.write(chunk)
received += len(chunk)
if received != size:
raise ValueError(
f"stored object is {received} bytes, not the declared {size}"
)
content_hash = digest.hexdigest()
self._guard_ingest(
deployment_id=deployment_id,
source_kind=UPLOAD_SOURCE_KIND,
source_ref=content_hash,
content_hash=content_hash,
)
spool.flush()
if received == 0:
detected = self._detected_mime(
content=b"", filename=filename, mime=mime
try:
if received != size:
raise ValueError(
f"stored object is {received} bytes, not the declared {size}"
)
self._guard_ingest(
deployment_id=deployment_id,
source_kind=UPLOAD_SOURCE_KIND,
source_ref=content_hash,
content_hash=content_hash,
)
else:
with mmap.mmap(spool.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
spool.flush()
if received == 0:
detected = self._detected_mime(
content=mapped, filename=filename, mime=mime
content=b"", filename=filename, mime=mime
)
metering: ManagedTextMeasurementDraft | None = None
if self._meter_scope is not None:
if received > DOC_TEXT_MAX_SOURCE_BYTES:
raise ManagedTextClassificationError(
code="source_bytes_limit_exceeded"
else:
with mmap.mmap(
spool.fileno(), 0, access=mmap.ACCESS_READ
) as mapped:
detected = self._detected_mime(
content=mapped, filename=filename, mime=mime
)
metering: ManagedTextMeasurementDraft | None = None
if self._meter_scope is not None:
if received > DOC_TEXT_MAX_SOURCE_BYTES:
raise ManagedTextClassificationError(
code="source_bytes_limit_exceeded"
)
spool.seek(0)
measured, metering = self._prepare_managed_text(
deployment_id=deployment_id,
upload=DocumentUpload(
filename=filename,
mime=detected,
content=spool.read(),
title=title,
source_path=source_path,
),
)
spool.seek(0)
measured, metering = self._prepare_managed_text(
deployment_id=deployment_id,
upload=DocumentUpload(
filename=filename,
mime=detected,
content=spool.read(),
title=title,
source_path=source_path,
),
)
detected = measured.mime
detected = measured.mime
except _STORED_REFUSALS as refusal:
raise self._refused(
deployment_id=deployment_id, key=key, refusal=refusal
) from refusal
doc_id = uuid5(
NAMESPACE_URL, f"rememberstack:upload:{deployment_id}:{content_hash}"
)
routable = self._routable
if exceeds_reading_limit(mime=detected, byte_size=received):
routable = routable | {detected}
ingested = self._catalog.record_upload(
record=UploadRecord(
deployment_id=deployment_id,
doc_id=doc_id,
source_kind=UPLOAD_SOURCE_KIND,
source_ref=content_hash,
source_uri=None,
title=title or PurePosixPath(filename).stem,
content_hash=content_hash,
mime=detected,
byte_size=received,
raw_uri=key.root,
ingested_by=ingested_by,
file_name=filename,
declared_title=title,
source_path=source_path,
),
convert_component_version=E0_CONVERT_VERSION,
lane=lane,
metering=metering,
routable_mimes=routable,
)
try:
ingested = self._catalog.record_upload(
record=UploadRecord(
deployment_id=deployment_id,
doc_id=doc_id,
source_kind=UPLOAD_SOURCE_KIND,
source_ref=content_hash,
source_uri=None,
title=title or PurePosixPath(filename).stem,
content_hash=content_hash,
mime=detected,
byte_size=received,
raw_uri=key.root,
ingested_by=ingested_by,
file_name=filename,
declared_title=title,
source_path=source_path,
),
convert_component_version=E0_CONVERT_VERSION,
lane=lane,
metering=metering,
routable_mimes=routable,
)
except _STORED_REFUSALS as refusal:
raise self._refused(
deployment_id=deployment_id, key=key, refusal=refusal
) from refusal
self._release_unretained(
deployment_id=deployment_id, content_hash=content_hash, key=key
)
return ingested

def _refused(
self, *, deployment_id: UUID, key: ObjectKey, refusal: Exception
) -> StoredObjectRefusedError:
"""Delete a refused stored object unless a content keeps its key."""
deleted = self.discard_unregistered(deployment_id=deployment_id, key=key)
return StoredObjectRefusedError(refusal=refusal, raw_object_deleted=deleted)

def discard_unregistered(self, *, deployment_id: UUID, key: ObjectKey) -> bool:
"""Delete a directly uploaded object that no content keeps (D147).

For objects that never became a version: an upload whose registration
was never completed or retried, swept after it is abandoned, since
unregistered bytes would escape hard forget. Returns ``False`` and
keeps the object when a content keeps ``key`` as its raw object;
otherwise deletes it (absence succeeds) and returns ``True``.
:meth:`ingest_stored` uses the same rule for an object it refuses.
``key`` must be in the ``uploads/`` namespace.

The check and the delete are not one transaction: the caller must not
run this while an :meth:`ingest_stored` of the same key is in flight
(serialize per key).
"""
if _STORED_KEY.fullmatch(key.root) is None:
raise ValueError(
"a stored object's key must be uploads/<16-128 of [A-Za-z0-9_-]>"
)
if not isinstance(self._raw_store, ObjectPurgePort):
raise TypeError("discarding needs a raw store that purges")
if self._catalog.raw_object_registered(
deployment_id=deployment_id, key=key.root
):
return False
self._raw_store.purge_objects(keys=(key,), prefixes=())
return True

def ingest_observed(
self,
*,
Expand Down
11 changes: 9 additions & 2 deletions src/tests/spine/test_managed_metering_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from rememberstack.model import DeploymentBootstrapInput
from rememberstack.model import DocumentUpload
from rememberstack.model import ObjectKey
from rememberstack.model import StoredObjectRefusedError
from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2
from rememberstack.model.metering import ManagedIngestMeasurementV2
from rememberstack.model.metering import ManagedMeterScope
Expand Down Expand Up @@ -650,12 +651,18 @@ def test_a_stored_object_is_metered_like_an_upload(
too_large = ObjectKey("uploads/meteredmetered0002")
big = b"x" * (DOC_TEXT_MAX_SOURCE_BYTES + 1)
raw_store.write_bytes(key=too_large, content=big, storage_class="cold")
with pytest.raises(ManagedTextClassificationError) as refused:
with pytest.raises(StoredObjectRefusedError) as refused:
ingestor.ingest_stored(
deployment_id=_DEPLOYMENT_ID,
key=too_large,
size=len(big),
mime="text/plain",
filename="big.txt",
)
assert refused.value.code == "source_bytes_limit_exceeded"
refusal = refused.value.refusal
assert isinstance(refusal, ManagedTextClassificationError)
assert refusal.code == "source_bytes_limit_exceeded"
# Refused and never registered: the engine deleted the object.
assert refused.value.raw_object_deleted is True
with pytest.raises(FileNotFoundError):
raw_store.read_bytes(key=too_large)
Loading
Loading