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
4 changes: 3 additions & 1 deletion docs/reporting-ledger-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
```
Expand Down
5 changes: 3 additions & 2 deletions docs/reporting-reconciliation-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 5 additions & 2 deletions docs/reporting-source-adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion docs/reporting-webhook-activity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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$;
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
25 changes: 25 additions & 0 deletions src/adcp/reporting/_data_through.py
Original file line number Diff line number Diff line change
@@ -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
9 changes: 8 additions & 1 deletion src/adcp/reporting/conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading