Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/adcp-reporting-storage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -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)
);
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand Down
12 changes: 11 additions & 1 deletion src/adcp/reporting/ledger/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -295,6 +301,10 @@
"StatusProjectionResult",
"project_status_scope",
"ReportingStatusParticipant",
"ReportingStatusWalk",
"ReportingStatusWalkPage",
"ReportingStatusWalkParticipant",
"ReportingStatusWalkRecord",
"ConsumerMismatch",
"ConsumerStatusDisabledError",
"ConsumerStatusIngest",
Expand Down
Loading