diff --git a/docs/reporting-ledger-migration.md b/docs/reporting-ledger-migration.md index 38ca19b7b..4f306ab6f 100644 --- a/docs/reporting-ledger-migration.md +++ b/docs/reporting-ledger-migration.md @@ -63,6 +63,7 @@ this release: startup now refuses legacy storage, including beta.15. Use the reporting work. It creates missing tables and applies the bundled `reporting_ledger_account_generations.sql`, `reporting_ledger_obligation_currency.sql`, + `reporting_ledger_data_through_precision.sql`, `reporting_ledger_reconciliation.sql`, and `reporting_notification_outbox.sql` and `reporting_webhook_activity.sql` migrations in one transaction. For the later A-to-B additive upgrade and @@ -80,13 +81,14 @@ store with no shared retry state to avoid silently retrying on every replica. For deployments managed by a migration tool, the standalone migration is [`reporting_ledger_account_generations.sql`](../packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_account_generations.sql). It upgrades an existing beta.15 ledger by itself, including in autocommit mode. -For a combined bootstrap and upgrade, run all five bundled files in one transaction: +For a combined bootstrap and upgrade, run all six bundled files in one transaction: ```sh psql "$REPORTING_DATABASE_URL" --set=ON_ERROR_STOP=1 --single-transaction \ -f packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql \ -f packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_account_generations.sql \ -f packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_obligation_currency.sql \ + -f packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql \ -f packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_reconciliation.sql \ -f packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_notification_outbox.sql ``` diff --git a/docs/reporting-reconciliation-storage.md b/docs/reporting-reconciliation-storage.md index cb224f679..641bc2c1c 100644 --- a/docs/reporting-reconciliation-storage.md +++ b/docs/reporting-reconciliation-storage.md @@ -265,9 +265,10 @@ store opened can report retained damage. ## Migration and operational limits -Run `create_schema()` or all four bundled SQL resources in one transaction: +Run `create_schema()` or all five bundled SQL resources in one transaction: `reporting_ledger.sql`, `reporting_ledger_account_generations.sql`, -`reporting_ledger_obligation_currency.sql`, then `reporting_ledger_reconciliation.sql`. +`reporting_ledger_obligation_currency.sql`, `reporting_ledger_data_through_precision.sql`, +then `reporting_ledger_reconciliation.sql`. The last migration is also one atomic statement in autocommit mode. All migrations share the schema advisory lock. Drain older writers before upgrading. diff --git a/docs/reporting-source-adapters.md b/docs/reporting-source-adapters.md index 907a31552..a21359c25 100644 --- a/docs/reporting-source-adapters.md +++ b/docs/reporting-source-adapters.md @@ -202,8 +202,11 @@ totals -- only an explicitly declared cell withdraws one, under the `InlineFetchResult` accepts these six positional arguments, in order: `rows`, `data_through`, `covered_constituent_ids`, `unavailable_constituents`, -`unavailable_status`, and `warnings`. The remaining fields -- `currency`, -`provisional_until`, and `cell_availability` -- are keyword-only. +`unavailable_status`, and `warnings`. The remaining fields -- +`data_through_precision`, `currency`, `provisional_until`, and +`cell_availability` -- are keyword-only. Precision accepts `exact`, +`lower_bound`, or `unknown`; omitting it preserves the derived exact behavior, +and `unknown` requires `data_through=None`. If your adapter previously passed `currency` or `provisional_until` as the seventh or eighth positional argument, move them to explicit keywords: diff --git a/docs/reporting-webhook-activity.md b/docs/reporting-webhook-activity.md index e66a619d9..0519bcb41 100644 --- a/docs/reporting-webhook-activity.md +++ b/docs/reporting-webhook-activity.md @@ -206,6 +206,7 @@ sweeper or broad unscoped tenant purge is installed by this slice. The ordered packaged chain is `reporting_ledger.sql`, `reporting_ledger_account_generations.sql`, `reporting_ledger_obligation_currency.sql`, +`reporting_ledger_data_through_precision.sql`, `reporting_ledger_reconciliation.sql`, `reporting_notification_outbox.sql` (#1168A), then `reporting_webhook_activity.sql` (#1168B). `create_schema()` executes the chain in one transaction. The B step is also atomic on its own, serializes concurrent @@ -240,7 +241,7 @@ Install a missing migration, re-enable a disabled required object, or restore a changed required definition from the matching release before advertising. Do not regenerate the bundled manifest from a damaged adopter database to bypass checks. -The manifest regression compares all 453 required objects across two fresh random +The manifest regression compares all 471 required objects across two fresh random schemas, repeats each unchanged migration with zero manifest diff, and compares installed wheel/sdist migrations to the same manifest. Schema names and OIDs do not identify required objects. Function source, security mode, volatility, diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py index 6e6c4932e..abcf58d85 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py @@ -28,8 +28,9 @@ The raw DDL ships in :file:`reporting_ledger.sql` followed by :file:`reporting_ledger_account_generations.sql`, :file:`reporting_ledger_obligation_currency.sql`, +:file:`reporting_ledger_data_through_precision.sql`, :file:`reporting_ledger_reconciliation.sql`, and -:file:`reporting_notification_outbox.sql`; run all five in one transaction +:file:`reporting_notification_outbox.sql`; run all six in one transaction when using Alembic, Flyway, or psql. See :file:`docs/reporting-ledger-migration.md` for deployment and compatibility notes. @@ -150,10 +151,12 @@ issue_is_retirable, provisional_observation_reuse_candidate, reject_reserved_authoritative_party, + revision_data_through_evidence_matches, validate_adjustment_currency, validate_managed_revision_rows, validate_retained_provisional_observation, validate_revision_currency, + validate_revision_data_through, ) from adcp_reporting_storage.ledger.row_storage import ( REPORTING_ROW_STORAGE_DDL_PATH, @@ -200,6 +203,9 @@ _DDL_PATH = Path(__file__).parent / "reporting_ledger.sql" _ACCOUNT_GENERATIONS_DDL_PATH = Path(__file__).parent / "reporting_ledger_account_generations.sql" _CURRENCY_DDL_PATH = Path(__file__).parent / "reporting_ledger_obligation_currency.sql" +_DATA_THROUGH_PRECISION_DDL_PATH = ( + Path(__file__).parent / "reporting_ledger_data_through_precision.sql" +) _RECONCILIATION_DDL_PATH = Path(__file__).parent / "reporting_ledger_reconciliation.sql" _NOTIFICATIONS_DDL_PATH = Path(__file__).parent / "reporting_notification_outbox.sql" _ACTIVITY_DDL_PATH = Path(__file__).parent / "reporting_webhook_activity.sql" @@ -769,6 +775,7 @@ async def _create_schema_on(self, connection: Any) -> None: _DDL_PATH, _ACCOUNT_GENERATIONS_DDL_PATH, _CURRENCY_DDL_PATH, + _DATA_THROUGH_PRECISION_DDL_PATH, _RECONCILIATION_DDL_PATH, _NOTIFICATIONS_DDL_PATH, _ACTIVITY_DDL_PATH, @@ -1476,7 +1483,14 @@ async def commit_revision( f"revision {revision.reporting_revision_id} already exists with " "different content; a restatement is a new revision", ) - return _revision_from_row(existing[:-1]) + retained = _revision_from_row(existing[:-1]) + if not revision_data_through_evidence_matches(retained, revision): + raise LedgerConflictError( + "REVISION_IMMUTABLE", + f"revision {revision.reporting_revision_id} already exists with " + "different data-through evidence", + ) + return retained obligation = await ( await connection.execute( f"SELECT {_OBLIGATION_COLUMNS} FROM reporting_obligations" # noqa: S608 # nosec B608 @@ -1498,6 +1512,7 @@ async def commit_revision( "this period is being retired; no revision may be added to it", ) validate_revision_currency(_obligation_from_row(obligation), revision, rows) + validate_revision_data_through(_obligation_from_row(obligation), revision) if revision.supersedes_reporting_revision_id: await self._require_current_leaf(connection, revision) write_error = None @@ -1506,12 +1521,13 @@ async def commit_revision( "INSERT INTO reporting_revisions" " (reporting_revision_id, account_id, reporting_obligation_id, finality," " revision_content_sha256, row_count, control_totals, observed_at," - " data_through, created_at, supersedes_reporting_revision_id," + " data_through, data_through_precision, created_at," + " supersedes_reporting_revision_id," " finality_basis, finality_policy_id, finalized_at, readable," " readable_at_commit, source_publication_id, source_manifest_sha256," " content_sha256, canonical_content_digest, managed_control_totals)" " VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s, %s, %s, %s, %s," - " %s, %s, %s, %s, %s, %s::jsonb, %s::jsonb)", + " %s, %s, %s, %s, %s, %s, %s::jsonb, %s::jsonb)", ( revision.reporting_revision_id, revision.account_id, @@ -1522,6 +1538,7 @@ async def commit_revision( _json([[name, value] for name, value in revision.control_totals]), revision.observed_at, revision.data_through, + revision.data_through_precision, revision.created_at, revision.supersedes_reporting_revision_id, revision.finality_basis, diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql index cb57362cc..06f452d88 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql @@ -153,6 +153,7 @@ CREATE TABLE IF NOT EXISTS reporting_revisions ( control_totals JSONB NOT NULL DEFAULT '[]'::jsonb, observed_at TIMESTAMPTZ NOT NULL, data_through TIMESTAMPTZ, + data_through_precision TEXT COLLATE "C" NOT NULL, created_at TIMESTAMPTZ NOT NULL, supersedes_reporting_revision_id TEXT COLLATE "C", finality_basis TEXT, @@ -167,7 +168,14 @@ CREATE TABLE IF NOT EXISTS reporting_revisions ( source_publication_id TEXT COLLATE "C", source_manifest_sha256 TEXT COLLATE "C", -- Binds what was published, excluding mutable readability. - content_sha256 TEXT COLLATE "C" NOT NULL + content_sha256 TEXT COLLATE "C" NOT NULL, + CONSTRAINT reporting_revisions_data_through_precision_value CHECK ( + data_through_precision IN ('exact', 'lower_bound', 'unknown') + ), + CONSTRAINT reporting_revisions_data_through_precision_pairing CHECK ( + (data_through_precision = 'unknown' AND data_through IS NULL) + OR (data_through_precision IN ('exact', 'lower_bound') AND data_through IS NOT NULL) + ) ); -- An official revision is terminal: at most one per obligation. A later source diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql new file mode 100644 index 000000000..92ed4f734 --- /dev/null +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql @@ -0,0 +1,83 @@ +-- Retain the source's qualification of each revision watermark. Apply after +-- the obligation-currency migration and before reconciliation migrations. +-- The backfill maps a timestamp to exact and a null watermark to unknown, +-- matching the compatibility rule used by the in-memory ledger. + +DO $data_through_precision$ +DECLARE + precision_exists BOOLEAN; + precision_type OID; + precision_collation NAME; + precision_default TEXT; +BEGIN + PERFORM pg_advisory_xact_lock(hashtext('adcp.reporting.schema'), hashtext(current_schema())); + LOCK TABLE reporting_revisions IN ACCESS EXCLUSIVE MODE; + + SELECT EXISTS ( + SELECT 1 FROM pg_attribute + WHERE attrelid = 'reporting_revisions'::regclass + AND attname = 'data_through_precision' + AND NOT attisdropped + ) INTO precision_exists; + IF NOT precision_exists THEN + -- A stored generated value backfills retained rows as part of the table + -- rewrite, without firing immutable-publication or outbox triggers. + ALTER TABLE reporting_revisions ADD COLUMN data_through_precision TEXT COLLATE "C" + GENERATED ALWAYS AS ( + CASE WHEN data_through IS NULL THEN 'unknown' ELSE 'exact' END + ) STORED; + ALTER TABLE reporting_revisions + ALTER COLUMN data_through_precision DROP EXPRESSION; + END IF; + + SELECT a.atttypid, co.collname, pg_get_expr(d.adbin, d.adrelid) + INTO precision_type, precision_collation, precision_default + FROM pg_attribute a + LEFT JOIN pg_collation co ON co.oid = a.attcollation + LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE a.attrelid = 'reporting_revisions'::regclass + AND a.attname = 'data_through_precision' + AND NOT a.attisdropped; + IF precision_type <> 'text'::regtype + OR precision_collation IS DISTINCT FROM 'C' + OR precision_default IS NOT NULL THEN + RAISE EXCEPTION 'Unexpected reporting_revisions.data_through_precision definition' + USING HINT = 'Inspect the adopter schema; precision must be C-collated text with no default.'; + END IF; + + IF EXISTS ( + SELECT 1 FROM reporting_revisions + WHERE data_through_precision IS NULL + OR data_through_precision NOT IN ('exact', 'lower_bound', 'unknown') + OR (data_through_precision = 'unknown') <> (data_through IS NULL) + ) THEN + RAISE EXCEPTION 'Invalid reporting revision data-through precision evidence'; + END IF; + + ALTER TABLE reporting_revisions ALTER COLUMN data_through_precision SET NOT NULL; + + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'reporting_revisions'::regclass + AND conname = 'reporting_revisions_data_through_precision_value' + ) THEN + ALTER TABLE reporting_revisions + ADD CONSTRAINT reporting_revisions_data_through_precision_value + CHECK (data_through_precision IN ('exact', 'lower_bound', 'unknown')); + END IF; + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'reporting_revisions'::regclass + AND conname = 'reporting_revisions_data_through_precision_pairing' + ) THEN + ALTER TABLE reporting_revisions + ADD CONSTRAINT reporting_revisions_data_through_precision_pairing CHECK ( + (data_through_precision = 'unknown' AND data_through IS NULL) + OR ( + data_through_precision IN ('exact', 'lower_bound') + AND data_through IS NOT NULL + ) + ); + END IF; +END +$data_through_precision$; diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py index 5f9704714..a11976db8 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py @@ -619,6 +619,7 @@ async def migrate_legacy_reporting( "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", "reporting_webhook_activity.sql", @@ -813,6 +814,12 @@ async def backfill_legacy_reporting( params.append(mapping.consumer_id) elif column == "quarantined": selected.append(sql.SQL("TRUE")) + elif table == "reporting_revisions" and column == "data_through_precision": + selected.append( + sql.SQL( + "CASE WHEN data_through IS NULL THEN 'unknown' ELSE 'exact' END" + ) + ) elif column in {"lease_worker_id", "lease_expires_at"}: selected.append(sql.SQL("NULL")) elif column in row: diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json b/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json index 38cbc3623..ed96d4029 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json @@ -767,6 +767,10 @@ "enabled": true, "fingerprint": "6f1466ce5d0aaac8471e39834b9c4b1f85d6f7169d9238a245ac035ff518e0fc" }, + "column:reporting_revisions.data_through_precision": { + "enabled": true, + "fingerprint": "fdc4b549138bf90a5af5ed00b87a86ff9a0cbea553e7f017b4d95510708f6f88" + }, "column:reporting_revisions.finality": { "enabled": true, "fingerprint": "10ccaa0dc3b93d48a1f32c7ef2352a11676632e1e871d77ef9ef4393eea15d27" @@ -1267,6 +1271,14 @@ "enabled": true, "fingerprint": "3cb1592e1e5bb1fd77955efe4598fc6cce7d6639ef0fb5bbdd48dc9ad8ad17d5" }, + "constraint:reporting_revisions.reporting_revisions_data_through_precision_pairing": { + "enabled": true, + "fingerprint": "10cb398920d657d3e62a4dcd100bcd34f7c4a32049a22b3fe2cabfa2474cbbb7" + }, + "constraint:reporting_revisions.reporting_revisions_data_through_precision_value": { + "enabled": true, + "fingerprint": "e619c8545868f9cb2402cd6787cf4356acf36dd0176a15d01eb1d7643f9f4a18" + }, "constraint:reporting_revisions.reporting_revisions_pkey": { "enabled": true, "fingerprint": "662ad170109383adfe0ff8802d20f28909467d25f0700014b1e0ef14b1ccc963" diff --git a/src/adcp/reporting/_data_through.py b/src/adcp/reporting/_data_through.py new file mode 100644 index 000000000..6980b38ce --- /dev/null +++ b/src/adcp/reporting/_data_through.py @@ -0,0 +1,25 @@ +"""Shared data-through precision rules for reporting evidence.""" + +from __future__ import annotations + +from datetime import datetime +from typing import Literal + +ReportingDataThroughPrecision = Literal["exact", "lower_bound", "unknown"] + + +def resolve_data_through_precision( + data_through: datetime | None, + precision: ReportingDataThroughPrecision | None, +) -> ReportingDataThroughPrecision: + """Resolve the compatibility default and validate its timestamp pairing.""" + if precision is None: + return "exact" if data_through is not None else "unknown" + if precision not in {"exact", "lower_bound", "unknown"}: + raise ValueError("data_through_precision must be exact, lower_bound, or unknown") + if precision == "unknown": + if data_through is not None: + raise ValueError("unknown data_through_precision requires data_through to be null") + elif data_through is None: + raise ValueError(f"{precision} data_through_precision requires data_through") + return precision diff --git a/src/adcp/reporting/conformance.py b/src/adcp/reporting/conformance.py index b240f8ebe..d533cda15 100644 --- a/src/adcp/reporting/conformance.py +++ b/src/adcp/reporting/conformance.py @@ -739,13 +739,20 @@ def _assert_freshness_does_not_regress( predecessor.period.source_read_cutoff_at, successor.period.source_read_cutoff_at, ), - ("data_through", predecessor.data_through, successor.data_through), ): if _utc(after) < _utc(before): raise _fail( "REVISION_SEQUENCE_INVALID", f"{label} must not regress {field} from its predecessor", ) + if predecessor.data_through is not None and ( + successor.data_through is None + or _utc(successor.data_through) < _utc(predecessor.data_through) + ): + raise _fail( + "REVISION_SEQUENCE_INVALID", + f"{label} must not regress data_through from its predecessor", + ) def _assert_cells_do_not_regress( diff --git a/src/adcp/reporting/inline_source.py b/src/adcp/reporting/inline_source.py index 87c4721a7..a8538124f 100644 --- a/src/adcp/reporting/inline_source.py +++ b/src/adcp/reporting/inline_source.py @@ -76,6 +76,10 @@ from pydantic import TypeAdapter, ValidationError from adcp._deferred_adapters import deferred_adapter +from adcp.reporting._data_through import ( + ReportingDataThroughPrecision, + resolve_data_through_precision, +) from adcp.reporting._settlement import settle_task from adcp.reporting._source_authorization import inline_publication from adcp.reporting.currency import ( @@ -237,6 +241,14 @@ class InlineFetchResult: known-unsupported rather than known-empty. """ + data_through_precision: ReportingDataThroughPrecision | None = field(default=None, kw_only=True) + """How the source qualifies :attr:`data_through`. + + Omit this to retain the compatibility behavior, which derives an exact + bounded watermark for the requested slice. ``unknown`` requires an + explicit null watermark. + """ + rows: Sequence[Mapping[str, Any]] """Normalized rows. Empty means an observed zero for every covered scope.""" @@ -306,6 +318,10 @@ class InlineFetchResult: be wholly explicit-zero or wholly unavailable under the existing contract. """ + def __post_init__(self) -> None: + if self.data_through_precision is not None: + resolve_data_through_precision(self.data_through, self.data_through_precision) + @classmethod def all_present( cls, rows: Sequence[Mapping[str, Any]], *, data_through: datetime @@ -896,7 +912,28 @@ async def _publish( cancel: asyncio.Event, ) -> ReportingSourceExecutorResult: observed_at = self._clock() - data_through = _clamp_watermark(request, result.data_through, observed_at) + availability_data_through: datetime | None = _clamp_watermark( + request, result.data_through, observed_at + ) + data_through: datetime | None = availability_data_through + if result.data_through_precision is not None: + precision = resolve_data_through_precision( + result.data_through, result.data_through_precision + ) + if precision == "unknown": + availability_data_through = None + data_through = None + else: + assert result.data_through is not None + declared = _utc(result.data_through) + if not _utc(request.period.start) <= declared <= _utc(request.period.end): + raise ValueError("data_through must be inside the reporting period") + if declared > min(_utc(request.period.source_read_cutoff_at), _utc(observed_at)): + raise ValueError( + "data_through must not follow observed_at or the source read cutoff" + ) + availability_data_through = declared + data_through = declared overrides = _validate_cell_availability(request, result.cell_availability) covered = ( {item.constituent_id for item in request.coverage.constituents} @@ -926,7 +963,7 @@ async def _publish( ) statuses = self._derive_statuses( - request, result, covered, rows_by_constituent, data_through + request, result, covered, rows_by_constituent, availability_data_through ) constituents, cells = self._resolve_availability( request, @@ -934,14 +971,40 @@ async def _publish( overrides=overrides, statuses=statuses, rows_by_constituent=rows_by_constituent, - data_through=data_through, + data_through=availability_data_through, observed_at=observed_at, ) # Granular watermarks are bounded by the batch watermark on the wire. # Advancing it for an explicit cell must not advance fallback cells. - data_through = max(data_through, *(cell.data_through or data_through for cell in cells)) + if result.data_through_precision is None and data_through is not None: + data_through = max(data_through, *(cell.data_through or data_through for cell in cells)) + event_time_through = ( + data_through + if data_through is not None + else min( + _utc(request.period.end), + _utc(request.period.source_read_cutoff_at), + _utc(observed_at), + ) + ) coverage_status = _roll_up([item.status for item in constituents]) + if ( + request.publication_class == "AUTHORITATIVE" + and data_through is None + and coverage_status == "full" + ): + return ReportingSourceExecutorResult.failed( + ReportingSourceErrorV1( + code="PARTIAL_RESULT", + retry="retryable", + safe_message=( + "an authoritative reporting source cannot prove full coverage " + "while its batch watermark is unknown" + ), + ) + ) + if request.coverage.expected == "full" and coverage_status != "full": # Never publish a partial answer to a full-coverage slice; the # producer needs a truthful failure so it can retry or escalate. @@ -1012,6 +1075,8 @@ async def _publish( request, observed_at=observed_at, data_through=data_through, + data_through_precision=result.data_through_precision, + event_time_through=event_time_through, staged=staged, constituents=constituents, cells=cells, @@ -1044,7 +1109,7 @@ def _derive_statuses( result: InlineFetchResult, covered: set[str], rows_by_constituent: Mapping[str, Sequence[Mapping[str, Any]]], - data_through: datetime, + data_through: datetime | None, ) -> dict[str, ReportingAvailabilityStatus]: """Turn "what came back" into per-constituent publication evidence. @@ -1053,9 +1118,10 @@ def _derive_statuses( numbers are real but the window is not finished, which is ``delayed``, not complete. """ - short_of_the_window = request.publication_class == "AUTHORITATIVE" and _utc( - data_through - ) < _utc(request.period.end) + short_of_the_window = data_through is None or ( + request.publication_class == "AUTHORITATIVE" + and _utc(data_through) < _utc(request.period.end) + ) statuses: dict[str, ReportingAvailabilityStatus] = {} for item in request.coverage.constituents: constituent_id = item.constituent_id @@ -1079,7 +1145,7 @@ def _resolve_availability( overrides: Mapping[str, Mapping[str, MetricEvidence]], statuses: Mapping[str, ReportingAvailabilityStatus], rows_by_constituent: Mapping[str, Sequence[Mapping[str, Any]]], - data_through: datetime, + data_through: datetime | None, observed_at: datetime, ) -> tuple[list[ReportingConstituentCoverageV1], list[ReportingMetricAvailabilityV1]]: """Resolve cells first, then derive coverage without widening their claims.""" @@ -1119,8 +1185,23 @@ def _resolve_availability( "data_through must not precede the reporting period" ) watermark = _clamp_watermark(request, watermark, observed_at) + if ( + result.data_through_precision is not None + and result.data_through_precision != "unknown" + and data_through is not None + and watermark > data_through + ): + raise _CellEvidenceError( + f"cell_availability ({constituent_id!r}, {metric!r}) " + "data_through must not follow the declared batch watermark" + ) elif status == "explicit_zero": watermark = data_through + if status in _AVAILABLE and watermark is None: + raise _CellEvidenceError( + f"cell_availability ({constituent_id!r}, {metric!r}) " + "needs a watermark when batch precision is unknown" + ) if ( status in _AVAILABLE and request.publication_class == "AUTHORITATIVE" @@ -1186,7 +1267,9 @@ def _seal_manifest( request: ReportingSourceSliceRequestV1, *, observed_at: datetime, - data_through: datetime, + data_through: datetime | None, + data_through_precision: ReportingDataThroughPrecision | None, + event_time_through: datetime, staged: SourceBatchObjectV1, constituents: list[ReportingConstituentCoverageV1], cells: list[ReportingMetricAvailabilityV1], @@ -1241,6 +1324,7 @@ def _seal_manifest( ), "observed_at": observed_at, "data_through": data_through, + "data_through_precision": data_through_precision, "acquired_at": max(_utc(observed_at), finality_at), "currency": request.currency, "requested_dimensions": list(request.requested_dimensions), @@ -1252,7 +1336,9 @@ def _seal_manifest( "metric_availability": cells, "coverage": coverage, "explicit_zero": explicit_zero, - "event_time_range": None if row_count == 0 else (request.period.start, data_through), + "event_time_range": ( + None if row_count == 0 else (request.period.start, event_time_through) + ), "prior_checkpoint": request.prior_checkpoint, "warnings": warnings, } diff --git a/src/adcp/reporting/ledger/__init__.py b/src/adcp/reporting/ledger/__init__.py index 52c46d7ef..2d52a480d 100644 --- a/src/adcp/reporting/ledger/__init__.py +++ b/src/adcp/reporting/ledger/__init__.py @@ -141,6 +141,7 @@ ReportingCaller, ReportingConfiguration, ReportingConfigurationGenerationKey, + ReportingDataThroughPrecision, ReportingDefinitionBinding, ReportingDeliveryEscalation, ReportingFinality, @@ -254,6 +255,7 @@ "ReportingCanonicalDigest", "ReportingConfiguration", "ReportingConfigurationGenerationKey", + "ReportingDataThroughPrecision", "ReportingControlTotalRecord", "ReportingCurrencyError", "ReportingCurrentRevisionsPageV1", diff --git a/src/adcp/reporting/ledger/_record_rows.py b/src/adcp/reporting/ledger/_record_rows.py index 50d08fe44..47c345739 100644 --- a/src/adcp/reporting/ledger/_record_rows.py +++ b/src/adcp/reporting/ledger/_record_rows.py @@ -42,7 +42,8 @@ _REVISION_COLUMNS = ( "reporting_revision_id, account_id, reporting_obligation_id, finality," " revision_content_sha256, row_count, control_totals, observed_at, data_through," - " created_at, supersedes_reporting_revision_id, finality_basis, finality_policy_id," + " data_through_precision, created_at, supersedes_reporting_revision_id, finality_basis," + " finality_policy_id," " finalized_at, readable, readable_at_commit, source_publication_id, source_manifest_sha256," " canonical_content_digest, managed_control_totals" ) @@ -201,21 +202,22 @@ def _revision_from_row(row: Sequence[Any]) -> ReportingRevisionRecord: control_totals=tuple((name, value) for name, value in (row[6] or [])), observed_at=_utc(row[7]), data_through=_utc(row[8]) if row[8] else None, - created_at=_utc(row[9]), - supersedes_reporting_revision_id=row[10], - finality_basis=row[11], - finality_policy_id=row[12], - finalized_at=_utc(row[13]) if row[13] else None, - readable=row[14], - readable_at_commit=row[15], - source_publication_id=row[16], - source_manifest_sha256=row[17], + data_through_precision=row[9], + created_at=_utc(row[10]), + supersedes_reporting_revision_id=row[11], + finality_basis=row[12], + finality_policy_id=row[13], + finalized_at=_utc(row[14]) if row[14] else None, + readable=row[15], + readable_at_commit=row[16], + source_publication_id=row[17], + source_manifest_sha256=row[18], canonical_content_digest=( - ReportingCanonicalDigest.from_wire(row[18]) if row[18] is not None else None + ReportingCanonicalDigest.from_wire(row[19]) if row[19] is not None else None ), managed_control_totals=( - tuple(ReportingControlTotalRecord.from_wire(item) for item in row[19]) - if row[19] is not None + tuple(ReportingControlTotalRecord.from_wire(item) for item in row[20]) + if row[20] is not None else None ), ) @@ -303,6 +305,9 @@ def _revision_payload(revision: ReportingRevisionRecord) -> dict[str, Any]: "obligation": revision.reporting_obligation_id, "supersedes": revision.supersedes_reporting_revision_id, } + if revision.data_through_precision == "lower_bound": + payload["data_through_precision"] = revision.data_through_precision + payload["data_through"] = _utc(revision.data_through).isoformat() # type: ignore[arg-type] if revision.canonical_content_digest is not None: payload["canonical_content_digest"] = revision.canonical_content_digest.to_wire() if revision.managed_control_totals is not None: diff --git a/src/adcp/reporting/ledger/models.py b/src/adcp/reporting/ledger/models.py index eebffbbfb..46e9a2719 100644 --- a/src/adcp/reporting/ledger/models.py +++ b/src/adcp/reporting/ledger/models.py @@ -28,6 +28,10 @@ from typing import Any, Literal, Protocol from zoneinfo import ZoneInfo +from adcp.reporting._data_through import ( + ReportingDataThroughPrecision, + resolve_data_through_precision, +) from adcp.reporting.currency import validate_currency, validate_currency_units from adcp.reporting.evidence import ( ReportingCanonicalDigest, @@ -41,6 +45,7 @@ "ReportingCaller", "ConsumerStatusRecord", "ConsumerStatusValue", + "ReportingDataThroughPrecision", "ReportingDefinitionBinding", "LedgerChange", "LedgerRecordKind", @@ -495,6 +500,7 @@ class ReportingRevisionRecord: observed_at: datetime data_through: datetime | None created_at: datetime + data_through_precision: ReportingDataThroughPrecision | None = field(default=None, kw_only=True) supersedes_reporting_revision_id: str | None = None finality_basis: Literal["source_final", "contractual_cutoff", "stabilized"] | None = None finality_policy_id: str | None = None @@ -509,6 +515,11 @@ class ReportingRevisionRecord: managed_control_totals: tuple[ReportingControlTotalRecord, ...] | None = None def __post_init__(self) -> None: + object.__setattr__( + self, + "data_through_precision", + resolve_data_through_precision(self.data_through, self.data_through_precision), + ) if ( self.canonical_content_digest is not None and type(self.canonical_content_digest) is not ReportingCanonicalDigest diff --git a/src/adcp/reporting/ledger/producer.py b/src/adcp/reporting/ledger/producer.py index 3505ec34d..1f9953e79 100644 --- a/src/adcp/reporting/ledger/producer.py +++ b/src/adcp/reporting/ledger/producer.py @@ -1836,6 +1836,7 @@ async def commit_revision_from_manifest( managed_control_totals=typed_totals, observed_at=manifest.observed_at, data_through=manifest.data_through, + data_through_precision=manifest.resolved_data_through_precision, created_at=created_at, supersedes_reporting_revision_id=supersedes, finality_basis=( @@ -1893,6 +1894,11 @@ async def commit_revision_from_manifest( and predecessor.source_manifest_sha256 == manifest.content_fingerprint.split(":", 1)[-1] and predecessor.revision_content_sha256 == predecessor_content_sha256 + and predecessor.data_through_precision == manifest.resolved_data_through_precision + and ( + manifest.resolved_data_through_precision != "lower_bound" + or predecessor.data_through == manifest.data_through + ) ): retained = predecessor staged = staging is not None and bool(await staging.stage_revision_rows(revision, rows)) @@ -1905,9 +1911,9 @@ async def commit_revision_from_manifest( finality, now, acquisition, - retained_revision_id=retained.reporting_revision_id - if retained is not None - else None, + retained_revision_id=( + retained.reporting_revision_id if retained is not None else None + ), ) finally: if staged and staging is not None: @@ -1956,7 +1962,13 @@ async def _commit_publication( checked_at, _utc(boundary), next_due, - manifest.model_dump_json(), + manifest.model_dump_json( + exclude=( + {"data_through_precision"} + if manifest.data_through_precision is None + else None + ) + ), ), revision, rows, diff --git a/src/adcp/reporting/ledger/status.py b/src/adcp/reporting/ledger/status.py index bb3b564c7..8b771cb48 100644 --- a/src/adcp/reporting/ledger/status.py +++ b/src/adcp/reporting/ledger/status.py @@ -624,11 +624,15 @@ def _scope_data_through(projections: Any) -> datetime | None: A scope is only good through its *weakest* member: reporting the newest watermark would claim completeness the laggard has not delivered. """ - watermarks = [ - projection.current_revision.data_through + revisions = [ + projection.current_revision for projection in projections if projection.current_revision is not None - and projection.current_revision.data_through is not None + ] + if any(revision.data_through is None for revision in revisions): + return None + watermarks = [ + revision.data_through for revision in revisions if revision.data_through is not None ] return min(watermarks) if watermarks else None @@ -847,6 +851,8 @@ def _revision_to_wire( is the honest outcome, because the seller has not supplied what Core requires. """ + data_through_precision = revision.data_through_precision + assert data_through_precision is not None payload: dict[str, Any] = { "reporting_revision_id": revision.reporting_revision_id, "revision_content_sha256": revision.revision_content_sha256, @@ -854,7 +860,7 @@ def _revision_to_wire( "finality": revision.finality, "observed_at": _iso(revision.observed_at), "data_through": _iso(revision.data_through) if revision.data_through else None, - "data_through_precision": "exact" if revision.data_through else "unknown", + "data_through_precision": data_through_precision, "row_count": revision.row_count, "control_totals": [ _legacy_total_to_wire(name, value, obligation) diff --git a/src/adcp/reporting/ledger/store.py b/src/adcp/reporting/ledger/store.py index f55a83a8d..f402b95e2 100644 --- a/src/adcp/reporting/ledger/store.py +++ b/src/adcp/reporting/ledger/store.py @@ -648,6 +648,9 @@ def _revision_identity(revision: ReportingRevisionRecord) -> str: "obligation": revision.reporting_obligation_id, "supersedes": revision.supersedes_reporting_revision_id, } + if revision.data_through_precision == "lower_bound": + payload["data_through_precision"] = revision.data_through_precision + payload["data_through"] = _utc(revision.data_through).isoformat() # type: ignore[arg-type] if revision.canonical_content_digest is not None: payload["canonical_content_digest"] = revision.canonical_content_digest.to_wire() if revision.managed_control_totals is not None: @@ -661,7 +664,7 @@ def _revision_identity(revision: ReportingRevisionRecord) -> str: def managed_revision_metadata(revision: ReportingRevisionRecord) -> dict[str, Any]: """New evidence is exact; omit this block entirely for legacy replay hashes.""" - return { + metadata = { "account_id": revision.account_id, "created_at": _utc(revision.created_at).isoformat(), "observed_at": _utc(revision.observed_at).isoformat(), @@ -673,6 +676,9 @@ def managed_revision_metadata(revision: ReportingRevisionRecord) -> dict[str, An "source_publication_id": revision.source_publication_id, "source_manifest_sha256": revision.source_manifest_sha256, } + if revision.data_through_precision == "lower_bound": + metadata["data_through_precision"] = revision.data_through_precision + return metadata def validate_managed_revision_rows( @@ -716,6 +722,17 @@ def validate_retained_provisional_observation( raise LedgerConflictError( "REVISION_IMMUTABLE", "observation content differs from the snapshot predecessor" ) + from adcp.reporting.source import SourceBatchManifestV1 + + source_manifest = SourceBatchManifestV1.model_validate(manifest) + if revision.data_through_precision != source_manifest.resolved_data_through_precision or ( + revision.data_through_precision == "lower_bound" + and revision.data_through != source_manifest.data_through + ): + raise LedgerConflictError( + "REVISION_IMMUTABLE", + "observation data-through evidence differs from the snapshot predecessor", + ) from adcp.reporting.ledger.producer import recompute_revision_content_sha256 if len(rows) != revision.row_count: @@ -1181,6 +1198,12 @@ async def commit_revision( f"revision {revision.reporting_revision_id} already exists with " "different content; a restatement is a new revision", ) + if not revision_data_through_evidence_matches(existing, revision): + raise LedgerConflictError( + "REVISION_IMMUTABLE", + f"revision {revision.reporting_revision_id} already exists with " + "different data-through evidence", + ) return existing obligation = self._obligations.get(revision.reporting_obligation_id) if obligation is None or obligation.account_id != revision.account_id: @@ -1193,6 +1216,7 @@ async def commit_revision( "REPORTING_GENERATION_QUARANTINED", "legacy evidence is read-only" ) validate_revision_currency(obligation, revision, rows) + validate_revision_data_through(obligation, revision) siblings = [ item for item in self._revisions.values() @@ -2253,6 +2277,32 @@ def validate_revision_currency( validate_managed_total_units(obligation, revision.managed_control_totals) +def validate_revision_data_through( + obligation: ReportingObligationRecord, revision: ReportingRevisionRecord +) -> None: + """Require stored revision watermarks to belong to their obligation period.""" + if revision.data_through is None: + return + if not ( + _utc(obligation.period.start) <= _utc(revision.data_through) <= _utc(obligation.period.end) + ): + raise LedgerConflictError( + "INVALID_DATA_THROUGH", + "revision data_through must be inside the reporting obligation period", + ) + + +def revision_data_through_evidence_matches( + retained: ReportingRevisionRecord, proposed: ReportingRevisionRecord +) -> bool: + """Compare evidence added after legacy revision digests were frozen.""" + if retained.data_through_precision != proposed.data_through_precision: + return False + if retained.data_through_precision == "lower_bound": + return retained.data_through == proposed.data_through + return True + + def validate_adjustment_currency( obligation: ReportingObligationRecord, adjustment: ReportingAdjustmentRecord ) -> None: diff --git a/src/adcp/reporting/source.py b/src/adcp/reporting/source.py index 3963c500d..f48fabfad 100644 --- a/src/adcp/reporting/source.py +++ b/src/adcp/reporting/source.py @@ -77,6 +77,10 @@ model_validator, ) +from adcp.reporting._data_through import ( + ReportingDataThroughPrecision, + resolve_data_through_precision, +) from adcp.reporting.canonical_json import ( canonical_json_sha256_v1, canonical_json_utf8_v1, @@ -102,6 +106,7 @@ "ReportingConstituentCoverageV1", "ReportingContractIdentityV1", "ReportingCoverageStatus", + "ReportingDataThroughPrecision", "ReportingFinalityEvidenceV1", "ReportingManifestStrictness", "ReportingMetricAvailabilityV1", @@ -1367,7 +1372,8 @@ class SourceBatchManifestV1(_Frozen): supersedes_publication_id: OpaqueReference | None = None finality_evidence: ReportingFinalityEvidenceV1 observed_at: datetime - data_through: datetime + data_through: datetime | None + data_through_precision: ReportingDataThroughPrecision | None = None acquired_at: datetime currency: Annotated[str, StringConstraints(pattern=r"^[A-Z]{3}$")] requested_dimensions: list[MetricName] = Field(default_factory=list, max_length=1_000) @@ -1404,6 +1410,10 @@ def _manifest_is_internally_consistent(self) -> SourceBatchManifestV1: ) return self + @property + def resolved_data_through_precision(self) -> ReportingDataThroughPrecision: + return resolve_data_through_precision(self.data_through, self.data_through_precision) + # -- object set ------------------------------------------------------ def _validate_objects(self) -> None: @@ -1439,16 +1449,23 @@ def _validate_time_evidence(self) -> None: end = _aware(self.period.end, "period.end") cutoff = _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at") observed_at = _aware(self.observed_at, "observed_at") - data_through = _aware(self.data_through, "data_through") + precision = self.resolved_data_through_precision + data_through = ( + _aware(self.data_through, "data_through") if self.data_through is not None else None + ) acquired_at = _aware(self.acquired_at, "acquired_at") finality_at = _aware(self.finality_evidence.observed_at, "finality_evidence.observed_at") - if not (start <= data_through <= end): + if ( + precision != "unknown" + and data_through is not None + and not (start <= data_through <= end) + ): raise ValueError("data_through must be inside the reporting period") - if data_through > observed_at or data_through > cutoff: + if data_through is not None and (data_through > observed_at or data_through > cutoff): raise ValueError("data_through must not follow observed_at or the source read cutoff") if acquired_at < observed_at: raise ValueError("acquired_at must not precede the reported source observation") - if finality_at < data_through or finality_at > acquired_at: + if (data_through is not None and finality_at < data_through) or finality_at > acquired_at: raise ValueError( "finality evidence must be observed no earlier than data_through and " "no later than acquisition completion" @@ -1465,15 +1482,14 @@ def _validate_time_evidence(self) -> None: def _require_bounded_watermark(self, value: datetime, label: str) -> None: moment = _aware(value, f"{label} data_through") - if not ( - _aware(self.period.start, "period.start") - <= moment - <= min( - _aware(self.period.end, "period.end"), - _aware(self.data_through, "data_through"), - _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at"), - ) - ): + upper_bounds = [ + _aware(self.period.end, "period.end"), + _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at"), + _aware(self.observed_at, "observed_at"), + ] + if self.data_through is not None: + upper_bounds.append(_aware(self.data_through, "data_through")) + if not (_aware(self.period.start, "period.start") <= moment <= min(upper_bounds)): raise ValueError( f"granular {label} data_through must be inside the period and no later than " "the batch watermark or the requested source cutoff" @@ -1485,7 +1501,7 @@ def _validate_authoritative_full_window(self, end: datetime) -> None: # period boundary stays delayed/stale/partial instead. if self.publication_class != "AUTHORITATIVE" or self.coverage.status != "full": return - if _aware(self.data_through, "data_through") != end: + if self.data_through is None or _aware(self.data_through, "data_through") != end: raise ValueError("full authoritative coverage must prove the complete reporting window") for item in self.coverage.constituents: if item.status in _AVAILABLE_STATUSES and ( @@ -1617,8 +1633,11 @@ def _validate_event_range(self) -> None: raise ValueError("event-time range must start within the period") if event_end > _aware(self.period.end, "period.end"): raise ValueError("event-time range must end within the period") - if event_end > _aware(self.data_through, "data_through") or event_end > _aware( - self.period.source_read_cutoff_at, "period.source_read_cutoff_at" + if ( + self.data_through is not None and event_end > _aware(self.data_through, "data_through") + ) or event_end > min( + _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at"), + _aware(self.observed_at, "observed_at"), ): raise ValueError( "event-time range must end no later than data_through or the source cutoff" @@ -1803,6 +1822,8 @@ def __init__(self, code: str, message: str) -> None: def encode_source_batch_manifest_v1(manifest: SourceBatchManifestV1) -> bytes: """Seal a manifest into its ``canonical_json_utf8_v1`` bytes.""" payload = manifest.model_dump(mode="json", exclude_none=True) + if manifest.data_through is None: + payload["data_through"] = None encoded = canonical_json_utf8_v1(payload) if len(encoded) > SOURCE_BATCH_MANIFEST_MAX_BYTES_V1: raise SourceBatchManifestError( diff --git a/tests/conformance/reporting/_empty_ledger_support.py b/tests/conformance/reporting/_empty_ledger_support.py index 0c1f2d93c..05464c883 100644 --- a/tests/conformance/reporting/_empty_ledger_support.py +++ b/tests/conformance/reporting/_empty_ledger_support.py @@ -41,6 +41,7 @@ def _storage_split(): "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", "reporting_webhook_activity.sql", diff --git a/tests/conformance/reporting/_generation_support.py b/tests/conformance/reporting/_generation_support.py index def96d60d..cc7d46823 100644 --- a/tests/conformance/reporting/_generation_support.py +++ b/tests/conformance/reporting/_generation_support.py @@ -173,9 +173,9 @@ def revision_for( ), row_count=1, control_totals=totals, - observed_at=END, - data_through=END, - created_at=END, + observed_at=obligation.period.end, + data_through=obligation.period.end, + created_at=obligation.period.end, ), rows, ) diff --git a/tests/conformance/reporting/test_inline_cell_availability.py b/tests/conformance/reporting/test_inline_cell_availability.py index d5cb5786c..47bd6da81 100644 --- a/tests/conformance/reporting/test_inline_cell_availability.py +++ b/tests/conformance/reporting/test_inline_cell_availability.py @@ -128,6 +128,122 @@ async def _seal( ) +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +async def test_inline_source_seals_declared_data_through_precision(precision: Any) -> None: + request = _request() + watermark = request.period.start + timedelta(minutes=30) + + manifest = await _seal( + InlineFetchResult( + rows=[ROW], + data_through=watermark, + data_through_precision=precision, + ), + request, + ) + + assert manifest.data_through == watermark + assert manifest.data_through_precision == precision + + +async def test_inline_source_unknown_data_through_cannot_satisfy_full_coverage() -> None: + base = _request() + request = base.model_copy( + update={"coverage": base.coverage.model_copy(update={"expected": "full"})} + ) + source = _source( + lambda req: InlineFetchResult( + rows=[ROW], data_through=None, data_through_precision="unknown" + ) + ) + result = await source.execute(request, cancel=asyncio.Event()) + assert result.error is not None + assert result.error.code == "PARTIAL_RESULT" + + +async def test_inline_source_seals_unknown_data_through_for_partial_request() -> None: + request = _request() + manifest = await _seal( + InlineFetchResult(rows=[ROW], data_through=None, data_through_precision="unknown"), + request, + ) + assert manifest.data_through is None + assert manifest.data_through_precision == "unknown" + assert manifest.coverage.status == "none" + + +async def test_authoritative_unknown_full_cell_evidence_fails_before_staging() -> None: + request = _request(authoritative=True) + source = _source( + lambda req: InlineFetchResult( + rows=[ROW], + data_through=None, + data_through_precision="unknown", + cell_availability={ + CID: { + metric: MetricEvidence.present(req.period.end) + for metric in req.requested_metrics + } + }, + ) + ) + result = await source.execute(request, cancel=asyncio.Event()) + assert result.error is not None + assert result.error.code == "PARTIAL_RESULT" + assert source.staging._objects == {} + + +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +async def test_declared_batch_watermark_is_not_advanced_by_cell_evidence(precision: Any) -> None: + request = _request() + batch = request.period.start + timedelta(minutes=5) + cell = batch + timedelta(minutes=5) + with pytest.raises(ValueError, match="declared batch watermark"): + await _seal( + InlineFetchResult( + rows=[ROW], + data_through=batch, + data_through_precision=precision, + cell_availability={CID: {"impressions": MetricEvidence.present(cell)}}, + ), + request, + ) + + +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("unknown", OBSERVED_AT), + ("exact", None), + ("lower_bound", None), + ], +) +def test_inline_fetch_rejects_inconsistent_data_through_precision( + precision: Any, data_through: datetime | None +) -> None: + with pytest.raises(ValueError, match="data_through"): + InlineFetchResult( + rows=[ROW], + data_through=data_through, + data_through_precision=precision, + ) + + +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +async def test_inline_source_rejects_declared_watermark_outside_period(precision: Any) -> None: + request = _request() + + with pytest.raises(ValueError, match="inside the reporting period"): + await _seal( + InlineFetchResult( + rows=[ROW], + data_through=request.period.start - timedelta(seconds=1), + data_through_precision=precision, + ), + request, + ) + + @pytest.mark.parametrize("authoritative", [False, True], ids=["snapshot", "official"]) @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) async def test_one_constituent_has_four_independent_metric_statuses( diff --git a/tests/conformance/reporting/test_pg_reporting_ledger.py b/tests/conformance/reporting/test_pg_reporting_ledger.py index 2de8aff41..ded880b74 100644 --- a/tests/conformance/reporting/test_pg_reporting_ledger.py +++ b/tests/conformance/reporting/test_pg_reporting_ledger.py @@ -26,6 +26,7 @@ import os import secrets from collections.abc import AsyncIterator +from dataclasses import replace from datetime import datetime, timedelta, timezone import pytest @@ -270,6 +271,56 @@ async def test_obligation_round_trips_with_its_period(store: PgReportingLedgerSt assert loaded.scope_resolved_at == obligation.period.end +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("exact", _boundary().end), + ("lower_bound", _boundary().start + timedelta(minutes=30)), + ("unknown", None), + ], +) +async def test_revision_data_through_precision_round_trips( + store: PgReportingLedgerStore, + precision: str, + data_through: datetime | None, +) -> None: + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=data_through, + data_through_precision=precision, + ) + + committed = await store.commit_revision(revision, rows) + loaded = await store.get_revision( + account_id=ACCOUNT, + reporting_revision_id=committed.reporting_revision_id, + ) + + assert loaded == revision + assert loaded.data_through_precision == precision + + +async def test_revision_rejects_changed_lower_bound_on_replay( + store: PgReportingLedgerStore, +) -> None: + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=obligation.period.start, + data_through_precision="lower_bound", + ) + await store.commit_revision(revision, rows) + with pytest.raises(LedgerConflictError, match="different (content|data-through evidence)"): + await store.commit_revision( + replace(revision, data_through=obligation.period.start + timedelta(minutes=1)), rows + ) + + async def test_obligations_are_account_scoped(store: PgReportingLedgerStore) -> None: await store.put_configuration(_configuration()) obligation = await store.commit_obligation(_obligation(_configuration())) diff --git a/tests/conformance/reporting/test_reporting_caller_ownership.py b/tests/conformance/reporting/test_reporting_caller_ownership.py index 7059e090d..66185ebcb 100644 --- a/tests/conformance/reporting/test_reporting_caller_ownership.py +++ b/tests/conformance/reporting/test_reporting_caller_ownership.py @@ -366,7 +366,12 @@ async def test_maintenance_archive_backfill_preserves_evidence_and_never_replays await c.execute("SELECT to_jsonb(t) FROM reporting_revisions t") ).fetchone() )[0] - assert active_revision == original_revision + assert active_revision == { + **original_revision, + "data_through_precision": ( + "unknown" if original_revision["data_through"] is None else "exact" + ), + } assert await store.list_all_configurations() == () # A new service process starts over retained data without asking # for source authority or constructing workers for the old work. diff --git a/tests/conformance/reporting/test_reporting_core_lifecycle.py b/tests/conformance/reporting/test_reporting_core_lifecycle.py index 563400f9f..2e6d05dfe 100644 --- a/tests/conformance/reporting/test_reporting_core_lifecycle.py +++ b/tests/conformance/reporting/test_reporting_core_lifecycle.py @@ -725,6 +725,7 @@ async def test_the_status_projection_validates_as_adcp_wire( InlineFetchResult( rows=[{"media_buy_id": "mb_lifecycle", "impressions": 7, "spend": "0.03"}], data_through=first.end, + data_through_precision="lower_bound", ), ) await _run_worker_at(ledger, source, now=first.expected_at) @@ -742,7 +743,7 @@ async def test_the_status_projection_validates_as_adcp_wire( published = periods.revisions[0] assert str(published.report_definition_uri) == DEFINITION.report_definition_uri assert published.schema_sha256 == DEFINITION.schema_sha256 - assert published.data_through_precision is not None + assert published.data_through_precision == "lower_bound" exact = GetReportingStatusResponse.model_validate( await handler.handle( diff --git a/tests/conformance/reporting/test_reporting_data_through_precision_migration.py b/tests/conformance/reporting/test_reporting_data_through_precision_migration.py new file mode 100644 index 000000000..71f458fdf --- /dev/null +++ b/tests/conformance/reporting/test_reporting_data_through_precision_migration.py @@ -0,0 +1,100 @@ +"""Upgrade retained revision watermarks without inventing partial-source evidence.""" + +from __future__ import annotations + +from importlib.resources import files +from pathlib import Path + +import pytest + +from ._generation_support import isolated_reporting_pool, require_rolling_database + +FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" +MIGRATION = files("adcp_reporting_storage.ledger").joinpath( + "reporting_ledger_data_through_precision.sql" +) + + +@pytest.mark.parametrize( + ("clear_data_through", "expected_precision"), + [(False, "exact"), (True, "unknown")], +) +@pytest.mark.parametrize("autocommit", [False, True]) +async def test_migration_backfills_existing_revision_precision( + autocommit: bool, + clear_data_through: bool, + expected_precision: str, +) -> None: + require_rolling_database() + async with isolated_reporting_pool(autocommit=autocommit) as pool: + async with pool.connection() as connection: + await connection.execute((FIXTURES / "reporting_ledger_beta15.sql").read_text()) + await connection.execute((FIXTURES / "reporting_ledger_beta15_data.sql").read_text()) + if clear_data_through: + await connection.execute("UPDATE reporting_revisions SET data_through = NULL") + before = await ( + await connection.execute( + "SELECT reporting_revision_id, data_through, content_sha256 " + "FROM reporting_revisions" + ) + ).fetchall() + + await connection.execute(MIGRATION.read_text()) + await connection.execute(MIGRATION.read_text()) + + after = await ( + await connection.execute( + "SELECT reporting_revision_id, data_through, content_sha256, " + "data_through_precision FROM reporting_revisions" + ) + ).fetchall() + assert [row[:3] for row in after] == before + assert {row[3] for row in after} == {expected_precision} + + +async def test_database_rejects_invalid_revision_precision_pairings() -> None: + require_rolling_database() + from psycopg.errors import CheckViolation + + async with isolated_reporting_pool() as pool: + async with pool.connection() as connection: + await connection.execute((FIXTURES / "reporting_ledger_beta15.sql").read_text()) + await connection.execute((FIXTURES / "reporting_ledger_beta15_data.sql").read_text()) + await connection.execute(MIGRATION.read_text()) + + for precision, data_through in ( + ("unknown", "2026-09-01 01:00:00+00"), + ("exact", None), + ("lower_bound", None), + ("unsupported", "2026-09-01 01:00:00+00"), + ): + with pytest.raises(CheckViolation): + async with pool.connection() as connection: + await connection.execute( + "UPDATE reporting_revisions " + "SET data_through_precision = %s, data_through = %s", + (precision, data_through), + ) + + +async def test_migration_backfill_does_not_fire_revision_update_triggers() -> None: + require_rolling_database() + async with isolated_reporting_pool() as pool: + async with pool.connection() as connection: + await connection.execute((FIXTURES / "reporting_ledger_beta15.sql").read_text()) + await connection.execute((FIXTURES / "reporting_ledger_beta15_data.sql").read_text()) + await connection.execute( + """ + CREATE FUNCTION reject_retained_revision_update() RETURNS trigger + LANGUAGE plpgsql AS $$ BEGIN + RAISE EXCEPTION 'retained revision is immutable' USING ERRCODE = '23514'; + END $$; + CREATE TRIGGER reporting_reconciliation_reference_immutable + BEFORE UPDATE ON reporting_revisions FOR EACH ROW + EXECUTE FUNCTION reject_retained_revision_update() + """ + ) + await connection.execute(MIGRATION.read_text()) + assert await ( + await connection.execute("SELECT data_through_precision FROM reporting_revisions") + ).fetchone() == ("exact",) diff --git a/tests/conformance/reporting/test_reporting_feed_migration.py b/tests/conformance/reporting/test_reporting_feed_migration.py index 07ff2a81d..5e4be5f00 100644 --- a/tests/conformance/reporting/test_reporting_feed_migration.py +++ b/tests/conformance/reporting/test_reporting_feed_migration.py @@ -80,7 +80,7 @@ async def test_feed_migration_preserves_parent_catalog_receipts_pending_and_fair .read_text() ) ) - assert len(parent_manifest) == 767 + assert len(parent_manifest) == 770 assert {key: original[key] for key in parent_manifest} == parent_manifest assert original == {**parent_manifest, **PROVISIONAL_OBJECTS} new = PgReportingFeedStore(pool=pool, notifications=notifications) diff --git a/tests/conformance/reporting/test_reporting_notification_migration.py b/tests/conformance/reporting/test_reporting_notification_migration.py index 0f34c401d..ddfa7f88b 100644 --- a/tests/conformance/reporting/test_reporting_notification_migration.py +++ b/tests/conformance/reporting/test_reporting_notification_migration.py @@ -29,6 +29,7 @@ "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", ) diff --git a/tests/conformance/reporting/test_reporting_period_retirement_pg.py b/tests/conformance/reporting/test_reporting_period_retirement_pg.py index 543d528ca..1a120e5da 100644 --- a/tests/conformance/reporting/test_reporting_period_retirement_pg.py +++ b/tests/conformance/reporting/test_reporting_period_retirement_pg.py @@ -2,6 +2,8 @@ from __future__ import annotations +from dataclasses import replace +from datetime import timedelta from pathlib import Path from typing import Any @@ -98,13 +100,18 @@ async def test_the_window_is_anchored_at_the_newest_record_and_may_be_lengthened obligation = await seeded(store) rows = many_rows(3) await store.commit_revision(typed_revision(obligation, rows, suffix="a"), rows) - await age(pool, days=500) + age_days = 500 + await age(pool, days=age_days) assert (await store.retire_expired_periods(ledger_record_retention_days=3650)).retired == 0 # A newer revision moves the anchor: the period is not retired until it ages too. newest = typed_revision(obligation, rows, suffix="b", supersedes="rpr_acct_a_a") + newest = replace( + newest, + data_through=obligation.period.end - timedelta(days=age_days), + ) await store.commit_revision(newest, rows) assert (await store.retire_expired_periods()).retired == 0 - await age(pool, days=500) + await age(pool, days=age_days) assert (await store.retire_expired_periods()).retired == 1 for bad in (0, 10_001): with pytest.raises(ValueError): diff --git a/tests/conformance/reporting/test_reporting_provisional_catalog.py b/tests/conformance/reporting/test_reporting_provisional_catalog.py index c1e97a845..ba3f72958 100644 --- a/tests/conformance/reporting/test_reporting_provisional_catalog.py +++ b/tests/conformance/reporting/test_reporting_provisional_catalog.py @@ -24,7 +24,7 @@ @pytest.mark.parametrize("autocommit", [False, True]) -async def test_atomic_observation_bootstrap_preserves_exact_767_parent_objects( +async def test_atomic_observation_bootstrap_preserves_exact_770_parent_objects( autocommit, monkeypatch ): # This is a source-level DDL control, not installed historical-binary proof. @@ -34,6 +34,7 @@ async def test_atomic_observation_bootstrap_preserves_exact_767_parent_objects( "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", "reporting_webhook_activity.sql", @@ -56,7 +57,7 @@ async def test_atomic_observation_bootstrap_preserves_exact_767_parent_objects( .read_text() ) ) - assert len(expected_parent) == 767 + assert len(expected_parent) == 770 async with isolated_reporting_pool(autocommit=autocommit) as pool: async with pool.connection() as connection, connection.transaction(): for name in chain: diff --git a/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py b/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py index 43ce63d73..a63fb9635 100644 --- a/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py +++ b/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py @@ -68,14 +68,14 @@ async def test_exact_catalog_scope_preserves_full_contract_and_excludes_overload .read_text() ) ) - assert len(expected) == 792 and len(PROVISIONAL_REQUIRED_OBJECTS) == 25 + assert len(expected) == 795 and len(PROVISIONAL_REQUIRED_OBJECTS) == 25 async with isolated_reporting_pool(autocommit=autocommit) as pool: await PgReportingReceiptStore(pool=pool).create_schema() async with pool.connection() as connection: full = CatalogProbe(connection) assert await schema_objects(full) == expected assert len(full.calls) == 6 - assert sum(len(rows) for _, _, rows in full.calls) == 792 + assert sum(len(rows) for _, _, rows in full.calls) == 795 await connection.execute( "CREATE TABLE reporting_unrelated_catalog_scope (value integer);" " CREATE FUNCTION reporting_provisional_immutable(integer) RETURNS integer" diff --git a/tests/conformance/reporting/test_reporting_status_wire_contract.py b/tests/conformance/reporting/test_reporting_status_wire_contract.py index a8875622a..9822dc77b 100644 --- a/tests/conformance/reporting/test_reporting_status_wire_contract.py +++ b/tests/conformance/reporting/test_reporting_status_wire_contract.py @@ -98,6 +98,45 @@ async def test_whole_summary_and_periods_schema_including_empty_scope(status_har assert response["scope"]["media_buy_ids"] == ["mb_acct_a"] +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("exact", END), + ("lower_bound", END - timedelta(minutes=5)), + ("unknown", None), + ], +) +async def test_period_status_preserves_revision_data_through_precision( + status_harness, precision, data_through +): + h = status_harness + config = configuration() + await h.ledger.put_configuration(config) + obligation = obligation_for(config) + await h.ledger.commit_obligation(obligation) + revision, rows = revision_for(obligation) + await h.ledger.commit_revision( + replace( + revision, + data_through=data_through, + data_through_precision=precision, + ), + rows, + ) + + response = ReportingStatusHandler(h.ledger).render_snapshot( + {"view": "periods"}, + caller=CALLER, + snapshot=await h.ledger.read_status_snapshot(caller=OwnershipCaller("acct_a", "buyer")), + ) + + validate_read(response) + assert response["revisions"][0]["data_through_precision"] == precision + assert response["revisions"][0]["data_through"] == ( + data_through.isoformat().replace("+00:00", "Z") if data_through else None + ) + + async def test_current_unreadable_leaf_cannot_be_masked_by_a_readable_superseded_revision( status_harness, ): diff --git a/tests/fixtures/public_api_snapshot.json b/tests/fixtures/public_api_snapshot.json index 48f3b62c8..21d103cb5 100644 --- a/tests/fixtures/public_api_snapshot.json +++ b/tests/fixtures/public_api_snapshot.json @@ -840,6 +840,7 @@ "ReportingControlTotalRecord": "adcp.reporting.evidence", "ReportingCurrencyError": "adcp.reporting.currency", "ReportingCurrentRevisionsPageV1": "adcp.reporting.ledger.host_reads", + "ReportingDataThroughPrecision": "union[value:'exact',value:'lower_bound',value:'unknown']", "ReportingDefinitionBinding": "adcp.reporting.ledger.models", "ReportingDeliveryEscalation": "adcp.reporting.ledger.models", "ReportingDeliveryPrincipal": "adcp.reporting.ledger.delivery_models", diff --git a/tests/test_reporting_ledger.py b/tests/test_reporting_ledger.py index e6dc209e4..0609fbb13 100644 --- a/tests/test_reporting_ledger.py +++ b/tests/test_reporting_ledger.py @@ -8,6 +8,7 @@ from __future__ import annotations +from dataclasses import fields, replace from datetime import datetime, timedelta, timezone from typing import Any, cast @@ -175,6 +176,95 @@ def test_both_sides_derive_the_same_period_and_expected_at() -> None: assert boundary.expected_at == datetime(2026, 9, 1, 3, 0, tzinfo=timezone.utc) +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("unknown", datetime(2026, 9, 1, 2, tzinfo=timezone.utc)), + ("exact", None), + ("lower_bound", None), + ], +) +def test_revision_rejects_inconsistent_data_through_precision( + precision: Any, data_through: datetime | None +) -> None: + obligation = _obligation(_configuration()) + + with pytest.raises(ValueError, match="data_through"): + _revision( + obligation, + data_through=data_through, + data_through_precision=precision, + ) + + +@pytest.mark.parametrize( + ("data_through", "precision"), + [ + (datetime(2026, 9, 1, 2, tzinfo=timezone.utc), "exact"), + (None, "unknown"), + ], +) +def test_revision_defaults_data_through_precision_for_existing_callers( + data_through: datetime | None, precision: str +) -> None: + obligation = _obligation(_configuration()) + + revision, _ = _revision(obligation, data_through=data_through) + + assert revision.data_through_precision == precision + + +def test_revision_data_through_precision_does_not_shift_positional_arguments() -> None: + precision = next( + item for item in fields(ReportingRevisionRecord) if item.name == "data_through_precision" + ) + assert precision.kw_only + + +async def test_revision_rejects_watermark_outside_obligation_period() -> None: + store = InMemoryReportingLedgerStore() + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=obligation.period.end + timedelta(seconds=1), + data_through_precision="lower_bound", + ) + with pytest.raises(LedgerConflictError, match="inside the reporting obligation period"): + await store.commit_revision(revision, rows) + + +async def test_revision_replay_rejects_changed_data_through_evidence() -> None: + store = InMemoryReportingLedgerStore() + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=obligation.period.start, + data_through_precision="lower_bound", + ) + await store.commit_revision(revision, rows) + with pytest.raises(LedgerConflictError, match="different (content|data-through evidence)"): + await store.commit_revision( + replace(revision, data_through=obligation.period.start + timedelta(minutes=1)), rows + ) + + +async def test_revision_replay_rejects_exact_to_unknown_precision_change() -> None: + store = InMemoryReportingLedgerStore() + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision(obligation) + await store.commit_revision(revision, rows) + with pytest.raises(LedgerConflictError, match="different data-through evidence"): + await store.commit_revision( + replace(revision, data_through=None, data_through_precision="unknown"), rows + ) + + def test_expected_at_is_always_period_end_plus_the_sla() -> None: schedule = ReportingScheduleSpec(period_duration="P1D", delivery_sla="PT6H") boundary = derive_period(schedule, account_timezone="UTC", ordinal=100) @@ -722,6 +812,25 @@ async def test_scope_data_through_is_the_weakest_member() -> None: assert payload["data_through"] == early.period.end.isoformat().replace("+00:00", "Z") +async def test_scope_data_through_is_unknown_when_one_satisfied_member_is_unknown() -> None: + store = InMemoryReportingLedgerStore(clock=lambda: datetime(2026, 9, 30, tzinfo=timezone.utc)) + configuration = _configuration() + await store.put_configuration(configuration) + obligations = ( + await store.commit_obligation(_obligation(configuration, ordinal=1)), + await store.commit_obligation( + _obligation(configuration, ordinal=2, reporting_obligation_id="rpo_2") + ), + ) + for index, obligation in enumerate(obligations): + revision, rows = _revision(obligation, reporting_revision_id=f"rpr_{index}") + if index: + revision = replace(revision, data_through=None, data_through_precision="unknown") + await store.commit_revision(revision, rows) + payload = await ReportingStatusHandler(store).handle({"view": "summary"}, caller=CALLER) + assert payload["data_through"] is None + + # -- consumer status preview ------------------------------------------------ diff --git a/tests/test_reporting_source_contract.py b/tests/test_reporting_source_contract.py index 0814b4328..3554897ec 100644 --- a/tests/test_reporting_source_contract.py +++ b/tests/test_reporting_source_contract.py @@ -80,6 +80,8 @@ def _rebind(manifest: SourceBatchManifestV1, **updates) -> SourceBatchManifestV1 """ draft = SourceBatchManifestV1.model_construct(**{**dict(manifest), **updates}) payload = draft.model_dump(mode="json", exclude_none=True) + if draft.data_through is None: + payload["data_through"] = None payload["content_fingerprint"] = publication_content_fingerprint_v1(draft) return SourceBatchManifestV1.model_validate(payload) @@ -99,6 +101,107 @@ def test_manifest_preserves_declared_source_stability_evidence() -> None: assert encode_source_batch_manifest_v1(retained) == manifest_bytes +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +def test_manifest_accepts_declared_data_through_precision(precision: str) -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + + rebound = _rebind(manifest, data_through_precision=precision) + + assert rebound.data_through_precision == precision + assert rebound.resolved_data_through_precision == precision + + +def test_manifest_accepts_unknown_data_through() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + + rebound = _rebind( + manifest, + data_through=None, + data_through_precision="unknown", + ) + + assert rebound.data_through is None + assert rebound.resolved_data_through_precision == "unknown" + + +def test_unknown_batch_still_bounds_granular_watermarks_by_observation() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + with pytest.raises(ValidationError, match="granular .* data_through"): + _rebind( + manifest, + observed_at=manifest.period.start, + data_through=None, + data_through_precision="unknown", + ) + + +def test_unknown_batch_still_bounds_event_range_by_observation() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + cells = [ + cell.model_copy(update={"data_through": manifest.period.start}) + for cell in manifest.metric_availability + ] + constituents = [ + item.model_copy(update={"data_through": manifest.period.start}) + for item in manifest.coverage.constituents + ] + with pytest.raises(ValidationError, match="event-time range"): + _rebind( + manifest, + observed_at=manifest.period.start, + data_through=None, + data_through_precision="unknown", + metric_availability=cells, + coverage=manifest.coverage.model_copy(update={"constituents": constituents}), + ) + + +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("unknown", datetime(2026, 11, 1, 1, tzinfo=timezone.utc)), + ("exact", None), + ("lower_bound", None), + ], +) +def test_manifest_rejects_inconsistent_data_through_precision( + precision: str, data_through: datetime | None +) -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + + with pytest.raises(ValidationError, match="data_through"): + _rebind( + manifest, + data_through=data_through, + data_through_precision=precision, + ) + + +@pytest.mark.parametrize("offset", [timedelta(seconds=-1), timedelta(seconds=1)]) +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +def test_declared_data_through_must_be_inside_the_period(precision: str, offset: timedelta) -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + boundary = manifest.period.start if offset < timedelta() else manifest.period.end + + with pytest.raises(ValidationError, match="inside the reporting period"): + _rebind( + manifest, + data_through=boundary + offset, + data_through_precision=precision, + ) + + +def test_omitted_data_through_precision_preserves_manifest_bytes() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + manifest_bytes = encode_source_batch_manifest_v1(manifest) + + retained = SourceBatchManifestV1.model_validate_json(manifest_bytes) + + assert "data_through_precision" not in retained.model_dump(exclude_none=True) + assert retained.resolved_data_through_precision == "exact" + assert encode_source_batch_manifest_v1(retained) == manifest_bytes + + # -- capability admission ---------------------------------------------------