diff --git a/.github/ci/unit-paths.txt b/.github/ci/unit-paths.txt index 5675362f9..b54e476b2 100644 --- a/.github/ci/unit-paths.txt +++ b/.github/ci/unit-paths.txt @@ -62,7 +62,7 @@ src/tests/core/test_source_passages.py src/tests/core/test_source_origins.py src/tests/core/test_structure_skeleton.py src/tests/core/test_temporal.py -src/tests/core/test_text_metering.py +src/tests/core/test_metering.py src/tests/eval/test_s55_hard_forget.py src/tests/eval/test_s55_selfhost_restore.py src/tests/model/test_component_version.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea307e5b8..3aa2883e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -468,7 +468,7 @@ jobs: trap - EXIT test "$(docker compose --env-file .env exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ - 'SELECT version_num FROM alembic_version')" = 'p9_45_0066' + 'SELECT version_num FROM alembic_version')" = 'p9_46_0067' test "$(docker compose --env-file .env exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ 'SELECT count(*) FROM deployments')" = '1' diff --git a/decisions.md b/decisions.md index b3f8073bf..26fd7fc0a 100644 --- a/decisions.md +++ b/decisions.md @@ -6387,8 +6387,8 @@ declaration contradicting a recognizable byte class raises a typed client error. For formats indistinguishable within a class, the filename and declaration select the D133/D138 registry family and posture, while legacy OLE needs a declared office subtype. Store the resulting MIME, and use -it consistently for the conversion route, original storage class, and managed -text metering. Every object-store write must provide a class: raw media hot, +it consistently for the conversion route, original storage class, and (through +the route) the managed meter's cost class (D150). Every object-store write must provide a class: raw media hot, other raw originals cold; query-facing derived objects and P3 snapshots hot; retry checkpoints and private K transcripts cold. Make the port argument required so future omissions fail before storage. @@ -6877,8 +6877,8 @@ therefore scales with every accepted page. The engine records only the registry's `scan_page` cost class with that quantity; provider-reported `pages_processed` is diagnostic evidence, not the billable quantity. The separate managed cloud copies the same quantity to a `doc-scan` receipt and -does not also charge `doc-text` for that PDF. This receipt mapping is a -required cloud follow-up, not a claim about current cloud behavior. +does not also charge `doc-text` for that PDF. The engine reports that +quantity to a metered deployment's control plane before any OCR call (D150). Conversion, source mapping and coverage stay in the engine under D60/D61. The PDF route needs a configured OCR provider and parks under D117 when it is unavailable. Converter and route changes require versioned re-conversion; @@ -7300,8 +7300,8 @@ evaluated separately as a retrieval aid. Measured LoCoMo cost shares (2026-09-14 derived from open gaps. Rule 4 holds: no re-chunking, no chunk re-embedding, unchanged reuse identities, each later snapshot version pays only for its edit. - **Readiness** expects the enabled layers' stages (all on: unchanged; facts off: `reconcile` at - either version). `processing_profile_id` is `doc-text-standard-v1`, `doc-text-claims-v1` or - `doc-text-sources-v1`; `profile_complete` certifies every stage the measured profile requires + either version). `processing_profile_id` is `-standard-v1`, `-claims-v1` or + `-sources-v1` (D150; for example `doc-text-claims-v1`); `profile_complete` certifies every stage the measured profile requires (standard: today's predicate), otherwise `failed` / `processing_profile_changed`. Frontiers order lineages; they are not readiness. - **Retrieval** reads the served (enabled) layers. A `layers` selection on @@ -7475,10 +7475,8 @@ deployment's values into another's work. 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 - before it is read into memory, and an accepted one is measured from the spooled copy - and released to the raw store on approval, where it already is. + metered deployment measures the version in the convert stage, as for every ingest + path (D150); registration itself measures nothing. - *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 @@ -7655,3 +7653,70 @@ No ingestion or paid-product reuse identity changes. See [analysis](plan/analysis/retrieval_work_amplification_20261106.md), [D91 §4.2](plan/designs/request_path_metering_and_cost_export_design.md#42-request-scope-exact-interface) and [D142 §8.2](plan/designs/postgres_p1_search_projection_design.md#8-query-and-filtering-contract). + + +## D150. A metered deployment measures each new version in the convert stage + +**Status:** accepted. **Date:** 2026-11-07. **Amends:** the managed text metering of +D139, D143 §4.5 and D147 (in-entry notes). + +**Context.** A managed deployment (one with a meter scope) reports how much work each new +source version needs to a commercial control plane, which places holds on the customer's +balance before any work that costs money. Until now the engine measured at ingest, and +only plain UTF-8 text and Markdown up to 10 MB could be measured: every PDF, office +document, HTML page or larger text was refused at the door (`409`/`413`/`422`), and the +accepted bytes were staged in the measurement row until approval. The control plane's +D94 asks instead for one generic receipt per source version — a cost class, an integer +quantity and its unit — with every PDF page billed as one `doc-scan` unit and any other +text a provider-free route reads billed as `doc-text` characters. + +**Decision.** Measurement moves from ingest into the convert stage, where the route that +will read the file is known. + +- *Which class.* The conversion route decides (`core/metering.py`). The `pdf` route — + every page through OCR (D139) — is `doc-scan`: the page count from the page tree, + taken **before** the OCR call, through the route's `count_pages` (bytes) or + `count_pages_from_url` (a by-URL route, D147). A local reading route (text, Markdown, + code, HTML, EPUB, office documents, email, notebooks, spreadsheets, delimited files, + datasets) is `doc-text`: the whitespace-normalized character count of the + `document.md` it produced. These routes call no model provider, so counting their + output still comes before every paid stage (structure models, embeddings, + extraction). `card` reads nothing and is free: no measurement. Any other route has no + managed cost class, and a metered deployment fails the version + (`rate_class_unavailable`) rather than run provider work it cannot bill. +- *Parking.* After recording the measurement the convert work parks with the defer + reason `admission`, which no claim takes. The meter drain's approval releases it in the + same transaction that records the approval (`release_admission_on`); the park reads the + approval under the lock the approval takes, so a race leaves the work queued, never + stranded. On release, a PDF is OCR'd; a reading route re-chains its stored reading + (replay before regenerate), so nothing is converted twice. +- *Ingest refuses nothing for metering.* Every entry point writes the original to the raw + store at once and enqueues convert, metered or not. Unchanged bytes create no version + and are never measured, so there are no `no_op` receipts. +- *Receipt.* `rememberstack.ingest_measurement.v3`: role `primary`, the Project triple, + stable opaque lineage and source-version IDs, `format_family`, `cost_class`, + `native_quantity`, `unit` (exactly one per class: `normalized_character`, `page`, + `image`, `millisecond`), canonical source bytes, classifier and algorithm versions, + the processing profile and `measured_at`. The terminal receipt + (`rememberstack.document_version_outcome.v3`) is `succeeded` or `failed`. The + processing profile is `--v1`, the layers being D143's + `standard`, `claims` or `sources`. + +**Alternatives.** Measuring office and HTML text at ingest would run every converter twice, +inside the request, and the shared API of a hosted deployment does not convert at all. +Billing a PDF by its text layer or splitting text and scanned pages contradicts D139. +Staging bytes in the outbox cannot hold large files (PostgreSQL's `bytea` stops at 1 GB) +and is moot for objects a client already uploaded directly. Refusing formats at ingest +turned a pricing gap into a capability gap. + +**Consequences.** A metered deployment accepts every format its routes read, of any size +the routes handle. One reuse boundary is declared (CLAUDE.md Rule 4): the ingest-time text +classifier stored every metered text as `text/plain` or `text/markdown`; without it a metered +deployment keeps the registry MIME, so CSV, code, configuration and logs take their own D138 +routes (`table`, `text` with their postures) like an unmetered one. A lineage whose previous +version was ingested under the old classifier re-converts, re-chunks and re-extracts once at its +next version, accepted because the hosted service relaunches without customer data. The meter outbox drops `staged_content` and the `no_op` disposition +and gains `cost_class`, `unit` and `format_family` (`p9_46_0067`, which refuses to run +while staged originals remain undrained). Unmetered deployments are unaffected. The +control plane must accept the v3 receipt before a deployment runs this release. + diff --git a/openapi.json b/openapi.json index 713bbc364..834fce961 100644 --- a/openapi.json +++ b/openapi.json @@ -3948,7 +3948,8 @@ "scheduled", "retry_backoff", "budget", - "no_route" + "no_route", + "admission" ], "type": "string" }, diff --git a/packages/typescript-client/contracts/metadata.json b/packages/typescript-client/contracts/metadata.json index 6c5f10dd2..ceeb669f8 100644 --- a/packages/typescript-client/contracts/metadata.json +++ b/packages/typescript-client/contracts/metadata.json @@ -1,9 +1,9 @@ { - "openapiHash": "44060532567a00d7f0bd59eca87660c429a199c2ce19589d4583267b6e3da7f0", + "openapiHash": "f1e84090bd89fa81174d84ac101553d2e25a0e0997fa67b9c7b8b588f3741402", "publishedBaseline": { "revision": "dd0c78015099cdd84ab5f3501744d6e225125989", "version": "0.17.2" }, "pythonSourceRevision": "2cde3baf7a820164170f2e4b91065056309f68e8", - "sourceHash": "a1c11187ef1d89412ff46decee1eb0582e73660144adb728bdf6393848b7df31" + "sourceHash": "f92cfe0d9da6e54d591038b96ff13699b491c4409825dc9d38b4d6540ef951ba" } diff --git a/packages/typescript-client/contracts/openapi-types.json b/packages/typescript-client/contracts/openapi-types.json index 12d22357a..65065744d 100644 --- a/packages/typescript-client/contracts/openapi-types.json +++ b/packages/typescript-client/contracts/openapi-types.json @@ -9017,7 +9017,8 @@ "scheduled", "retry_backoff", "budget", - "no_route" + "no_route", + "admission" ], "type": "string" }, @@ -11765,7 +11766,8 @@ "scheduled", "retry_backoff", "budget", - "no_route" + "no_route", + "admission" ], "type": "string" }, diff --git a/packages/typescript-client/contracts/schemas.json b/packages/typescript-client/contracts/schemas.json index 0aac39a49..a1d283eb9 100644 --- a/packages/typescript-client/contracts/schemas.json +++ b/packages/typescript-client/contracts/schemas.json @@ -4446,7 +4446,8 @@ "scheduled", "retry_backoff", "budget", - "no_route" + "no_route", + "admission" ], "type": "string" }, diff --git a/packages/typescript-client/src/generated/models/OutputPipelineStageReadiness.ts b/packages/typescript-client/src/generated/models/OutputPipelineStageReadiness.ts index 5de78dbf0..5d9466d9e 100644 --- a/packages/typescript-client/src/generated/models/OutputPipelineStageReadiness.ts +++ b/packages/typescript-client/src/generated/models/OutputPipelineStageReadiness.ts @@ -4,7 +4,7 @@ /* eslint-disable */ export type OutputPipelineStageReadiness = { component_version: string; - defer_reason: 'scheduled' | 'retry_backoff' | 'budget' | 'no_route' | null; + defer_reason: 'scheduled' | 'retry_backoff' | 'budget' | 'no_route' | 'admission' | null; finished_at: string | null; stage: string; status: 'missing' | 'pending' | 'running' | 'succeeded' | 'failed' | 'dead_letter' | 'skipped'; diff --git a/packages/typescript-client/src/generated/models/PipelineStageReadiness.ts b/packages/typescript-client/src/generated/models/PipelineStageReadiness.ts index 7b9e886da..ba3ef311c 100644 --- a/packages/typescript-client/src/generated/models/PipelineStageReadiness.ts +++ b/packages/typescript-client/src/generated/models/PipelineStageReadiness.ts @@ -4,7 +4,7 @@ /* eslint-disable */ export type PipelineStageReadiness = { component_version: string; - defer_reason?: 'scheduled' | 'retry_backoff' | 'budget' | 'no_route' | null; + defer_reason?: 'scheduled' | 'retry_backoff' | 'budget' | 'no_route' | 'admission' | null; finished_at?: string | null; stage: string; status: 'missing' | 'pending' | 'running' | 'succeeded' | 'failed' | 'dead_letter' | 'skipped'; diff --git a/packages/typescript-client/src/metadata.generated.ts b/packages/typescript-client/src/metadata.generated.ts index 56a5640cb..a7452dd44 100644 --- a/packages/typescript-client/src/metadata.generated.ts +++ b/packages/typescript-client/src/metadata.generated.ts @@ -1,10 +1,10 @@ /* Generated from Python; regenerate with npm run generate. */ export default { - "openapiHash": "44060532567a00d7f0bd59eca87660c429a199c2ce19589d4583267b6e3da7f0", + "openapiHash": "f1e84090bd89fa81174d84ac101553d2e25a0e0997fa67b9c7b8b588f3741402", "publishedBaseline": { "revision": "dd0c78015099cdd84ab5f3501744d6e225125989", "version": "0.17.2" }, "pythonSourceRevision": "2cde3baf7a820164170f2e4b91065056309f68e8", - "sourceHash": "a1c11187ef1d89412ff46decee1eb0582e73660144adb728bdf6393848b7df31" + "sourceHash": "f92cfe0d9da6e54d591038b96ff13699b491c4409825dc9d38b4d6540ef951ba" }; diff --git a/packages/typescript-client/src/schemas.generated.ts b/packages/typescript-client/src/schemas.generated.ts index d3775c623..56f491416 100644 --- a/packages/typescript-client/src/schemas.generated.ts +++ b/packages/typescript-client/src/schemas.generated.ts @@ -4447,7 +4447,8 @@ export default { "scheduled", "retry_backoff", "budget", - "no_route" + "no_route", + "admission" ], "type": "string" }, diff --git a/packages/typescript-client/src/version.generated.ts b/packages/typescript-client/src/version.generated.ts index ccc1e2157..556818245 100644 --- a/packages/typescript-client/src/version.generated.ts +++ b/packages/typescript-client/src/version.generated.ts @@ -1,3 +1,3 @@ /* Generated package version; regenerate with npm run generate. */ export const version = "0.1.0"; -export const pythonCompatibility = {"openapiHash":"44060532567a00d7f0bd59eca87660c429a199c2ce19589d4583267b6e3da7f0","publishedBaseline":{"revision":"dd0c78015099cdd84ab5f3501744d6e225125989","version":"0.17.2"},"pythonSourceRevision":"2cde3baf7a820164170f2e4b91065056309f68e8","sourceHash":"a1c11187ef1d89412ff46decee1eb0582e73660144adb728bdf6393848b7df31"} as const; +export const pythonCompatibility = {"openapiHash":"f1e84090bd89fa81174d84ac101553d2e25a0e0997fa67b9c7b8b588f3741402","publishedBaseline":{"revision":"dd0c78015099cdd84ab5f3501744d6e225125989","version":"0.17.2"},"pythonSourceRevision":"2cde3baf7a820164170f2e4b91065056309f68e8","sourceHash":"f92cfe0d9da6e54d591038b96ff13699b491c4409825dc9d38b4d6540ef951ba"} as const; diff --git a/plan/designs/e0_files_design.md b/plan/designs/e0_files_design.md index a1b50f38f..8cc42e59e 100644 --- a/plan/designs/e0_files_design.md +++ b/plan/designs/e0_files_design.md @@ -94,14 +94,15 @@ for a family D132 does not cover (for example, an archive); the converter validates that format. Remaining unrecognized binary is stored as a D138 binary card. The stored `content_objects.mime` is the decided MIME and drives the D38 route, D51 -original class, and managed text metering. Text flavours cannot be settled by +original class, and, through that route, a metered deployment's cost class +(D150). Text flavours cannot be settled by bytes: once bytes establish text, D133/D138 registry hints select Markdown, CSV, code, configuration, or plain text and their distinct processing postures. Textual email, notebooks, RTF, and delimited data keep their registry families; their converters validate full structure. Recognizable HTML markup retains `text/html` for its separate converter, and an empty upload -is valid text in the self-host profile (the managed text profile rejects an -empty measured source). +is valid text in every deployment; a metered one bills it at the per-source +minimum (D150). For legacy OLE office containers, bytes establish the office class and the declared legacy office MIME selects its subtype. Otherwise an ambiguous OLE diff --git a/plan/designs/processing_layers_design.md b/plan/designs/processing_layers_design.md index d488d7c1a..5d06a6c9c 100644 --- a/plan/designs/processing_layers_design.md +++ b/plan/designs/processing_layers_design.md @@ -263,14 +263,15 @@ whose gap was discharged (§5.3) reports that layer's stages as `skipped`. The c (`p1`, `live_graph`, `p3`) are unchanged. A version with an open gap in an enabled layer is not ready until it is processed. -**Metering.** Every model call is metered per stage in `cost_ledger` as today. The managed text -meter stamps the `processing_profile_id` from the layers enabled at measurement time: +**Metering.** Every model call is metered per stage in `cost_ledger` as today. The managed +meter (D150) stamps the `processing_profile_id` from the measured cost class and the layers +enabled at measurement time, `--v1` (for example `doc-scan-claims-v1`): -| Enabled layers | `processing_profile_id` | Stages its receipt requires | +| Enabled layers | `processing_profile_id` suffix | Stages its receipt requires | | --- | --- | --- | -| sources, claims, facts | `doc-text-standard-v1` (unchanged) | today's twelve | -| sources, claims | `doc-text-claims-v1` | the eight above (`reconcile` at either version) | -| sources | `doc-text-sources-v1` | the four above | +| sources, claims, facts | `-standard-v1` | today's twelve | +| sources, claims | `-claims-v1` | the eight above (`reconcile` at either version) | +| sources | `-sources-v1` | the four above | The outcome receipt certifies **the measured profile**, not the current configuration and not a frontier: `profile_complete` is true only when every stage the measured profile requires succeeded, diff --git a/src/remember/models.py b/src/remember/models.py index 4ed6c4ea1..fdea88d1e 100644 --- a/src/remember/models.py +++ b/src/remember/models.py @@ -105,11 +105,13 @@ class PipelineStageReadiness(BaseModel): ] finished_at: datetime | None = None # Why waiting work waits: `no_route` (no converter for the file's type), - # `budget` (the spend budget is exhausted), `scheduled` (due later), or - # `retry_backoff` (a `failed` stage waiting for its next attempt). - defer_reason: Literal["scheduled", "retry_backoff", "budget", "no_route"] | None = ( - None - ) + # `admission` (a metered deployment's conversion waiting for its control + # plane's approval), `budget` (the spend budget is exhausted), `scheduled` + # (due later), or `retry_backoff` (a `failed` stage waiting for its next + # attempt). + defer_reason: ( + Literal["scheduled", "retry_backoff", "budget", "no_route", "admission"] | None + ) = None class VersionPipelineReadiness(BaseModel): diff --git a/src/rememberstack/adapters/converters/pdf.py b/src/rememberstack/adapters/converters/pdf.py index 4e617ebab..cbc889e5d 100644 --- a/src/rememberstack/adapters/converters/pdf.py +++ b/src/rememberstack/adapters/converters/pdf.py @@ -77,6 +77,10 @@ def provider_limit_bytes(self) -> int | None: """The configured OCR input ceiling for pre-converter admission.""" return self._provider_limit_bytes + def count_pages(self, *, content: bytes) -> int: + """Count the PDF's pages from its page tree, before any OCR call.""" + return pdf_page_count(content=content) + def convert_path(self, *, path: Path, mime: str) -> ConversionResult: """:meth:`convert` for a PDF on local disk, never holding it whole (D147). diff --git a/src/rememberstack/adapters/selfhost/managed_metering.py b/src/rememberstack/adapters/selfhost/managed_metering.py index 754ab8536..dad7b14c6 100644 --- a/src/rememberstack/adapters/selfhost/managed_metering.py +++ b/src/rememberstack/adapters/selfhost/managed_metering.py @@ -5,8 +5,8 @@ import httpx from pydantic import SecretStr -from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2 -from rememberstack.model.metering import ManagedIngestMeasurementV2 +from rememberstack.model.metering import ManagedDocumentVersionOutcome +from rememberstack.model.metering import ManagedIngestMeasurement from rememberstack.model.metering import MeterAdmissionResult from rememberstack.model.metering import MeterReceiptConflict from rememberstack.model.metering import MeterReceiptUnauthorized @@ -14,7 +14,7 @@ class ControlPlaneMeterReceipts: - """Deliver v2 receipts with a deployment-scoped ``umc_mi_`` bearer.""" + """Deliver v3 receipts with a deployment-scoped ``umc_mi_`` bearer.""" def __init__( self, @@ -30,7 +30,7 @@ def __init__( self._client = httpx.Client(timeout=timeout_s, transport=transport) def admit_measurement( - self, *, measurement: ManagedIngestMeasurementV2 + self, *, measurement: ManagedIngestMeasurement ) -> MeterAdmissionResult: """Post one canonical measurement and validate its stable decision.""" body = self._post( @@ -44,7 +44,7 @@ def admit_measurement( "meter admission returned an invalid decision" ) from error - def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcomeV2) -> None: + def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcome) -> None: """Post one terminal receipt and require an explicit acknowledgement.""" body = self._post( path="/processed-input/outcomes", payload=outcome.model_dump(mode="json") diff --git a/src/rememberstack/core/__init__.py b/src/rememberstack/core/__init__.py index c255fa3c6..0d93a6608 100644 --- a/src/rememberstack/core/__init__.py +++ b/src/rememberstack/core/__init__.py @@ -28,9 +28,11 @@ from rememberstack.core.conversion import LaneCheckpointStore from rememberstack.core.conversion import LaneUsageRecorder from rememberstack.core.conversion import MarkdownPassthroughConverter +from rememberstack.core.conversion import PageCountingConverter 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.conversion import UrlPageCountingConverter from rememberstack.core.core_manifest import CORE_MANIFEST from rememberstack.core.core_manifest import CoreManifest from rememberstack.core.core_manifest import EntityTypeDefinition @@ -123,7 +125,9 @@ "CONSUMPTION_SKILL_VERSION", "Converter", "LaneCheckpointConverter", + "PageCountingConverter", "UrlConverter", + "UrlPageCountingConverter", "LaneCheckpointStore", "LaneUsageRecorder", "CoreManifest", diff --git a/src/rememberstack/core/conversion.py b/src/rememberstack/core/conversion.py index b10d5c20e..2f1dd6db6 100644 --- a/src/rememberstack/core/conversion.py +++ b/src/rememberstack/core/conversion.py @@ -189,6 +189,33 @@ def convert_from_url( ... +@runtime_checkable +class PageCountingConverter(Protocol): + """A paged route that counts its source's pages without converting it. + + A metered deployment records a PDF's page count before any OCR call, so + the control plane can hold the charge first (D139). Counting reads only + the page tree, never a text layer. + """ + + def count_pages(self, *, content: bytes) -> int: + """The source's structural page count; raise ``ConversionError`` if unreadable.""" + ... + + +@runtime_checkable +class UrlPageCountingConverter(Protocol): + """A paged URL route (D147) that counts its source's pages from the URL. + + The by-URL counterpart of :class:`PageCountingConverter`: the convert + worker never reads the object, so the route fetches it to count. + """ + + def count_pages_from_url(self, *, url: str, size: int) -> int: + """The structural page count of the object behind ``url``.""" + ... + + class ConversionRouter: """Route an input MIME type to its configured converter (D38 routing table).""" diff --git a/src/rememberstack/core/metering.py b/src/rememberstack/core/metering.py new file mode 100644 index 000000000..28b201e98 --- /dev/null +++ b/src/rememberstack/core/metering.py @@ -0,0 +1,79 @@ +"""Which cost class a conversion route bills, and how its quantity is counted. + +A managed deployment reports one measurement per new source version before +the work that calls model providers (D139 and the cloud's D94 meter). The +conversion route decides the class: + +- ``pdf`` — every PDF, every page through OCR — is ``doc-scan``: the page + count from the PDF page tree, taken before any OCR call. +- A local reading route (text, Markdown, code, HTML, office documents, email, + notebooks, spreadsheets, delimited files, datasets) is ``doc-text``: the + whitespace-normalized character count of the ``document.md`` it produced. + These routes call no model provider, so counting their output still + precedes every paid stage. +- ``card`` reads nothing and is free: it sends no measurement. + +Any other route has no managed cost class, so a metered deployment refuses +to run it rather than process unbilled provider work. +""" + +from __future__ import annotations + +from typing import Final + +from rememberstack.model.metering import CostClass + +METERING_CLASSIFIER_VERSION: Final = "route-cost-class-v1" +"""Pins the route → cost-class table below.""" + +DOC_TEXT_ALGORITHM_VERSION: Final = "document-md-unicode-whitespace-scalars-v1" +"""Pins how ``doc-text`` is counted: :func:`normalized_character_count` of +the route's ``document.md``.""" + +DOC_SCAN_ALGORITHM_VERSION: Final = "pdf-page-tree-v1" +"""Pins how ``doc-scan`` is counted: the PDF's structural page count.""" + +FREE_ROUTES: Final = frozenset({"card"}) +"""Routes that read nothing; their storage is billed, their processing is not.""" + +_ROUTE_CLASSES: Final[dict[str, CostClass]] = { + "pdf": "doc-scan", + "passthrough": "doc-text", + "text": "doc-text", + "markitdown": "doc-text", + "office": "doc-text", + "email": "doc-text", + "notebook": "doc-text", + "spreadsheet": "doc-text", + "table": "doc-text", + "dataset": "doc-text", +} + + +class UnmeteredRouteError(ValueError): + """A metered deployment was asked to run a route that has no cost class.""" + + +def cost_class_for_route(*, route: str) -> CostClass: + """The cost class a non-free route bills; refuse a route with none.""" + try: + return _ROUTE_CLASSES[route] + except KeyError: + raise UnmeteredRouteError( + f"route {route!r} has no managed cost class (rate_class_unavailable)" + ) from None + + +def normalized_character_count(*, text: str) -> int: + """Count Unicode scalars after collapsing each maximal whitespace run to one.""" + count = 0 + in_whitespace = False + for scalar in text: + whitespace = scalar.isspace() + if whitespace: + if not in_whitespace: + count += 1 + else: + count += 1 + in_whitespace = whitespace + return count diff --git a/src/rememberstack/core/text_metering.py b/src/rememberstack/core/text_metering.py deleted file mode 100644 index 19217cee6..000000000 --- a/src/rememberstack/core/text_metering.py +++ /dev/null @@ -1,109 +0,0 @@ -"""Bounded, content-local classification for the managed doc-text profile.""" - -from __future__ import annotations - -from dataclasses import dataclass -import re - -from rememberstack.core.content_detection import detect_content_mime -from rememberstack.model.metering import ManagedTextClassificationError - -DOC_TEXT_CLASSIFIER_VERSION = "doc-text-classifier-v1" -DOC_TEXT_MEASUREMENT_ALGORITHM_VERSION = "unicode-whitespace-scalars-v1" -DOC_TEXT_MAX_SOURCE_BYTES = 10_000_000 - -_BINARY_MAGICS: tuple[bytes, ...] = ( - b"\x89PNG\r\n\x1a\n", - b"\xff\xd8\xff", - b"PK\x03\x04", - b"\x1f\x8b", - b"\x00\x00\x00\x18ftyp", - b"\x00\x00\x00\x20ftyp", -) -_DOC_TEXT_MIMES = frozenset({"", "application/octet-stream"}) -_STRUCTURED_TEXT_PREFIX = re.compile( - rb"(?:\{\\rtf|)|<\?xml(?:\s|>)|)|<[/!?]?[a-z][^>]{0,128}>)", - re.IGNORECASE, -) - - -@dataclass(frozen=True, slots=True) -class ClassifiedText: - """The only native operands allowed out of the bounded classifier.""" - - normalized_character_count: int - canonical_source_bytes: int - canonical_mime: str - - -def normalized_character_count(*, text: str) -> int: - """Count Unicode scalars after collapsing each maximal whitespace run.""" - count = 0 - in_whitespace = False - for scalar in text: - whitespace = scalar.isspace() - if whitespace: - if not in_whitespace: - count += 1 - else: - count += 1 - in_whitespace = whitespace - return count - - -def classify_doc_text(*, content: bytes, declared_mime: str) -> ClassifiedText: - """Inspect bounded bytes and accept only unambiguous native Unicode text. - - Caller MIME and filename never turn binary material into text. Once bytes - are proven textual, MIME only preserves the markdown rendering hint; every - other declaration is normalized to plain text for the stock local route. - """ - if len(content) > DOC_TEXT_MAX_SOURCE_BYTES: - raise ManagedTextClassificationError(code="source_bytes_limit_exceeded") - if not content: - raise ManagedTextClassificationError(code="empty_text") - if any(content.startswith(magic) for magic in _BINARY_MAGICS): - raise ManagedTextClassificationError(code="rate_class_unavailable") - byte_mime = detect_content_mime( - content=content, declared_mime="application/octet-stream" - ) - if byte_mime not in { - "application/octet-stream", - "text/plain", - "text/markdown", - "text/html", - }: - raise ManagedTextClassificationError(code="rate_class_unavailable") - mime = declared_mime.partition(";")[0].strip().lower() - if mime not in _DOC_TEXT_MIMES and not mime.startswith("text/"): - raise ManagedTextClassificationError(code="rate_class_ambiguous") - stripped = content - while True: - next_prefix = stripped.lstrip().removeprefix(b"\xef\xbb\xbf") - if next_prefix == stripped: - break - stripped = next_prefix - if _STRUCTURED_TEXT_PREFIX.match(stripped) or stripped.startswith(b"JVBERi0"): - raise ManagedTextClassificationError(code="rate_class_ambiguous") - try: - decoded = content.decode("utf-8-sig") - except UnicodeDecodeError as error: - raise ManagedTextClassificationError(code="rate_class_ambiguous") from error - if any( - (ord(scalar) < 32 and scalar not in {"\t", "\n", "\r"}) or ord(scalar) == 127 - for scalar in decoded - ): - raise ManagedTextClassificationError(code="rate_class_ambiguous") - quantity = normalized_character_count(text=decoded) - if quantity == 0 or decoded.isspace(): - raise ManagedTextClassificationError(code="empty_text") - canonical_mime = ( - "text/markdown" - if mime in {"text/markdown", "text/x-markdown"} - else "text/plain" - ) - return ClassifiedText( - normalized_character_count=quantity, - canonical_source_bytes=len(content), - canonical_mime=canonical_mime, - ) diff --git a/src/rememberstack/model/__init__.py b/src/rememberstack/model/__init__.py index 1b0bd25a7..8849f34c4 100644 --- a/src/rememberstack/model/__init__.py +++ b/src/rememberstack/model/__init__.py @@ -288,12 +288,11 @@ from rememberstack.model.knowledge_planner import KnowledgeSplitPageProposal from rememberstack.model.lifecycle import CurrencyTransition from rememberstack.model.lifecycle import ReconciliationDelta -from rememberstack.model.metering import DocTextQuantity -from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2 -from rememberstack.model.metering import ManagedIngestMeasurementV2 +from rememberstack.model.metering import CostClass +from rememberstack.model.metering import ManagedDocumentVersionOutcome +from rememberstack.model.metering import ManagedIngestMeasurement +from rememberstack.model.metering import ManagedMeasurementDraft from rememberstack.model.metering import ManagedMeterScope -from rememberstack.model.metering import ManagedTextClassificationError -from rememberstack.model.metering import ManagedTextMeasurementDraft from rememberstack.model.metering import MeterAdmissionResult from rememberstack.model.metering import MeterReceiptConflict from rememberstack.model.metering import MeterReceiptUnauthorized @@ -537,13 +536,12 @@ "IngestedVersion", "IngestPrincipal", "IngestPrincipalKind", - "DocTextQuantity", - "ManagedDocumentVersionOutcomeV2", - "ManagedIngestMeasurementV2", + "CostClass", + "ManagedDocumentVersionOutcome", + "ManagedIngestMeasurement", "ManagedMeterScope", - "ManagedTextClassificationError", "ContentDetectionError", - "ManagedTextMeasurementDraft", + "ManagedMeasurementDraft", "MeterAdmissionResult", "MeterReceiptConflict", "MeterReceiptUnauthorized", diff --git a/src/rememberstack/model/metering.py b/src/rememberstack/model/metering.py index 188bcbb97..8606d773e 100644 --- a/src/rememberstack/model/metering.py +++ b/src/rememberstack/model/metering.py @@ -17,62 +17,82 @@ from pydantic import model_validator from pydantic import SecretStr +CostClass = Literal["doc-text", "doc-scan", "image", "audio", "video"] +"""A processed-input cost class: what kind of work one source version needs.""" -class DocTextQuantity(BaseModel): - """Whitespace-normalized Unicode scalar count for one text source.""" +EvidenceUnit = Literal["normalized_character", "page", "image", "millisecond"] +"""The integer unit a cost class is measured in.""" - model_config = ConfigDict(frozen=True, extra="forbid") +EVIDENCE_UNIT: dict[str, EvidenceUnit] = { + "doc-text": "normalized_character", + "doc-scan": "page", + "image": "image", + "audio": "millisecond", + "video": "millisecond", +} +"""Each cost class has exactly one evidence unit.""" - kind: Literal["doc_text"] = "doc_text" - normalized_character_count: int = Field(ge=0) +class ManagedIngestMeasurement(BaseModel): + """The generic v3 receipt for one source version, sent before costly work. -class ManagedIngestMeasurementV2(BaseModel): - """The v2 primary-source receipt sent before expensive pipeline work.""" + It names what was measured (``cost_class``, an integer ``native_quantity`` + in ``unit``) and nothing about the content: no bytes, text, name, hash or + locator. Only primary sources exist: the engine extracts no automatic + children, so there is no parent link. + """ model_config = ConfigDict(frozen=True, extra="forbid") - contract_version: Literal["rememberstack.ingest_measurement.v2"] = ( - "rememberstack.ingest_measurement.v2" + contract_version: Literal["rememberstack.ingest_measurement.v3"] = ( + "rememberstack.ingest_measurement.v3" ) + role: Literal["primary"] = "primary" measurement_id: UUID ingest_attempt_id: str = Field(min_length=1, max_length=128) org_id: UUID project_id: UUID deployment_id: UUID - parent_measurement_id: UUID | None = None opaque_lineage_id: str = Field(min_length=1, max_length=128) opaque_source_version_id: str = Field(min_length=1, max_length=128) - rate_class: Literal["doc-text"] = "doc-text" - quantity: DocTextQuantity + format_family: str = Field(min_length=1, max_length=64) + cost_class: CostClass + native_quantity: int = Field(ge=0) + unit: EvidenceUnit canonical_source_bytes: int = Field(ge=0) - document_version_disposition: Literal["new_version", "no_op"] classifier_version: str = Field(min_length=1, max_length=128) measurement_algorithm_version: str = Field(min_length=1, max_length=128) processing_profile_id: str = Field(min_length=1, max_length=128) measured_at: datetime + @model_validator(mode="after") + def unit_matches_cost_class(self) -> ManagedIngestMeasurement: + """Require the class's own unit and real evidence for non-text classes.""" + if EVIDENCE_UNIT[self.cost_class] != self.unit: + raise ValueError("unit does not match cost_class") + if self.cost_class != "doc-text" and self.native_quantity < 1: + raise ValueError("native_quantity must be positive for this cost_class") + return self + -class ManagedDocumentVersionOutcomeV2(BaseModel): - """The v2 terminal receipt replayed until the control plane acknowledges it.""" +class ManagedDocumentVersionOutcome(BaseModel): + """The v3 terminal receipt replayed until the control plane acknowledges it.""" model_config = ConfigDict(frozen=True, extra="forbid") - contract_version: Literal["rememberstack.document_version_outcome.v2"] = ( - "rememberstack.document_version_outcome.v2" + contract_version: Literal["rememberstack.document_version_outcome.v3"] = ( + "rememberstack.document_version_outcome.v3" ) measurement_id: UUID document_version_id: str | None = Field(default=None, max_length=128) - outcome: Literal["succeeded", "failed", "no_op"] + outcome: Literal["succeeded", "failed"] completed_at: datetime reason_code: str | None = Field(default=None, max_length=64) profile_complete: bool version_commit_sequence: int | None = Field(default=None, ge=0) - derived_normalized_character_count: int | None = Field(default=None, ge=0) - provider_cost_evidence_id: str | None = Field(default=None, max_length=128) @model_validator(mode="after") - def successful_append_is_complete(self) -> ManagedDocumentVersionOutcomeV2: + def successful_append_is_complete(self) -> ManagedDocumentVersionOutcome: """Require the immutable version evidence that makes success billable.""" if self.outcome == "succeeded" and ( not self.document_version_id @@ -85,8 +105,8 @@ def successful_append_is_complete(self) -> ManagedDocumentVersionOutcomeV2: return self -class ManagedTextMeasurementDraft(BaseModel): - """Local pre-version evidence passed into the transactional spine write.""" +class ManagedMeasurementDraft(BaseModel): + """One source version's measurement before the spine assigns opaque IDs.""" model_config = ConfigDict(frozen=True, extra="forbid") @@ -94,14 +114,15 @@ class ManagedTextMeasurementDraft(BaseModel): ingest_attempt_id: str = Field(min_length=1, max_length=128) org_id: UUID project_id: UUID - normalized_character_count: int = Field(ge=0) + format_family: str = Field(min_length=1, max_length=64) + cost_class: CostClass + native_quantity: int = Field(ge=0) canonical_source_bytes: int = Field(ge=0) classifier_version: str = Field(min_length=1, max_length=128) measurement_algorithm_version: str = Field(min_length=1, max_length=128) processing_profile_id: str = Field(min_length=1, max_length=128) measured_at: datetime identity_key: SecretStr = Field(exclude=True) - staged_content: bytes = Field(exclude=True, min_length=1) class ManagedMeterScope(BaseModel): @@ -119,7 +140,7 @@ class MeterAdmissionResult(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") - decision: Literal["approved", "no_op", "parked"] + decision: Literal["approved", "parked"] reason_code: str | None = Field(default=None, max_length=64) processing_hold_id: UUID | None = None storage_growth_hold_id: UUID | None = None @@ -153,12 +174,3 @@ class MeterReceiptUnauthorized(MeterReceiptUnavailable): class MeterReceiptConflict(MeterReceiptError): """The control plane rejected a changed or contradictory stable identity.""" - - -class ManagedTextClassificationError(ValueError): - """A source cannot enter the bounded managed doc-text profile.""" - - def __init__(self, *, code: str) -> None: - """Capture the safe rejection code exposed at the ingest boundary.""" - super().__init__(code) - self.code = code diff --git a/src/rememberstack/model/operations.py b/src/rememberstack/model/operations.py index 24a0966f2..0cc23f56f 100644 --- a/src/rememberstack/model/operations.py +++ b/src/rememberstack/model/operations.py @@ -24,7 +24,7 @@ class PipelineRouteStatus(BaseModel): stage: PipelineStage lane: ProcessingLane | None status: ProcessingStatus - # Why waiting rows wait, so parked work (`no_route`, `budget`) is not + # Why waiting rows wait, so parked work (`no_route`, `admission`, `budget`) is not # counted as ordinary `pending`. defer_reason: DeferReason | None count: int = Field(ge=0) diff --git a/src/rememberstack/model/processing.py b/src/rememberstack/model/processing.py index e7a0585e3..8e2515bb0 100644 --- a/src/rememberstack/model/processing.py +++ b/src/rememberstack/model/processing.py @@ -54,6 +54,13 @@ class DeferReason(StrEnum): the dead-letter queue: nothing is broken, the format is simply not supported yet. Registering the converter and resuming releases the backlog.""" + ADMISSION = "admission" + """Convert work of a metered deployment waiting for the control plane's holds. + + The convert stage measured the version (a PDF's pages before OCR, or a + read document's characters before any paid stage) and parks until the + meter drain records the approval, which releases it. No attempt is spent + while it waits.""" class EnqueueWork(BaseModel): @@ -192,6 +199,7 @@ class RunResultOutcome(StrEnum): NO_WORK = "no_work" BUDGET_PARKED = "budget_parked" NO_ROUTE_PARKED = "no_route_parked" + ADMISSION_PARKED = "admission_parked" SUCCEEDED = "succeeded" RETRY_SCHEDULED = "retry_scheduled" DEAD_LETTERED = "dead_lettered" diff --git a/src/rememberstack/model/processing_layers.py b/src/rememberstack/model/processing_layers.py index ecbf198f4..35a00aea5 100644 --- a/src/rememberstack/model/processing_layers.py +++ b/src/rememberstack/model/processing_layers.py @@ -15,14 +15,15 @@ from remember.models import ProcessingLayer -STANDARD_PROCESSING_PROFILE_ID: Final = "doc-text-standard-v1" -"""Measured profile of a version processed by all three layers (unchanged).""" +_STANDARD_PROFILE: Final = "standard" +"""A version processed by all three layers.""" -CLAIMS_PROCESSING_PROFILE_ID: Final = "doc-text-claims-v1" -"""Measured profile of a version processed by sources and claims only.""" +_CLAIMS_PROFILE: Final = "claims" +"""A version processed by sources and claims only.""" + +_SOURCES_PROFILE: Final = "sources" +"""A version processed by sources only.""" -SOURCES_PROCESSING_PROFILE_ID: Final = "doc-text-sources-v1" -"""Measured profile of a version processed by sources only.""" SwitchableLayer = Literal[ProcessingLayer.CLAIMS, ProcessingLayer.FACTS] @@ -56,14 +57,19 @@ def served(self) -> frozenset[ProcessingLayer]: layer for layer in ProcessingLayer if self.enabled(layer=layer) ) - @property - def processing_profile_id(self) -> str: - """The managed-meter profile a version measured now is processed under.""" + def processing_profile_id(self, *, cost_class: str) -> str: + """The managed-meter profile a version measured now is processed under. + + ``--v1``: the cost class says what kind of input + it is, the layers what processing it receives (D143 §4.5). + """ if self.facts_enabled: - return STANDARD_PROCESSING_PROFILE_ID - if self.claims_enabled: - return CLAIMS_PROCESSING_PROFILE_ID - return SOURCES_PROCESSING_PROFILE_ID + layers = _STANDARD_PROFILE + elif self.claims_enabled: + layers = _CLAIMS_PROFILE + else: + layers = _SOURCES_PROFILE + return f"{cost_class}-{layers}-v1" UNCONFIGURED: Final = LayerConfiguration( @@ -74,9 +80,9 @@ def processing_profile_id(self) -> str: def profile_layers(*, processing_profile_id: str) -> frozenset[ProcessingLayer]: """The layers a measured processing profile requires (D143 §4.5).""" - if processing_profile_id == SOURCES_PROCESSING_PROFILE_ID: + if processing_profile_id.endswith(f"-{_SOURCES_PROFILE}-v1"): return frozenset({ProcessingLayer.SOURCES}) - if processing_profile_id == CLAIMS_PROCESSING_PROFILE_ID: + if processing_profile_id.endswith(f"-{_CLAIMS_PROFILE}-v1"): return frozenset({ProcessingLayer.SOURCES, ProcessingLayer.CLAIMS}) return frozenset(ProcessingLayer) diff --git a/src/rememberstack/ports/metering.py b/src/rememberstack/ports/metering.py index 800da8a74..ee81c1736 100644 --- a/src/rememberstack/ports/metering.py +++ b/src/rememberstack/ports/metering.py @@ -2,8 +2,8 @@ from typing import Protocol -from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2 -from rememberstack.model.metering import ManagedIngestMeasurementV2 +from rememberstack.model.metering import ManagedDocumentVersionOutcome +from rememberstack.model.metering import ManagedIngestMeasurement from rememberstack.model.metering import MeterAdmissionResult @@ -11,11 +11,11 @@ class MeterReceiptPort(Protocol): """Deliver content-free receipts to a commercial authority.""" def admit_measurement( - self, *, measurement: ManagedIngestMeasurementV2 + self, *, measurement: ManagedIngestMeasurement ) -> MeterAdmissionResult: """Return the stable two-hold admission decision for a measurement.""" ... - def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcomeV2) -> None: + def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcome) -> None: """Acknowledge a terminal outcome or raise so it remains replayable.""" ... diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index d720d16d5..26150dc82 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -1504,7 +1504,6 @@ def meter_catalog(self): # noqa: ANN202 model_bindings=self._model_bindings(), build_revision=_build_revision(), ), - raw_store=self._raw_store, ) def run_meter_receipts(self, *, once: bool = False, limit: int = 100) -> None: @@ -1759,6 +1758,7 @@ def _handler(self, *, stage: PipelineStage) -> StageHandler: raw_store=self._raw_store, artifact_store=self._artifact_store, router=ConversionRouter(routes=dict(self._conversion_route_table())), + meter_scope=self._managed_meter_scope(), ) if stage is PipelineStage.STRUCTURE: return StructureHandler( diff --git a/src/rememberstack/spine/document_catalog.py b/src/rememberstack/spine/document_catalog.py index 3b5a3584b..95e8a082f 100644 --- a/src/rememberstack/spine/document_catalog.py +++ b/src/rememberstack/spine/document_catalog.py @@ -43,13 +43,14 @@ from rememberstack.model.document_metadata import DocumentMetadata from rememberstack.model.documents import IngestPrincipal from rememberstack.model.documents import IngestPrincipalKind -from rememberstack.model.metering import ManagedTextMeasurementDraft +from rememberstack.model.metering import ManagedMeasurementDraft from rememberstack.spine.document_metadata import merge_converter_metadata_on from rememberstack.spine.document_metadata import observe_names_on from rememberstack.spine.document_metadata import record_ingest_metadata_on from rememberstack.spine.document_metadata import refresh_family_on from rememberstack.spine.effective_time import declare_at_ingest_on from rememberstack.spine.effective_time import resolve_version_key_on +from rememberstack.spine.managed_metering import measurement_state_on from rememberstack.spine.managed_metering import record_managed_measurement_on from rememberstack.spine.period_adjudication import request_window_review_on from rememberstack.spine.references import activate_extracted_on @@ -61,26 +62,53 @@ class DocumentCatalog: """E0 row writes and stage loads over an explicitly composed engine.""" - def processing_profile_id(self, *, deployment_id: UUID) -> str: + def processing_profile_id(self, *, deployment_id: UUID, cost_class: str) -> str: """The managed-meter processing profile of the layers enabled now (D143).""" from rememberstack.spine.processing_layers import layer_configuration_on with self._engine.connect() as connection: return layer_configuration_on( connection=connection, deployment_id=deployment_id - ).processing_profile_id + ).processing_profile_id(cost_class=cost_class) def __init__(self, *, engine: Engine) -> None: """Bind the catalog to the spine database.""" self._engine = engine + def measurement_state(self, *, version_id: UUID) -> str | None: + """The version's managed-meter delivery state; None before measurement.""" + with self._engine.connect() as connection: + return measurement_state_on(connection=connection, version_id=version_id) + + def record_measurement( + self, + *, + draft: ManagedMeasurementDraft, + deployment_id: UUID, + doc_id: UUID, + version_id: UUID, + convert_component_version: str, + lane: str, + ) -> None: + """Record the version's one managed-meter measurement (idempotent).""" + with self._engine.begin() as connection: + record_managed_measurement_on( + connection=connection, + draft=draft, + deployment_id=deployment_id, + doc_id=doc_id, + version_id=version_id, + convert_component_version=convert_component_version, + lane=lane, + ) + def record_upload( self, *, record: UploadRecord, convert_component_version: str, lane: ProcessingLane = ProcessingLane.STEADY, - metering: ManagedTextMeasurementDraft | None = None, + metered: bool = False, routable_mimes: Collection[str] | None = None, ) -> IngestedVersion: """Land one upload's rows and enqueue its convert work in one transaction. @@ -223,7 +251,7 @@ def record_upload( "source_version_ref": record.source_version_ref, "sync_cycle_id": record.sync_cycle_id, "ingested_by_principal_id": principal_id, - "status": "ingesting" if metering is not None else "converting", + "status": "converting", "version_key": record.version_key, }, ) @@ -284,41 +312,28 @@ def record_upload( doc_id=doc_id, reason="ingest_period_declared", ) - parked = False - if metering is None: - convert = enqueue_on( - connection=connection, - work=EnqueueWork( - deployment_id=record.deployment_id, - # the idempotency key names the VERSION (D12/D55): a - # lineage's second version must never collide with the - # first version's completed work row - target_kind=ProcessingTarget.DOCUMENT_VERSION, - target_id=version_id, - stage=PipelineStage.CONVERT, - component_version=convert_component_version, - content_hash=record.content_hash, - lane=lane, - payload={"version_id": str(version_id)}, - defer_reason=convert_defer_reason, - ), - ) - # Read the work row, not today's route table: an identical - # re-ingest must report what its existing convert row does. - parked = connection.execute( - _CONVERT_PARKED_NO_ROUTE, {"processing_id": convert.processing_id} - ).scalar_one() - else: - record_managed_measurement_on( - connection=connection, - draft=metering, + convert = enqueue_on( + connection=connection, + work=EnqueueWork( deployment_id=record.deployment_id, - doc_id=doc_id, - version_id=version_id, - created=created, - convert_component_version=convert_component_version, - lane=lane.value, - ) + # the idempotency key names the VERSION (D12/D55): a + # lineage's second version must never collide with the + # first version's completed work row + target_kind=ProcessingTarget.DOCUMENT_VERSION, + target_id=version_id, + stage=PipelineStage.CONVERT, + component_version=convert_component_version, + content_hash=record.content_hash, + lane=lane, + payload={"version_id": str(version_id)}, + defer_reason=convert_defer_reason, + ), + ) + # Read the work row, not today's route table: an identical + # re-ingest must report what its existing convert row does. + parked = connection.execute( + _CONVERT_PARKED_NO_ROUTE, {"processing_id": convert.processing_id} + ).scalar_one() return IngestedVersion( deployment_id=record.deployment_id, doc_id=doc_id, @@ -329,9 +344,7 @@ def record_upload( title=lineage["title"], versioning_mode=lineage["versioning_mode"], parked="no_route" if parked else None, - processing_admission=( - "pending" if metering is not None else "not_required" - ), + processing_admission="pending" if metered else "not_required", version_key=( record.version_key if created or latest is None diff --git a/src/rememberstack/spine/forget.py b/src/rememberstack/spine/forget.py index 491fca2ba..1bf2443f8 100644 --- a/src/rememberstack/spine/forget.py +++ b/src/rememberstack/spine/forget.py @@ -1222,8 +1222,7 @@ def _text_values( text( """ UPDATE managed_ingest_measurements - SET staged_content = NULL, - delivery_state = 'cancelled', + SET delivery_state = 'cancelled', decision_reason = 'source_forgotten', next_attempt_at = NULL WHERE deployment_id = :deployment_id @@ -1823,8 +1822,7 @@ def _text_values( UNION ALL SELECT 1 FROM managed_ingest_measurements WHERE deployment_id = :deployment_id AND doc_id = :doc_id - AND (staged_content IS NOT NULL - OR delivery_state IN ('pending', 'parked', 'quarantined')) + AND delivery_state IN ('pending', 'parked', 'quarantined') UNION ALL SELECT 1 FROM document_sections WHERE deployment_id = :deployment_id AND doc_id = :doc_id diff --git a/src/rememberstack/spine/lifecycle.py b/src/rememberstack/spine/lifecycle.py index 1d762047e..7ce2189cc 100644 --- a/src/rememberstack/spine/lifecycle.py +++ b/src/rememberstack/spine/lifecycle.py @@ -1553,10 +1553,12 @@ def _record_adjudication( WHERE v.sync_cycle_id = y.cycle_id AND w.status IN ('pending', 'running', 'failed') -- D117: live no-route work still lacks conversion evidence and - -- holds the retraction barrier. Explicitly deleted sources no - -- longer participate, and must not strand their cycle forever. + -- holds the retraction barrier; so does work parked for the + -- meter's approval (D150). Explicitly deleted sources no longer + -- participate, and must not strand their cycle forever. AND ( - w.defer_reason IS DISTINCT FROM 'no_route'::processing_defer_reason + w.defer_reason IS NULL + OR w.defer_reason::text NOT IN ('no_route', 'admission') OR ( v.deleted_at IS NULL AND EXISTS ( diff --git a/src/rememberstack/spine/managed_metering.py b/src/rememberstack/spine/managed_metering.py index b5ebd513e..16f6e5e26 100644 --- a/src/rememberstack/spine/managed_metering.py +++ b/src/rememberstack/spine/managed_metering.py @@ -1,4 +1,11 @@ -"""Durable managed-ingest receipt outbox and admission-controlled dispatch.""" +"""Durable managed-meter receipt outbox and admission-controlled processing. + +The convert stage measures each new source version of a metered deployment +(:mod:`rememberstack.core.metering`), records the measurement here and parks +its convert work. The drain delivers the measurement; the control plane's +approval releases the parked work, and a terminal outcome is replayed until +acknowledged. +""" from __future__ import annotations @@ -17,27 +24,20 @@ from sqlalchemy.engine import Connection from sqlalchemy.engine import Engine -from rememberstack.core import storage_class_for -from rememberstack.model import EnqueueWork -from rememberstack.model import ObjectAlreadyExistsError -from rememberstack.model import ObjectKey -from rememberstack.model import PipelineStage -from rememberstack.model import ProcessingTarget from rememberstack.model import ReadinessRequirements from rememberstack.model.client import ProcessingLayer -from rememberstack.model.metering import DocTextQuantity -from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2 -from rememberstack.model.metering import ManagedIngestMeasurementV2 -from rememberstack.model.metering import ManagedTextMeasurementDraft +from rememberstack.model.metering import EVIDENCE_UNIT +from rememberstack.model.metering import ManagedDocumentVersionOutcome +from rememberstack.model.metering import ManagedIngestMeasurement +from rememberstack.model.metering import ManagedMeasurementDraft from rememberstack.model.metering import MeterReceiptConflict from rememberstack.model.metering import MeterReceiptUnauthorized from rememberstack.model.metering import MeterReceiptUnavailable from rememberstack.model.processing_layers import profile_layers from rememberstack.ports.metering import MeterReceiptPort -from rememberstack.ports.object_store import ObjectStorePort from rememberstack.spine.processing_layers import layer_configuration_on from rememberstack.spine.readiness import PipelineReadinessCatalog -from rememberstack.spine.work_ledger import enqueue_on +from rememberstack.spine.work_ledger import release_admission_on _logger = logging.getLogger(__name__) @@ -55,42 +55,15 @@ class MeterDrainResult: def record_managed_measurement_on( *, connection: Connection, - draft: ManagedTextMeasurementDraft, + draft: ManagedMeasurementDraft, deployment_id: UUID, doc_id: UUID, version_id: UUID, - created: bool, convert_component_version: str, lane: str, ) -> None: - """Persist one immutable receipt in the same transaction as version choice.""" - if not created: - requeued = connection.execute( - _REQUEUE_QUARANTINED_VERSION, - {"deployment_id": deployment_id, "version_id": version_id}, - ) - if int(requeued.rowcount or 0) > 0: - return - prior_no_op = connection.execute( - _EXISTING_NOOP_VERSION, - {"deployment_id": deployment_id, "version_id": version_id}, - ).scalar_one_or_none() - if prior_no_op is not None: - return + """Persist a version's one immutable measurement; a repeat changes nothing.""" identity_key = draft.identity_key.get_secret_value().encode("utf-8") - opaque_lineage_id = _opaque_identity( - identity_key=identity_key, - domain="lineage", - deployment_id=deployment_id, - local_id=doc_id, - ) - opaque_source_version_id = _opaque_identity( - identity_key=identity_key, - domain=("source-version" if created else "no-op-observation"), - deployment_id=deployment_id, - local_id=version_id, - ) - disposition = "new_version" if created else "no_op" connection.execute( _INSERT_MEASUREMENT, { @@ -101,40 +74,42 @@ def record_managed_measurement_on( "ingest_attempt_id": draft.ingest_attempt_id, "org_id": draft.org_id, "project_id": draft.project_id, - "opaque_lineage_id": opaque_lineage_id, - "opaque_source_version_id": opaque_source_version_id, - "normalized_character_count": draft.normalized_character_count, + "opaque_lineage_id": _opaque_identity( + identity_key=identity_key, + domain="lineage", + deployment_id=deployment_id, + local_id=doc_id, + ), + "opaque_source_version_id": _opaque_identity( + identity_key=identity_key, + domain="source-version", + deployment_id=deployment_id, + local_id=version_id, + ), + "format_family": draft.format_family, + "cost_class": draft.cost_class, + "native_quantity": draft.native_quantity, + "unit": EVIDENCE_UNIT[draft.cost_class], "canonical_source_bytes": draft.canonical_source_bytes, - "document_version_disposition": disposition, "classifier_version": draft.classifier_version, "measurement_algorithm_version": draft.measurement_algorithm_version, "processing_profile_id": draft.processing_profile_id, "measured_at": draft.measured_at, "convert_component_version": convert_component_version, "lane": lane, - "staged_content": (draft.staged_content if created else None), }, ) - if not created: - connection.execute( - _INSERT_OUTCOME, - { - "measurement_id": draft.measurement_id, - "document_version_id": None, - "outcome": "no_op", - "completed_at": draft.measured_at, - "reason_code": "source_unchanged", - "profile_complete": False, - "version_commit_sequence": None, - "derived_normalized_character_count": ( - draft.normalized_character_count - ), - }, - ) + + +def measurement_state_on(*, connection: Connection, version_id: UUID) -> str | None: + """A version's measurement delivery state, or None before it is measured.""" + return connection.execute( + _MEASUREMENT_STATE, {"version_id": version_id} + ).scalar_one_or_none() class ManagedMeterCatalog: - """Replay local v2 receipts and open pipeline work only after two-hold ACK.""" + """Replay local v3 receipts and release parked work only after two-hold ACK.""" def __init__( self, @@ -142,13 +117,11 @@ def __init__( engine: Engine, receipts: MeterReceiptPort, readiness: PipelineReadinessCatalog, - raw_store: ObjectStorePort, ) -> None: """Bind the spine, control-plane adapter, and exact profile readiness.""" self._engine = engine self._receipts = receipts self._readiness = readiness - self._raw_store = raw_store def drain_once(self, *, limit: int = 100) -> MeterDrainResult: """Run one bounded measurement, terminalization, and outcome replay pass.""" @@ -165,7 +138,7 @@ def drain_once(self, *, limit: int = 100) -> MeterDrainResult: ) def _deliver_measurements(self, *, limit: int) -> tuple[int, int]: - """Replay due measurements and enqueue convert only after full approval.""" + """Replay due measurements and release parked convert only after approval.""" with self._engine.connect() as connection: rows = ( connection.execute(_DUE_MEASUREMENTS, {"limit": limit}).mappings().all() @@ -209,19 +182,6 @@ def _deliver_measurements(self, *, limit: int) -> tuple[int, int]: ) parked += 1 continue - if ( - receipt.document_version_disposition == "new_version" - and decision.decision != "approved" - ) or ( - receipt.document_version_disposition == "no_op" - and decision.decision != "no_op" - ): - self._record_measurement_retry( - measurement_id=receipt.measurement_id, - reason_code="decision_shape_mismatch", - ) - parked += 1 - continue with self._engine.begin() as connection: current = ( connection.execute( @@ -234,67 +194,37 @@ def _deliver_measurements(self, *, limit: int) -> tuple[int, int]: continue if current["delivery_state"] == "accepted": continue - if receipt.document_version_disposition == "new_version": - if ( - current["delivery_state"] == "cancelled" - or current["version_status"] == "deleted" - ): - connection.execute( - _ACCEPT_MEASUREMENT, - { - "measurement_id": receipt.measurement_id, - "processing_hold_id": decision.processing_hold_id, - "storage_growth_hold_id": ( - decision.storage_growth_hold_id - ), - }, - ) - connection.execute( - _INSERT_OUTCOME, - { - "measurement_id": receipt.measurement_id, - "document_version_id": str(current["version_id"]), - "outcome": "failed", - "completed_at": datetime.now(timezone.utc), - "reason_code": "source_forgotten", - "profile_complete": False, - "version_commit_sequence": None, - "derived_normalized_character_count": current[ - "normalized_character_count" - ], - }, - ) - accepted += 1 - continue - staged_content = current["staged_content"] - if not isinstance(staged_content, bytes) or not staged_content: - raise RuntimeError( - "managed staged content missing before approval" - ) - try: - self._raw_store.write_bytes( - key=ObjectKey(str(current["raw_uri"])), - content=staged_content, - storage_class=storage_class_for(mime=str(current["mime"])), - ) - except ObjectAlreadyExistsError: - pass + if ( + current["delivery_state"] == "cancelled" + or current["version_status"] == "deleted" + ): connection.execute( - _OPEN_VERSION_FOR_CONVERT, {"version_id": current["version_id"]} + _ACCEPT_MEASUREMENT, + { + "measurement_id": receipt.measurement_id, + "processing_hold_id": decision.processing_hold_id, + "storage_growth_hold_id": decision.storage_growth_hold_id, + }, ) - enqueue_on( - connection=connection, - work=EnqueueWork( - deployment_id=current["deployment_id"], - target_kind=ProcessingTarget.DOCUMENT_VERSION, - target_id=current["version_id"], - stage=PipelineStage.CONVERT, - component_version=current["convert_component_version"], - content_hash=current["content_hash"], - lane=current["lane"], - payload={"version_id": str(current["version_id"])}, - ), + connection.execute( + _INSERT_OUTCOME, + { + "measurement_id": receipt.measurement_id, + "document_version_id": str(current["version_id"]), + "outcome": "failed", + "completed_at": datetime.now(timezone.utc), + "reason_code": "source_forgotten", + "profile_complete": False, + "version_commit_sequence": None, + }, ) + accepted += 1 + continue + release_admission_on( + connection=connection, + deployment_id=current["deployment_id"], + version_id=current["version_id"], + ) connection.execute( _ACCEPT_MEASUREMENT, { @@ -429,9 +359,6 @@ def _materialize_outcomes(self, *, limit: int) -> int: "reason_code": reason_code, "profile_complete": profile_complete, "version_commit_sequence": sequence, - "derived_normalized_character_count": row[ - "normalized_character_count" - ], }, ) if int(result.rowcount or 0) > 0: @@ -539,9 +466,9 @@ def _opaque_identity( return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") -def _measurement_from_row(*, row: dict[str, Any]) -> ManagedIngestMeasurementV2: +def _measurement_from_row(*, row: dict[str, Any]) -> ManagedIngestMeasurement: """Reconstruct the exact immutable wire receipt from local columns.""" - return ManagedIngestMeasurementV2.model_validate( + return ManagedIngestMeasurement.model_validate( { "measurement_id": row["measurement_id"], "ingest_attempt_id": row["ingest_attempt_id"], @@ -550,11 +477,11 @@ def _measurement_from_row(*, row: dict[str, Any]) -> ManagedIngestMeasurementV2: "deployment_id": row["deployment_id"], "opaque_lineage_id": row["opaque_lineage_id"], "opaque_source_version_id": row["opaque_source_version_id"], - "quantity": DocTextQuantity( - normalized_character_count=int(row["normalized_character_count"]) - ).model_dump(), + "format_family": row["format_family"], + "cost_class": row["cost_class"], + "native_quantity": row["native_quantity"], + "unit": row["unit"], "canonical_source_bytes": row["canonical_source_bytes"], - "document_version_disposition": row["document_version_disposition"], "classifier_version": row["classifier_version"], "measurement_algorithm_version": row["measurement_algorithm_version"], "processing_profile_id": row["processing_profile_id"], @@ -563,9 +490,9 @@ def _measurement_from_row(*, row: dict[str, Any]) -> ManagedIngestMeasurementV2: ) -def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2: +def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcome: """Reconstruct the exact immutable terminal wire receipt from local columns.""" - return ManagedDocumentVersionOutcomeV2.model_validate( + return ManagedDocumentVersionOutcome.model_validate( { "measurement_id": row["measurement_id"], "document_version_id": row["document_version_id"], @@ -574,10 +501,6 @@ def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2 "reason_code": row["reason_code"], "profile_complete": row["profile_complete"], "version_commit_sequence": row["version_commit_sequence"], - "derived_normalized_character_count": row[ - "derived_normalized_character_count" - ], - "provider_cost_evidence_id": row["provider_cost_evidence_id"], } ) @@ -587,53 +510,34 @@ def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2 INSERT INTO managed_ingest_measurements ( measurement_id, deployment_id, doc_id, version_id, ingest_attempt_id, org_id, project_id, opaque_lineage_id, opaque_source_version_id, - normalized_character_count, canonical_source_bytes, - document_version_disposition, classifier_version, - measurement_algorithm_version, processing_profile_id, measured_at, - convert_component_version, lane, staged_content + format_family, cost_class, native_quantity, unit, canonical_source_bytes, + classifier_version, measurement_algorithm_version, processing_profile_id, + measured_at, convert_component_version, lane ) VALUES ( :measurement_id, :deployment_id, :doc_id, :version_id, :ingest_attempt_id, :org_id, :project_id, :opaque_lineage_id, :opaque_source_version_id, - :normalized_character_count, :canonical_source_bytes, - :document_version_disposition, :classifier_version, + :format_family, :cost_class, :native_quantity, :unit, + :canonical_source_bytes, :classifier_version, :measurement_algorithm_version, :processing_profile_id, :measured_at, - :convert_component_version, CAST(:lane AS processing_lane), :staged_content + :convert_component_version, CAST(:lane AS processing_lane) ) + ON CONFLICT (deployment_id, version_id) DO NOTHING """ ) -_REQUEUE_QUARANTINED_VERSION = text( - """ - UPDATE managed_ingest_measurements - SET delivery_state = 'pending', decision_reason = NULL, next_attempt_at = NULL - WHERE deployment_id = :deployment_id - AND version_id = :version_id - AND document_version_disposition = 'new_version' - AND delivery_state = 'quarantined' - """ -) - -_EXISTING_NOOP_VERSION = text( - """ - SELECT measurement_id - FROM managed_ingest_measurements - WHERE deployment_id = :deployment_id - AND version_id = :version_id - AND document_version_disposition = 'no_op' - LIMIT 1 - """ +_MEASUREMENT_STATE = text( + "SELECT delivery_state FROM managed_ingest_measurements " + "WHERE version_id = :version_id" ) _INSERT_OUTCOME = text( """ INSERT INTO managed_ingest_outcomes ( measurement_id, document_version_id, outcome, completed_at, reason_code, - profile_complete, version_commit_sequence, - derived_normalized_character_count, provider_cost_evidence_id + profile_complete, version_commit_sequence ) VALUES ( :measurement_id, :document_version_id, :outcome, :completed_at, :reason_code, - :profile_complete, :version_commit_sequence, - :derived_normalized_character_count, NULL + :profile_complete, :version_commit_sequence ) ON CONFLICT (measurement_id) DO NOTHING """ @@ -642,10 +546,10 @@ def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2 _DUE_MEASUREMENTS = text( """ SELECT measurement_id, ingest_attempt_id, org_id, project_id, deployment_id, - opaque_lineage_id, opaque_source_version_id, - normalized_character_count, canonical_source_bytes, - document_version_disposition, classifier_version, - measurement_algorithm_version, processing_profile_id, measured_at + opaque_lineage_id, opaque_source_version_id, format_family, + cost_class, native_quantity, unit, canonical_source_bytes, + classifier_version, measurement_algorithm_version, + processing_profile_id, measured_at FROM managed_ingest_measurements WHERE delivery_state IN ('pending', 'parked') AND (next_attempt_at IS NULL OR next_attempt_at <= statement_timestamp()) @@ -656,24 +560,14 @@ def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2 _LOCK_MEASUREMENT = text( """ - SELECT m.*, v.content_hash, v.status::text AS version_status, c.raw_uri, c.mime + SELECT m.*, v.status::text AS version_status FROM managed_ingest_measurements m JOIN document_versions v ON v.version_id = m.version_id - JOIN content_objects c - ON c.deployment_id = v.deployment_id AND c.content_hash = v.content_hash WHERE m.measurement_id = :measurement_id FOR UPDATE OF m, v """ ) -_OPEN_VERSION_FOR_CONVERT = text( - """ - UPDATE document_versions - SET status = 'converting' - WHERE version_id = :version_id AND status = 'ingesting' - """ -) - _ACCEPT_MEASUREMENT = text( """ UPDATE managed_ingest_measurements @@ -682,7 +576,7 @@ def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2 storage_growth_hold_id = :storage_growth_hold_id, delivery_attempts = delivery_attempts + 1, last_attempt_at = statement_timestamp(), next_attempt_at = NULL, - accepted_at = statement_timestamp(), staged_content = NULL + accepted_at = statement_timestamp() WHERE measurement_id = :measurement_id AND delivery_state <> 'accepted' """ ) @@ -716,13 +610,12 @@ def _outcome_from_row(*, row: dict[str, Any]) -> ManagedDocumentVersionOutcomeV2 _AWAITING_OUTCOMES = text( """ SELECT m.measurement_id, m.deployment_id, m.version_id, - m.normalized_character_count, m.processing_profile_id, + m.processing_profile_id, v.status::text AS version_status FROM managed_ingest_measurements m JOIN document_versions v ON v.version_id = m.version_id LEFT JOIN managed_ingest_outcomes o ON o.measurement_id = m.measurement_id WHERE m.delivery_state = 'accepted' - AND m.document_version_disposition = 'new_version' AND o.measurement_id IS NULL AND (m.outcome_next_attempt_at IS NULL OR m.outcome_next_attempt_at <= statement_timestamp() diff --git a/src/rememberstack/spine/migrations/versions/p9_46_0067_generic_meter.py b/src/rememberstack/spine/migrations/versions/p9_46_0067_generic_meter.py new file mode 100644 index 000000000..abd6b3fc2 --- /dev/null +++ b/src/rememberstack/spine/migrations/versions/p9_46_0067_generic_meter.py @@ -0,0 +1,195 @@ +"""The managed meter measures any cost class, in the convert stage. + +revision: p9_46_0067 + +The measurement outbox becomes the generic v3 receipt: a ``cost_class``, an +integer ``native_quantity`` in that class's ``unit`` and the ``format_family``, +in place of a text-only character count. Measurement moves from ingest into +the convert stage, so: + +- uploads write their original to the raw store at ingest, and the outbox + no longer stages bytes (``staged_content`` is dropped); +- unchanged bytes create no version and are never measured, so ``no_op`` + measurements and outcomes are deleted and the disposition column dropped; +- a version has at most one measurement; +- convert work waiting for the control plane's holds parks with the new + ``admission`` defer reason, which no claim takes until approval releases it. + +Refuses to run while any measurement still holds staged bytes: those +originals exist nowhere else. Drain the outbox with the previous release +first. The downgrade restores the text-only shape while the outbox holds +only delivered text receipts and no work is parked for admission. +""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "p9_46_0067" +down_revision: str | None = "p9_45_0066" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +_UP = """ +-- Writers of the previous release must not stage new bytes between the check +-- and the drop: hold the table until this transaction commits. +LOCK TABLE managed_ingest_measurements IN ACCESS EXCLUSIVE MODE; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM managed_ingest_measurements WHERE staged_content IS NOT NULL + ) THEN + RAISE EXCEPTION + 'managed_ingest_measurements holds staged originals; drain the meter ' + 'outbox with the previous release before upgrading'; + END IF; +END $$; + +DELETE FROM managed_ingest_measurements +WHERE document_version_disposition = 'no_op'; + +DROP INDEX IF EXISTS ix_managed_ingest_unaccepted_version; +DROP INDEX IF EXISTS ix_managed_ingest_measurements_terminal; +ALTER TABLE managed_ingest_measurements DROP COLUMN staged_content; +ALTER TABLE managed_ingest_measurements DROP COLUMN document_version_disposition; +ALTER TABLE managed_ingest_measurements + RENAME COLUMN normalized_character_count TO native_quantity; +ALTER TABLE managed_ingest_measurements + ADD COLUMN cost_class text NOT NULL DEFAULT 'doc-text', + ADD COLUMN unit text NOT NULL DEFAULT 'normalized_character', + ADD COLUMN format_family text NOT NULL DEFAULT 'text' + CHECK (char_length(format_family) BETWEEN 1 AND 64); +ALTER TABLE managed_ingest_measurements + ALTER COLUMN cost_class DROP DEFAULT, + ALTER COLUMN unit DROP DEFAULT, + ALTER COLUMN format_family DROP DEFAULT, + ADD CONSTRAINT managed_ingest_measurements_class_unit CHECK ( + (cost_class = 'doc-text' AND unit = 'normalized_character') OR + (cost_class = 'doc-scan' AND unit = 'page' AND native_quantity >= 1) OR + (cost_class = 'image' AND unit = 'image' AND native_quantity >= 1) OR + (cost_class IN ('audio', 'video') AND unit = 'millisecond' + AND native_quantity >= 1) + ), + ADD CONSTRAINT managed_ingest_measurements_one_per_version + UNIQUE (deployment_id, version_id); +CREATE INDEX ix_managed_ingest_measurements_terminal + ON managed_ingest_measurements (deployment_id, accepted_at) + WHERE delivery_state = 'accepted'; + +ALTER TABLE managed_ingest_outcomes + DROP COLUMN derived_normalized_character_count, + DROP COLUMN provider_cost_evidence_id; +DO $$ +DECLARE + constraint_name text; +BEGIN + SELECT con.conname INTO constraint_name + FROM pg_constraint con + JOIN pg_class rel ON rel.oid = con.conrelid + WHERE rel.relname = 'managed_ingest_outcomes' + AND con.contype = 'c' + AND pg_get_constraintdef(con.oid) LIKE '%no_op%'; + EXECUTE format( + 'ALTER TABLE managed_ingest_outcomes DROP CONSTRAINT %I', constraint_name + ); +END $$; +ALTER TABLE managed_ingest_outcomes + ADD CONSTRAINT managed_ingest_outcomes_outcome + CHECK (outcome IN ('succeeded', 'failed')); + +COMMENT ON TABLE managed_ingest_measurements IS + 'Content-free v3 managed meter receipt outbox: one measurement per new source version, taken in the convert stage before provider work. Its convert work stays parked (defer_reason admission) until both control-plane holds are accepted.'; +COMMENT ON TABLE managed_ingest_outcomes IS + 'Content-free terminal v3 receipt outbox replayed until CP acknowledgement.'; + +ALTER TYPE processing_defer_reason ADD VALUE IF NOT EXISTS 'admission'; +ALTER TABLE processing_state + DROP CONSTRAINT processing_state_defer_reason_check; +ALTER TABLE processing_state ADD CONSTRAINT processing_state_defer_reason_check +CHECK ( + (status = 'failed' AND defer_reason = 'retry_backoff') OR + (status = 'pending' AND ( + defer_reason IS NULL + OR defer_reason::text IN ('scheduled', 'budget', 'no_route', 'admission') + )) OR + (status NOT IN ('pending', 'failed') AND defer_reason IS NULL) +); +""" + + +def upgrade() -> None: + """Generalize the outbox and add the admission parking reason.""" + op.execute(_UP) + + +_DOWN = """ +LOCK TABLE managed_ingest_measurements IN ACCESS EXCLUSIVE MODE; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM managed_ingest_measurements WHERE cost_class <> 'doc-text' + ) OR EXISTS ( + SELECT 1 FROM managed_ingest_measurements WHERE delivery_state <> 'accepted' + ) OR EXISTS ( + SELECT 1 FROM processing_state WHERE defer_reason::text = 'admission' + ) THEN + RAISE EXCEPTION + 'p9_46_0067 downgrade refused: non-text or undelivered measurements or ' + 'admission-parked work exist'; + END IF; +END $$; + +ALTER TABLE processing_state + DROP CONSTRAINT processing_state_defer_reason_check; +ALTER TABLE processing_state ADD CONSTRAINT processing_state_defer_reason_check +CHECK ( + (status = 'failed' AND defer_reason = 'retry_backoff') OR + (status = 'pending' AND ( + defer_reason IS NULL + OR defer_reason::text IN ('scheduled', 'budget', 'no_route') + )) OR + (status NOT IN ('pending', 'failed') AND defer_reason IS NULL) +); + +ALTER TABLE managed_ingest_outcomes DROP CONSTRAINT managed_ingest_outcomes_outcome; +ALTER TABLE managed_ingest_outcomes + ADD CONSTRAINT managed_ingest_outcomes_outcome + CHECK (outcome IN ('succeeded', 'failed', 'no_op')), + ADD COLUMN derived_normalized_character_count bigint + CHECK (derived_normalized_character_count IS NULL + OR derived_normalized_character_count >= 0), + ADD COLUMN provider_cost_evidence_id text; + +DROP INDEX ix_managed_ingest_measurements_terminal; +ALTER TABLE managed_ingest_measurements + DROP CONSTRAINT managed_ingest_measurements_one_per_version, + DROP CONSTRAINT managed_ingest_measurements_class_unit, + DROP COLUMN cost_class, + DROP COLUMN unit, + DROP COLUMN format_family; +ALTER TABLE managed_ingest_measurements + RENAME COLUMN native_quantity TO normalized_character_count; +ALTER TABLE managed_ingest_measurements + ADD COLUMN document_version_disposition text NOT NULL DEFAULT 'new_version' + CHECK (document_version_disposition IN ('new_version', 'no_op')), + ADD COLUMN staged_content bytea; +ALTER TABLE managed_ingest_measurements + ALTER COLUMN document_version_disposition DROP DEFAULT; +CREATE INDEX ix_managed_ingest_measurements_terminal + ON managed_ingest_measurements (deployment_id, accepted_at) + WHERE delivery_state = 'accepted' AND document_version_disposition = 'new_version'; +CREATE INDEX ix_managed_ingest_unaccepted_version + ON managed_ingest_measurements (deployment_id, version_id) + WHERE document_version_disposition = 'new_version' AND accepted_at IS NULL; +""" + + +def downgrade() -> None: + """Restore the text-only outbox while it holds only delivered text receipts. + + The ``admission`` enum value stays (PostgreSQL cannot drop one); nothing + uses it once the constraint excludes it. + """ + op.execute(_DOWN) diff --git a/src/rememberstack/spine/projection.py b/src/rememberstack/spine/projection.py index 23d706050..2972ca1d6 100644 --- a/src/rememberstack/spine/projection.py +++ b/src/rememberstack/spine/projection.py @@ -327,8 +327,7 @@ def _require_p3_plane(plane: str) -> None: stored.ingested_at AS stored_ingested_at, work.defer_reason::text AS stored_defer_reason FROM documents d - -- Raw availability is independent of processed currency (D117). Managed - -- metadata can predate the raw write, so only accepted originals qualify. + -- Raw availability is independent of processed currency (D117). JOIN LATERAL ( SELECT dv.version_id, dv.content_hash, dv.status, dv.source_modified_at, dv.ingested_at, co.raw_uri, co.mime @@ -338,13 +337,6 @@ def _require_p3_plane(plane: str) -> None: AND co.content_hash = dv.content_hash AND co.purged_at IS NULL WHERE dv.deployment_id = d.deployment_id AND dv.doc_id = d.doc_id AND dv.deleted_at IS NULL - AND NOT EXISTS ( - SELECT 1 FROM managed_ingest_measurements m - WHERE m.deployment_id = dv.deployment_id - AND m.version_id = dv.version_id - AND m.document_version_disposition = 'new_version' - AND m.accepted_at IS NULL - ) ORDER BY dv.version_no DESC LIMIT 1 ) stored ON TRUE diff --git a/src/rememberstack/spine/work_ledger.py b/src/rememberstack/spine/work_ledger.py index 0c234727e..41d8a63ef 100644 --- a/src/rememberstack/spine/work_ledger.py +++ b/src/rememberstack/spine/work_ledger.py @@ -945,6 +945,32 @@ def park_no_route(self, *, processing_id: UUID, attempt: int, mime: str) -> None if parked[0] is None: connection.execute(_WAKE, {"processing_id": str(processing_id)}) + def park_for_admission(self, *, processing_id: UUID, attempt: int) -> None: + """Return a measured convert claim to wait for the meter's approval. + + The handler recorded the version's measurement before raising, so + only the matching running convert attempt transitions; its claim is + refunded. The approval may already have been recorded meanwhile: the + park locks the measurement row (the lock the approval takes) and + parks only while it is unaccepted; otherwise the claim returns to the + queue unparked and is announced. + """ + with self._engine.begin() as connection: + parked = ( + connection.execute( + _PARK_ADMISSION, + {"processing_id": processing_id, "attempt": attempt}, + ) + .mappings() + .all() + ) + if len(parked) != 1: + raise WorkNotRunningError( + f"processing row {processing_id} is not the running convert attempt" + ) + if parked[0]["defer_reason"] is None: + _announce_released_on(connection=connection, row=parked[0]) + def resume_no_route( self, *, deployment_id: UUID, routable_mimes: Collection[str] ) -> tuple[UUID, ...]: @@ -1902,6 +1928,43 @@ def enqueue_on(*, connection: Connection, work: EnqueueWork) -> EnqueueOutcome: ) +def release_admission_on( + *, connection: Connection, deployment_id: UUID, version_id: UUID +) -> int: + """Release a version's convert work parked for the meter's approval. + + Runs in the caller's transaction, which records the approval; the wake and + the announcement take effect when it commits. Returns the rows released. + """ + released = ( + connection.execute( + _RELEASE_ADMISSION, + {"deployment_id": deployment_id, "version_id": version_id}, + ) + .mappings() + .all() + ) + for row in released: + _announce_released_on(connection=connection, row=row) + return len(released) + + +def _announce_released_on(*, connection: Connection, row: RowMapping) -> None: + """Wake listeners and record one released convert row for push delivery.""" + connection.execute(_WAKE, {"processing_id": str(row["processing_id"])}) + record_new_work( + work=NewWork( + processing_id=row["processing_id"], + route=QueueRoute( + deployment_id=row["deployment_id"], + stage=PipelineStage.CONVERT, + lane=(None if row["lane"] is None else ProcessingLane(row["lane"])), + ), + not_before=None, + ) + ) + + def _claimed_work(*, row: RowMapping) -> ClaimedWork: """Build the typed claimed-work record from a returned ledger row.""" return ClaimedWork( @@ -1985,6 +2048,43 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: """ ) +_PARK_ADMISSION = text( + """ + WITH measured AS ( + SELECT m.accepted_at + FROM processing_state p + JOIN managed_ingest_measurements m + ON m.deployment_id = p.deployment_id AND m.version_id = p.target_id + WHERE p.processing_id = :processing_id + FOR SHARE OF m + ) + UPDATE processing_state + SET status = 'pending', + defer_reason = CASE + WHEN EXISTS (SELECT 1 FROM measured WHERE accepted_at IS NOT NULL) + THEN NULL + ELSE 'admission'::processing_defer_reason + END, + attempts = attempts - 1, started_at = NULL, not_before = now() + WHERE processing_id = :processing_id AND status = 'running' + AND stage = 'convert' AND attempts = :attempt AND attempts > 0 + RETURNING processing_id, deployment_id, lane::text AS lane, + defer_reason::text AS defer_reason + """ +) + +_RELEASE_ADMISSION = text( + """ + UPDATE processing_state + SET defer_reason = NULL, not_before = now() + WHERE deployment_id = :deployment_id + AND target_kind = 'document_version' AND target_id = :version_id + AND stage = 'convert' AND status = 'pending' + AND defer_reason::text = 'admission' + RETURNING processing_id, deployment_id, lane::text AS lane + """ +) + _RESUME_NO_ROUTE = text( """ UPDATE processing_state p @@ -2013,7 +2113,10 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: -- There is no instant at which it becomes ready, so it is excluded by -- its reason rather than by a sentinel timestamp; registering the -- converter and resuming is what releases it. - AND (defer_reason IS NULL OR defer_reason::text <> 'no_route') + -- A metered conversion waiting for the control plane's holds is + -- likewise parked on a fact, the approval, which releases it. + AND (defer_reason IS NULL + OR defer_reason::text NOT IN ('no_route', 'admission')) """ _CLAIM_DUE_ON_ROUTE = f""" diff --git a/src/rememberstack/surfaces/http_api.py b/src/rememberstack/surfaces/http_api.py index 527c4df20..2ee844ddc 100644 --- a/src/rememberstack/surfaces/http_api.py +++ b/src/rememberstack/surfaces/http_api.py @@ -114,7 +114,6 @@ from rememberstack.model import IngestedVersion from rememberstack.model import IngestPrincipal from rememberstack.model import IngestPrincipalKind -from rememberstack.model import ManagedTextClassificationError from rememberstack.model import PerimeterCredential from rememberstack.model import PipelineReadinessReport from rememberstack.model import ProviderCallError @@ -2164,14 +2163,6 @@ def _parse_ingest_principal( ) from error -def _managed_text_http_error(*, error: ManagedTextClassificationError) -> HTTPException: - """Map bounded pre-version classifier refusals to stable HTTP failures.""" - status = 413 if error.code == "source_bytes_limit_exceeded" else 422 - if error.code == "rate_class_unavailable": - status = 409 - return HTTPException(status_code=status, detail=error.code) - - def _forgotten_source_http_error() -> HTTPException: """A hard forget covers these bytes or this source identity; it is permanent.""" return HTTPException(status_code=409, detail="source_forgotten") @@ -2367,8 +2358,6 @@ def ingest_document( return ingest.ingest( deployment_id=deployment_id, upload=upload, **attribution ) - except ManagedTextClassificationError as error: - raise _managed_text_http_error(error=error) from error except ContentDetectionError as error: raise HTTPException(status_code=422, detail=error.code) from error except ForgottenSourceError as error: @@ -2385,8 +2374,6 @@ def ingest_document( sync_cycle_id=None, **attribution, ) - except ManagedTextClassificationError as error: - raise _managed_text_http_error(error=error) from error except ContentDetectionError as error: raise HTTPException(status_code=422, detail=error.code) from error except ForgottenSourceError as error: diff --git a/src/rememberstack/workers/base.py b/src/rememberstack/workers/base.py index e94ab38c2..b7f0daca6 100644 --- a/src/rememberstack/workers/base.py +++ b/src/rememberstack/workers/base.py @@ -57,6 +57,10 @@ def __init__(self, message: str, *, mime: str) -> None: self.mime = mime +class AdmissionPendingError(Exception): + """Convert measured a metered version and must wait for the meter's approval.""" + + class ExtractChunkBarrier(BaseModel): """D84: after a chunk extract succeeds, complete+barrier in one ledger txn.""" @@ -398,6 +402,28 @@ def _run_claimed(self, *, claimed: ClaimedWork, started_ns: int) -> RunResult: try: with _LeaseRenewal(ledger=self._ledger, work=claimed): outcome = handler.handle(work=claimed, meter=meter) + except AdmissionPendingError: + try: + self._ledger.park_for_admission( + processing_id=claimed.processing_id, attempt=claimed.attempt + ) + except WorkNotRunningError: + return self._lease_lost(claimed=claimed, started_ns=started_ns) + self._export_event( + event=_worker_event( + deployment_id=claimed.deployment_id, + processing_id=claimed.processing_id, + stage=claimed.stage, + lane=claimed.lane, + attempt=None, + outcome=RunResultOutcome.ADMISSION_PARKED, + started_ns=started_ns, + ) + ) + return RunResult( + processing_id=claimed.processing_id, + outcome=RunResultOutcome.ADMISSION_PARKED, + ) except NoRouteHandlerError as no_route: try: self._ledger.park_no_route( diff --git a/src/rememberstack/workers/e0.py b/src/rememberstack/workers/e0.py index 4bca9211f..5539543d2 100644 --- a/src/rememberstack/workers/e0.py +++ b/src/rememberstack/workers/e0.py @@ -50,6 +50,7 @@ from rememberstack.core import LONG_TITLE from rememberstack.core import MAX_FALLBACK_DEPTH from rememberstack.core import MIN_CHECK_SECTIONS +from rememberstack.core import PageCountingConverter from rememberstack.core import parse_heading_skeleton from rememberstack.core import resolve_fallback_skeleton from rememberstack.core import SECTION_ROLES @@ -59,6 +60,7 @@ from rememberstack.core import SkeletonAnalysis from rememberstack.core import storage_class_for from rememberstack.core import UrlConverter +from rememberstack.core import UrlPageCountingConverter from rememberstack.core import with_content_hashes from rememberstack.core.content_detection import detect_content_mime from rememberstack.core.extraction_eligibility import block_eligibility @@ -69,11 +71,14 @@ from rememberstack.core.format_registry import detect_mime from rememberstack.core.format_registry import exceeds_reading_limit from rememberstack.core.format_registry import family_for_mime +from rememberstack.core.metering import cost_class_for_route +from rememberstack.core.metering import DOC_SCAN_ALGORITHM_VERSION +from rememberstack.core.metering import DOC_TEXT_ALGORITHM_VERSION +from rememberstack.core.metering import FREE_ROUTES +from rememberstack.core.metering import METERING_CLASSIFIER_VERSION +from rememberstack.core.metering import normalized_character_count +from rememberstack.core.metering import UnmeteredRouteError from rememberstack.core.storage_routing import storage_class_for_derived -from rememberstack.core.text_metering import classify_doc_text -from rememberstack.core.text_metering import DOC_TEXT_CLASSIFIER_VERSION -from rememberstack.core.text_metering import DOC_TEXT_MAX_SOURCE_BYTES -from rememberstack.core.text_metering import DOC_TEXT_MEASUREMENT_ALGORITHM_VERSION from rememberstack.model import Block from rememberstack.model import ClaimedWork from rememberstack.model import ConversionError @@ -112,9 +117,9 @@ from rememberstack.model import StructureSource from rememberstack.model import UnroutableMimeError from rememberstack.model import UploadRecord +from rememberstack.model.metering import CostClass +from rememberstack.model.metering import ManagedMeasurementDraft from rememberstack.model.metering import ManagedMeterScope -from rememberstack.model.metering import ManagedTextClassificationError -from rememberstack.model.metering import ManagedTextMeasurementDraft from rememberstack.model.occurrence_provenance import ( parse_persisted_conversion_manifest, ) @@ -125,6 +130,7 @@ from rememberstack.ports.object_store import StreamingReadPort from rememberstack.ports.purge import ObjectPurgePort from rememberstack.spine.document_catalog import DocumentCatalog +from rememberstack.workers.base import AdmissionPendingError from rememberstack.workers.base import HandlerOutcome from rememberstack.workers.base import NoRouteHandlerError from rememberstack.workers.e0_summary import SectionSummarizer @@ -189,7 +195,7 @@ _STORED_REFUSALS: Final = (ValueError, ForgottenSourceError) -"""What refuses a stored object for good (size, content type, metering, +"""What refuses a stored object for good (size, content type, metadata, a forgotten identity); anything else may succeed on retry.""" @@ -270,25 +276,21 @@ def ingest( content_hash=content_hash, ) upload = self._detect_upload(upload=upload) - upload, metering = self._prepare_managed_text( - deployment_id=deployment_id, upload=upload - ) doc_id = uuid5( NAMESPACE_URL, f"rememberstack:upload:{deployment_id}:{content_hash}" ) suffix = PurePosixPath(upload.filename).suffix raw_uri = f"{doc_id}/{content_hash}/original{suffix}" - if metering is None: - try: - self._raw_store.write_bytes( - key=ObjectKey(raw_uri), - content=upload.content, - # D51: media a harness reads stays hot; text originals - # kept only for audit go cold — routed at the write - storage_class=storage_class_for(mime=upload.mime), - ) - except ObjectAlreadyExistsError: - pass # identical bytes already landed — ingest retries are no-ops + try: + self._raw_store.write_bytes( + key=ObjectKey(raw_uri), + content=upload.content, + # D51: media a harness reads stays hot; text originals + # kept only for audit go cold — routed at the write + storage_class=storage_class_for(mime=upload.mime), + ) + except ObjectAlreadyExistsError: + pass # identical bytes already landed — ingest retries are no-ops ingested = self._catalog.record_upload( record=UploadRecord( deployment_id=deployment_id, @@ -308,15 +310,14 @@ def ingest( ), convert_component_version=E0_CONVERT_VERSION, lane=lane, - metering=metering, + metered=self._meter_scope is not None, routable_mimes=self._routable_for(upload=upload), ) - if metering is None: - self._release_unretained( - deployment_id=deployment_id, - content_hash=content_hash, - key=ObjectKey(raw_uri), - ) + self._release_unretained( + deployment_id=deployment_id, + content_hash=content_hash, + key=ObjectKey(raw_uri), + ) return ingested def ingest_stored( @@ -347,7 +348,7 @@ 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 + A refusal (declared size, content type, 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 @@ -366,12 +367,8 @@ def ingest_stored( manifests. ``size`` must match the stored object. The uploader chooses the storage class (D51 routing is not applied). - A deployment with managed text metering measures the object exactly - as :meth:`ingest` does. That profile accepts only native text of at - most ``DOC_TEXT_MAX_SOURCE_BYTES`` (10 MB), so a larger object is - refused before anything is read into memory, and an accepted one is - measured from the spooled copy; its staged bytes are released to the - raw store on approval, where the object already is. + A metered deployment measures the version in the convert stage, as + for every other entry point; registration itself sends nothing. """ if _STORED_KEY.fullmatch(key.root) is None: raise ValueError( @@ -418,24 +415,6 @@ def ingest_stored( 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, - ), - ) - detected = measured.mime except _STORED_REFUSALS as refusal: raise self._refused( deployment_id=deployment_id, key=key, refusal=refusal @@ -466,7 +445,7 @@ def ingest_stored( ), convert_component_version=E0_CONVERT_VERSION, lane=lane, - metering=metering, + metered=self._meter_scope is not None, routable_mimes=routable, ) except _STORED_REFUSALS as refusal: @@ -544,9 +523,6 @@ def ingest_observed( content_hash=content_hash, ) upload = self._detect_upload(upload=upload) - upload, metering = self._prepare_managed_text( - deployment_id=deployment_id, upload=upload - ) doc_id = uuid5( NAMESPACE_URL, f"rememberstack:{source_kind}:{deployment_id}:{source_ref}" ) @@ -575,30 +551,28 @@ def ingest_observed( effective_from=upload.effective_from, effective_until=upload.effective_until, ) - if metering is None: - try: - self._raw_store.write_bytes( - key=ObjectKey(raw_uri), - content=upload.content, - # D51: media a harness reads stays hot; text originals - # kept only for audit go cold — routed at the write - storage_class=storage_class_for(mime=upload.mime), - ) - except ObjectAlreadyExistsError: - pass + try: + self._raw_store.write_bytes( + key=ObjectKey(raw_uri), + content=upload.content, + # D51: media a harness reads stays hot; text originals + # kept only for audit go cold — routed at the write + storage_class=storage_class_for(mime=upload.mime), + ) + except ObjectAlreadyExistsError: + pass ingested = self._catalog.record_upload( record=record, convert_component_version=E0_CONVERT_VERSION, lane=lane, - metering=metering, + metered=self._meter_scope is not None, routable_mimes=self._routable_for(upload=upload), ) - if metering is None: - self._release_unretained( - deployment_id=deployment_id, - content_hash=content_hash, - key=ObjectKey(raw_uri), - ) + self._release_unretained( + deployment_id=deployment_id, + content_hash=content_hash, + key=ObjectKey(raw_uri), + ) return ingested def _release_unretained( @@ -622,38 +596,6 @@ def _release_unretained( ): self._raw_store.purge_objects(keys=(key,), prefixes=()) - def _prepare_managed_text( - self, *, deployment_id: UUID, upload: DocumentUpload - ) -> tuple[DocumentUpload, ManagedTextMeasurementDraft | None]: - """Measure managed text after the common byte-class admission check. - - The processing profile follows the layers enabled now (D143 §4.5). - """ - scope = self._meter_scope - if scope is None: - return upload, None - classified = classify_doc_text( - content=upload.content, declared_mime=upload.mime - ) - measurement_id = uuid4() - prepared = upload.model_copy(update={"mime": classified.canonical_mime}) - return prepared, ManagedTextMeasurementDraft( - measurement_id=measurement_id, - ingest_attempt_id=f"ing_{uuid4().hex}", - org_id=scope.org_id, - project_id=scope.project_id, - normalized_character_count=classified.normalized_character_count, - canonical_source_bytes=classified.canonical_source_bytes, - classifier_version=DOC_TEXT_CLASSIFIER_VERSION, - measurement_algorithm_version=(DOC_TEXT_MEASUREMENT_ALGORITHM_VERSION), - processing_profile_id=self._catalog.processing_profile_id( - deployment_id=deployment_id - ), - measured_at=datetime.now(timezone.utc), - identity_key=scope.identity_key, - staged_content=upload.content, - ) - def _detect_upload(self, *, upload: DocumentUpload) -> DocumentUpload: """Use byte classes first and registry hints within compatible families.""" detected = self._detected_mime( @@ -742,12 +684,19 @@ def __init__( raw_store: ObjectStorePort, artifact_store: ObjectStorePort, router: ConversionRouter, + meter_scope: ManagedMeterScope | None = None, ) -> None: - """Bind the handler to its catalog, both stores, and the route table.""" + """Bind the handler to its catalog, both stores, and the route table. + + ``meter_scope`` makes this a metered deployment: each new version is + measured here and waits for the control plane's approval before any + work that calls a model provider. + """ self._catalog = catalog self._raw_store = raw_store self._artifact_store = artifact_store self._router = router + self._meter_scope = meter_scope def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: """Convert one document version and record its representation. @@ -755,6 +704,12 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: Replay before regenerate (D65/D7): a representation this toolchain already produced for the version is re-chained as-is — the converter is never re-called on a retried or replayed attempt. + + Metered (D139, cloud D94): a PDF is measured in pages before OCR and a + locally read file in characters of its ``document.md``; either way + the version's work parks until the measurement is approved, and only + then is OCR called or structure chained. A card reads nothing and is + not measured; any other route is refused. """ source = self._catalog.convert_source( version_id=_payload_uuid(work=work, field="version_id") @@ -789,6 +744,7 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: error = f"PDF exceeds the pre-OCR provider limit of {provider_limit} bytes" self._catalog.mark_version_failed(version_id=source.version_id, error=error) raise NonRetryableHandlerError(error) + cost_class = self._admission(work=work, source=source, converter=converter) existing = self._catalog.existing_representation( version_id=source.version_id, route=converter.name, @@ -796,6 +752,14 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: blockizer_version=BLOCKIZER_VERSION, ) if existing is not None: + if cost_class == "doc-text": + # A reading made before its measurement was recorded. + markdown = self._artifact_store.read_bytes( + key=ObjectKey( + f"{source.doc_id}/{source.content_hash}/{existing}/document.md" + ) + ).decode("utf-8") + self._measure_text(work=work, source=source, markdown=markdown) return self._structure_follow_up( work=work, version_id=source.version_id, representation_id=existing ) @@ -1015,10 +979,128 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: ), metadata=result.metadata, ) + if cost_class == "doc-text": + self._measure_text(work=work, source=source, markdown=result.document_md) return self._structure_follow_up( work=work, version_id=source.version_id, representation_id=representation_id ) + def _admission( + self, *, work: ClaimedWork, source: ConvertSource, converter: Converter + ) -> CostClass | None: + """Gate a metered conversion; return ``doc-text`` when it must be measured. + + Returns None when nothing is metered here: no meter, a free card, or + an approved measurement. A recorded but unapproved measurement parks + the work again. A PDF is measured now, before its OCR call, and + parks. A reading route converts first and is measured after. + """ + if self._meter_scope is None or converter.name in FREE_ROUTES: + return None + try: + cost_class = cost_class_for_route(route=converter.name) + except UnmeteredRouteError as err: + self._catalog.mark_version_failed( + version_id=source.version_id, error=str(err) + ) + raise NonRetryableHandlerError(str(err)) from err + state = self._catalog.measurement_state(version_id=source.version_id) + if state == "accepted": + return None + if state is not None: + raise AdmissionPendingError(f"measurement {state}") + if cost_class == "doc-text": + return cost_class + by_url = ( + isinstance(converter, UrlConverter) + and isinstance(self._raw_store, PresignedReadPort) + and source.byte_size is not None + ) + try: + if by_url and isinstance(converter, UrlPageCountingConverter): + assert isinstance(converter, UrlConverter) + assert isinstance(self._raw_store, PresignedReadPort) + assert source.byte_size is not None + pages = converter.count_pages_from_url( + url=self._raw_store.presign_get( + key=ObjectKey(source.raw_uri), ttl_s=converter.url_ttl_s + ), + size=source.byte_size, + ) + elif not by_url and isinstance(converter, PageCountingConverter): + pages = converter.count_pages( + content=self._raw_store.read_bytes(key=ObjectKey(source.raw_uri)) + ) + else: + error = f"route {converter.name!r} cannot count pages before OCR" + self._catalog.mark_version_failed( + version_id=source.version_id, error=error + ) + raise NonRetryableHandlerError(error) + except ConversionError as err: + self._catalog.mark_version_failed( + version_id=source.version_id, error=str(err) + ) + raise NonRetryableHandlerError(str(err)) from err + self._record_measurement( + work=work, + source=source, + cost_class=cost_class, + native_quantity=pages, + algorithm_version=DOC_SCAN_ALGORITHM_VERSION, + ) + raise AdmissionPendingError("measured pages before OCR") + + def _measure_text( + self, *, work: ClaimedWork, source: ConvertSource, markdown: str + ) -> NoReturn: + """Record a reading's character count and park until it is approved.""" + self._record_measurement( + work=work, + source=source, + cost_class="doc-text", + native_quantity=normalized_character_count(text=markdown), + algorithm_version=DOC_TEXT_ALGORITHM_VERSION, + ) + raise AdmissionPendingError("measured characters before paid stages") + + def _record_measurement( + self, + *, + work: ClaimedWork, + source: ConvertSource, + cost_class: CostClass, + native_quantity: int, + algorithm_version: str, + ) -> None: + """Record the version's one content-free measurement.""" + scope = self._meter_scope + assert scope is not None + self._catalog.record_measurement( + draft=ManagedMeasurementDraft( + measurement_id=uuid4(), + ingest_attempt_id=f"convert:{work.processing_id}:{work.attempt}", + org_id=scope.org_id, + project_id=scope.project_id, + format_family=family_for_mime(mime=source.mime).name, + cost_class=cost_class, + native_quantity=native_quantity, + canonical_source_bytes=source.byte_size or 0, + classifier_version=METERING_CLASSIFIER_VERSION, + measurement_algorithm_version=algorithm_version, + processing_profile_id=self._catalog.processing_profile_id( + deployment_id=source.deployment_id, cost_class=cost_class + ), + measured_at=datetime.now(timezone.utc), + identity_key=scope.identity_key, + ), + deployment_id=source.deployment_id, + doc_id=source.doc_id, + version_id=source.version_id, + convert_component_version=work.component_version, + lane=(work.lane or ProcessingLane.STEADY).value, + ) + def _converter_for(self, *, source: ConvertSource) -> Converter: """The routed converter, or a card for an oversized non-PDF file. diff --git a/src/tests/adapters/test_managed_metering.py b/src/tests/adapters/test_managed_metering.py index ccdf87832..7655eaec1 100644 --- a/src/tests/adapters/test_managed_metering.py +++ b/src/tests/adapters/test_managed_metering.py @@ -10,9 +10,8 @@ import pytest from rememberstack.adapters.selfhost.managed_metering import ControlPlaneMeterReceipts -from rememberstack.model import DocTextQuantity -from rememberstack.model import ManagedDocumentVersionOutcomeV2 -from rememberstack.model import ManagedIngestMeasurementV2 +from rememberstack.model import ManagedDocumentVersionOutcome +from rememberstack.model import ManagedIngestMeasurement from rememberstack.model import MeterAdmissionResult from rememberstack.model import MeterReceiptConflict from rememberstack.model import MeterReceiptUnauthorized @@ -24,9 +23,9 @@ _MEASUREMENT = UUID("40000000-0000-0000-0000-000000000001") -def _measurement() -> ManagedIngestMeasurementV2: - """Build one canonical text receipt without any source metadata.""" - return ManagedIngestMeasurementV2( +def _measurement() -> ManagedIngestMeasurement: + """Build one canonical page receipt without any source metadata.""" + return ManagedIngestMeasurement( measurement_id=_MEASUREMENT, ingest_attempt_id="ing_1", org_id=_ORG, @@ -34,12 +33,14 @@ def _measurement() -> ManagedIngestMeasurementV2: deployment_id=_DEPLOYMENT, opaque_lineage_id="lineage-1", opaque_source_version_id="source-version-1", - quantity=DocTextQuantity(normalized_character_count=1234), + format_family="pdf", + cost_class="doc-scan", + native_quantity=12, + unit="page", canonical_source_bytes=1400, - document_version_disposition="new_version", - classifier_version="doc-text-classifier-v1", - measurement_algorithm_version="unicode-whitespace-scalars-v1", - processing_profile_id="doc-text-standard-v1", + classifier_version="route-cost-class-v1", + measurement_algorithm_version="pdf-page-tree-v1", + processing_profile_id="doc-scan-standard-v1", measured_at=datetime(2026, 9, 1, tzinfo=UTC), ) @@ -69,7 +70,7 @@ def handler(request: httpx.Request) -> httpx.Response: assert decision.decision == "approved" assert seen["authorization"] == "Bearer umc_mi_secret" body = str(seen["body"]) - assert "normalized_character_count" in body + assert '"cost_class":"doc-scan"' in body and '"native_quantity":12' in body for forbidden in ("filename", "content_hash", "source_uri", "hello"): assert forbidden not in body @@ -85,7 +86,7 @@ def test_adapter_replays_terminal_outcome_until_explicit_ack() -> None: ) with pytest.raises(MeterReceiptUnavailable): adapter.acknowledge_outcome( - outcome=ManagedDocumentVersionOutcomeV2( + outcome=ManagedDocumentVersionOutcome( measurement_id=_MEASUREMENT, outcome="failed", completed_at=datetime(2026, 9, 1, tzinfo=UTC), @@ -135,10 +136,22 @@ def test_generic_bad_request_remains_retryable_transport_failure() -> None: def test_non_approved_decisions_cannot_smuggle_hold_ids() -> None: - """A malformed no-op/parked response cannot crash the SQL acceptance write.""" + """A malformed parked response cannot crash the SQL acceptance write.""" with pytest.raises(ValidationError): MeterAdmissionResult( - decision="no_op", + decision="parked", processing_hold_id=UUID("50000000-0000-0000-0000-000000000001"), storage_growth_hold_id=UUID("60000000-0000-0000-0000-000000000001"), ) + + +def test_a_receipt_unit_must_be_its_cost_class_unit() -> None: + """Page evidence cannot be labelled as cheaper characters, or vice versa.""" + with pytest.raises(ValidationError, match="unit does not match"): + _measurement().model_copy( + update={"unit": "normalized_character"} + ).model_validate(_measurement().model_dump() | {"unit": "normalized_character"}) + with pytest.raises(ValidationError, match="must be positive"): + ManagedIngestMeasurement.model_validate( + _measurement().model_dump() | {"native_quantity": 0} + ) diff --git a/src/tests/core/test_metering.py b/src/tests/core/test_metering.py new file mode 100644 index 000000000..7aeddab3b --- /dev/null +++ b/src/tests/core/test_metering.py @@ -0,0 +1,38 @@ +"""Route cost classes and the doc-text character count.""" + +from __future__ import annotations + +import pytest + +from rememberstack.core.conversion import STOCK_CONVERSION_ROUTE_NAMES +from rememberstack.core.metering import cost_class_for_route +from rememberstack.core.metering import FREE_ROUTES +from rememberstack.core.metering import normalized_character_count +from rememberstack.core.metering import UnmeteredRouteError + + +def test_every_stock_route_is_billed_or_free() -> None: + """A metered deployment can run every route the engine ships by default.""" + for route in set(STOCK_CONVERSION_ROUTE_NAMES.values()) - FREE_ROUTES: + cost_class_for_route(route=route) + + +def test_pdf_is_scan_and_local_readers_are_text() -> None: + """Every PDF bills pages; reading routes bill characters.""" + assert cost_class_for_route(route="pdf") == "doc-scan" + for route in ("text", "markitdown", "office", "spreadsheet", "email"): + assert cost_class_for_route(route=route) == "doc-text" + + +@pytest.mark.parametrize("route", ["image_ocr_description", "mistral_ocr", "x"]) +def test_provider_routes_without_a_class_are_refused(route: str) -> None: + """A route that would call a provider unbilled never runs under metering.""" + with pytest.raises(UnmeteredRouteError, match="rate_class_unavailable"): + cost_class_for_route(route=route) + + +def test_whitespace_runs_count_once() -> None: + """Each maximal whitespace run is one character; every other scalar is one.""" + assert normalized_character_count(text="a b\n\n\tc") == 5 + assert normalized_character_count(text=" é") == 2 + assert normalized_character_count(text="") == 0 diff --git a/src/tests/core/test_text_metering.py b/src/tests/core/test_text_metering.py deleted file mode 100644 index 9211de20f..000000000 --- a/src/tests/core/test_text_metering.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Adversarial vectors for the bounded managed doc-text classifier.""" - -import pytest - -from rememberstack.core.text_metering import classify_doc_text -from rememberstack.core.text_metering import DOC_TEXT_MAX_SOURCE_BYTES -from rememberstack.core.text_metering import normalized_character_count -from rememberstack.model import ManagedTextClassificationError - - -@pytest.mark.parametrize( - ("value", "expected"), - [("hello", 5), ("a \n\t b", 3), (" alpha\u2003beta ", 12), ("A😀B", 3)], -) -def test_normalized_character_count_collapses_unicode_whitespace( - value: str, expected: int -) -> None: - """Every maximal Unicode whitespace run counts as one scalar.""" - assert normalized_character_count(text=value) == expected - - -@pytest.mark.parametrize( - "payload", - [ - b"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF", - b"\x89PNG\r\n\x1a\n" + b"text-looking-tail", - b"\xff\xd8\xff\xe0image-only", - b"PK\x03\x04archive-with-text.txt", - ], -) -def test_binary_and_scanned_sources_never_misclassify_as_doc_text( - payload: bytes, -) -> None: - """Magic wins over a hostile caller claiming text/plain.""" - with pytest.raises(ManagedTextClassificationError) as raised: - classify_doc_text(content=payload, declared_mime="text/plain") - assert raised.value.code == "rate_class_unavailable" - - -@pytest.mark.parametrize("payload", [b"hello\x00world", b"\xff\xfeA\x00"]) -def test_ambiguous_binary_text_fails_before_measurement(payload: bytes) -> None: - """NUL/control or invalid UTF-8 cannot reach the cheap text route.""" - with pytest.raises(ManagedTextClassificationError) as raised: - classify_doc_text(content=payload, declared_mime="text/markdown") - assert raised.value.code == "rate_class_ambiguous" - - -@pytest.mark.parametrize( - "payload", (b"%PDF-1.4 is only a header\n", b"ID3 tags are metadata\n") -) -def test_printable_binary_markers_remain_managed_text(payload: bytes) -> None: - """Metering uses the same structural signatures as E0 admission.""" - result = classify_doc_text(content=payload, declared_mime="text/plain") - assert result.canonical_mime == "text/plain" - - -def test_mime_does_not_hide_native_text_or_change_quantity() -> None: - """Verified native text is measured from bytes, not the caller MIME label.""" - result = classify_doc_text( - content="A\u2009 B".encode(), declared_mime="application/octet-stream" - ) - assert result.canonical_mime == "text/plain" - assert result.normalized_character_count == 3 - assert result.canonical_source_bytes == 6 - - -def test_csv_and_bom_text_share_plain_text_metering() -> None: - """Text flavour and BOM do not create a different billing class.""" - result = classify_doc_text( - content=b"\xef\xbb\xbfalpha,beta\r\n1,2", declared_mime="text/csv" - ) - assert result.canonical_mime == "text/plain" - assert result.normalized_character_count == len("alpha,beta 1,2") - - -@pytest.mark.parametrize( - ("payload", "mime"), - [ - (b"{\\rtf1 formatted}", "text/plain"), - (b"

hello

", "text/plain"), - (b"hello", "application/octet-stream"), - (b"JVBERi0xLjQK", "text/plain"), - ], -) -def test_structured_or_armoured_text_is_not_native_doc_text( - payload: bytes, mime: str -) -> None: - """Markup, structured MIME, and armoured binary remain ambiguous.""" - with pytest.raises(ManagedTextClassificationError) as raised: - classify_doc_text(content=payload, declared_mime=mime) - assert raised.value.code == "rate_class_ambiguous" - - -@pytest.mark.parametrize( - "payload", - ( - b"

text

", - b"{\\rtf1 formatted}", - b"text", - b"", - b"JVBERi0xLjQK", - ), -) -@pytest.mark.parametrize( - "prefix", (b"\xef\xbb\xbf", b"\r\n\xef\xbb\xbf", b"\xef\xbb\xbf\xef\xbb\xbf") -) -def test_bom_cannot_hide_structured_or_armoured_text( - payload: bytes, prefix: bytes -) -> None: - """Repeated or whitespace-separated BOMs preserve text exclusions.""" - with pytest.raises(ManagedTextClassificationError) as raised: - classify_doc_text(content=prefix + payload, declared_mime="text/plain") - assert raised.value.code == "rate_class_ambiguous" - - -def test_prefixed_pdf_cannot_enter_managed_text_rate() -> None: - """PDF body tokens remain unavailable even with preamble and tail padding.""" - content = b"\n%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF\n" + b" " * 2049 - with pytest.raises(ManagedTextClassificationError) as raised: - classify_doc_text(content=content, declared_mime="text/plain") - assert raised.value.code == "rate_class_unavailable" - - -def test_bound_exceed_is_typed_before_any_source_version() -> None: - """The published v1 profile has a hard, byte-counted source ceiling.""" - with pytest.raises(ManagedTextClassificationError) as raised: - classify_doc_text( - content=b"a" * (DOC_TEXT_MAX_SOURCE_BYTES + 1), declared_mime="text/plain" - ) - assert raised.value.code == "source_bytes_limit_exceeded" diff --git a/src/tests/database_reset.py b/src/tests/database_reset.py index bd40c55ae..1ea813b88 100644 --- a/src/tests/database_reset.py +++ b/src/tests/database_reset.py @@ -52,6 +52,7 @@ def reset_database(*, config: Config) -> None: "p9_43_0064", "p9_44_0065", "p9_45_0066", + "p9_46_0067", } or connection.execute( text("SELECT to_regclass('public.fact_applications') IS NOT NULL") diff --git a/src/tests/spine/test_forget_catalog.py b/src/tests/spine/test_forget_catalog.py index 9e57f85ea..26da9e019 100644 --- a/src/tests/spine/test_forget_catalog.py +++ b/src/tests/spine/test_forget_catalog.py @@ -587,18 +587,19 @@ def _seed_documents(*, connection: Connection) -> None: INSERT INTO managed_ingest_measurements ( measurement_id, deployment_id, doc_id, version_id, ingest_attempt_id, org_id, project_id, opaque_lineage_id, - opaque_source_version_id, normalized_character_count, - canonical_source_bytes, document_version_disposition, + opaque_source_version_id, format_family, cost_class, + native_quantity, unit, canonical_source_bytes, classifier_version, measurement_algorithm_version, processing_profile_id, measured_at, convert_component_version, - lane, staged_content, delivery_state, decision_reason + lane, delivery_state, decision_reason ) VALUES ( :measurement_id, :deployment_id, :doc_id, :version_id, 'ing_forget_proof', :org_id, :project_id, 'opaque-lineage', - 'opaque-version', 24, :source_bytes, 'new_version', - 'doc-text-classifier-v1', 'unicode-whitespace-scalars-v1', + 'opaque-version', 'text', 'doc-text', 24, 'normalized_character', + :source_bytes, 'route-cost-class-v1', + 'document-md-unicode-whitespace-scalars-v1', 'doc-text-standard-v1', :measured_at, 'e0-test', 'steady', - :staged_content, 'parked', 'control_plane_unavailable' + 'parked', 'control_plane_unavailable' ) """ ), @@ -611,7 +612,6 @@ def _seed_documents(*, connection: Connection) -> None: "project_id": UUID("75000000-0000-0000-0000-000000000032"), "source_bytes": len(_TOKEN.encode("utf-8")), "measured_at": _NOW, - "staged_content": _TOKEN.encode("utf-8"), }, ) connection.execute( @@ -1320,13 +1320,13 @@ def _assert_scrubbed_and_control_survives(*, engine: Engine) -> None: assert target.deleted_at is not None meter = connection.execute( text( - "SELECT staged_content, delivery_state, decision_reason " + "SELECT delivery_state, decision_reason " "FROM managed_ingest_measurements " "WHERE measurement_id = :measurement_id" ), {"measurement_id": _TARGET_MEASUREMENT_ID}, ).one() - assert meter == (None, "cancelled", "source_forgotten") + assert meter == ("cancelled", "source_forgotten") assert _count(connection, "chunks", "doc_id", _TARGET_DOC_ID) == 0 assert _count(connection, "chunk_search", "chunk_id", _TARGET_CHUNK_ID) == 0 assert _count(connection, "chunk_search", "chunk_id", _CONTROL_CHUNK_ID) == 1 diff --git a/src/tests/spine/test_managed_metering_sql.py b/src/tests/spine/test_managed_metering_sql.py index ded21b263..f38cd6e77 100644 --- a/src/tests/spine/test_managed_metering_sql.py +++ b/src/tests/spine/test_managed_metering_sql.py @@ -1,4 +1,4 @@ -"""PostgreSQL acceptance for managed text admission and receipt replay.""" +"""PostgreSQL acceptance for the managed meter: measure in convert, park, release.""" from __future__ import annotations @@ -23,27 +23,35 @@ from sqlalchemy.engine import Engine from rememberstack.adapters.selfhost import LocalFSObjectStore -from rememberstack.core.text_metering import classify_doc_text -from rememberstack.core.text_metering import DOC_TEXT_MAX_SOURCE_BYTES +from rememberstack.core import ConversionRouter +from rememberstack.core import Converter +from rememberstack.core import MarkdownPassthroughConverter +from rememberstack.core.metering import normalized_character_count +from rememberstack.model import ConversionResult 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 import PipelineStage +from rememberstack.model import ProcessingLane +from rememberstack.model import RunResultOutcome +from rememberstack.model.metering import ManagedDocumentVersionOutcome +from rememberstack.model.metering import ManagedIngestMeasurement from rememberstack.model.metering import ManagedMeterScope -from rememberstack.model.metering import ManagedTextClassificationError from rememberstack.model.metering import MeterAdmissionResult from rememberstack.model.metering import MeterReceiptConflict from rememberstack.ports.metering import MeterReceiptPort from rememberstack.spine import DeploymentBootstrapper from rememberstack.spine import DocumentCatalog -from rememberstack.spine import managed_metering as managed_metering_module +from rememberstack.spine import WorkLedger +from rememberstack.spine import WorkLedgerSettings from rememberstack.spine.managed_metering import ManagedMeterCatalog from rememberstack.spine.managed_metering import MeterDrainResult from rememberstack.spine.readiness import PipelineReadinessCatalog from rememberstack.spine.settings import load_database_settings +from rememberstack.workers import ConvertHandler +from rememberstack.workers import HandlerRegistry from rememberstack.workers import UploadIngestor +from rememberstack.workers import Worker from tests.database_reset import reset_database _ROOT = Path(__file__).resolve().parents[3] @@ -125,20 +133,18 @@ def __init__(self) -> None: """Start approved, with an opt-in one-shot parking decision.""" self.park_next = False self.conflict_next = False - self.measurements: list[ManagedIngestMeasurementV2] = [] - self.outcomes: list[ManagedDocumentVersionOutcomeV2] = [] + self.measurements: list[ManagedIngestMeasurement] = [] + self.outcomes: list[ManagedDocumentVersionOutcome] = [] self.holds: dict[UUID, tuple[UUID, UUID]] = {} def admit_measurement( - self, *, measurement: ManagedIngestMeasurementV2 + self, *, measurement: ManagedIngestMeasurement ) -> MeterAdmissionResult: - """Return no-op, one-shot parked, or an idempotent two-hold approval.""" + """Return one-shot parked or an idempotent two-hold approval.""" self.measurements.append(measurement) if self.conflict_next: self.conflict_next = False raise MeterReceiptConflict("synthetic changed receipt") - if measurement.document_version_disposition == "no_op": - return MeterAdmissionResult(decision="no_op") if self.park_next: self.park_next = False return MeterAdmissionResult( @@ -153,7 +159,7 @@ def admit_measurement( storage_growth_hold_id=storage, ) - def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcomeV2) -> None: + def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcome) -> None: """Capture the terminal receipt as the durable remote acknowledgement.""" self.outcomes.append(outcome) @@ -208,418 +214,481 @@ def _work_count(*, engine: Engine, version_id: UUID) -> int: ) -def _version_status(*, engine: Engine, version_id: UUID) -> str: - """Read the durable pre-dispatch version state.""" +def _convert_row(*, engine: Engine, version_id: UUID) -> dict[str, object]: + """The version's convert work row: its status and defer reason.""" with engine.connect() as connection: - return str( + return dict( connection.execute( - text("SELECT status::text FROM document_versions WHERE version_id=:id"), - {"id": version_id}, - ).scalar_one() + text( + "SELECT status::text AS status, defer_reason::text AS defer_reason," + " attempts FROM processing_state" + " WHERE target_id = :version_id AND stage::text = 'convert'" + ), + {"version_id": version_id}, + ) + .mappings() + .one() ) -def test_managed_ingest_waits_for_two_holds_and_replays_terminal_outcomes( - database_engine: Engine, tmp_path: Path -) -> None: - """Park, approve, no-op, succeed, and fail through the real SQL spine.""" - receipts = ControlledReceipts() - readiness = ControlledReadiness() - raw_store = LocalFSObjectStore(root=tmp_path / "raw") - meter = ManagedMeterCatalog( - engine=database_engine, - receipts=receipts, - readiness=cast(PipelineReadinessCatalog, readiness), - raw_store=raw_store, - ) - ingestor = UploadIngestor( - catalog=DocumentCatalog(engine=database_engine), - raw_store=raw_store, - admission=AllowIngest(), - routable_mimes=frozenset({"text/markdown", "text/plain"}), - meter_scope=ManagedMeterScope( - org_id=_ORG_ID, - project_id=_PROJECT_ID, - identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), - ), - ) +def _measurement(*, engine: Engine, version_id: UUID) -> dict[str, object] | None: + """The version's measurement row, or None.""" + with engine.connect() as connection: + row = ( + connection.execute( + text( + "SELECT cost_class, native_quantity, unit, format_family," + " canonical_source_bytes, processing_profile_id, delivery_state" + " FROM managed_ingest_measurements WHERE version_id = :version_id" + ), + {"version_id": version_id}, + ) + .mappings() + .one_or_none() + ) + return None if row is None else dict(row) - receipts.park_next = True - first = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="first.txt", mime="text/plain", content=b"hello world" - ), - ) - assert first.created is True and first.processing_admission == "pending" - assert _version_status(engine=database_engine, version_id=first.version_id) == ( - "ingesting" - ) - assert _work_count(engine=database_engine, version_id=first.version_id) == 0 - with database_engine.connect() as connection: - raw_uri = str( + +def _structure_count(*, engine: Engine, version_id: UUID) -> int: + """Count structure work chained for one version.""" + with engine.connect() as connection: + return int( connection.execute( text( - "SELECT c.raw_uri FROM content_objects c " - "JOIN document_versions v USING (deployment_id, content_hash) " - "WHERE v.version_id = :version_id" + "SELECT count(*) FROM processing_state " + "WHERE target_id = :version_id AND stage::text = 'structure'" ), - {"version_id": first.version_id}, + {"version_id": version_id}, ).scalar_one() ) - with pytest.raises(FileNotFoundError): - raw_store.read_bytes(key=ObjectKey(raw_uri)) - parked = meter.drain_once() - assert parked.measurements_parked == 1 - assert _work_count(engine=database_engine, version_id=first.version_id) == 0 - with database_engine.begin() as connection: + +def _due(*, engine: Engine) -> None: + """Make every backed-off measurement and outcome check due now.""" + with engine.begin() as connection: connection.execute( text( - "UPDATE managed_ingest_measurements SET next_attempt_at = NULL " - "WHERE version_id = :version_id" - ), - {"version_id": first.version_id}, + "UPDATE managed_ingest_measurements SET next_attempt_at = NULL," + " outcome_next_attempt_at = NULL" + ) ) - approved = meter.drain_once() - assert approved.measurements_accepted == 1 - assert _version_status(engine=database_engine, version_id=first.version_id) == ( - "converting" - ) - assert _work_count(engine=database_engine, version_id=first.version_id) == 1 - assert raw_store.read_bytes(key=ObjectKey(raw_uri)) == b"hello world" - readiness.ready.add(first.version_id) - with database_engine.begin() as connection: - connection.execute( - text( - "UPDATE managed_ingest_measurements " - "SET outcome_next_attempt_at = NULL WHERE version_id = :version_id" - ), - {"version_id": first.version_id}, + +_SCOPE = ManagedMeterScope( + org_id=_ORG_ID, + project_id=_PROJECT_ID, + identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), +) + + +class FakePdf: + """A ``pdf`` route that counts pages and records when it is asked to OCR.""" + + def __init__(self, *, pages: int = 3) -> None: + """Start with no OCR calls.""" + self.pages = pages + self.ocr_calls = 0 + + @property + def name(self) -> str: + """The PDF route name.""" + return "pdf" + + @property + def version(self) -> str: + """A fixed test version.""" + return "fake-pdf-v1" + + def count_pages(self, *, content: bytes) -> int: + """The page count, without OCR.""" + del content + return self.pages + + def convert(self, *, content: bytes, mime: str) -> ConversionResult: + """The 'OCR' reading; counted so a test can prove it waited.""" + del content, mime + self.ocr_calls += 1 + return MarkdownPassthroughConverter().convert( + content=b"# Scanned\n\nocr text", mime="text/markdown" ) - succeeded = meter.drain_once() - assert succeeded.outcomes_created == 1 - assert succeeded.outcomes_accepted == 1 - assert receipts.outcomes[-1].outcome == "succeeded" - assert receipts.outcomes[-1].document_version_id == str(first.version_id) - assert receipts.outcomes[-1].version_commit_sequence == 1 - - noop = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="first-again.txt", mime="text/plain", content=b"hello world" + + +class NamedConverter: + """A passthrough reading under another route name.""" + + def __init__(self, *, name: str) -> None: + """Bind the route name.""" + self._name = name + self.calls = 0 + + @property + def name(self) -> str: + """The route name under test.""" + return self._name + + @property + def version(self) -> str: + """A fixed test version.""" + return "named-v1" + + def convert(self, *, content: bytes, mime: str) -> ConversionResult: + """Read the bytes as Markdown.""" + del mime + self.calls += 1 + return MarkdownPassthroughConverter().convert( + content=content, mime="text/markdown" + ) + + +@dataclass +class Rig: + """A metered deployment: ingest, the convert worker and the meter drain.""" + + engine: Engine + receipts: ControlledReceipts + readiness: ControlledReadiness + raw_store: LocalFSObjectStore + ingestor: UploadIngestor + meter: ManagedMeterCatalog + worker: Worker + ledger: WorkLedger + + def convert(self) -> RunResultOutcome: + """Run one convert attempt.""" + return self.worker.run_one( + deployment_id=_DEPLOYMENT_ID, + stage=PipelineStage.CONVERT, + lane=ProcessingLane.STEADY, + ).outcome + + def upload(self, *, name: str, mime: str, content: bytes) -> UUID: + """Ingest one file and return its version.""" + return self.ingestor.ingest( + deployment_id=_DEPLOYMENT_ID, + upload=DocumentUpload(filename=name, mime=mime, content=content), + ).version_id + + +def _rig(*, engine: Engine, tmp_path: Path, routes: dict[str, Converter]) -> Rig: + """Compose a metered deployment over the real SQL spine.""" + receipts = ControlledReceipts() + readiness = ControlledReadiness() + raw_store = LocalFSObjectStore(root=tmp_path / "raw") + catalog = DocumentCatalog(engine=engine) + ledger = WorkLedger(engine=engine, settings=WorkLedgerSettings()) + registry = HandlerRegistry() + registry.register( + stage=PipelineStage.CONVERT, + handler=ConvertHandler( + catalog=catalog, + raw_store=raw_store, + artifact_store=LocalFSObjectStore(root=tmp_path / "artifacts"), + router=ConversionRouter(routes=routes), + meter_scope=_SCOPE, ), ) - assert noop.created is False - no_op_result = meter.drain_once() - assert no_op_result.measurements_accepted == 1 - assert no_op_result.outcomes_accepted == 1 - assert receipts.outcomes[-1].outcome == "no_op" - assert _work_count(engine=database_engine, version_id=noop.version_id) == 1 - repeated_noop = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="first-third.txt", mime="text/plain", content=b"hello world" + return Rig( + engine=engine, + receipts=receipts, + readiness=readiness, + raw_store=raw_store, + ingestor=UploadIngestor( + catalog=catalog, + raw_store=raw_store, + admission=AllowIngest(), + routable_mimes=frozenset(routes), + meter_scope=_SCOPE, ), - ) - assert repeated_noop.created is False - assert meter.drain_once() == MeterDrainResult() - - failed = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="failed.txt", mime="text/plain", content=b"different text" + meter=ManagedMeterCatalog( + engine=engine, + receipts=receipts, + readiness=cast(PipelineReadinessCatalog, readiness), ), + worker=Worker(ledger=ledger, registry=registry), + ledger=ledger, ) - assert meter.drain_once().measurements_accepted == 1 - retried = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="retried.txt", mime="text/plain", content=b"retry this work" - ), - ) - assert meter.drain_once().measurements_accepted == 1 - readiness.stage_status[retried.version_id] = "failed" - transient = meter.drain_once() - assert transient.outcomes_created == 0 - assert all( - outcome.document_version_id != str(retried.version_id) - for outcome in receipts.outcomes - ) - readiness.stage_status[retried.version_id] = "dead_letter" - with database_engine.begin() as connection: - connection.execute( - text( - "UPDATE managed_ingest_measurements " - "SET outcome_next_attempt_at = NULL WHERE version_id = :version_id" - ), - {"version_id": retried.version_id}, - ) - terminal = meter.drain_once() - assert terminal.outcomes_created == 1 - assert terminal.outcomes_accepted == 1 - assert receipts.outcomes[-1].document_version_id == str(retried.version_id) - assert receipts.outcomes[-1].outcome == "failed" - with database_engine.begin() as connection: - connection.execute( - text( - "UPDATE document_versions SET status = 'failed' " - "WHERE version_id = :version_id" - ), - {"version_id": failed.version_id}, + +def _version_status(*, engine: Engine, version_id: UUID) -> str: + """Read the durable pre-dispatch version state.""" + with engine.connect() as connection: + return str( + connection.execute( + text("SELECT status::text FROM document_versions WHERE version_id=:id"), + {"id": version_id}, + ).scalar_one() ) - failure = meter.drain_once() - assert failure.outcomes_created == 1 - assert failure.outcomes_accepted == 1 - assert receipts.outcomes[-1].outcome == "failed" - assert receipts.outcomes[-1].reason_code == "pipeline_terminal_failure" - forgotten = ingestor.ingest( + +def test_text_is_read_measured_and_parked_until_both_holds_exist( + database_engine: Engine, tmp_path: Path +) -> None: + """Read locally, count document.md, park; approval chains structure once.""" + rig = _rig( + engine=database_engine, + tmp_path=tmp_path, + routes={"text/plain": MarkdownPassthroughConverter()}, + ) + content = b"hello world\n\nagain" + version = rig.ingestor.ingest( deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="forgotten.txt", mime="text/plain", content=b"forget this" - ), + upload=DocumentUpload(filename="first.txt", mime="text/plain", content=content), ) - assert meter.drain_once().measurements_accepted == 1 - with database_engine.begin() as connection: - connection.execute( - text( - "UPDATE document_versions SET status = 'deleted' " - "WHERE version_id = :version_id" - ), - {"version_id": forgotten.version_id}, - ) - forgotten_result = meter.drain_once() - assert forgotten_result.outcomes_created == 1 - assert forgotten_result.outcomes_accepted == 1 - assert receipts.outcomes[-1].outcome == "failed" - assert receipts.outcomes[-1].reason_code == "source_forgotten" - - with database_engine.connect() as connection: - identities = ( - connection.execute( - text( - "SELECT opaque_lineage_id, opaque_source_version_id, doc_id " - "FROM managed_ingest_measurements " - "WHERE version_id = :version_id " - "AND document_version_disposition = 'new_version'" - ), - {"version_id": first.version_id}, - ) - .mappings() - .one() - ) - public_lineage_guess = str( - uuid5( - NAMESPACE_URL, - f"rememberstack:meter-lineage:{_DEPLOYMENT_ID}:{identities['doc_id']}", - ) + assert version.created is True and version.processing_admission == "pending" + assert _version_status(engine=database_engine, version_id=version.version_id) == ( + "converting" ) - public_version_guess = str( - uuid5( - NAMESPACE_URL, - f"rememberstack:meter-source-version:{_DEPLOYMENT_ID}:{first.version_id}", - ) + source = DocumentCatalog(engine=database_engine).convert_source( + version_id=version.version_id ) - assert identities["opaque_lineage_id"] != public_lineage_guess - assert identities["opaque_source_version_id"] != public_version_guess - - receipts.conflict_next = True - quarantined = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="conflict.txt", mime="text/plain", content=b"conflicting receipt" - ), + assert rig.raw_store.read_bytes(key=ObjectKey(source.raw_uri)) == content + + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + row = _convert_row(engine=database_engine, version_id=version.version_id) + assert row == {"status": "pending", "defer_reason": "admission", "attempts": 0} + measured = _measurement(engine=database_engine, version_id=version.version_id) + assert measured is not None + assert measured["cost_class"] == "doc-text" + assert measured["unit"] == "normalized_character" + assert measured["native_quantity"] == normalized_character_count( + text=MarkdownPassthroughConverter() + .convert(content=content, mime="text/plain") + .document_md ) - assert meter.drain_once().measurements_parked == 1 - with database_engine.connect() as connection: - state = connection.execute( - text( - "SELECT delivery_state FROM managed_ingest_measurements " - "WHERE version_id = :version_id" - ), - {"version_id": quarantined.version_id}, - ).scalar_one() - assert state == "quarantined" - assert meter.drain_once().measurements_parked == 0 - healed = ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="conflict-retry.txt", - mime="text/plain", - content=b"conflicting receipt", - ), + assert measured["canonical_source_bytes"] == len(content) + assert measured["processing_profile_id"] == "doc-text-standard-v1" + assert _structure_count(engine=database_engine, version_id=version.version_id) == 0 + assert rig.convert() is RunResultOutcome.NO_WORK + + rig.receipts.park_next = True + assert rig.meter.drain_once().measurements_parked == 1 + assert _convert_row(engine=database_engine, version_id=version.version_id)[ + "defer_reason" + ] == ("admission") + _due(engine=database_engine) + assert rig.meter.drain_once().measurements_accepted == 1 + assert ( + _convert_row(engine=database_engine, version_id=version.version_id)[ + "defer_reason" + ] + is None ) - assert healed.created is False and healed.version_id == quarantined.version_id - assert meter.drain_once().measurements_accepted == 1 + sent = rig.receipts.measurements[-1] + assert (sent.cost_class, sent.unit, sent.format_family) == ( + "doc-text", + "normalized_character", + "text", + ) + + assert rig.convert() is RunResultOutcome.SUCCEEDED + assert _structure_count(engine=database_engine, version_id=version.version_id) == 1 - cancelled = ingestor.ingest( + rig.readiness.ready.add(version.version_id) + _due(engine=database_engine) + succeeded = rig.meter.drain_once() + assert succeeded.outcomes_created == 1 and succeeded.outcomes_accepted == 1 + assert rig.receipts.outcomes[-1].outcome == "succeeded" + assert rig.receipts.outcomes[-1].version_commit_sequence == 1 + + again = rig.ingestor.ingest( deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="cancelled.txt", mime="text/plain", content=b"cancel before retry" - ), + upload=DocumentUpload(filename="again.txt", mime="text/plain", content=content), ) - with database_engine.begin() as connection: - connection.execute( - text( - "UPDATE managed_ingest_measurements " - "SET staged_content = NULL, delivery_state = 'cancelled', " - "decision_reason = 'source_forgotten' " - "WHERE version_id = :version_id" - ), - {"version_id": cancelled.version_id}, - ) - cancelled_measurement_id = UUID( - str( - connection.execute( - text( - "SELECT measurement_id FROM managed_ingest_measurements " - "WHERE version_id = :version_id" - ), - {"version_id": cancelled.version_id}, - ).scalar_one() - ) - ) - meter._record_measurement_retry( - measurement_id=cancelled_measurement_id, reason_code="control_plane_unavailable" + assert again.created is False + assert rig.meter.drain_once() == MeterDrainResult() + assert len(rig.receipts.measurements) == 2 + + +def test_a_pdf_is_counted_before_ocr_and_ocr_waits_for_approval( + database_engine: Engine, tmp_path: Path +) -> None: + """Every PDF page is one doc-scan unit, counted from the page tree first.""" + pdf = FakePdf(pages=3) + rig = _rig( + engine=database_engine, tmp_path=tmp_path, routes={"application/pdf": pdf} ) - with database_engine.connect() as connection: - cancelled_state = connection.execute( - text( - "SELECT delivery_state, decision_reason " - "FROM managed_ingest_measurements WHERE version_id = :version_id" - ), - {"version_id": cancelled.version_id}, - ).one() - assert tuple(cancelled_state) == ("cancelled", "source_forgotten") + content = b"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF" + version_id = rig.upload(name="scan.pdf", mime="application/pdf", content=content) + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + assert pdf.ocr_calls == 0 + measured = _measurement(engine=database_engine, version_id=version_id) + assert measured is not None + assert (measured["cost_class"], measured["native_quantity"], measured["unit"]) == ( + "doc-scan", + 3, + "page", + ) + assert measured["processing_profile_id"] == "doc-scan-standard-v1" + assert measured["format_family"] == "pdf" + assert rig.meter.drain_once().measurements_accepted == 1 + assert rig.convert() is RunResultOutcome.SUCCEEDED + assert pdf.ocr_calls == 1 + assert _structure_count(engine=database_engine, version_id=version_id) == 1 + +def test_a_card_is_free_and_an_unmetered_route_is_refused( + database_engine: Engine, tmp_path: Path +) -> None: + """A card sends no measurement; a provider route without a class never runs.""" + vision = NamedConverter(name="image_ocr_description") + rig = _rig( + engine=database_engine, + tmp_path=tmp_path, + routes={"text/plain": NamedConverter(name="card"), "image/png": vision}, + ) + card = rig.upload(name="notes.txt", mime="text/plain", content=b"carded") + assert rig.convert() is RunResultOutcome.SUCCEEDED + assert _measurement(engine=database_engine, version_id=card) is None + assert _structure_count(engine=database_engine, version_id=card) == 1 -def test_due_measurement_scan_never_loads_staged_source_bytes() -> None: - """The bounded replay scan carries only the content-free receipt envelope.""" - statement = str(managed_metering_module._DUE_MEASUREMENTS) - assert "SELECT *" not in statement - assert "staged_content" not in statement + image = rig.upload( + name="photo.png", mime="image/png", content=b"\x89PNG\r\n\x1a\nimage" + ) + assert rig.convert() is RunResultOutcome.DEAD_LETTERED + assert vision.calls == 0 + assert _measurement(engine=database_engine, version_id=image) is None + assert _version_status(engine=database_engine, version_id=image) == "failed" -def test_missing_managed_text_route_parks_only_after_meter_approval( +def test_an_approval_that_wins_the_race_with_the_park_releases_the_claim( database_engine: Engine, tmp_path: Path ) -> None: - """Managed storage stays behind holds; a missing route never creates failure.""" - from rememberstack.core import ConversionRouter - from rememberstack.model import PipelineStage - from rememberstack.model import ProcessingLane - from rememberstack.model import RunResultOutcome - from rememberstack.spine import WorkLedger - from rememberstack.spine import WorkLedgerSettings - from rememberstack.workers import ConvertHandler - from rememberstack.workers import HandlerRegistry - from rememberstack.workers import Worker + """The park reads the approval under the lock it takes, so work never strands.""" + from rememberstack.model import ClaimedWork + from rememberstack.model.metering import ManagedMeasurementDraft - receipts = ControlledReceipts() - raw_store = LocalFSObjectStore(root=tmp_path / "raw") - catalog = DocumentCatalog(engine=database_engine) - meter = ManagedMeterCatalog( + rig = _rig( engine=database_engine, - receipts=receipts, - readiness=cast(PipelineReadinessCatalog, ControlledReadiness()), - raw_store=raw_store, + tmp_path=tmp_path, + routes={"text/plain": MarkdownPassthroughConverter()}, ) - ingestor = UploadIngestor( - catalog=catalog, - raw_store=raw_store, - admission=AllowIngest(), - routable_mimes=frozenset(), - meter_scope=ManagedMeterScope( + version_id = rig.upload(name="race.txt", mime="text/plain", content=b"race") + claimed = rig.ledger.claim_one( + deployment_id=_DEPLOYMENT_ID, + stage=PipelineStage.CONVERT, + lane=ProcessingLane.STEADY, + ) + assert isinstance(claimed, ClaimedWork) + catalog = DocumentCatalog(engine=database_engine) + source = catalog.convert_source(version_id=version_id) + catalog.record_measurement( + draft=ManagedMeasurementDraft( + measurement_id=uuid4(), + ingest_attempt_id="race", org_id=_ORG_ID, project_id=_PROJECT_ID, - identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), + format_family="text", + cost_class="doc-text", + native_quantity=4, + canonical_source_bytes=4, + classifier_version="test", + measurement_algorithm_version="test", + processing_profile_id="doc-text-standard-v1", + measured_at=datetime.now(timezone.utc), + identity_key=_SCOPE.identity_key, ), - ) - version = ingestor.ingest( deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="stored.txt", mime="text/plain", content=b"stored text" - ), - ) - assert version.processing_admission == "pending" - assert _work_count(engine=database_engine, version_id=version.version_id) == 0 - assert meter.drain_once().measurements_accepted == 1 - assert receipts.holds - source = catalog.convert_source(version_id=version.version_id) - assert raw_store.read_bytes(key=ObjectKey(source.raw_uri)) == b"stored text" - registry = HandlerRegistry() - registry.register( - stage=PipelineStage.CONVERT, - handler=ConvertHandler( - catalog=catalog, - raw_store=raw_store, - artifact_store=LocalFSObjectStore(root=tmp_path / "artifacts"), - router=ConversionRouter(routes={}), - ), + doc_id=source.doc_id, + version_id=version_id, + convert_component_version=claimed.component_version, + lane="steady", ) - worker = Worker( - ledger=WorkLedger(engine=database_engine, settings=WorkLedgerSettings()), - registry=registry, + assert rig.meter.drain_once().measurements_accepted == 1 + rig.ledger.park_for_admission( + processing_id=claimed.processing_id, attempt=claimed.attempt ) - assert ( - worker.run_one( - deployment_id=_DEPLOYMENT_ID, - stage=PipelineStage.CONVERT, - lane=ProcessingLane.STEADY, - ).outcome - is RunResultOutcome.NO_ROUTE_PARKED + assert _convert_row(engine=database_engine, version_id=version_id) == { + "status": "pending", + "defer_reason": None, + "attempts": 0, + } + + +def test_failed_forgotten_and_conflicting_measurements( + database_engine: Engine, tmp_path: Path +) -> None: + """Terminal failure and forgetting report failed; a conflict quarantines.""" + rig = _rig( + engine=database_engine, + tmp_path=tmp_path, + routes={"text/plain": MarkdownPassthroughConverter()}, ) + retried = rig.upload(name="retried.txt", mime="text/plain", content=b"retry") + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + assert rig.meter.drain_once().measurements_accepted == 1 + assert rig.convert() is RunResultOutcome.SUCCEEDED + rig.readiness.stage_status[retried] = "failed" + assert rig.meter.drain_once().outcomes_created == 0 + rig.readiness.stage_status[retried] = "dead_letter" + _due(engine=database_engine) + terminal = rig.meter.drain_once() + assert terminal.outcomes_created == 1 and terminal.outcomes_accepted == 1 + assert rig.receipts.outcomes[-1].outcome == "failed" + assert rig.receipts.outcomes[-1].reason_code == "pipeline_terminal_failure" + + forgotten = rig.upload(name="forgotten.txt", mime="text/plain", content=b"forget") + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + with database_engine.begin() as connection: + connection.execute( + text( + "UPDATE document_versions SET status = 'deleted' WHERE version_id = :v" + ), + {"v": forgotten}, + ) + result = rig.meter.drain_once() + assert result.measurements_accepted == 1 and result.outcomes_accepted == 1 + assert rig.receipts.outcomes[-1].reason_code == "source_forgotten" + with database_engine.connect() as connection: - parked = ( + identities = ( connection.execute( text( - "SELECT defer_reason::text, attempts, last_error FROM processing_state WHERE target_id=:id" + "SELECT opaque_lineage_id, opaque_source_version_id, doc_id " + "FROM managed_ingest_measurements WHERE version_id = :v" ), - {"id": version.version_id}, + {"v": retried}, ) .mappings() .one() ) - assert parked["defer_reason"] == "no_route" - assert parked["attempts"] == 0 and parked["last_error"] is None - assert ( - _version_status(engine=database_engine, version_id=version.version_id) - == "converting" + assert identities["opaque_lineage_id"] != str( + uuid5( + NAMESPACE_URL, + f"rememberstack:meter-lineage:{_DEPLOYMENT_ID}:{identities['doc_id']}", + ) + ) + assert identities["opaque_source_version_id"] != str( + uuid5( + NAMESPACE_URL, + f"rememberstack:meter-source-version:{_DEPLOYMENT_ID}:{retried}", + ) ) - assert receipts.outcomes == [] + + conflict = rig.upload(name="conflict.txt", mime="text/plain", content=b"conflict") + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + rig.receipts.conflict_next = True + assert rig.meter.drain_once().measurements_parked == 1 + measured = _measurement(engine=database_engine, version_id=conflict) + assert measured is not None and measured["delivery_state"] == "quarantined" + assert rig.meter.drain_once().measurements_parked == 0 + assert _convert_row(engine=database_engine, version_id=conflict)[ + "defer_reason" + ] == ("admission") def test_a_stored_object_is_metered_like_an_upload( database_engine: Engine, tmp_path: Path ) -> None: - """D147: a directly uploaded text is measured, held and released as ingest is.""" - receipts = ControlledReceipts() - readiness = ControlledReadiness() - raw_store = LocalFSObjectStore(root=tmp_path / "raw") - meter = ManagedMeterCatalog( + """D147: a directly uploaded object is read, measured and parked like ingest.""" + rig = _rig( engine=database_engine, - receipts=receipts, - readiness=cast(PipelineReadinessCatalog, readiness), - raw_store=raw_store, - ) - ingestor = UploadIngestor( - catalog=DocumentCatalog(engine=database_engine), - raw_store=raw_store, - admission=AllowIngest(), - routable_mimes=frozenset({"text/markdown", "text/plain"}), - meter_scope=ManagedMeterScope( - org_id=_ORG_ID, - project_id=_PROJECT_ID, - identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), - ), + tmp_path=tmp_path, + routes={"text/plain": MarkdownPassthroughConverter()}, ) content = b"stored hello\n\nworld" key = ObjectKey("uploads/meteredmetered0001") - raw_store.write_bytes(key=key, content=content, storage_class="cold") - - version = ingestor.ingest_stored( + rig.raw_store.write_bytes(key=key, content=content, storage_class="cold") + version = rig.ingestor.ingest_stored( deployment_id=_DEPLOYMENT_ID, key=key, size=len(content), @@ -627,42 +696,78 @@ def test_a_stored_object_is_metered_like_an_upload( filename="stored.txt", ) assert version.created is True and version.processing_admission == "pending" - assert _work_count(engine=database_engine, version_id=version.version_id) == 0 - with database_engine.connect() as connection: - measured = connection.execute( - text( - "SELECT normalized_character_count, canonical_source_bytes" - " FROM managed_ingest_measurements WHERE version_id = :version_id" - ), - {"version_id": version.version_id}, - ).one() - assert tuple(measured) == ( - classify_doc_text( - content=content, declared_mime="text/plain" - ).normalized_character_count, - len(content), + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + measured = _measurement(engine=database_engine, version_id=version.version_id) + assert measured is not None + assert measured["canonical_source_bytes"] == len(content) + assert rig.raw_store.read_bytes(key=key) == content + + +class _PresigningStore(LocalFSObjectStore): + """A local store that lends objects by a fake URL (D147).""" + + def presign_get(self, *, key: ObjectKey, ttl_s: int) -> str: + """A URL naming the key.""" + return f"https://raw.invalid/{key.root}?ttl={ttl_s}" + + +class FakeUrlPdf(FakePdf): + """A by-URL ``pdf`` route: it counts and converts from the URL only.""" + + accepts_url = True + url_ttl_s = 60 + + def __init__(self, *, pages: int = 5) -> None: + """Record the URLs it was handed.""" + super().__init__(pages=pages) + self.counted_urls: list[str] = [] + + def count_pages(self, *, content: bytes) -> int: + """Never used: the worker must not read a by-URL object.""" + raise AssertionError("a by-URL route was asked to count bytes") + + def count_pages_from_url(self, *, url: str, size: int) -> int: + """Count from the URL.""" + del size + self.counted_urls.append(url) + return self.pages + + def convert_from_url( + self, *, url: str, size: int, mime: str, hints: object + ) -> ConversionResult: + """The 'OCR' reading by URL.""" + del url, size, hints + return self.convert(content=b"", mime=mime) + + +def test_a_by_url_pdf_is_counted_from_its_url( + database_engine: Engine, tmp_path: Path +) -> None: + """With a presigning store the worker never reads the PDF to count it.""" + pdf = FakeUrlPdf(pages=5) + rig = _rig( + engine=database_engine, tmp_path=tmp_path, routes={"application/pdf": pdf} ) - approved = meter.drain_once() - assert approved.measurements_accepted == 1 - # Released to convert, with the raw object still where the client put it. - assert _work_count(engine=database_engine, version_id=version.version_id) == 1 - assert raw_store.read_bytes(key=key) == content - - 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(StoredObjectRefusedError) as refused: - ingestor.ingest_stored( - deployment_id=_DEPLOYMENT_ID, - key=too_large, - size=len(big), - mime="text/plain", - filename="big.txt", - ) - 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) + store = _PresigningStore(root=tmp_path / "raw") + handler = ConvertHandler( + catalog=DocumentCatalog(engine=database_engine), + raw_store=store, + artifact_store=LocalFSObjectStore(root=tmp_path / "artifacts"), + router=ConversionRouter(routes={"application/pdf": pdf}), + meter_scope=_SCOPE, + ) + registry = HandlerRegistry() + registry.register(stage=PipelineStage.CONVERT, handler=handler) + rig.worker = Worker(ledger=rig.ledger, registry=registry) + version_id = rig.upload( + name="big.pdf", + mime="application/pdf", + content=b"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF", + ) + assert rig.convert() is RunResultOutcome.ADMISSION_PARKED + assert len(pdf.counted_urls) == 1 and pdf.ocr_calls == 0 + measured = _measurement(engine=database_engine, version_id=version_id) + assert measured is not None and measured["native_quantity"] == 5 + assert rig.meter.drain_once().measurements_accepted == 1 + assert rig.convert() is RunResultOutcome.SUCCEEDED + assert pdf.ocr_calls == 1 diff --git a/src/tests/spine/test_migrations.py b/src/tests/spine/test_migrations.py index 288c09de5..b705160c3 100644 --- a/src/tests/spine/test_migrations.py +++ b/src/tests/spine/test_migrations.py @@ -149,6 +149,7 @@ def test_revision_graph_is_one_linear_structural_chain() -> None: "p9_43_0064", "p9_44_0065", "p9_45_0066", + "p9_46_0067", ) assert len(script.get_heads()) == 1 @@ -690,7 +691,7 @@ def test_postgresql_fresh_downgrade_reupgrade_mutation_and_noop_lifecycle() -> N head_before_noop = _head_revision(database_url=database_url) command.upgrade(config=config, revision="head") head_after_noop = _head_revision(database_url=database_url) - assert head_before_noop == head_after_noop == "p9_45_0066" + assert head_before_noop == head_after_noop == "p9_46_0067" assert _inventory(database_url=database_url) == restored_inventory @@ -1307,7 +1308,7 @@ def test_fresh_setup_runs_on_a_server_without_sql_pgq() -> None: assert graph_catalog_problems(connection=connection) == () finally: engine.dispose() - assert _head_revision(database_url=database_url) == "p9_45_0066" + assert _head_revision(database_url=database_url) == "p9_46_0067" def test_citation_projection_migration_round_trips_graph_metadata() -> None: @@ -1398,7 +1399,7 @@ def test_d118_refuses_lossy_downgrade() -> None: command.upgrade(config=config, revision="head") with pytest.raises(RuntimeError, match="explicitly reviewed restore/conversion"): command.downgrade(config=config, revision="p9_27_0048") - assert _head_revision(database_url=database_url) == "p9_45_0066" + assert _head_revision(database_url=database_url) == "p9_46_0067" def test_d122_refuses_a_populated_store() -> None: @@ -1442,7 +1443,51 @@ def test_d122_refuses_a_populated_store() -> None: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_45_0066" + assert _head_revision(database_url=database_url) == "p9_46_0067" + + +def test_d150_refuses_to_drop_staged_originals() -> None: + """p9_46_0067 never drops the only copy of a staged managed original.""" + database_url = _database_url() + config = _alembic_config(database_url=database_url) + reset_database(config=config) + command.upgrade(config=config, revision="p9_45_0066") + engine = create_engine(database_url) + try: + with engine.begin() as connection: + # Only the staged row matters here, so its parent rows are skipped. + connection.execute(text("SET LOCAL session_replication_role = replica")) + connection.execute( + text( + """INSERT INTO managed_ingest_measurements ( + measurement_id, deployment_id, doc_id, version_id, + ingest_attempt_id, org_id, project_id, opaque_lineage_id, + opaque_source_version_id, normalized_character_count, + canonical_source_bytes, document_version_disposition, + classifier_version, measurement_algorithm_version, + processing_profile_id, measured_at, convert_component_version, + lane, staged_content + ) VALUES (:m, :d, :doc, :v, 'ing', :org, :project, 'l', 's', 5, + 5, 'new_version', 'c', 'a', 'doc-text-standard-v1', now(), + 'e0', 'steady', 'bytes')""" + ), + { + "m": uuid4(), + "d": uuid4(), + "doc": uuid4(), + "v": uuid4(), + "org": uuid4(), + "project": uuid4(), + }, + ) + with pytest.raises(Exception, match="holds staged originals"): + command.upgrade(config=config, revision="p9_46_0067") + assert _head_revision(database_url=database_url) == "p9_45_0066" + finally: + engine.dispose() + reset_database(config=config) + command.upgrade(config=config, revision="head") + assert _head_revision(database_url=database_url) == "p9_46_0067" _BACKFILL_MIMES = ( @@ -1651,7 +1696,7 @@ def families() -> dict[object, str]: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_45_0066" + assert _head_revision(database_url=database_url) == "p9_46_0067" def test_d134_own_document_name_span_downgrade_guard() -> None: @@ -1710,7 +1755,7 @@ def span_column_exists() -> bool: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_45_0066" + assert _head_revision(database_url=database_url) == "p9_46_0067" def test_d138_downgrade_guard_protects_search_only_readings() -> None: @@ -1845,4 +1890,4 @@ def eligibility_column_exists() -> bool: engine.dispose() reset_database(config=config) command.upgrade(config=config, revision="head") - assert _head_revision(database_url=database_url) == "p9_45_0066" + assert _head_revision(database_url=database_url) == "p9_46_0067" diff --git a/src/tests/surfaces/test_d143_openapi_additive.py b/src/tests/surfaces/test_d143_openapi_additive.py index 77e061434..eed2ea525 100644 --- a/src/tests/surfaces/test_d143_openapi_additive.py +++ b/src/tests/surfaces/test_d143_openapi_additive.py @@ -5,6 +5,8 @@ those reference. Removing exactly those from today's export must give back the pre-D143 document, byte for byte after canonical serialisation; its hash is pinned here because the old document itself is a build product of history. +D150 adds one more enum value, ``admission``, to a readiness stage's +``defer_reason``; it is stripped the same way. """ from __future__ import annotations @@ -55,6 +57,8 @@ def without_d143_additions(document: dict[str, Any]) -> dict[str, Any]: schemas = stripped.get("components", {}).get("schemas", {}) for name in _ADDED_SCHEMAS: schemas.pop(name, None) + reasons = schemas["PipelineStageReadiness"]["properties"]["defer_reason"]["anyOf"] + reasons[0]["enum"] = [value for value in reasons[0]["enum"] if value != "admission"] return stripped diff --git a/src/tests/workers/test_ingest_routability.py b/src/tests/workers/test_ingest_routability.py index 7af1db326..7a64a2839 100644 --- a/src/tests/workers/test_ingest_routability.py +++ b/src/tests/workers/test_ingest_routability.py @@ -23,7 +23,6 @@ from rememberstack.model import DeferReason from rememberstack.model import DocumentUpload from rememberstack.model import IngestedVersion -from rememberstack.model import ManagedTextClassificationError from rememberstack.model import ObjectKey from rememberstack.model import ProcessingLane from rememberstack.model import StoredObjectRefusedError @@ -52,6 +51,7 @@ def __init__(self) -> None: self.calls = 0 self.defer_reason: DeferReason | None = None self.recorded_mime: str | None = None + self.metered: bool | None = None def raw_object_key(self, *, deployment_id: object, content_hash: str) -> None: """No content is kept here, so no written copy is ever released.""" @@ -63,12 +63,13 @@ def record_upload( record: UploadRecord, convert_component_version: str, lane: ProcessingLane = ProcessingLane.STEADY, - metering: object | None = None, + metered: bool = False, routable_mimes: Collection[str] | None = None, ) -> IngestedVersion: """Record the scheduling decision and return a fixed receipt.""" - _ = convert_component_version, lane, metering + _ = convert_component_version, lane self.calls += 1 + self.metered = metered self.recorded_mime = record.mime self.defer_reason = ( None @@ -341,8 +342,8 @@ def test_ingest_and_the_router_read_the_same_key_set() -> None: assert frozenset(build_conversion_routes(route_names=_ROUTES)) == frozenset(_ROUTES) -def test_managed_binary_still_requires_a_supported_metered_rate_class() -> None: - """No-route storage must not bypass managed admission or binary classification.""" +def test_a_metered_binary_is_stored_and_measured_later_in_convert() -> None: + """Metered ingest refuses no type: convert measures it or cards it for free.""" catalog, store = _RecordingCatalog(), _CountingStore() ingestor = UploadIngestor( catalog=cast(DocumentCatalog, catalog), @@ -355,15 +356,14 @@ def test_managed_binary_still_requires_a_supported_metered_rate_class() -> None: identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), ), ) - with pytest.raises(ManagedTextClassificationError): - ingestor.ingest( - deployment_id=_DEPLOYMENT_ID, - upload=DocumentUpload( - filename="scan.png", mime="image/png", content=b"\x89PNG\r\n\x1a\nimage" - ), - ) - assert store.writes == 0 - assert catalog.calls == 0 + ingestor.ingest( + deployment_id=_DEPLOYMENT_ID, + upload=DocumentUpload( + filename="scan.png", mime="image/png", content=b"\x89PNG\r\n\x1a\nimage" + ), + ) + assert store.writes == 1 + assert catalog.calls == 1 and catalog.metered is True def test_ingest_stores_the_detected_family_mime() -> None: diff --git a/src/tests/workers/test_lifecycle_reconciliation.py b/src/tests/workers/test_lifecycle_reconciliation.py index 96f5215c4..f1e284c24 100644 --- a/src/tests/workers/test_lifecycle_reconciliation.py +++ b/src/tests/workers/test_lifecycle_reconciliation.py @@ -1083,11 +1083,16 @@ def test_restore_support_plants_a_canary_the_pack_rechecks(rig: _LifecycleRig) - assert flag_rates[E2_EXTRACTOR_VERSION]["flags_raised"] == 1.0 +@pytest.mark.parametrize("reason", ["no_route", "admission"]) @pytest.mark.parametrize("deletion", ["version", "lineage"]) def test_no_route_holds_absence_retraction_until_explicit_source_deletion( - rig: _LifecycleRig, deletion: str + rig: _LifecycleRig, deletion: str, reason: str ) -> None: - """Missing conversion is incomplete testimony, while deleted input is excluded.""" + """Parked conversion is incomplete testimony, while deleted input is excluded. + + ``admission`` is conversion parked for a metered deployment's approval + (D150); it holds and releases the barrier exactly like ``no_route``. + """ first_cycle = rig.sync.open_cycle( deployment_id=_DEPLOYMENT_ID, source_kind="watched_directory" ) @@ -1117,6 +1122,15 @@ def test_no_route_holds_absence_retraction_until_explicit_source_deletion( source_version_ref=None, sync_cycle_id=cycle, ) + if reason == "admission": + with rig.engine.begin() as connection: + connection.execute( + text( + "UPDATE processing_state SET defer_reason = 'admission'" + " WHERE target_id = :v AND stage = 'convert'" + ), + {"v": parked.version_id}, + ) rig.sync.complete_cycle(cycle_id=cycle, observed=2, failed=0) rig.drain() assert rig.finalizer.finalize_ready(deployment_id=_DEPLOYMENT_ID) == () diff --git a/src/tests/workers/test_p3_corpusfs.py b/src/tests/workers/test_p3_corpusfs.py index 21183240b..0bb8446dd 100644 --- a/src/tests/workers/test_p3_corpusfs.py +++ b/src/tests/workers/test_p3_corpusfs.py @@ -612,8 +612,8 @@ def test_new_raw_version_does_not_replace_processed_evidence( assert doc_id not in {row["doc_id"] for row in export.documents()} -def test_purged_and_unaccepted_originals_are_not_advertised(corpus: _Corpus) -> None: - """Catalog metadata for purged or unadmitted bytes cannot create raw links.""" +def test_purged_originals_are_not_advertised(corpus: _Corpus) -> None: + """Catalog metadata for purged bytes cannot create raw links.""" doc_id = corpus.docs["Annual Report"] version_id = _store_unprocessed_version(corpus=corpus, doc_id=doc_id) catalog = ProjectionCatalog(engine=corpus.engine) @@ -634,36 +634,6 @@ def test_purged_and_unaccepted_originals_are_not_advertised(corpus: _Corpus) -> ), {"d": _DEPLOYMENT_ID, "h": str(version_id)}, ) - connection.execute( - text("""INSERT INTO managed_ingest_measurements ( - measurement_id, deployment_id, doc_id, version_id, ingest_attempt_id, - org_id, project_id, opaque_lineage_id, opaque_source_version_id, - normalized_character_count, canonical_source_bytes, - document_version_disposition, classifier_version, - measurement_algorithm_version, processing_profile_id, measured_at, - convert_component_version, lane, staged_content - ) VALUES (:m, :d, :doc, :v, 'test', :org, :project, 'lineage', 'version', - 9, 9, 'new_version', 'test', 'test', 'test', now(), 'test', 'steady', :bytes)"""), - { - "m": uuid4(), - "d": _DEPLOYMENT_ID, - "doc": doc_id, - "v": version_id, - "org": uuid4(), - "project": uuid4(), - "bytes": b"staged", - }, - ) - with catalog.corpus_export(deployment_id=_DEPLOYMENT_ID) as export: - row = next(row for row in export.documents() if row["doc_id"] == doc_id) - assert row["stored_version_id"] != version_id - with corpus.engine.begin() as connection: - connection.execute( - text( - "UPDATE managed_ingest_measurements SET delivery_state = 'accepted', accepted_at = now(), staged_content = NULL WHERE version_id = :v" - ), - {"v": version_id}, - ) with catalog.corpus_export(deployment_id=_DEPLOYMENT_ID) as export: row = next(row for row in export.documents() if row["doc_id"] == doc_id) assert row["stored_version_id"] == version_id diff --git a/src/tests/workers/test_processing_layers_pg.py b/src/tests/workers/test_processing_layers_pg.py index 0c25ce535..ba975f388 100644 --- a/src/tests/workers/test_processing_layers_pg.py +++ b/src/tests/workers/test_processing_layers_pg.py @@ -51,8 +51,8 @@ from rememberstack.model import RunResultOutcome from rememberstack.model import StructuredResponseModel from rememberstack.model.client import ProcessingLayer -from rememberstack.model.metering import ManagedDocumentVersionOutcomeV2 -from rememberstack.model.metering import ManagedIngestMeasurementV2 +from rememberstack.model.metering import ManagedDocumentVersionOutcome +from rememberstack.model.metering import ManagedIngestMeasurement from rememberstack.model.metering import ManagedMeterScope from rememberstack.model.metering import MeterAdmissionResult from rememberstack.ports.metering import MeterReceiptPort @@ -284,6 +284,7 @@ def __init__(self, *, engine: Engine, root: Path, params: ChunkerParams) -> None raw_store = LocalFSObjectStore(root=root / "raw") self.raw_store = raw_store artifact_store = LocalFSObjectStore(root=root / "artifacts") + self.artifact_store = artifact_store self.extraction_calls: list[tuple[str, str]] = [] """Every Selection/Claimify call as (response type, target span).""" self.fact_sentence: str | None = None @@ -1089,17 +1090,26 @@ def test_layer_states_and_profile_ids(rig: _LayerRig) -> None: """Configuration drives the derived states and the measured profile.""" configuration = rig.layers.configuration(deployment_id=_DEPLOYMENT_ID) assert not configuration.configured - assert configuration.processing_profile_id == "doc-text-standard-v1" + assert configuration.processing_profile_id(cost_class="doc-text") == ( + "doc-text-standard-v1" + ) + assert configuration.processing_profile_id(cost_class="doc-scan") == ( + "doc-scan-standard-v1" + ) rig.configure(claims=True, facts=False) configuration = rig.layers.configuration(deployment_id=_DEPLOYMENT_ID) assert configuration.configured - assert configuration.processing_profile_id == "doc-text-claims-v1" + assert configuration.processing_profile_id(cost_class="doc-text") == ( + "doc-text-claims-v1" + ) assert configuration.served == frozenset( {ProcessingLayer.SOURCES, ProcessingLayer.CLAIMS} ) rig.configure(claims=False, facts=False) assert ( - rig.layers.configuration(deployment_id=_DEPLOYMENT_ID).processing_profile_id + rig.layers.configuration(deployment_id=_DEPLOYMENT_ID).processing_profile_id( + cost_class="doc-text" + ) == "doc-text-sources-v1" ) with pytest.raises(ValueError, match="FACTS_LAYER=true requires"): @@ -1495,11 +1505,11 @@ class _ApprovingReceipts(MeterReceiptPort): def __init__(self) -> None: """Start with no receipts.""" - self.measurements: list[ManagedIngestMeasurementV2] = [] - self.outcomes: list[ManagedDocumentVersionOutcomeV2] = [] + self.measurements: list[ManagedIngestMeasurement] = [] + self.outcomes: list[ManagedDocumentVersionOutcome] = [] def admit_measurement( - self, *, measurement: ManagedIngestMeasurementV2 + self, *, measurement: ManagedIngestMeasurement ) -> MeterAdmissionResult: """Approve with two holds.""" self.measurements.append(measurement) @@ -1509,37 +1519,62 @@ def admit_measurement( storage_growth_hold_id=uuid4(), ) - def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcomeV2) -> None: + def acknowledge_outcome(self, *, outcome: ManagedDocumentVersionOutcome) -> None: """Capture the terminal receipt.""" self.outcomes.append(outcome) class _Metered: - """Managed text ingestion over the rig: measure, approve, then receipt.""" + """Managed text ingestion over the rig: read, measure, approve, receipt.""" def __init__(self, *, rig: _LayerRig) -> None: - """Bind a metered ingestor and the meter to the rig's spine and raw store.""" + """Bind a metered ingestor, convert worker and meter to the rig's spine.""" self.rig = rig self.receipts = _ApprovingReceipts() self.meter = ManagedMeterCatalog( engine=rig.engine, receipts=self.receipts, readiness=_readiness(engine=rig.engine), - raw_store=rig.raw_store, + ) + scope = ManagedMeterScope( + org_id=UUID("a1430000-0000-0000-0000-000000000001"), + project_id=UUID("b1430000-0000-0000-0000-000000000001"), + identity_key=SecretStr("umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD"), ) self.ingestor = UploadIngestor( catalog=DocumentCatalog(engine=rig.engine), raw_store=rig.raw_store, admission=ForgetCatalog(engine=rig.engine), routable_mimes=frozenset({"text/markdown"}), - meter_scope=ManagedMeterScope( - org_id=UUID("a1430000-0000-0000-0000-000000000001"), - project_id=UUID("b1430000-0000-0000-0000-000000000001"), - identity_key=SecretStr( - "umc_mik_abcdefghijklmnopqrstuvwxyz0123456789ABCD" + meter_scope=scope, + ) + registry = HandlerRegistry() + registry.register( + stage=PipelineStage.CONVERT, + handler=ConvertHandler( + catalog=DocumentCatalog(engine=rig.engine), + raw_store=rig.raw_store, + artifact_store=rig.artifact_store, + router=ConversionRouter( + routes={"text/markdown": MarkdownPassthroughConverter()} ), + meter_scope=scope, ), ) + self._convert = Worker( + ledger=WorkLedger(engine=rig.engine, settings=WorkLedgerSettings()), + registry=registry, + ) + + def approve(self) -> None: + """Measure the waiting version in convert and let the meter approve it.""" + outcome = self._convert.run_one( + deployment_id=_DEPLOYMENT_ID, + stage=PipelineStage.CONVERT, + lane=ProcessingLane.STEADY, + ).outcome + assert outcome is RunResultOutcome.ADMISSION_PARKED + assert self.meter.drain_once().measurements_accepted == 1 def ingest_approved(self, *, name: str) -> IngestedVersion: """Ingest one managed text and let the control plane approve it.""" @@ -1551,7 +1586,7 @@ def ingest_approved(self, *, name: str) -> IngestedVersion: content=_document(edited=False, paragraphs=3).encode("utf-8"), ), ) - assert self.meter.drain_once().measurements_accepted == 1 + self.approve() return version def outcome(self, *, version_id: UUID) -> dict[str, object]: @@ -2106,7 +2141,7 @@ def _observed_metered( source_version_ref=None, sync_cycle_id=None, ) - assert metered.meter.drain_once().measurements_accepted == 1 + metered.approve() return version diff --git a/website/public/llms-full.txt b/website/public/llms-full.txt index daf8fca36..e442cc1cd 100644 --- a/website/public/llms-full.txt +++ b/website/public/llms-full.txt @@ -4508,7 +4508,8 @@ stage has `succeeded` or been `skipped` and has a `finished_at`. A move until an operator adds a conversion route, so waiting does not help. With `budget`, a spend budget has reached its ceiling: the work resumes by itself when the budget window ends, or sooner if an operator raises the -ceiling. +ceiling. With `admission`, a metered deployment has measured the file and +waits for its control plane's approval; the work resumes once it is approved. Capability reasons when not ready: @@ -8452,7 +8453,7 @@ The report has five parts: | Field | Contents | |---|---| -| `routes` | For each stage and lane, how many items are in each status (`pending`, `running`, `succeeded`, `failed` while waiting to retry, `dead_letter`, `skipped`), split by `defer_reason`: `no_route` or `budget` for parked work, `scheduled` for work due later, `retry_backoff` for a failure waiting to retry, `null` otherwise. A large `pending` count with no reason on one stage shows where the pipeline is behind. | +| `routes` | For each stage and lane, how many items are in each status (`pending`, `running`, `succeeded`, `failed` while waiting to retry, `dead_letter`, `skipped`), split by `defer_reason`: `no_route`, `admission` or `budget` for parked work, `scheduled` for work due later, `retry_backoff` for a failure waiting to retry, `null` otherwise. A large `pending` count with no reason on one stage shows where the pipeline is behind. | | `dead_letters` | Items that ran out of attempts: a total, groups by stage and error class, and individual items with their `processing_id`, attempts and `last_error`. | | `poison_targets` | Items that dead-lettered under two or more component versions: an upgrade did not fix them. | | `latest_projections` | The latest filesystem snapshot, if any. | @@ -9053,7 +9054,9 @@ docker compose logs --since 1h store (with the bundled SeaweedFS or any other S3 store). Summed per `stage`, they show which stages move the most data to and from storage. The outcome is one of `succeeded`, `retry_scheduled`, `dead_lettered`, `budget_parked`, - `no_route_parked`, `lease_lost` or `no_work`. `lease_lost` means the + `no_route_parked`, `admission_parked` (a metered deployment's conversion + waiting for its control plane's approval), `lease_lost` or `no_work`. + `lease_lost` means the worker took longer than its hold on the item without renewing it, the item was handed back to the queue, and this run's result was discarded. A failure adds an `exception` object with the error type, message and full traceback. @@ -14209,7 +14212,7 @@ The `require` object of `POST /readiness`. All four fields are required. | `component_version` | string | The version of that stage's component the deployment expects. | | `status` | string | `missing`, `pending`, `running`, `succeeded`, `failed`, `dead_letter`, `skipped`. | | `finished_at` | date-time, nullable | | -| `defer_reason` | string, nullable | Why a `pending` or `failed` stage waits: `no_route` (no converter for the file's type), `budget` (a spend budget is used up), `scheduled` (due later), `retry_backoff` (a `failed` stage waiting for its next attempt). `null` for any other status, and for pending work that is simply queued. | +| `defer_reason` | string, nullable | Why a `pending` or `failed` stage waits: `no_route` (no converter for the file's type), `admission` (a metered deployment waiting for its control plane's approval), `budget` (a spend budget is used up), `scheduled` (due later), `retry_backoff` (a `failed` stage waiting for its next attempt). `null` for any other status, and for pending work that is simply queued. | `missing` means no work for that stage and component version exists yet. `failed` may be retried by the pipeline; `dead_letter` will not be. @@ -17448,7 +17451,7 @@ models below are Pydantic models (frozen) unless noted. | `ReadinessRequirements` | The capabilities a readiness check must confirm: `pipeline`, `p1`, `live_graph`, `p3`, all required booleans. | | `PipelineReadinessReport` | `ready`, `versions` (tuple of `VersionPipelineReadiness`), `capabilities` (dict of capability name to `CapabilityReadiness`), `document_binding_generation`, `model_bindings`, `build_revision`. | | `VersionPipelineReadiness` | `version_id`, `ready`, `stages` (tuple of `PipelineStageReadiness`). | -| `PipelineStageReadiness` | `stage`, `component_version`, `status` (`missing`, `pending`, `running`, `succeeded`, `failed`, `dead_letter`, `skipped`), `finished_at`, `defer_reason` (why waiting work waits: `no_route`, `budget`, `scheduled`, `retry_backoff`, or `None`). | +| `PipelineStageReadiness` | `stage`, `component_version`, `status` (`missing`, `pending`, `running`, `succeeded`, `failed`, `dead_letter`, `skipped`), `finished_at`, `defer_reason` (why waiting work waits: `no_route`, `admission`, `budget`, `scheduled`, `retry_backoff`, or `None`). | | `ProcessingLayer` | String enum: `sources`, `claims`, `facts`. | | `ProcessingLayerStates` | The result of `processing_layers`: `claims` and `facts`, each `enabled`, `backfilling` or `disabled`. | | `CapabilityReadiness` | `required`, `ready`, `checked_at`, `reason`, `version`, `built_at`, `published_at`. | diff --git a/website/src/app/docs/guides/wait-for-readiness/page.mdx b/website/src/app/docs/guides/wait-for-readiness/page.mdx index 93f046c0c..0021b54b6 100644 --- a/website/src/app/docs/guides/wait-for-readiness/page.mdx +++ b/website/src/app/docs/guides/wait-for-readiness/page.mdx @@ -96,7 +96,8 @@ stage has `succeeded` or been `skipped` and has a `finished_at`. A move until an operator adds a conversion route, so waiting does not help. With `budget`, a spend budget has reached its ceiling: the work resumes by itself when the budget window ends, or sooner if an operator raises the -ceiling. +ceiling. With `admission`, a metered deployment has measured the file and +waits for its control plane's approval; the work resumes once it is approved. Capability reasons when not ready: diff --git a/website/src/app/docs/reference/python-sdk/page.mdx b/website/src/app/docs/reference/python-sdk/page.mdx index 7db59ee9b..8675e1a7b 100644 --- a/website/src/app/docs/reference/python-sdk/page.mdx +++ b/website/src/app/docs/reference/python-sdk/page.mdx @@ -1448,7 +1448,7 @@ models below are Pydantic models (frozen) unless noted. | `ReadinessRequirements` | The capabilities a readiness check must confirm: `pipeline`, `p1`, `live_graph`, `p3`, all required booleans. | | `PipelineReadinessReport` | `ready`, `versions` (tuple of `VersionPipelineReadiness`), `capabilities` (dict of capability name to `CapabilityReadiness`), `document_binding_generation`, `model_bindings`, `build_revision`. | | `VersionPipelineReadiness` | `version_id`, `ready`, `stages` (tuple of `PipelineStageReadiness`). | -| `PipelineStageReadiness` | `stage`, `component_version`, `status` (`missing`, `pending`, `running`, `succeeded`, `failed`, `dead_letter`, `skipped`), `finished_at`, `defer_reason` (why waiting work waits: `no_route`, `budget`, `scheduled`, `retry_backoff`, or `None`). | +| `PipelineStageReadiness` | `stage`, `component_version`, `status` (`missing`, `pending`, `running`, `succeeded`, `failed`, `dead_letter`, `skipped`), `finished_at`, `defer_reason` (why waiting work waits: `no_route`, `admission`, `budget`, `scheduled`, `retry_backoff`, or `None`). | | `ProcessingLayer` | String enum: `sources`, `claims`, `facts`. | | `ProcessingLayerStates` | The result of `processing_layers`: `claims` and `facts`, each `enabled`, `backfilling` or `disabled`. | | `CapabilityReadiness` | `required`, `ready`, `checked_at`, `reason`, `version`, `built_at`, `published_at`. | diff --git a/website/src/app/docs/reference/result-types/page.mdx b/website/src/app/docs/reference/result-types/page.mdx index 331bdb354..aa164bbfe 100644 --- a/website/src/app/docs/reference/result-types/page.mdx +++ b/website/src/app/docs/reference/result-types/page.mdx @@ -666,7 +666,7 @@ The `require` object of `POST /readiness`. All four fields are required. | `component_version` | string | The version of that stage's component the deployment expects. | | `status` | string | `missing`, `pending`, `running`, `succeeded`, `failed`, `dead_letter`, `skipped`. | | `finished_at` | date-time, nullable | | -| `defer_reason` | string, nullable | Why a `pending` or `failed` stage waits: `no_route` (no converter for the file's type), `budget` (a spend budget is used up), `scheduled` (due later), `retry_backoff` (a `failed` stage waiting for its next attempt). `null` for any other status, and for pending work that is simply queued. | +| `defer_reason` | string, nullable | Why a `pending` or `failed` stage waits: `no_route` (no converter for the file's type), `admission` (a metered deployment waiting for its control plane's approval), `budget` (a spend budget is used up), `scheduled` (due later), `retry_backoff` (a `failed` stage waiting for its next attempt). `null` for any other status, and for pending work that is simply queued. | `missing` means no work for that stage and component version exists yet. `failed` may be retried by the pipeline; `dead_letter` will not be. diff --git a/website/src/app/docs/self-hosting/observability/page.mdx b/website/src/app/docs/self-hosting/observability/page.mdx index e1e7c75ce..b95a3f183 100644 --- a/website/src/app/docs/self-hosting/observability/page.mdx +++ b/website/src/app/docs/self-hosting/observability/page.mdx @@ -31,7 +31,9 @@ docker compose logs --since 1h store (with the bundled SeaweedFS or any other S3 store). Summed per `stage`, they show which stages move the most data to and from storage. The outcome is one of `succeeded`, `retry_scheduled`, `dead_lettered`, `budget_parked`, - `no_route_parked`, `lease_lost` or `no_work`. `lease_lost` means the + `no_route_parked`, `admission_parked` (a metered deployment's conversion + waiting for its control plane's approval), `lease_lost` or `no_work`. + `lease_lost` means the worker took longer than its hold on the item without renewing it, the item was handed back to the queue, and this run's result was discarded. A failure adds an `exception` object with the error type, message and full traceback. diff --git a/website/src/app/docs/self-hosting/operating/page.mdx b/website/src/app/docs/self-hosting/operating/page.mdx index 83003fa85..480badecc 100644 --- a/website/src/app/docs/self-hosting/operating/page.mdx +++ b/website/src/app/docs/self-hosting/operating/page.mdx @@ -55,7 +55,7 @@ The report has five parts: | Field | Contents | |---|---| -| `routes` | For each stage and lane, how many items are in each status (`pending`, `running`, `succeeded`, `failed` while waiting to retry, `dead_letter`, `skipped`), split by `defer_reason`: `no_route` or `budget` for parked work, `scheduled` for work due later, `retry_backoff` for a failure waiting to retry, `null` otherwise. A large `pending` count with no reason on one stage shows where the pipeline is behind. | +| `routes` | For each stage and lane, how many items are in each status (`pending`, `running`, `succeeded`, `failed` while waiting to retry, `dead_letter`, `skipped`), split by `defer_reason`: `no_route`, `admission` or `budget` for parked work, `scheduled` for work due later, `retry_backoff` for a failure waiting to retry, `null` otherwise. A large `pending` count with no reason on one stage shows where the pipeline is behind. | | `dead_letters` | Items that ran out of attempts: a total, groups by stage and error class, and individual items with their `processing_id`, attempts and `last_error`. | | `poison_targets` | Items that dead-lettered under two or more component versions: an upgrade did not fix them. | | `latest_projections` | The latest filesystem snapshot, if any. |