diff --git a/packages/adcp-reporting-storage/README.md b/packages/adcp-reporting-storage/README.md index 89ed1d154..8493aa2c6 100644 --- a/packages/adcp-reporting-storage/README.md +++ b/packages/adcp-reporting-storage/README.md @@ -76,7 +76,8 @@ Install `adcp>=10.0.0b7` with this release. | 0.2.0b0 | 1 | `>=9.0.0,<11` (**do not pair with 10.0.0b4+**: 10.0.0b4 and b5 install beside it and fail, b7+ refuse it, [#1763](https://github.com/adcontextprotocol/adcp-client-python/issues/1763)) | | 0.2.0b1–0.2.0b4 | 2 | `>=10.0.0b4,<11` | | 0.2.0b5–0.2.0b9 | 3 | first adcp of contract 3 (10.0.0b24) | -| 0.2.0b11+ | 4 | first adcp of contract 4 (10.2.0); 0.2.0b10 was never published | +| 0.2.0b11 | 4 | first adcp of contract 4 (10.2.0); 0.2.0b10 was never published | +| 0.2.0b12+ | 5 | first adcp of contract 5 (10.2.2) | `adcp` never imports this package; a test in the main repository enforces that. diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py index 84cf97a13..8dc249e5d 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py @@ -17,7 +17,9 @@ ``all_media_buys``; schema migration ``0009``). Shipped by adcp-reporting-storage 0.2.0b5 through 0.2.0b9. * **4** — ``data_through_precision`` on revisions (schema migration ``0011``). Shipped by - adcp-reporting-storage 0.2.0b10 and later. + adcp-reporting-storage 0.2.0b10 and 0.2.0b11. +* **5** — materialized reporting-status walk headers and ordinal records + (schema migration ``0012``). Shipped by adcp-reporting-storage 0.2.0b12 and later. :func:`require_adcp_contract` runs when a PostgreSQL ledger store is built, so an incompatible pair fails at startup with the pair named and the fix spelled @@ -32,11 +34,11 @@ __all__ = ["STORAGE_CONTRACT", "adcp_storage_contract", "require_adcp_contract"] #: The reporting storage contract this distribution's DDL and stores implement. -STORAGE_CONTRACT = 4 +STORAGE_CONTRACT = 5 #: The first adcp release that reads the ledger with :data:`STORAGE_CONTRACT`. -_FIRST_ADCP = "10.2.0" +_FIRST_ADCP = "10.2.2" #: The last adcp-reporting-storage release of each earlier contract. -_LAST_STORAGE = {1: "0.2.0b0", 2: "0.2.0b4", 3: "0.2.0b9"} +_LAST_STORAGE = {1: "0.2.0b0", 2: "0.2.0b4", 3: "0.2.0b9", 4: "0.2.0b11"} def adcp_storage_contract() -> int: 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 919ca444c..401d5b729 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 @@ -85,7 +85,7 @@ from datetime import datetime, timedelta, timezone from pathlib import Path from time import monotonic -from typing import TYPE_CHECKING, Any, ClassVar, Literal +from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast _BOUND_CONNECTION: ContextVar[tuple[object, object, Any] | None] = ContextVar( "reporting_bound_connection", default=None @@ -172,6 +172,7 @@ from adcp.reporting._source_authorization import InlineSealPublisher from adcp.reporting.inline_source import ReportingSealStore, SealedSlice from adcp.reporting.ledger.status_projection import ReportingStatusSnapshot + from adcp.reporting.ledger.status_snapshot import ReportingStatusWalk, ReportingStatusWalkPage from adcp_reporting_storage.ledger.change_feed import ( ReportingChangeKindV1, ReportingChangesPageV1, @@ -3376,6 +3377,154 @@ async def read_status_snapshot(self, *, caller: ReportingCaller) -> ReportingSta ) from error return private_snapshot(settled, principal) + async def save_status_walk(self, walk: ReportingStatusWalk, *, ttl: timedelta) -> None: + """Persist a projected periods walk and retire one unlocked expired walk.""" + if ttl <= timedelta(0): + raise ValueError("status walk ttl must be positive") + async with self._connection() as connection, connection.transaction(): + if not await self._status_walks_ready(connection): + return + await connection.execute( + "WITH expired AS (" + " SELECT walk_id FROM reporting_status_walks" + " WHERE expires_at <= now() ORDER BY expires_at, walk_id" + " FOR UPDATE SKIP LOCKED LIMIT 1" + ") DELETE FROM reporting_status_walks w USING expired e" + " WHERE w.walk_id = e.walk_id" + ) + await connection.execute( + "INSERT INTO reporting_status_walks" + " (walk_id, account_id, consumer_id, snapshot_id, source_sequence," + " lower_sequence, ledger_as_of, filters, header, total_count, expires_at)" + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s::jsonb, %s, now() + %s)" + " ON CONFLICT (walk_id) DO UPDATE SET" + " expires_at = GREATEST(reporting_status_walks.expires_at, EXCLUDED.expires_at)", + ( + walk.walk_id, + walk.account_id, + walk.consumer_id, + walk.snapshot_id, + walk.source_sequence, + walk.lower, + walk.as_of, + _json(walk.filters), + _json(walk.header), + len(walk.records), + ttl, + ), + ) + if walk.records: + await connection.cursor().executemany( + "INSERT INTO reporting_status_walk_records" + " (walk_id, ordinal, record_kind, payload, node_count)" + " VALUES (%s, %s, %s, %s::jsonb, %s)" + " ON CONFLICT (walk_id, ordinal) DO NOTHING", + [ + ( + walk.walk_id, + record.ordinal, + record.kind, + _json(record.payload), + record.node_count, + ) + for record in walk.records + ], + ) + + async def read_status_walk_page( + self, + *, + caller: ReportingCaller, + walk_id: str, + offset: int, + limit: int, + ) -> ReportingStatusWalkPage | None: + """Read one bounded ordinal slice while fencing expiry cleanup.""" + from adcp.reporting.ledger.status_snapshot import ( + ReportingStatusWalk, + ReportingStatusWalkPage, + ReportingStatusWalkRecord, + StatusWalkRecordKind, + ) + + async with self._connection() as connection, connection.transaction(): + if not await self._status_walks_ready(connection): + return None + row = await ( + await connection.execute( + "SELECT walk_id, account_id, consumer_id, snapshot_id, source_sequence," + " lower_sequence, ledger_as_of, filters, header, total_count" + " FROM reporting_status_walks" + " WHERE walk_id = %s AND account_id = %s AND consumer_id = %s" + " AND expires_at > now() FOR SHARE", + (walk_id, caller.account_id, caller.consumer_id), + ) + ).fetchone() + if row is None: + return None + boundary = await ( + await connection.execute( + "SELECT COALESCE(MAX(seq), 0) FROM reporting_ledger_changes" + " WHERE account_id=%s AND consumer_id=%s AND record_kind IN" + " ('obligation','revision','adjustment','consumer_status')", + (caller.account_id, caller.consumer_id), + ) + ).fetchone() + assert boundary is not None + if int(boundary[0]) != int(row[4]): + raise LedgerConflictError( + "CURSOR_SNAPSHOT_MISMATCH", + "this cursor belongs to a changed ledger snapshot; restart the walk", + ) + record_rows = await ( + await connection.execute( + "SELECT ordinal, record_kind, payload, node_count" + " FROM reporting_status_walk_records" + " WHERE walk_id = %s AND ordinal >= %s" + " ORDER BY ordinal LIMIT %s", + (walk_id, offset, limit), + ) + ).fetchall() + expected = min(limit, max(0, int(row[9]) - offset)) + if len(record_rows) != expected or any( + int(item[0]) != offset + index for index, item in enumerate(record_rows) + ): + return None + records = tuple( + ReportingStatusWalkRecord( + int(item[0]), + cast(StatusWalkRecordKind, item[1]), + dict(item[2]), + int(item[3]), + ) + for item in record_rows + ) + walk = ReportingStatusWalk( + row[0], + row[1], + row[2], + row[3], + int(row[4]), + int(row[5]), + _utc(row[6]), + dict(row[7]), + dict(row[8]), + records, + ) + return ReportingStatusWalkPage(walk, int(row[9])) + + @staticmethod + async def _status_walks_ready(connection: Any) -> bool: + row = await ( + await connection.execute( + "SELECT to_regclass(quote_ident(current_schema())" + " || '.reporting_status_walks') IS NOT NULL" + " AND to_regclass(quote_ident(current_schema())" + " || '.reporting_status_walk_records') IS NOT NULL" + ) + ).fetchone() + return bool(row and row[0]) + async def _settled_status_snapshot(self, account_id: str) -> ReportingStatusSnapshot: from adcp_reporting_storage.ledger.status_snapshot import settle_snapshot_on diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/0012_reporting_status_walks.sql b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/0012_reporting_status_walks.sql new file mode 100644 index 000000000..84cc84f42 --- /dev/null +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/0012_reporting_status_walks.sql @@ -0,0 +1,32 @@ +-- adcp-migration: 0012 reporting_status_walks +-- adcp-upgrade: additive +-- Materialized get_reporting_status periods walks. Additive: earlier workers +-- do not read or write these tables, and the ledger evidence remains unchanged. + +CREATE TABLE IF NOT EXISTS reporting_status_walks ( + walk_id TEXT PRIMARY KEY, + account_id TEXT NOT NULL, + consumer_id TEXT NOT NULL, + snapshot_id TEXT NOT NULL, + source_sequence BIGINT NOT NULL CHECK (source_sequence >= 0), + lower_sequence BIGINT NOT NULL CHECK (lower_sequence >= 0), + ledger_as_of TIMESTAMPTZ NOT NULL, + filters JSONB NOT NULL, + header JSONB NOT NULL, + total_count INTEGER NOT NULL CHECK (total_count >= 0), + expires_at TIMESTAMPTZ NOT NULL +); + +CREATE INDEX IF NOT EXISTS reporting_status_walks_expires_idx + ON reporting_status_walks (expires_at, walk_id); + +CREATE TABLE IF NOT EXISTS reporting_status_walk_records ( + walk_id TEXT NOT NULL REFERENCES reporting_status_walks(walk_id) ON DELETE CASCADE, + ordinal INTEGER NOT NULL CHECK (ordinal >= 0), + record_kind TEXT NOT NULL CHECK ( + record_kind IN ('obligation', 'revision', 'adjustment', 'consumer_status') + ), + payload JSONB NOT NULL, + node_count INTEGER NOT NULL CHECK (node_count >= 0), + PRIMARY KEY (walk_id, ordinal) +); diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py index 08fb869d7..bffc33f07 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py @@ -45,7 +45,7 @@ starts on a ledger whose only pending migration is a contract step. A migration after a waiting contract step is applied only when it is -``additive`` (``0008``–``0011``); the walk stops at the first +``additive`` (``0008``–``0012``); the walk stops at the first one that is not, since it may depend on the contract. An additive migration is therefore applied, and recorded, before the contract step it follows. """ diff --git a/src/adcp/reporting/ledger/__init__.py b/src/adcp/reporting/ledger/__init__.py index 6f58469d1..43463eff1 100644 --- a/src/adcp/reporting/ledger/__init__.py +++ b/src/adcp/reporting/ledger/__init__.py @@ -223,7 +223,13 @@ StatusProjectionResult, project_status_scope, ) -from adcp.reporting.ledger.status_snapshot import ReportingStatusParticipant +from adcp.reporting.ledger.status_snapshot import ( + ReportingStatusParticipant, + ReportingStatusWalk, + ReportingStatusWalkPage, + ReportingStatusWalkParticipant, + ReportingStatusWalkRecord, +) from adcp.reporting.ledger.store import ( InMemoryReportingLedgerStore, LeasedConfiguration, @@ -295,6 +301,10 @@ "StatusProjectionResult", "project_status_scope", "ReportingStatusParticipant", + "ReportingStatusWalk", + "ReportingStatusWalkPage", + "ReportingStatusWalkParticipant", + "ReportingStatusWalkRecord", "ConsumerMismatch", "ConsumerStatusDisabledError", "ConsumerStatusIngest", diff --git a/src/adcp/reporting/ledger/status.py b/src/adcp/reporting/ledger/status.py index 5ac6b88a2..6d17e42aa 100644 --- a/src/adcp/reporting/ledger/status.py +++ b/src/adcp/reporting/ledger/status.py @@ -32,9 +32,10 @@ import hashlib import logging from collections.abc import Mapping, Sequence +from copy import deepcopy from dataclasses import dataclass, replace from datetime import datetime, timedelta, timezone -from typing import Any, Literal +from typing import Any, Literal, cast from adcp._version import ( is_adcp_version_at_least, @@ -67,6 +68,13 @@ project_status_scope, status_retained_from, ) +from adcp.reporting.ledger.status_snapshot import ( + ReportingStatusWalk, + ReportingStatusWalkPage, + ReportingStatusWalkParticipant, + ReportingStatusWalkRecord, + StatusWalkRecordKind, +) from adcp.reporting.ledger.store import ( LedgerConflictError, ReportingLedgerStore, @@ -112,6 +120,7 @@ } _STATUS_ISSUE_LIMIT = 100 _ISSUE_SEVERITY_PRIORITY = {"action_required": 0, "delayed": 1, "info": 2} +_DEFAULT_STATUS_WALK_TTL = timedelta(minutes=15) def _utc(value: datetime) -> datetime: @@ -173,6 +182,8 @@ class ReportingStatusHandler: ``ledger_as_of`` at that boundary while the period's obligation is not yet committed. Defaults to :data:`~adcp.reporting.ledger.period_close.DEFAULT_PERIOD_CLOSE_GRACE`. + status_walk_ttl: How long a store may retain a materialized periods + walk for cursor continuations. Defaults to 15 minutes. """ def __init__( @@ -184,6 +195,7 @@ def __init__( consumer_status_enabled: bool = False, escalation: ReportingDeliveryEscalation | None = None, period_close_grace: timedelta = DEFAULT_PERIOD_CLOSE_GRACE, + status_walk_ttl: timedelta = _DEFAULT_STATUS_WALK_TTL, ) -> None: if type(page_size) is not int or page_size < 1: raise ValueError("page_size must be a positive integer") @@ -193,12 +205,15 @@ def __init__( raise ValueError("page_node_budget must be a positive integer or None") if not isinstance(period_close_grace, timedelta) or period_close_grace < timedelta(0): raise ValueError("period_close_grace must be a non-negative timedelta") + if not isinstance(status_walk_ttl, timedelta) or status_walk_ttl <= timedelta(0): + raise ValueError("status_walk_ttl must be a positive timedelta") self._store = store self._page_size = page_size self._page_node_budget = page_node_budget self._consumer_status_enabled = consumer_status_enabled self._escalation = escalation self._period_close_grace = period_close_grace + self._status_walk_ttl = status_walk_ttl @property def page_size(self) -> int: @@ -226,9 +241,159 @@ def _page_limit(self, request: Mapping[str, Any]) -> int: async def handle( self, request: dict[str, Any], *, caller: ReportingStatusCaller ) -> dict[str, Any]: + if request.get("view", "summary") == "periods" and isinstance( + self._store, ReportingStatusWalkParticipant + ): + cursor = (request.get("pagination") or {}).get("cursor") + decoded = decode_cursor(cursor) if cursor else None + if decoded is not None and isinstance(decoded.get("walk"), str): + page = await self._read_status_walk_page( + request, + caller=caller, + decoded=decoded, + ) + if page is not None: + return self._render_status_walk_page( + request, + caller=caller, + page=page, + offset=decoded.get("offset"), + ) + snapshot = await self._load(caller) + response, walk = self._render_snapshot_result( + request, + caller=caller, + snapshot=snapshot, + materialize_walk=True, + ) + if walk is not None and response["pagination"]["has_more"]: + await self._store.save_status_walk(walk, ttl=self._status_walk_ttl) + return response snapshot = await self._load(caller) return self.render_snapshot(request, caller=caller, snapshot=snapshot) + async def _read_status_walk_page( + self, + request: dict[str, Any], + *, + caller: ReportingStatusCaller, + decoded: dict[str, Any], + ) -> ReportingStatusWalkPage | None: + _require_owned_cursor(decoded, caller=caller) + offset = decoded.get("offset") + if type(offset) is not int or offset < 0: + raise LedgerConflictError("INVALID_CURSOR", "the pagination cursor offset is invalid") + participant = cast(ReportingStatusWalkParticipant, self._store) + return await participant.read_status_walk_page( + caller=caller, + walk_id=decoded["walk"], + offset=offset, + limit=self._page_limit(request), + ) + + def _render_status_walk_page( + self, + request: dict[str, Any], + *, + caller: ReportingStatusCaller, + page: ReportingStatusWalkPage, + offset: Any, + ) -> dict[str, Any]: + walk = page.walk + if type(offset) is not int or offset < 0: + raise LedgerConflictError("INVALID_CURSOR", "the pagination cursor offset is invalid") + filters = _filters(request) + version = normalize_to_release_precision( + request.get("adcp_version") or resolve_adcp_version(None) + ) + if is_adcp_version_at_least(version, "3.2-rc.6"): + filters["adcp_version"] = version + if filters != walk.filters: + raise LedgerConflictError( + "CURSOR_SNAPSHOT_MISMATCH", + "this cursor belongs to a different snapshot, caller or filter set;" + " restart the walk", + ) + cursor = (request.get("pagination") or {}).get("cursor") + if cursor: + decoded = decode_cursor(cursor) + _require_owned_cursor(decoded, caller=caller) + cursor_lower = decoded.get("lower") + if ( + decoded.get("snapshot") != walk.snapshot_id + or (decoded.get("walk") is not None and decoded.get("walk") != walk.walk_id) + or decoded.get("as_of") != walk.as_of.isoformat() + or type(cursor_lower) is not int + or cursor_lower != walk.lower + ): + raise LedgerConflictError( + "CURSOR_SNAPSHOT_MISMATCH", + "this cursor does not bind this materialized walk; restart the walk", + ) + explicit_lower = _checkpoint_sequence(request.get("changes_after"), caller=caller) + if "changes_after" in request and explicit_lower != walk.lower: + raise LedgerConflictError( + "CURSOR_SNAPSHOT_MISMATCH", + "this cursor belongs to a different incremental lower bound; restart the walk", + ) + records: dict[str, list[dict[str, Any]]] = { + "periods": [], + "revisions": [], + "adjustments": [], + "consumer_statuses": [], + } + payload = { + **deepcopy(walk.header), + "periods": records["periods"], + "revisions": records["revisions"], + "adjustments": records["adjustments"], + "pagination": {"total_count": page.total_count, "has_more": True, "cursor": ""}, + } + if "consumer_statuses" in walk.header: + payload["consumer_statuses"] = records["consumer_statuses"] + budget = self._page_node_budget + base_nodes = count_payload_nodes(payload) + page_nodes = base_nodes + taken = 0 + for record in walk.records: + if record.ordinal != offset + taken: + raise LedgerConflictError( + "STATUS_PROJECTION_UNAVAILABLE", "status walk ordinals are incomplete" + ) + if budget is not None and taken and page_nodes + record.node_count > budget: + break + records[_PAGE_RECORD_KEYS[record.kind]].append(deepcopy(record.payload)) + page_nodes += record.node_count + taken += 1 + if budget is not None and page_nodes > budget: + logger.warning( + "get_reporting_status periods page for account %s is %d nodes (%d of" + " scope and issues, %d record(s)), over the %d page node budget", + caller.account_id, + page_nodes, + base_nodes, + taken, + budget, + ) + has_more = offset + taken < page.total_count + cursor_payload = { + "ownership": 2, + "account": caller.account_id, + "consumer": caller.consumer_id, + "snapshot": walk.snapshot_id, + "offset": offset + taken, + "lower": walk.lower, + "as_of": walk.as_of.isoformat(), + } + if walk.walk_id: + cursor_payload["walk"] = walk.walk_id + payload["pagination"] = { + "total_count": page.total_count, + "has_more": has_more, + **({"cursor": encode_cursor(cursor_payload)} if has_more else {}), + } + return payload + async def _load(self, caller: ReportingStatusCaller) -> ReportingStatusSnapshot: from adcp.reporting.ledger.status_snapshot import ReportingStatusParticipant @@ -335,6 +500,25 @@ def render_snapshot( revision_ownership: bool = False, ) -> dict[str, Any]: """Render captured database evidence without any store calls or clock reads.""" + response, _ = self._render_snapshot_result( + request, + caller=caller, + snapshot=snapshot, + reconciliation=reconciliation, + revision_ownership=revision_ownership, + ) + return response + + def _render_snapshot_result( + self, + request: dict[str, Any], + *, + caller: ReportingStatusCaller, + snapshot: ReportingStatusSnapshot, + reconciliation: tuple[ReportingDeliveryRecord, ...] | None = None, + revision_ownership: bool = False, + materialize_walk: bool = False, + ) -> tuple[dict[str, Any], ReportingStatusWalk | None]: view = request.get("view", "summary") if view not in {"summary", "periods", "revision"}: raise LedgerConflictError("INVALID_VIEW", "unsupported reporting status view") @@ -507,7 +691,7 @@ def render_snapshot( response = with_revision_ownership( response, {revision.reporting_revision_id: revision.reporting_obligation_id} ) - return response + return response, None common["scope"] = _scope_to_wire( result.configurations, ledger_as_of=snapshot.as_of, @@ -574,7 +758,7 @@ def render_snapshot( **({"next_expected_at": _iso(next_expected)} if next_expected is not None else {}), "obligation_counts": counts, "issues": _issues_to_wire(result.issues), - } + }, None owners = {o.reporting_obligation_id: o for o in obligations} records: dict[tuple[str, str], Any] = { ("obligation", o.reporting_obligation_id): o for o in obligations @@ -599,36 +783,19 @@ def render_snapshot( for seq, kind, record_id, _ in sorted(snapshot.changes) if seq > lower and (kind, record_id) in records ] - limit = self._page_limit(request) - page: dict[str, list[dict[str, Any]]] = { - "periods": [], - "revisions": [], - "adjustments": [], - "consumer_statuses": [], - } - payload = { + header: dict[str, Any] = { **common, "health": result.health, "issues": _issues_to_wire(result.issues), "changes_checkpoint": _encode_checkpoint(sequence, caller=caller), - "periods": page["periods"], - "revisions": page["revisions"], - "adjustments": page["adjustments"], "materializations": [], "receipts": [], - # Sized at its largest, with a cursor, so the budget holds either way. - "pagination": {"total_count": 0, "has_more": True, "cursor": ""}, } if self._consumer_status_enabled: - payload["consumer_statuses"] = page["consumer_statuses"] - budget = self._page_node_budget - base_nodes = count_payload_nodes(payload) - page_nodes = base_nodes - taken = 0 - for kind, record in selected[offset : offset + limit]: + header["consumer_statuses"] = [] + rendered = [] + for ordinal, (kind, record) in enumerate(selected): if kind == "obligation": - # Shares value.snapshot, so the snapshot's index is built once - # per page and this costs the obligation's own records. scoped = project_status_scope( replace( value, scope=ReportingStatusScope.for_obligation(record, scope.consumer_id) @@ -650,47 +817,48 @@ def render_snapshot( wire = _adjustment_to_wire(record) else: wire = _consumer_status_to_wire(record) - nodes = count_payload_nodes(wire) - if budget is not None and taken and page_nodes + nodes > budget: - break - page[_PAGE_RECORD_KEYS[kind]].append(wire) - page_nodes += nodes - taken += 1 - if budget is not None and page_nodes > budget: - # Progress beats refusal: one record is served even when it does not - # fit, and validation downstream decides what happens to the page. - logger.warning( - "get_reporting_status periods page for account %s is %d nodes (%d of" - " scope and issues, %d record(s)), over the %d page node budget", - caller.account_id, - page_nodes, - base_nodes, - taken, - budget, + rendered.append( + ReportingStatusWalkRecord( + ordinal, + cast(StatusWalkRecordKind, kind), + wire, + count_payload_nodes(wire), + ) ) - has_more = offset + taken < len(selected) - payload["pagination"] = { - "total_count": len(selected), - "has_more": has_more, - **( - { - "cursor": encode_cursor( - { - "ownership": 2, - "account": caller.account_id, - "consumer": caller.consumer_id, - "snapshot": snapshot_id, - "offset": offset + taken, - "lower": lower, - "as_of": snapshot.as_of.isoformat(), - } - ) - } - if has_more - else {} - ), - } - return payload + walk_id = ( + "rplw_" + + _fingerprint( + [ + snapshot_id, + lower, + _iso(snapshot.as_of), + header, + [[record.kind, record.payload, record.node_count] for record in rendered], + ] + )[:32] + if materialize_walk + else "" + ) + walk = ReportingStatusWalk( + walk_id, + caller.account_id, + caller.consumer_id, + snapshot_id, + snapshot.max_sequence, + lower, + snapshot.as_of, + filters, + header, + tuple(rendered), + ) + page_walk = replace(walk, records=walk.records[offset : offset + self._page_limit(request)]) + payload = self._render_status_walk_page( + request, + caller=caller, + page=ReportingStatusWalkPage(page_walk, len(rendered)), + offset=offset, + ) + return payload, walk if materialize_walk else None def _consumer_status_pending( diff --git a/src/adcp/reporting/ledger/status_snapshot.py b/src/adcp/reporting/ledger/status_snapshot.py index d619fbdaf..90900c4e2 100644 --- a/src/adcp/reporting/ledger/status_snapshot.py +++ b/src/adcp/reporting/ledger/status_snapshot.py @@ -3,8 +3,9 @@ from __future__ import annotations from collections.abc import Callable -from dataclasses import replace -from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable +from dataclasses import dataclass, replace +from datetime import datetime, timedelta +from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable from adcp.reporting._timestamp import aware_timestamp from adcp.reporting.ledger.models import ConsumerStatusRecord, ReportingConfigurationGenerationKey @@ -33,6 +34,59 @@ async def record_consumer_status_with_lifecycle( ) -> tuple[ConsumerStatusRecord, bool]: ... +StatusWalkRecordKind = Literal["obligation", "revision", "adjustment", "consumer_status"] + + +@dataclass(frozen=True, slots=True) +class ReportingStatusWalkRecord: + """One pre-rendered periods record at its stable walk ordinal.""" + + ordinal: int + kind: StatusWalkRecordKind + payload: dict[str, Any] + node_count: int + + +@dataclass(frozen=True, slots=True) +class ReportingStatusWalk: + """The cursor-stable projection shared by every page in one periods walk.""" + + walk_id: str + account_id: str + consumer_id: str + snapshot_id: str + source_sequence: int + lower: int + as_of: datetime + filters: dict[str, Any] + header: dict[str, Any] + records: tuple[ReportingStatusWalkRecord, ...] + + +@dataclass(frozen=True, slots=True) +class ReportingStatusWalkPage: + """A bounded ordinal slice plus the immutable walk header.""" + + walk: ReportingStatusWalk + total_count: int + + +@runtime_checkable +class ReportingStatusWalkParticipant(Protocol): + """Optional materialized periods walks; other stores retain snapshot paging.""" + + async def save_status_walk(self, walk: ReportingStatusWalk, *, ttl: timedelta) -> None: ... + + async def read_status_walk_page( + self, + *, + caller: ReportingCaller, + walk_id: str, + offset: int, + limit: int, + ) -> ReportingStatusWalkPage | None: ... + + def validate_status_evidence( status: ConsumerStatusRecord, snapshot: ReportingStatusSnapshot ) -> None: diff --git a/src/adcp/reporting/ledger/storage_contract.py b/src/adcp/reporting/ledger/storage_contract.py index 68b3366ed..488307007 100644 --- a/src/adcp/reporting/ledger/storage_contract.py +++ b/src/adcp/reporting/ledger/storage_contract.py @@ -18,7 +18,9 @@ ``all_media_buys``; schema migration ``0009``). Implemented by adcp-reporting-storage 0.2.0b5 through 0.2.0b9. * **4** — ``data_through_precision`` on revisions. Implemented by - adcp-reporting-storage 0.2.0b10 and later. + adcp-reporting-storage 0.2.0b10 and 0.2.0b11. +* **5** — materialized reporting-status walk headers and ordinal records. + Implemented by adcp-reporting-storage 0.2.0b12 and later. :func:`require_storage_contract` runs at service startup and when ``postgres_storage`` is built, so an incompatible pair is refused once, with @@ -43,12 +45,12 @@ ] #: The storage contract this adcp reads the reporting ledger with. -REPORTING_STORAGE_CONTRACT = 4 +REPORTING_STORAGE_CONTRACT = 5 #: The distribution that implements the contract for PostgreSQL. STORAGE_DISTRIBUTION = "adcp-reporting-storage" #: Its first release of the current contract. -STORAGE_RELEASE = "0.2.0b10" +STORAGE_RELEASE = "0.2.0b12" def storage_contract_fingerprint() -> str: @@ -111,8 +113,8 @@ def require_storage_contract(store: Any) -> None: if implemented < REPORTING_STORAGE_CONTRACT: fix = ( f"Install {STORAGE_DISTRIBUTION}>={STORAGE_RELEASE} (storage contract " - f'{REPORTING_STORAGE_CONTRACT}), then run "python -m adcp migrate" or start the ' - "service, whose create_schema() upgrades the ledger in place." + f'{REPORTING_STORAGE_CONTRACT}), then run "python -m adcp migrate" before ' + "starting the service." ) else: fix = ( diff --git a/src/adcp/reporting/ledger/store.py b/src/adcp/reporting/ledger/store.py index 6964e8cf8..1d1b30298 100644 --- a/src/adcp/reporting/ledger/store.py +++ b/src/adcp/reporting/ledger/store.py @@ -93,6 +93,7 @@ if TYPE_CHECKING: from adcp.reporting.inline_source import ReportingSealStore from adcp.reporting.ledger.status_projection import ReportingStatusSnapshot + from adcp.reporting.ledger.status_snapshot import ReportingStatusWalk, ReportingStatusWalkPage from adcp.reporting.outbox.memory import NotificationState _MEMORY_TRANSACTION: ContextVar[tuple[int, object] | None] = ContextVar( @@ -1087,6 +1088,7 @@ def __init__( self._issue_event_seq = 0 self._notification_state: NotificationState | None = None self._status_notification_state: Any = None + self._status_walks: dict[str, tuple[datetime, ReportingStatusWalk]] = {} if notifications: from adcp.reporting.outbox.memory import NotificationState @@ -2103,6 +2105,72 @@ async def read_status_snapshot(self, *, caller: ReportingCaller) -> ReportingSta ) return replace(snapshot, owed_through=owed) if owed else snapshot + async def save_status_walk(self, walk: ReportingStatusWalk, *, ttl: timedelta) -> None: + """Retain a bounded periods walk until its cursor chain expires.""" + if ttl <= timedelta(0): + raise ValueError("status walk ttl must be positive") + async with self._lock: + now = _utc(self._clock()) + self._status_walks = { + walk_id: retained + for walk_id, retained in self._status_walks.items() + if retained[0] > now + } + self._status_walks[walk.walk_id] = (now + ttl, deepcopy(walk)) + + async def read_status_walk_page( + self, + *, + caller: ReportingCaller, + walk_id: str, + offset: int, + limit: int, + ) -> ReportingStatusWalkPage | None: + """Read one ordinal slice while holding the same lock as cleanup.""" + from adcp.reporting.ledger.status_snapshot import ( + ReportingStatusWalk, + ReportingStatusWalkPage, + ) + + async with self._lock: + retained = self._status_walks.get(walk_id) + if retained is None: + return None + expires_at, walk = retained + if expires_at <= _utc(self._clock()): + del self._status_walks[walk_id] + return None + if walk.account_id != caller.account_id or walk.consumer_id != caller.consumer_id: + return None + sequence = max( + ( + sequence + for sequence, account, _, _, _ in self._changes + if account == caller.account_id + and self._change_owners[sequence] == caller.consumer_id + ), + default=0, + ) + if sequence != walk.source_sequence: + raise LedgerConflictError( + "CURSOR_SNAPSHOT_MISMATCH", + "this cursor belongs to a changed ledger snapshot; restart the walk", + ) + records = walk.records[offset : offset + limit] + page_walk = ReportingStatusWalk( + walk.walk_id, + walk.account_id, + walk.consumer_id, + walk.snapshot_id, + walk.source_sequence, + walk.lower, + walk.as_of, + walk.filters, + walk.header, + records, + ) + return ReportingStatusWalkPage(page_walk, len(walk.records)) + def _current_status_leaf(self, chain_key: tuple[Any, ...]) -> ConsumerStatusRecord | None: for item in self._statuses.values(): if item.chain_key == chain_key and not item.superseded: diff --git a/tests/conformance/reporting/test_reporting_status_walk_pg.py b/tests/conformance/reporting/test_reporting_status_walk_pg.py new file mode 100644 index 000000000..abf809295 --- /dev/null +++ b/tests/conformance/reporting/test_reporting_status_walk_pg.py @@ -0,0 +1,241 @@ +"""Materialized status walks agree across memory and PostgreSQL.""" + +from __future__ import annotations + +import asyncio +import os +from contextlib import asynccontextmanager +from datetime import datetime, timedelta, timezone +from typing import Any + +import pytest + +from adcp.reporting.ledger import ( + InMemoryReportingLedgerStore, + LedgerConflictError, + ReportingStatusHandler, +) +from adcp.reporting.ledger.status_snapshot import ReportingStatusWalk +from adcp.reporting.ledger.store import decode_cursor +from tests.conformance.reporting._generation_support import isolated_reporting_pool +from tests.test_reporting_ledger import CALLER, _configuration, _obligation, _revision + +psycopg_pool = pytest.importorskip("psycopg_pool") + +if not os.environ.get("ADCP_PG_TEST_URL"): + pytest.skip("ADCP_PG_TEST_URL not set", allow_module_level=True) + +from adcp_reporting_storage.ledger.pg import PgReportingLedgerStore # noqa: E402 +from adcp_reporting_storage.migrations import migrate # noqa: E402 + +NOW = datetime(2026, 9, 30, tzinfo=timezone.utc) + + +async def _seed(store: Any, count: int) -> None: + configuration = _configuration() + await store.put_configuration(configuration) + for ordinal in range(1, count + 1): + obligation = await store.commit_obligation(_obligation(configuration, ordinal=ordinal)) + revision, rows = _revision(obligation, reporting_revision_id=f"rpr_{ordinal}") + await store.commit_revision(revision, rows) + + +async def _walk(handler: ReportingStatusHandler) -> list[dict[str, Any]]: + request: dict[str, Any] = {"view": "periods", "pagination": {"max_results": 100}} + pages = [] + while True: + page = await handler.handle(request, caller=CALLER) + pages.append(page) + if not page["pagination"]["has_more"]: + return pages + request = { + "view": "periods", + "pagination": {"max_results": 100, "cursor": page["pagination"]["cursor"]}, + } + + +async def test_memory_and_postgres_status_walks_are_byte_for_byte_equal() -> None: + memory = InMemoryReportingLedgerStore(clock=lambda: NOW) + await _seed(memory, 55) + + async with isolated_reporting_pool(autocommit=True) as pool: + await migrate(pool) + postgres = PgReportingLedgerStore(pool=pool, clock=lambda: NOW) + await _seed(postgres, 55) + + for node_budget in (None, 500): + assert await _walk( + ReportingStatusHandler(memory, page_node_budget=node_budget) + ) == await _walk(ReportingStatusHandler(postgres, page_node_budget=node_budget)) + + +def _empty_walk(walk_id: str) -> ReportingStatusWalk: + return ReportingStatusWalk( + walk_id, + CALLER.account_id, + CALLER.consumer_id, + f"snapshot_{walk_id}", + 0, + 0, + NOW, + {}, + {}, + (), + ) + + +async def test_expiry_cleanup_skips_a_walk_with_an_active_page_reader() -> None: + async with isolated_reporting_pool(autocommit=True) as pool: + await migrate(pool) + postgres = PgReportingLedgerStore(pool=pool, clock=lambda: NOW) + await postgres.save_status_walk(_empty_walk("walk_active"), ttl=timedelta(minutes=1)) + async with pool.connection() as connection: + await connection.execute( + "UPDATE reporting_status_walks SET expires_at = now() - interval '1 second'" + " WHERE walk_id = 'walk_active'" + ) + async with pool.connection() as reader, reader.transaction(): + await reader.execute( + "SELECT walk_id FROM reporting_status_walks" + " WHERE walk_id = 'walk_active' FOR SHARE" + ) + await asyncio.wait_for( + postgres.save_status_walk(_empty_walk("walk_other"), ttl=timedelta(minutes=1)), + timeout=1, + ) + async with pool.connection() as observer: + assert await ( + await observer.execute( + "SELECT count(*) FROM reporting_status_walks" + " WHERE walk_id = 'walk_active'" + ) + ).fetchone() == (1,) + await postgres.save_status_walk(_empty_walk("walk_cleanup"), ttl=timedelta(minutes=1)) + async with pool.connection() as observer: + assert await ( + await observer.execute( + "SELECT count(*) FROM reporting_status_walks" " WHERE walk_id = 'walk_active'" + ) + ).fetchone() == (0,) + + +async def test_a_missing_postgres_walk_record_rebuilds_from_the_unchanged_ledger() -> None: + async with isolated_reporting_pool(autocommit=True) as pool: + await migrate(pool) + postgres = PgReportingLedgerStore(pool=pool, clock=lambda: NOW) + await _seed(postgres, 3) + handler = ReportingStatusHandler(postgres, page_size=1) + first = await handler.handle({"view": "periods"}, caller=CALLER) + cursor = first["pagination"]["cursor"] + decoded = decode_cursor(cursor) + async with pool.connection() as connection: + await connection.execute( + "DELETE FROM reporting_status_walk_records" " WHERE walk_id = %s AND ordinal = %s", + (decoded["walk"], decoded["offset"]), + ) + snapshot_reads = 0 + original = postgres.read_status_snapshot + + async def counted_snapshot(*, caller): + nonlocal snapshot_reads + snapshot_reads += 1 + return await original(caller=caller) + + postgres.read_status_snapshot = counted_snapshot # type: ignore[method-assign] + second = await handler.handle( + {"view": "periods", "pagination": {"cursor": cursor}}, caller=CALLER + ) + + assert snapshot_reads == 1 + assert sum(len(second.get(key, ())) for key in ("periods", "revisions")) == 1 + + +async def test_a_postgres_walk_rejects_an_intervening_ledger_write() -> None: + async with isolated_reporting_pool(autocommit=True) as pool: + await migrate(pool) + postgres = PgReportingLedgerStore(pool=pool, clock=lambda: NOW) + await _seed(postgres, 2) + handler = ReportingStatusHandler(postgres, page_size=1) + first = await handler.handle({"view": "periods"}, caller=CALLER) + await postgres.commit_obligation(_obligation(_configuration(), ordinal=3)) + + with pytest.raises(LedgerConflictError) as error: + await handler.handle( + {"view": "periods", "pagination": {"cursor": first["pagination"]["cursor"]}}, + caller=CALLER, + ) + + assert error.value.code == "CURSOR_SNAPSHOT_MISMATCH" + + +@pytest.mark.slow +async def test_a_740_record_postgres_walk_reads_only_one_snapshot_and_bounded_pages() -> None: + async with isolated_reporting_pool(autocommit=True) as pool: + await migrate(pool) + postgres = PgReportingLedgerStore(pool=pool, clock=lambda: NOW) + await _seed(postgres, 370) + snapshot_reads = 0 + page_sizes: list[int] = [] + continuation_queries: list[tuple[str, Any]] = [] + original_snapshot = postgres.read_status_snapshot + original_page = postgres.read_status_walk_page + + async def counted_snapshot(*, caller): + nonlocal snapshot_reads + snapshot_reads += 1 + return await original_snapshot(caller=caller) + + async def counted_page(**kwargs): + page = await original_page(**kwargs) + if page is not None: + page_sizes.append(len(page.walk.records)) + return page + + postgres.read_status_snapshot = counted_snapshot # type: ignore[method-assign] + postgres.read_status_walk_page = counted_page # type: ignore[method-assign] + handler = ReportingStatusHandler(postgres) + request: dict[str, Any] = {"view": "periods", "pagination": {"max_results": 100}} + pages = [await handler.handle(request, caller=CALLER)] + + original_connection = postgres._connection + + class TracedConnection: + def __init__(self, connection: Any) -> None: + self._connection = connection + + def transaction(self) -> Any: + return self._connection.transaction() + + async def execute(self, query: str, params: Any = None) -> Any: + continuation_queries.append((query, params)) + return await self._connection.execute(query, params) + + @asynccontextmanager + async def traced_connection(): + async with original_connection() as connection: + yield TracedConnection(connection) + + postgres._connection = traced_connection # type: ignore[method-assign] + while pages[-1]["pagination"]["has_more"]: + request = { + "view": "periods", + "pagination": { + "max_results": 100, + "cursor": pages[-1]["pagination"]["cursor"], + }, + } + pages.append(await handler.handle(request, caller=CALLER)) + + assert len(pages) == 8 + assert snapshot_reads == 1 + assert page_sizes == [100, 100, 100, 100, 100, 100, 40] + record_queries = [ + (query, params) + for query, params in continuation_queries + if "FROM reporting_status_walk_records" in query + ] + assert len(record_queries) == 7 + assert all("LIMIT %s" in query and params[2] == 100 for query, params in record_queries) + assert not any( + "SELECT to_jsonb(r) FROM reporting_" in query for query, _ in continuation_queries + ) diff --git a/tests/conformance/reporting/test_reporting_storage_migrations_pg.py b/tests/conformance/reporting/test_reporting_storage_migrations_pg.py index 57190dd04..367b391e7 100644 --- a/tests/conformance/reporting/test_reporting_storage_migrations_pg.py +++ b/tests/conformance/reporting/test_reporting_storage_migrations_pg.py @@ -34,12 +34,13 @@ async def test_migrate_applies_every_version_once_and_status_reads_it() -> None: lines = describe(await migration_status(pool)) assert all(": applied " in line for line in lines) # A new ledger was never expanded: its contract step applied without --contract. - assert lines[-5].startswith("0007 reporting_contract_generation_keys: applied ") - assert lines[-5].endswith("[contract]") - assert lines[-4].startswith("0008 reporting_issue_events: applied ") - assert lines[-3].startswith("0009 reporting_all_media_buys: applied ") - assert lines[-2].startswith("0010 reporting_finality_evidence: applied ") - assert lines[-1].startswith("0011 reporting_data_through_precision: applied ") + assert lines[-6].startswith("0007 reporting_contract_generation_keys: applied ") + assert lines[-6].endswith("[contract]") + assert lines[-5].startswith("0008 reporting_issue_events: applied ") + assert lines[-4].startswith("0009 reporting_all_media_buys: applied ") + assert lines[-3].startswith("0010 reporting_finality_evidence: applied ") + assert lines[-2].startswith("0011 reporting_data_through_precision: applied ") + assert lines[-1].startswith("0012 reporting_status_walks: applied ") assert not any("stopped-worker" in line for line in lines) @@ -58,7 +59,9 @@ async def test_storage_refuses_a_schema_that_is_behind_and_starts_once_migrated( error = refused.value assert error.code == "REPORTING_SCHEMA_BEHIND" and error.recovery == "correctable" # The contract step alone never makes a schema "behind" (0007 is not listed). - assert "pending: 0001, 0002, 0003, 0004, 0005, 0006, 0008, 0009, 0010, 0011)" in str(error) + assert "pending: 0001, 0002, 0003, 0004, 0005, 0006, 0008, 0009, 0010, 0011, 0012)" in str( + error + ) assert "python -m adcp migrate" in str(error) assert "stopped-worker" not in str(error) # every upgrade is rolling-deploy safe await migrate(pool) @@ -101,7 +104,7 @@ async def test_the_cli_migrates_and_reports_status(capsys) -> None: "0007 reporting_contract_generation_keys: pending [contract: run once every" " earlier-release reporting process has stopped: python -m adcp migrate --contract]" ) in status - assert "11 pending" in status + assert "12 pending" in status assert await _run(dsn, status=False, dry_run=False) == 0 applied = capsys.readouterr().out assert "applied 0002 reporting_subscription_generations\n" in applied @@ -279,6 +282,7 @@ async def test_create_schema_builds_its_own_schema_beside_a_migrated_one() -> No "0009", "0010", "0011", + "0012", ] assert await _catalog(other, other_schema) == before @@ -332,6 +336,7 @@ async def test_a_new_ledger_is_created_contracted(entry: str, capsys) -> None: "0009", "0010", "0011", + "0012", ] assert await _expand_objects(pool) == [] assert not await needs_contract(pool) diff --git a/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py b/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py index b6797edb3..8aae33147 100644 --- a/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py +++ b/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py @@ -279,7 +279,7 @@ def _rest(*, contract: bool = True) -> list[str]: #: The contract steps: applied to an expanded ledger only with ``contract=True``. CONTRACT_VERSIONS = ["0007"] #: Additive migrations after the contract step: applied even while it is held. -ADDITIVE_AFTER_CONTRACT = ["0008", "0009", "0010", "0011"] +ADDITIVE_AFTER_CONTRACT = ["0008", "0009", "0010", "0011", "0012"] #: The objects that exist only while a ledger is expanded (catalog lines). EXPANDED_LEDGER = { "constraint reporting_configurations reporting_configurations_generation_key", @@ -577,7 +577,7 @@ async def test_adcp_b4_fails_on_the_published_storage_and_upgrades_with_this_one b4_with_this_storage: Path, workspace: Path, ) -> None: - """The reported failure; this storage (contract 4) then refuses adcp 10.0.0b4 (contract 2).""" + """The reported failure; this storage (contract 5) then refuses adcp 10.0.0b4 (contract 2).""" storage, python = published if storage != "0.2.0b0": pytest.skip("the 10.0.0b4 pairing concerns the 0.2.0b0 ledger") @@ -588,7 +588,7 @@ async def test_adcp_b4_fails_on_the_published_storage_and_upgrades_with_this_one ) assert "offering_id" in failed.get("error", ""), failed # #1763, reproduced versions = await _versions(pool) - with pytest.raises(AssertionError, match="implements contract 4"): + with pytest.raises(AssertionError, match="implements contract 5"): await asyncio.to_thread( _run, b4_with_this_storage, _settings(pool, "upgrade"), cwd=workspace ) @@ -1057,7 +1057,8 @@ async def test_a_ledger_the_published_0_2_0b1_widened_counts_as_contracted( before = booted # The contract step is recorded without --contract: it changes nothing here. applied = [item.version for item in await migrate(pool)] - assert applied[-5:] == [*CONTRACT_VERSIONS, *ADDITIVE_AFTER_CONTRACT] + expected = [*CONTRACT_VERSIONS, *ADDITIVE_AFTER_CONTRACT] + assert applied[-len(expected) :] == expected await postgres_storage(pool=pool).check_schema() after = await _catalog(pool) # 0004 and 0005 add their own tables assert set(before) <= set(after) and _expand_only(after) == set() @@ -1093,6 +1094,7 @@ async def test_migrate_holds_the_contract_step_and_status_says_when_to_run_it( assert "would apply 0009 reporting_all_media_buys\n" in planned assert "would apply 0010 reporting_finality_evidence\n" in planned assert "would apply 0011 reporting_data_through_precision\n" in planned + assert "would apply 0012 reporting_status_walks\n" in planned assert ( "not applied 0007 reporting_contract_generation_keys (contract): run" f' "python -m adcp migrate --contract" {when}' @@ -1106,23 +1108,25 @@ async def test_migrate_holds_the_contract_step_and_status_says_when_to_run_it( assert "applied 0009 reporting_all_media_buys\n" in applied assert "applied 0010 reporting_finality_evidence\n" in applied assert "applied 0011 reporting_data_through_precision\n" in applied + assert "applied 0012 reporting_status_walks\n" in applied assert "not applied 0007 reporting_contract_generation_keys (contract)" in applied await postgres_storage(pool=pool).check_schema() # starts: only the contract pends assert await _run(dsn, status=True, dry_run=False) == 0 status = capsys.readouterr().out.strip().splitlines() - assert status[-6] == ( + assert status[-7] == ( "0007 reporting_contract_generation_keys: pending [contract: run" f" {when}: python -m adcp migrate --contract]" ) - assert status[-5].startswith("0008 reporting_issue_events: applied ") - assert status[-4].startswith("0009 reporting_all_media_buys: applied ") - assert status[-3].startswith("0010 reporting_finality_evidence: applied ") - assert status[-2].startswith("0011 reporting_data_through_precision: applied ") + assert status[-6].startswith("0008 reporting_issue_events: applied ") + assert status[-5].startswith("0009 reporting_all_media_buys: applied ") + assert status[-4].startswith("0010 reporting_finality_evidence: applied ") + assert status[-3].startswith("0011 reporting_data_through_precision: applied ") + assert status[-2].startswith("0012 reporting_status_walks: applied ") assert status[-1] == ( f'up to date except the contract step: run "python -m adcp migrate --contract" {when}' ) - assert describe(await migration_status(pool))[-5] == status[-6] + assert describe(await migration_status(pool))[-6] == status[-7] _all_ok(await _old_pod(python, pool, workspace, notifications=False, ordinal=2)) assert await _run(dsn, status=False, dry_run=False, contract=True) == 0 diff --git a/tests/fixtures/public_api_snapshot.json b/tests/fixtures/public_api_snapshot.json index 74d29ebd2..3486b1084 100644 --- a/tests/fixtures/public_api_snapshot.json +++ b/tests/fixtures/public_api_snapshot.json @@ -953,6 +953,10 @@ "ReportingStatusParticipant": "adcp.reporting.ledger.status_snapshot", "ReportingStatusSnapshot": "adcp.reporting.ledger.status_projection", "ReportingStatusView": "union[value:'periods',value:'revision',value:'summary']", + "ReportingStatusWalk": "adcp.reporting.ledger.status_snapshot", + "ReportingStatusWalkPage": "adcp.reporting.ledger.status_snapshot", + "ReportingStatusWalkParticipant": "adcp.reporting.ledger.status_snapshot", + "ReportingStatusWalkRecord": "adcp.reporting.ledger.status_snapshot", "ReportingSubscriptionGeneration": "adcp.reporting.ledger.models", "ReportingSubscriptionLedger": "adcp.reporting.ledger.store", "ReportingVerificationRecord": "adcp.reporting.ledger.delivery_models", @@ -9129,7 +9133,7 @@ "ReportingRowStorageOptionsV1": "adcp_reporting_storage.ledger.row_storage", "ReportingRowStorageV1": "adcp_reporting_storage.ledger.row_storage", "ReportingUpgradeNotContractedError": "adcp_reporting_storage.migrations", - "STORAGE_CONTRACT": "value:4", + "STORAGE_CONTRACT": "value:5", "assert_gcs_reporting_row_bucket_policy_v1": "adcp_reporting_storage.ledger.row_storage_gcs", "backfill_legacy_reporting": "adcp_reporting_storage.migration", "create_azure_blob_reporting_row_object_provider_v1": "adcp_reporting_storage.ledger.row_storage_azure", diff --git a/tests/test_reporting_status_page_cost.py b/tests/test_reporting_status_page_cost.py index 42a45d562..5dd192877 100644 --- a/tests/test_reporting_status_page_cost.py +++ b/tests/test_reporting_status_page_cost.py @@ -7,8 +7,7 @@ records-on-the-page x statuses x obligations and a full walk of a large ledger grew with the cube of its size. -These tests pin two things: the pages are byte-for-byte what they were before -the projection was indexed (digests captured on the unindexed code), and the +These tests pin two things: the current pages are byte-for-byte stable, and the matching work behind one page grows linearly with the ledger. """ @@ -262,18 +261,15 @@ def _digest(pages: list[dict[str, Any]]) -> str: return hashlib.sha256(json.dumps(pages, sort_keys=True).encode()).hexdigest() -# SHA-256 of each walk's pages as JSON, captured on the code before the -# projection was indexed. A digest changes only with an intended wire change: -# the snapshot id binds the served adcp_version, so the 3.3.0 pin (served as -# "3.3", was "3.3-rc.3") moved every digest through ledger_snapshot_id and the -# cursors that carry it, and nothing else. -_PAGES_BEFORE_INDEXING: dict[str, str] = { - "periods": "c0ddf6b4d095ec8803146ca403a5094ad7a1702024440451e81a5fb50b0b7cfc", +# SHA-256 of each walk's pages as canonical JSON. Opaque cursor bindings +# participate in the digest alongside the public response fields. +_EXPECTED_PAGE_DIGESTS: dict[str, str] = { + "periods": "82d44d13e9c909898131f7f5fde64e75bf84eda9f02cf5be31ee35fa4c3cfc74", "periods_without_statuses": "083b7ede5117863fb784f5e557fd0f891e1453e9a9d64f20451f070676f539ae", - "periods_node_budget": "54610f26da2611f1a7dbbe678cdf1dea7982a68ae0c785646478ed11e1157553", - "periods_filtered": "adbb513a401fad27c1f64f3c34135c83b880b69971de42e895362ddcb91429af", - "periods_buy_horizon": "5e5eee3b09dcd0f89c6a1db1e2645c2cca49b14deda97edb40b286e2356c473e", - "periods_incremental": "95e32c3c66142db827290976339c4e99fa7ea466539fe813f83eda2ef54024e2", + "periods_node_budget": "b50c5c437610590cc7862c4df38d028fb74cdd130edf6464573f9ae308a30cb6", + "periods_filtered": "7c3e768de00ffde7da7ba381031d4428671c95425896e269f1b25a665fda87ed", + "periods_buy_horizon": "76f32a2cf248ffb659fa5b1c85d716f8d903fcdcd71b643a97ea6235b571799f", + "periods_incremental": "53acbb21ecf81400e50e573ff478a9dc1526097cbc874d506c66bd03f23e6c6b", "summary": "cbec158182ce3ee06ed7f44064072b1aa4706482b188c273ca497c14aa47ccbb", "summary_filtered": "1dc6cd549556afc710ab80b4726337b76b0165fcf99a65606c3f1029eafb2dd0", "revision": "d373d0d8dc601c7e0a7e61745bd7f1137a63d1c15b8af95fdfdcdef1a64fccbb", @@ -282,7 +278,7 @@ def _digest(pages: list[dict[str, Any]]) -> str: async def test_pages_are_identical_to_the_unindexed_projection() -> None: rendered = await _rendered() - assert {name: _digest(pages) for name, pages in rendered.items()} == _PAGES_BEFORE_INDEXING + assert {name: _digest(pages) for name, pages in rendered.items()} == _EXPECTED_PAGE_DIGESTS async def _ledger_with_statuses(obligations: int) -> InMemoryReportingLedgerStore: diff --git a/tests/test_reporting_status_paging.py b/tests/test_reporting_status_paging.py index db52866de..ac33a6270 100644 --- a/tests/test_reporting_status_paging.py +++ b/tests/test_reporting_status_paging.py @@ -22,6 +22,7 @@ LedgerConflictError, ReportingStatusHandler, ) +from adcp.reporting.ledger.store import decode_cursor, encode_cursor from adcp.validation import DEFAULT_MAX_PAYLOAD_NODES, count_payload_nodes from tests.test_reporting_ledger import CALLER, _configuration, _obligation, _revision, _seeded @@ -82,6 +83,134 @@ async def test_max_results_bounds_the_page_and_the_walk_returns_every_record_onc assert {p["pagination"]["total_count"] for p in pages} == {10} +async def test_continuation_pages_do_not_rebuild_the_status_snapshot() -> None: + store = await _ledger(5) + snapshot_reads = 0 + original = store.read_status_snapshot + + async def counted_snapshot(*, caller): + nonlocal snapshot_reads + snapshot_reads += 1 + return await original(caller=caller) + + store.read_status_snapshot = counted_snapshot # type: ignore[method-assign] + pages = await _walk( + ReportingStatusHandler(store), + {"view": "periods", "pagination": {"max_results": 2}}, + ) + + assert len(pages) == 5 + assert snapshot_reads == 1 + + +async def test_walk_identity_binds_the_materialized_projection() -> None: + store = await _ledger(3) + statuses = ReportingStatusHandler(store, page_size=1, consumer_status_enabled=True) + periods = ReportingStatusHandler(store, page_size=1, consumer_status_enabled=False) + + statuses_first = await statuses.handle({"view": "periods"}, caller=CALLER) + periods_first = await periods.handle({"view": "periods"}, caller=CALLER) + statuses_cursor = statuses_first["pagination"]["cursor"] + + assert ( + decode_cursor(statuses_cursor)["walk"] + != decode_cursor(periods_first["pagination"]["cursor"])["walk"] + ) + statuses_second = await statuses.handle( + {"view": "periods", "pagination": {"cursor": statuses_cursor}}, caller=CALLER + ) + assert "consumer_statuses" in statuses_second + + +async def test_a_missing_walk_rebuilds_without_invalidating_an_unchanged_cursor() -> None: + store = await _ledger(3) + handler = ReportingStatusHandler(store, page_size=1) + first = await handler.handle({"view": "periods"}, caller=CALLER) + decoded = decode_cursor(first["pagination"]["cursor"]) + del store._status_walks[decoded["walk"]] + snapshot_reads = 0 + original = store.read_status_snapshot + + async def counted_snapshot(*, caller): + nonlocal snapshot_reads + snapshot_reads += 1 + return await original(caller=caller) + + store.read_status_snapshot = counted_snapshot # type: ignore[method-assign] + second = await handler.handle( + {"view": "periods", "pagination": {"cursor": first["pagination"]["cursor"]}}, + caller=CALLER, + ) + + assert snapshot_reads == 1 + assert _records_on(second) == 1 + assert decode_cursor(second["pagination"]["cursor"])["walk"] == decoded["walk"] + + +async def test_a_cursor_without_a_walk_id_enters_the_materialized_path() -> None: + store = await _ledger(3) + handler = ReportingStatusHandler(store, page_size=1) + first = await handler.handle({"view": "periods"}, caller=CALLER) + decoded = decode_cursor(first["pagination"]["cursor"]) + decoded.pop("walk") + compatible_cursor = encode_cursor(decoded) + + second = await handler.handle( + {"view": "periods", "pagination": {"cursor": compatible_cursor}}, caller=CALLER + ) + + assert _records_on(second) == 1 + assert "walk" in decode_cursor(second["pagination"]["cursor"]) + + +async def test_a_materialized_cursor_rejects_changed_filters() -> None: + store = await _ledger(3) + handler = ReportingStatusHandler(store, page_size=1) + first = await handler.handle({"view": "periods"}, caller=CALLER) + + with pytest.raises(LedgerConflictError) as error: + await handler.handle( + { + "view": "periods", + "media_buy_ids": ["mb_other"], + "pagination": {"cursor": first["pagination"]["cursor"]}, + }, + caller=CALLER, + ) + + assert error.value.code == "CURSOR_SNAPSHOT_MISMATCH" + + +async def test_an_expired_walk_rebuilds_from_the_unchanged_ledger() -> None: + now = [datetime(2026, 9, 30, tzinfo=timezone.utc)] + store = InMemoryReportingLedgerStore(clock=lambda: now[0]) + configuration = _configuration() + await store.put_configuration(configuration) + for ordinal in range(1, 3): + obligation = await store.commit_obligation(_obligation(configuration, ordinal=ordinal)) + revision, rows = _revision(obligation, reporting_revision_id=f"rpr_{ordinal}") + await store.commit_revision(revision, rows) + handler = ReportingStatusHandler(store, page_size=1, status_walk_ttl=timedelta(seconds=1)) + first = await handler.handle({"view": "periods"}, caller=CALLER) + now[0] += timedelta(seconds=2) + snapshot_reads = 0 + original = store.read_status_snapshot + + async def counted_snapshot(*, caller): + nonlocal snapshot_reads + snapshot_reads += 1 + return await original(caller=caller) + + store.read_status_snapshot = counted_snapshot # type: ignore[method-assign] + second = await handler.handle( + {"view": "periods", "pagination": {"cursor": first["pagination"]["cursor"]}}, + caller=CALLER, + ) + + assert snapshot_reads == 1 + assert _records_on(second) == 1 + + async def test_an_omitted_max_results_uses_the_schema_default_of_50() -> None: store = await _ledger(30) page = await ReportingStatusHandler(store).handle({"view": "periods"}, caller=CALLER) @@ -181,6 +310,8 @@ async def test_a_budget_of_none_bounds_pages_by_record_count_only() -> None: {"page_node_budget": 0}, {"page_node_budget": False}, {"page_node_budget": 1.5}, + {"status_walk_ttl": timedelta(0)}, + {"status_walk_ttl": "15 minutes"}, ], ) async def test_invalid_handler_limits_are_refused(kwargs: dict[str, Any]) -> None: diff --git a/tests/test_reporting_storage_contract.py b/tests/test_reporting_storage_contract.py index 8a3018f8e..f6b3b029c 100644 --- a/tests/test_reporting_storage_contract.py +++ b/tests/test_reporting_storage_contract.py @@ -23,6 +23,7 @@ 2: "e6cb6454085a8fdc004f564f3882bcfe1a67fd9e622d72a36ba1f9d6ccd12af1", 3: "ca78bd2475be646a93df5ac562cc162f87602c873aa0ade4917fb9e1757d0837", 4: "a62f25f39505a54cabad2b971c13ab257bde6946b06914be295587fbe4a60aa7", + 5: "a62f25f39505a54cabad2b971c13ab257bde6946b06914be295587fbe4a60aa7", } @@ -59,7 +60,7 @@ class _Custom: @pytest.mark.parametrize( ("store", "expected"), - [(_Declared(), 4), (_Older(), 3), (_Newer(), 5), (_Undeclared(), 1), (_Custom(), None)], + [(_Declared(), 5), (_Older(), 4), (_Newer(), 6), (_Undeclared(), 1), (_Custom(), None)], ids=["declared", "older", "newer", "undeclared-storage-release", "custom"], ) def test_a_store_is_classified_by_declaration_or_provenance( @@ -83,12 +84,12 @@ def test_a_storage_release_of_an_older_contract_is_refused_with_the_fix() -> Non message = str(error) assert f"storage contract {REPORTING_STORAGE_CONTRACT}" in message assert "implements contract 1" in message - assert "Install adcp-reporting-storage>=0.2.0b10" in message - assert 'run "python -m adcp migrate"' in message and "create_schema()" in message + assert "Install adcp-reporting-storage>=0.2.0b12" in message + assert 'run "python -m adcp migrate"' in message and "before starting" in message def test_a_storage_release_of_a_newer_contract_is_refused_too() -> None: - with pytest.raises(ReliableReportingConfigurationError, match="implements contract 5"): + with pytest.raises(ReliableReportingConfigurationError, match="implements contract 6"): require_storage_contract(_Newer()) diff --git a/tests/test_reporting_storage_facade.py b/tests/test_reporting_storage_facade.py index 2e7a71947..1bd05e0b0 100644 --- a/tests/test_reporting_storage_facade.py +++ b/tests/test_reporting_storage_facade.py @@ -128,6 +128,7 @@ def test_migrations_are_numbered_files_with_their_upgrade_notes() -> None: "0009", "0010", "0011", + "0012", ] widened, offerings, contract, events = shipped[1], shipped[5], shipped[6], shipped[7] scope = shipped[8] @@ -139,6 +140,8 @@ def test_migrations_are_numbered_files_with_their_upgrade_notes() -> None: for item in (widened, offerings): assert "Rolling-deploy safe" in item.description assert not any(item.stopped_worker for item in shipped) + assert shipped[-1].name == "reporting_status_walks" + assert shipped[-1].additive # ... and the contract step runs only on request, once earlier releases stopped. assert contract.name == "reporting_contract_generation_keys" and contract.contract assert contract.includes == ( @@ -165,6 +168,7 @@ def test_migrations_are_numbered_files_with_their_upgrade_notes() -> None: "0009", "0010", "0011", + "0012", ] for item in shipped: assert item.statements(), item.version # every include resolves @@ -275,7 +279,7 @@ def test_storage_declares_the_contract_adcp_reads_with() -> None: import adcp_reporting_storage from adcp_reporting_storage.contract import STORAGE_CONTRACT, adcp_storage_contract - assert adcp_reporting_storage.STORAGE_CONTRACT == STORAGE_CONTRACT == 4 + assert adcp_reporting_storage.STORAGE_CONTRACT == STORAGE_CONTRACT == 5 assert adcp_storage_contract() == STORAGE_CONTRACT adcp_reporting_storage.require_adcp_contract() # the workspace pair agrees @@ -316,9 +320,9 @@ def test_a_postgres_store_refuses_an_adcp_of_another_contract(monkeypatch) -> No error = refused.value assert error.code == "REPORTING_SCHEMA_BEHIND" and error.recovery == "correctable" assert error.config_field == "adcp-reporting-storage" - assert "storage contract 1" in str(error) and "implements contract 4" in str(error) - assert "Install adcp 10.2.0 or later" in str(error) + assert "storage contract 1" in str(error) and "implements contract 5" in str(error) + assert "Install adcp 10.2.2 or later" in str(error) assert "adcp-reporting-storage 0.2.0b0 with this adcp" in str(error) - monkeypatch.setattr(contract, "adcp_storage_contract", lambda: 5) + monkeypatch.setattr(contract, "adcp_storage_contract", lambda: 6) with pytest.raises(ReliableReportingConfigurationError, match="newer than"): PgReportingLedgerStore(pool=object())