diff --git a/docs/reporting-row-storage.md b/docs/reporting-row-storage.md index c14cb958f4..8706d3030d 100644 --- a/docs/reporting-row-storage.md +++ b/docs/reporting-row-storage.md @@ -333,15 +333,15 @@ await store.save_feed_consumer_cursor("warehouse-sink", page.cursor) # holds ba await store.changes_after(account_id="acct_a", cursor=page.cursor) ``` -- **Account feeds** order by `seq` and, like the deployment-wide feed, return only changes whose transaction is older - than every transaction still in flight (`xid < pg_snapshot_xmin(pg_current_snapshot())`). `seq` is taken under the - account lock, but ordering does not rely on that lock: a slow commit with a lower `seq` holds back the readers - until it commits, instead of being skipped. A long-running transaction anywhere in the database delays account - feeds as well as the deployment feed; it never makes either lose a record. -- **Retirement events appear only in the shared feed.** `retire_expired_periods` appends a `retirement` change to - `adcp_reporting_changes`; the buyer-facing `reporting_ledger_changes` feed never carries one. The two feeds serve - different readers (host consumers such as warehouse sinks, and buyers holding `changes_after` cursors), so they stay - separate and merging them would change cursors buyers already hold. +- **Account feeds** order by `seq` and truncate each page before the first change whose transaction is not below + every transaction still in flight (`xid >= pg_snapshot_xmin(pg_current_snapshot())`): a page is the committed prefix + in `seq` order and stops there, and its cursor never moves past a held-back change. `seq` is taken under the account + lock, but ordering does not rely on that lock. Truncation is deliberate: a plain `xid < xmin` *filter* would be + wrong, because `seq` order and `xid` order can differ, and it would hand out a later change while skipping an earlier + one it excluded. `xmin` is cluster-wide, so **any older open transaction anywhere in the database holds account pages + back until it ends, and an empty page can mean "caught up" or "held back"**; poll again rather than concluding + nothing is new. The row scan is still served by the `(account_id, seq)` index. This narrows the window for a second + writer but does not close it for every interleaving: one writer SDK per database remains the contract. - **The deployment-wide feed** (no `account_id`) orders by `(xid, seq)` and returns only changes whose transaction is older than every transaction still in flight, so a slow commit is never skipped. A long-running transaction delays this feed; it never makes it lose a record. @@ -406,11 +406,13 @@ reads answer as expired, and the records stay. Phase 3 deletes every record of a is an audit-model decision for the maintainers, deliberately not made here; until it is, plan storage for the records themselves, which are small headers and receipts, not row bytes. -Stuck periods never crowd out the rest. A period that cannot finish is parked with an exponential backoff -(`attempts`, `next_attempt_at`, `last_outcome` on its tombstone; 5 minutes doubling to 24 hours) instead of occupying a -candidate slot on every pass, and fresh periods always keep half the slots of each pass. The result reports what was -left alone: `protected` (this pass), `held` (expired periods a hold kept out, bounded count) and `parked` (waiting out a -backoff). +Stuck periods never crowd out the rest, with the same names and numbers as the JavaScript SDK. A period that cannot +finish records `attempts`, `next_attempt_at` and `last_failure` (a stable code, `RECORDS_PROTECTED` for protected +records) on its tombstone and backs off: 1 minute, doubling, capped at 6 hours. Ready retries take at most half of a +pass, rounded up, and fresh periods fill the rest; retries only backfill slots fresh periods leave empty. The result +reports what was left alone: `protected` (this pass), `held` (expired periods a hold kept out, bounded count), +`deferred` (retiring periods backing off, not attempted this pass) and `stuck` (periods with five or more failed +attempts, worst first, at most 20: `(reporting_obligation_id, attempts, cause)`). Tombstones live in `adcp_reporting_period_tombstones`, created with row storage or the change feed. @@ -432,15 +434,17 @@ Only the closed operation name and integer counters are logged, never an excepti - `REPORTING_MAINTENANCE_FAILED` (warning): the operation raised or reported failed items (a binding that cannot delete, for example). Read `causes` from the result for the stable per-item code. - `REPORTING_MAINTENANCE_PENDING` (info): work was left in place on purpose, with the counters `protected`, `held`, - `parked`, `skipped_unconfigured` and `backed_off`. A retirement that does nothing because every period is held shows - up here instead of looking like a healthy idle worker. -- `REPORTING_MAINTENANCE_STALLED` (warning): intents have been expired for more than a day and are still unresolved - (`stalled`): a binding no host configures any more, or one that keeps failing, so its orphaned objects are never - cleaned up. + `deferred` and `skipped_unconfigured`. A retirement that does nothing because every period is held shows up here + instead of looking like a healthy idle worker. +- `REPORTING_MAINTENANCE_STALLED` (warning): work nobody is reaching, with `overdue` (intents expired for more than + `overdue_after_seconds`, default 24 hours, and still unswept: a binding no host configures any more, or one that + keeps failing, so objects leak) and `stuck` (periods with five or more failed retirement attempts). The last pass's counters are also on `ReportingProductionSupport.maintenance_report`, per operation. `prune_expired_row_sets` is scheduled so row bytes are reclaimed even while a period's records stay; its only hold is pending materializer work. The intent sweep skips bindings this host does not configure (counted in -`skipped_unconfigured`) and backs a failing intent off exponentially (1 minute doubling to 1 hour, in -`adcp_reporting_row_sweep_backoff`), trying never-failed intents first, so one broken binding cannot starve the others. +`skipped_unconfigured`, unless an intent has no recorded objects, which needs no binding) and backs a failing intent +off (`sweep_attempts` and `next_sweep_at` on the shared write-intent table, the same columns the JavaScript SDK adds: +1 minute, doubling, capped at 6 hours; counted as `deferred`), trying never-failed intents first, so one broken binding +cannot starve the others. Outside the production service, call the same methods from your own scheduler. diff --git a/src/adcp/reporting/ledger/change_feed.py b/src/adcp/reporting/ledger/change_feed.py index e73577a7f7..3a187f196e 100644 --- a/src/adcp/reporting/ledger/change_feed.py +++ b/src/adcp/reporting/ledger/change_feed.py @@ -131,6 +131,38 @@ def _require_feed(store: PgReportingLedgerStore) -> None: raise ValueError("this operation requires the store change_feed option") +def _page_query(*, account: bool) -> str: + """The change page query for an account feed (``seq`` order) or the deployment feed. + + Every column is qualified with the table alias, in the projection and in ORDER BY. + ``seq::text`` is *named* ``seq``, and PostgreSQL resolves a bare ORDER BY name to the output + column first, so ``ORDER BY seq`` would sort 100 before 95 as text and a page boundary would + silently skip changes. ``change.seq`` always means the bigint column. + """ + columns = ( + "change.seq::text AS cursor_seq, change.xid::text AS cursor_xid, change.account_id," + " change.record_kind, change.record_id, change.obligation_id," + " to_char(change.recorded_at AT TIME ZONE 'UTC'," + ' \'YYYY-MM-DD"T"HH24:MI:SS.US"Z"\')' + ) + if account: + return ( + f"SELECT {columns}," # noqa: S608 # nosec B608 + " change.xid >= pg_snapshot_xmin(pg_current_snapshot()) AS in_flight" + " FROM adcp_reporting_changes change" + " WHERE change.account_id = %s AND change.seq > %s::bigint" + " AND (%s::text[] IS NULL OR change.record_kind = ANY(%s::text[]))" + " ORDER BY change.seq LIMIT %s" + ) + return ( + f"SELECT {columns} FROM adcp_reporting_changes change" # noqa: S608 # nosec B608 + " WHERE (change.xid, change.seq) > (%s::text::xid8, %s::bigint)" + " AND change.xid < pg_snapshot_xmin(pg_current_snapshot())" + " AND (%s::text[] IS NULL OR change.record_kind = ANY(%s::text[]))" + " ORDER BY change.xid, change.seq LIMIT %s" + ) + + async def changes_after( store: PgReportingLedgerStore, *, @@ -177,39 +209,26 @@ async def changes_after( raise ReportingChangeCursorExpiredError() position_seq = decoded["seq"] if decoded else horizon_seq position_xid = decoded.get("xid", "0") if decoded else horizon_xid - # Every column is qualified with the table alias, in the projection and in ORDER BY. - # ``seq::text`` is *named* ``seq``, and PostgreSQL resolves a bare ORDER BY name to the - # output column first, so ``ORDER BY seq`` would sort 100 before 95 as text and a page - # boundary would silently skip changes. ``change.seq`` always means the bigint column. - columns = ( - "change.seq::text AS cursor_seq, change.xid::text AS cursor_xid, change.account_id," - " change.record_kind, change.record_id, change.obligation_id," - " to_char(change.recorded_at AT TIME ZONE 'UTC'," - ' \'YYYY-MM-DD"T"HH24:MI:SS.US"Z"\')' - ) + query = _page_query(account=account_id is not None) if account_id is not None: - query = ( - f"SELECT {columns} FROM adcp_reporting_changes change" # noqa: S608 # nosec B608 - " WHERE change.account_id = %s AND change.seq > %s::bigint" - # Like the deployment feed, only changes whose transaction is older than every - # transaction still in flight: ``seq`` is assigned in commit order only while one - # writer holds the account lock, so without this a slow commit with a lower - # ``seq`` would be skipped for good by a reader that already saw a higher one. - " AND change.xid < pg_snapshot_xmin(pg_current_snapshot())" - " AND (%s::text[] IS NULL OR change.record_kind = ANY(%s::text[]))" - " ORDER BY change.seq LIMIT %s" - ) params: tuple[Any, ...] = (account_id, position_seq, selected, selected, limit) else: - query = ( - f"SELECT {columns} FROM adcp_reporting_changes change" # noqa: S608 # nosec B608 - " WHERE (change.xid, change.seq) > (%s::text::xid8, %s::bigint)" - " AND change.xid < pg_snapshot_xmin(pg_current_snapshot())" - " AND (%s::text[] IS NULL OR change.record_kind = ANY(%s::text[]))" - " ORDER BY change.xid, change.seq LIMIT %s" - ) params = (position_xid, position_seq, selected, selected, limit) rows = await (await connection.execute(query, params)).fetchall() + if account_id is not None: + # The account feed orders by ``seq``, which equals commit order only while every writer + # takes the account lock before ``nextval``. Defense in depth for a writer that does not: + # stop the page at the first change whose transaction is not below every in-flight + # transaction (``xid >= xmin``). A plain ``xid < xmin`` filter would not do, because seq + # order and xid order can differ, and it would hand out a later change while skipping an + # earlier one it excluded. Truncating keeps the page a prefix of seq order. This narrows + # the window for a second writer but does not close it for every interleaving: one + # writer SDK per database remains the contract. ``xmin`` is cluster-wide, so any older + # open transaction holds account pages back until it ends; an empty page can mean + # "caught up" or "held back". The row scan is still served by the (account_id, seq) index. + blocked = next((index for index, row in enumerate(rows) if row[7]), None) + if blocked is not None: + rows = rows[:blocked] records = tuple(ReportingChangeRecordV1(row[3], row[4], row[5], row[2], row[6]) for row in rows) if rows: last = rows[-1] diff --git a/src/adcp/reporting/ledger/period_retirement.py b/src/adcp/reporting/ledger/period_retirement.py index 1f5a0b2425..2ab4e0a7f9 100644 --- a/src/adcp/reporting/ledger/period_retirement.py +++ b/src/adcp/reporting/ledger/period_retirement.py @@ -33,9 +33,10 @@ to relax those guards is an audit-model decision for the maintainers, not made here. Nothing is half-deleted: phase 3 either removes every record of the period or none. -**Fairness.** A period that cannot finish is parked with an exponential attempt backoff -(``attempts``, ``next_attempt_at``, ``last_outcome``) so it does not occupy a candidate slot -on every pass, and fresh periods always keep half of each pass's slots. +**Fairness.** A period that cannot finish records ``attempts``, ``next_attempt_at`` and +``last_failure`` and backs off (1 minute, doubling, capped at 6 hours), so it does not occupy a +candidate slot on every pass. Ready retries take at most half of a pass, rounded up, and fresh +periods fill the rest. The same names and numbers as the JavaScript SDK. """ from __future__ import annotations @@ -64,9 +65,13 @@ class ReportingPeriodRetirementV1: #: Expired periods this pass left alone because a hold applies (materializer work, a #: reconciliation record, or an unread registered feed consumer). Capped at 10,000. held: int = 0 - #: ``retiring`` periods waiting out an attempt backoff (protected records or a failing - #: provider), so they are not occupying candidate slots. - parked: int = 0 + #: ``retiring`` periods backing off after a failure (protected records or a failing + #: provider); they are not attempted this pass and occupy no candidate slot. + deferred: int = 0 + #: Periods still ``retiring`` after five or more failed attempts, worst first, at most 20: + #: ``(reporting_obligation_id, attempts, cause)``. They need operator attention, for + #: example a removed binding or a permanent provider error. + stuck: tuple[tuple[str, int, str], ...] = () async def _table_exists(connection: Any, name: str) -> bool: @@ -138,15 +143,13 @@ async def retire_expired_periods( fresh = await ( await connection.execute(_fresh_query("".join(holds), only=False), parameters) ).fetchall() - # Fresh periods always get a share of every pass: half the slots are reserved for them, - # and resumable periods take whatever the fresh ones leave. Otherwise a handful of - # periods that cannot finish would occupy every slot and starve retirement. - reserved = max(1, limit // 2) - take_fresh = min(len(fresh), max(reserved, limit - len(resumable))) - take_resumable = min(len(resumable), limit - take_fresh) - candidates = [*resumable[:take_resumable], *fresh[:take_fresh]] + # Ready retries (interrupted, failed or protected periods whose backoff has elapsed) are + # guaranteed at most half the pass, rounded up, ahead of fresh periods; a retry beyond + # that only fills the slots fresh periods leave empty. The same split as the JavaScript + # SDK, so a few periods that cannot finish never take every slot. + first = (limit + 1) // 2 + candidates = [*resumable[:first], *fresh, *resumable[first:]][:limit] held = await _held_count(connection, "".join(holds), parameters) - parked = await _parked_count(connection, account_id) has_rows = await _table_exists(connection, "adcp_reporting_row_sets") retired = 0 protected: list[str] = [] @@ -159,7 +162,11 @@ async def retire_expired_periods( except NoLongerEligibleError: continue except Exception as error: - await _back_off(store, obligation_id, "failed") + await _back_off( + store, + obligation_id, + error.code if isinstance(error, ReportingRowStoreError) else type(error).__name__, + ) failed.append(obligation_id) causes.append( ( @@ -176,19 +183,29 @@ async def retire_expired_periods( retired += 1 elif outcome == "protected": protected.append(obligation_id) + # What is left after this pass, so a host can see work no pass is reaching. + async with store._pool.connection() as connection: + deferred = await _deferred_count(connection, account_id) + stuck = await _stuck(connection, account_id) return ReportingPeriodRetirementV1( - retired, tuple(protected), tuple(failed), tuple(causes), held=held, parked=parked + retired, + tuple(protected), + tuple(failed), + tuple(causes), + held=held, + deferred=deferred, + stuck=stuck, ) def _resumable_query() -> str: - """``retiring`` periods whose attempt backoff has elapsed, oldest due first.""" + """``retiring`` periods whose backoff has elapsed: fewest failed attempts, then oldest.""" return ( "SELECT t.reporting_obligation_id, t.account_id" " FROM adcp_reporting_period_tombstones t WHERE t.state = 'retiring'" - " AND t.next_attempt_at <= clock_timestamp()" + " AND (t.next_attempt_at IS NULL OR t.next_attempt_at <= clock_timestamp())" " AND (%(account)s::text IS NULL OR t.account_id = %(account)s)" - " ORDER BY t.next_attempt_at, t.period_end, t.reporting_obligation_id LIMIT %(limit)s" + " ORDER BY t.attempts, t.period_end, t.reporting_obligation_id LIMIT %(limit)s" ) @@ -254,7 +271,7 @@ async def _held_count(connection: Any, holds: str, parameters: dict[str, Any]) - return max(0, int(row[0])) if row else 0 -async def _parked_count(connection: Any, account_id: str | None) -> int: +async def _deferred_count(connection: Any, account_id: str | None) -> int: row = await ( await connection.execute( "SELECT count(*) FROM adcp_reporting_period_tombstones WHERE state = 'retiring'" @@ -266,10 +283,28 @@ async def _parked_count(connection: Any, account_id: str | None) -> int: return int(row[0]) if row else 0 +#: Failed attempts after which a period is reported as stuck (the JavaScript SDK's threshold). +PERSISTENT_FAILURE_ATTEMPTS = 5 + + +async def _stuck(connection: Any, account_id: str | None) -> tuple[tuple[str, int, str], ...]: + rows = await ( + await connection.execute( + "SELECT reporting_obligation_id, attempts, last_failure" + " FROM adcp_reporting_period_tombstones" + " WHERE state = 'retiring' AND attempts >= %(threshold)s" + " AND (%(account)s::text IS NULL OR account_id = %(account)s)" + " ORDER BY attempts DESC, retiring_at, reporting_obligation_id LIMIT 20", + {"account": account_id, "threshold": PERSISTENT_FAILURE_ATTEMPTS}, + ) + ).fetchall() + return tuple((row[0], int(row[1]), row[2] or "Error") for row in rows) + + _BACKOFF = ( - "attempts = attempts + 1, last_outcome = %s," - " next_attempt_at = clock_timestamp() + LEAST(INTERVAL '24 hours'," - " INTERVAL '5 minutes' * power(2, LEAST(attempts, 10)))" + "attempts = attempts + 1, last_failure = %s," + " next_attempt_at = clock_timestamp()" + " + LEAST(21600, 60 * power(2, LEAST(attempts, 12))) * INTERVAL '1 second'" ) @@ -392,7 +427,7 @@ async def _retire_period( "UPDATE adcp_reporting_period_tombstones SET " # noqa: S608 # nosec B608 + _BACKOFF + " WHERE reporting_obligation_id = %s AND state = 'retiring'", - ("protected", obligation_id), + ("RECORDS_PROTECTED", obligation_id), ) return "protected" await connection.execute( diff --git a/src/adcp/reporting/ledger/pg.py b/src/adcp/reporting/ledger/pg.py index 0eba1baa56..1122265a2b 100644 --- a/src/adcp/reporting/ledger/pg.py +++ b/src/adcp/reporting/ledger/pg.py @@ -370,19 +370,28 @@ async def migrate_inline_rows( ) async def sweep_row_write_intents( - self, *, limit: int = 100, account_id: str | None = None + self, + *, + limit: int = 100, + account_id: str | None = None, + overdue_after_seconds: int = 24 * 3600, ) -> ReportingRowIntentSweepV1: """Resolve abandoned object uploads: delete only what an expired upload created. An expired write intent with no committed header moves to ``sweeping`` under the account lock, so no writer can commit against it, then the objects it created are deleted at their recorded versions. Adopted objects and objects a - committed chunk references are never touched. Schedule it alongside the + committed chunk references are never touched. An intent that fails backs off + (1 minute, doubling, capped at 6 hours) and never-failed intents go first, so one + broken binding cannot starve the rest; ``overdue_after_seconds`` (default 24 hours) + sets when an unswept intent is counted as ``overdue``. Schedule it alongside the producer. """ from adcp.reporting.ledger.row_retention import sweep_row_write_intents - return await sweep_row_write_intents(self, limit=limit, account_id=account_id) + return await sweep_row_write_intents( + self, limit=limit, account_id=account_id, overdue_after_seconds=overdue_after_seconds + ) async def prune_expired_row_sets( self, diff --git a/src/adcp/reporting/ledger/reporting_period_retirement.sql b/src/adcp/reporting/ledger/reporting_period_retirement.sql index 703edf39ad..a2c232f542 100644 --- a/src/adcp/reporting/ledger/reporting_period_retirement.sql +++ b/src/adcp/reporting/ledger/reporting_period_retirement.sql @@ -26,33 +26,40 @@ CREATE TABLE IF NOT EXISTS adcp_reporting_period_tombstones ( retiring_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), retired_at TIMESTAMPTZ, attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), - next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), - last_outcome TEXT, + next_attempt_at TIMESTAMPTZ, + last_failure TEXT, CHECK ((state = 'retired') = (retired_at IS NOT NULL)) ); -- A period that cannot finish (protected records, a failing provider) backs off exponentially --- instead of occupying a candidate slot on every pass. Added in place for earlier installs. +-- (1 minute, doubling, capped at 6 hours) instead of occupying a candidate slot on every pass. +-- Same column names and semantics as the JavaScript tombstones; NULL next_attempt_at means due. +-- Earlier installs are upgraded in place, including the first Python spelling of these columns. ALTER TABLE adcp_reporting_period_tombstones ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0); -ALTER TABLE adcp_reporting_period_tombstones - ADD COLUMN IF NOT EXISTS next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(); -ALTER TABLE adcp_reporting_period_tombstones - ADD COLUMN IF NOT EXISTS last_outcome TEXT; +ALTER TABLE adcp_reporting_period_tombstones ADD COLUMN IF NOT EXISTS next_attempt_at TIMESTAMPTZ; +ALTER TABLE adcp_reporting_period_tombstones ALTER COLUMN next_attempt_at DROP NOT NULL; +ALTER TABLE adcp_reporting_period_tombstones ALTER COLUMN next_attempt_at DROP DEFAULT; +ALTER TABLE adcp_reporting_period_tombstones ADD COLUMN IF NOT EXISTS last_failure TEXT; +DO $failure$ +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = 'adcp_reporting_period_tombstones' + AND column_name = 'last_outcome' + ) THEN + UPDATE adcp_reporting_period_tombstones SET last_failure = last_outcome + WHERE last_failure IS NULL AND last_outcome IS NOT NULL; + ALTER TABLE adcp_reporting_period_tombstones DROP COLUMN last_outcome; + END IF; +END +$failure$; +DROP INDEX IF EXISTS adcp_reporting_period_tombstones_due; CREATE INDEX IF NOT EXISTS adcp_reporting_period_tombstones_due - ON adcp_reporting_period_tombstones (next_attempt_at, period_end) + ON adcp_reporting_period_tombstones (attempts, period_end) WHERE state = 'retiring'; CREATE INDEX IF NOT EXISTS adcp_reporting_period_tombstones_account ON adcp_reporting_period_tombstones (account_id, delivery_config_id, period_start); --- Per-intent failure backoff for the intent sweep, so one binding that keeps failing cannot --- occupy every slot of every pass and starve the intents of other bindings. Python only: the --- shared write-intent table is not altered. -CREATE TABLE IF NOT EXISTS adcp_reporting_row_sweep_backoff ( - row_binding_id TEXT COLLATE "C" NOT NULL, - row_set_id TEXT COLLATE "C" NOT NULL, - content_sha256 TEXT COLLATE "C" NOT NULL, - attempts INTEGER NOT NULL CHECK (attempts > 0), - next_attempt_at TIMESTAMPTZ NOT NULL, - last_cause TEXT NOT NULL, - PRIMARY KEY (row_binding_id, row_set_id, content_sha256) -); +-- The first Python spelling of per-intent sweep backoff, replaced by sweep_attempts and +-- next_sweep_at on the shared write-intent table (the same columns the JavaScript SDK uses). +DROP TABLE IF EXISTS adcp_reporting_row_sweep_backoff; diff --git a/src/adcp/reporting/ledger/reporting_row_storage.sql b/src/adcp/reporting/ledger/reporting_row_storage.sql index ac8cbf431a..84c0622571 100644 --- a/src/adcp/reporting/ledger/reporting_row_storage.sql +++ b/src/adcp/reporting/ledger/reporting_row_storage.sql @@ -129,6 +129,8 @@ CREATE TABLE IF NOT EXISTS adcp_reporting_row_write_intents ( created_objects JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(created_objects) = 'array'), created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), expires_at TIMESTAMPTZ NOT NULL, + sweep_attempts INTEGER NOT NULL DEFAULT 0, + next_sweep_at TIMESTAMPTZ, PRIMARY KEY (row_binding_id, row_set_id, content_sha256) ); CREATE INDEX IF NOT EXISTS adcp_reporting_row_write_intents_expiry @@ -197,3 +199,9 @@ BEGIN END LOOP; END $triggers$; + +-- Per-intent sweep backoff (1 minute doubling to 6 hours), so one failing intent cannot hold the +-- head of every pass. The same columns the JavaScript SDK adds, for installs created before. +ALTER TABLE adcp_reporting_row_write_intents + ADD COLUMN IF NOT EXISTS sweep_attempts INTEGER NOT NULL DEFAULT 0; +ALTER TABLE adcp_reporting_row_write_intents ADD COLUMN IF NOT EXISTS next_sweep_at TIMESTAMPTZ; diff --git a/src/adcp/reporting/ledger/required_row_storage_schema.json b/src/adcp/reporting/ledger/required_row_storage_schema.json index 29ec2909be..0059c43f25 100644 --- a/src/adcp/reporting/ledger/required_row_storage_schema.json +++ b/src/adcp/reporting/ledger/required_row_storage_schema.json @@ -215,6 +215,10 @@ "enabled": true, "fingerprint": "1cac4e73af11a8ecafd646ef6a0ff6ecb087d46f150408dcfebc630fe1bf5e1e" }, + "column:adcp_reporting_row_write_intents.next_sweep_at": { + "enabled": true, + "fingerprint": "6f1466ce5d0aaac8471e39834b9c4b1f85d6f7169d9238a245ac035ff518e0fc" + }, "column:adcp_reporting_row_write_intents.owner_token": { "enabled": true, "fingerprint": "fdc4b549138bf90a5af5ed00b87a86ff9a0cbea553e7f017b4d95510708f6f88" @@ -231,6 +235,10 @@ "enabled": true, "fingerprint": "69ff456c4ece2240eee5eddda514b673f39e572f0191c402234ea6371a703b95" }, + "column:adcp_reporting_row_write_intents.sweep_attempts": { + "enabled": true, + "fingerprint": "007695a9578f516b3258aec34c21226bcc951e9cf02c8fc089e3926cbb871e25" + }, "constraint:adcp_persistence_installation.adcp_persistence_installation_pkey": { "enabled": true, "fingerprint": "6d646464d3fcdea76ac48511fecf27101a27ee2e0844407a8a9f933b021ba949" diff --git a/src/adcp/reporting/ledger/row_retention.py b/src/adcp/reporting/ledger/row_retention.py index 4df8ae7217..b8fd3ca362 100644 --- a/src/adcp/reporting/ledger/row_retention.py +++ b/src/adcp/reporting/ledger/row_retention.py @@ -49,17 +49,19 @@ class ReportingRowIntentSweepV1: swept: int objects_deleted: int + #: Intents whose sweep failed this pass. Each backs off before its next attempt. failed: int #: Stable, secret-free cause per failed intent: ``(row_set_id, code)``. causes: tuple[tuple[str, str], ...] = () - #: Expired intents of bindings this host does not configure; another host owns them. + #: Expired intents with objects to delete through a binding this host does not configure. + #: They are left untouched for a host that configures it; they are not this host's failures. skipped_unconfigured: int = 0 - #: Expired intents of configured bindings waiting out a failure backoff this pass. - backed_off: int = 0 - #: Intents of any binding that have been expired for more than a day and are still - #: unresolved: nobody is handling them (a binding no host configures any more, or one - #: that keeps failing), so their orphaned objects are never cleaned up. - stalled: int = 0 + #: Expired intents backing off after a failed sweep, not attempted this pass. + deferred: int = 0 + #: Intents expired for longer than ``overdue_after_seconds`` (default 24 hours) and still not + #: swept, including ones backing off. Their objects are leaking: check that a host configures + #: their binding and that provider deletes succeed. + overdue: int = 0 @dataclass(frozen=True, slots=True) @@ -78,10 +80,16 @@ def _positive(value: int, name: str) -> None: async def sweep_row_write_intents( - store: PgReportingLedgerStore, *, limit: int = 100, account_id: str | None = None + store: PgReportingLedgerStore, + *, + limit: int = 100, + account_id: str | None = None, + overdue_after_seconds: int = 24 * 3600, ) -> ReportingRowIntentSweepV1: """Resolve abandoned object uploads. Safe to run on a schedule from any worker.""" _positive(limit, "limit") + if type(overdue_after_seconds) is not int or overdue_after_seconds < 1: + raise ValueError("overdue_after_seconds must be a positive integer") storage = store._row_storage if storage is None: raise ReportingRowStoreError( @@ -92,43 +100,29 @@ async def sweep_row_write_intents( "account": account_id, "bindings": list(storage._bindings), "limit": limit, + "overdue": overdue_after_seconds, } + due = ( + "(%(account)s::text IS NULL OR account_id = %(account)s)" + " AND (state = 'sweeping' OR expires_at <= clock_timestamp())" + ) async with store._pool.connection() as connection: - # Intents that failed recently wait out an exponential backoff, and never-failed ones - # come first, so one binding that keeps failing cannot occupy every slot of every pass. + # An intent with no recorded objects needs no binding to sweep; one with objects is + # skipped unless this host configures its binding. Intents that failed before back off, + # and never-failed ones come first, so a failing intent cannot hold the head of every + # pass. (The same selection as the JavaScript SDK.) expired = await ( await connection.execute( - "SELECT i.row_binding_id, i.account_id, i.row_set_id, i.content_sha256" - " FROM adcp_reporting_row_write_intents i" - " LEFT JOIN adcp_reporting_row_sweep_backoff b" - " ON b.row_binding_id = i.row_binding_id AND b.row_set_id = i.row_set_id" - " AND b.content_sha256 = i.content_sha256" - " WHERE (%(account)s::text IS NULL OR i.account_id = %(account)s)" - " AND i.row_binding_id = ANY(%(bindings)s::text[])" - " AND (i.state = 'sweeping' OR i.expires_at <= clock_timestamp())" - " AND (b.next_attempt_at IS NULL OR b.next_attempt_at <= clock_timestamp())" - " ORDER BY COALESCE(b.attempts, 0), i.expires_at LIMIT %(limit)s", + "SELECT row_binding_id, account_id, row_set_id, content_sha256" + " FROM adcp_reporting_row_write_intents" + f" WHERE {due}" # noqa: S608 # nosec B608 + " AND (next_sweep_at IS NULL OR next_sweep_at <= clock_timestamp())" + " AND (row_binding_id = ANY(%(bindings)s::text[])" + " OR created_objects = '[]'::jsonb)" + " ORDER BY sweep_attempts, expires_at LIMIT %(limit)s", parameters, ) ).fetchall() - counts = await ( - await connection.execute( - "SELECT" - " count(*) FILTER (WHERE NOT (i.row_binding_id = ANY(%(bindings)s::text[])))" - " AS unconfigured," - " count(*) FILTER (WHERE i.row_binding_id = ANY(%(bindings)s::text[])" - " AND b.next_attempt_at > clock_timestamp()) AS backed_off" - " FROM adcp_reporting_row_write_intents i" - " LEFT JOIN adcp_reporting_row_sweep_backoff b" - " ON b.row_binding_id = i.row_binding_id AND b.row_set_id = i.row_set_id" - " AND b.content_sha256 = i.content_sha256" - " WHERE (%(account)s::text IS NULL OR i.account_id = %(account)s)" - " AND (i.state = 'sweeping' OR i.expires_at <= clock_timestamp())", - parameters, - ) - ).fetchone() - skipped = int(counts[0]) if counts else 0 - backed_off = int(counts[1]) if counts else 0 causes: list[tuple[str, str]] = [] swept = deleted = failed = 0 for binding_id, owner, row_set_id, content_sha256 in expired: @@ -158,21 +152,12 @@ async def sweep_row_write_intents( " AND state = 'sweeping'", key, ) - async with store._pool.connection() as connection: - await connection.execute( - "DELETE FROM adcp_reporting_row_sweep_backoff" - " WHERE row_binding_id = %s AND row_set_id = %s AND content_sha256 = %s", - key, - ) swept += 1 deleted += removed except Exception as error: failed += 1 - await _back_off_intent( - store, - key, - error.code if isinstance(error, ReportingRowStoreError) else type(error).__name__, - ) + # Cancellation is shutdown, not a fault: it is a BaseException, never recorded here. + await _back_off_intent(store, key) causes.append( ( row_set_id, @@ -184,19 +169,20 @@ async def sweep_row_write_intents( ) ) async with store._pool.connection() as connection: - # Backoff rows outlive nothing: drop those whose intent is gone, then count what is stuck. - await connection.execute( - "DELETE FROM adcp_reporting_row_sweep_backoff b WHERE NOT EXISTS (" - " SELECT 1 FROM adcp_reporting_row_write_intents i" - " WHERE i.row_binding_id = b.row_binding_id AND i.row_set_id = b.row_set_id" - " AND i.content_sha256 = b.content_sha256)" - ) - stalled_row = await ( + # What is still waiting after this pass, so a host can see work no pass is reaching. + backlog = await ( await connection.execute( - "SELECT count(*) FROM adcp_reporting_row_write_intents" - " WHERE (%(account)s::text IS NULL OR account_id = %(account)s)" - " AND expires_at <= clock_timestamp() - INTERVAL '1 day'", - {"account": account_id}, + "SELECT" + " count(*) FILTER (WHERE row_binding_id <> ALL(%(bindings)s::text[])" + " AND created_objects <> '[]'::jsonb) AS skipped," + " count(*) FILTER (WHERE (row_binding_id = ANY(%(bindings)s::text[])" + " OR created_objects = '[]'::jsonb)" + " AND next_sweep_at > clock_timestamp()) AS deferred," + " count(*) FILTER (WHERE expires_at <= clock_timestamp()" + " - (%(overdue)s::integer * INTERVAL '1 second')) AS overdue" + " FROM adcp_reporting_row_write_intents" + f" WHERE {due}", # noqa: S608 # nosec B608 + parameters, ) ).fetchone() return ReportingRowIntentSweepV1( @@ -204,30 +190,27 @@ async def sweep_row_write_intents( deleted, failed, tuple(causes), - skipped, - backed_off, - int(stalled_row[0]) if stalled_row else 0, + skipped_unconfigured=int(backlog[0]) if backlog else 0, + deferred=int(backlog[1]) if backlog else 0, + overdue=int(backlog[2]) if backlog else 0, ) -async def _back_off_intent( - store: PgReportingLedgerStore, key: tuple[str, str, str], cause: str -) -> None: - """Record a failed sweep of one intent; best effort, never raises.""" +async def _back_off_intent(store: PgReportingLedgerStore, key: tuple[str, str, str]) -> None: + """Record a failed sweep of one intent: 1 minute, doubling, capped at 6 hours. + + Best effort, never raises: a failure to record only means a retry on the next pass. + """ try: async with store._pool.connection() as connection: await connection.execute( - "INSERT INTO adcp_reporting_row_sweep_backoff" - " (row_binding_id, row_set_id, content_sha256, attempts, next_attempt_at," - " last_cause)" - " VALUES (%s, %s, %s, 1, clock_timestamp() + INTERVAL '1 minute', %s)" - " ON CONFLICT (row_binding_id, row_set_id, content_sha256) DO UPDATE SET" - " attempts = adcp_reporting_row_sweep_backoff.attempts + 1," - " next_attempt_at = clock_timestamp() + LEAST(INTERVAL '1 hour'," - " INTERVAL '1 minute' *" - " power(2, LEAST(adcp_reporting_row_sweep_backoff.attempts, 6)))," - " last_cause = EXCLUDED.last_cause", - (*key, cause), + "UPDATE adcp_reporting_row_write_intents" + " SET sweep_attempts = sweep_attempts + 1," + " next_sweep_at = clock_timestamp()" + " + LEAST(21600, 60 * power(2, LEAST(sweep_attempts, 12)))" + " * INTERVAL '1 second'" + " WHERE row_binding_id = %s AND row_set_id = %s AND content_sha256 = %s", + key, ) except Exception: # noqa: S110 # nosec B110 pass diff --git a/src/adcp/reporting/production/_diagnostics.py b/src/adcp/reporting/production/_diagnostics.py index e1837504a5..366574dd8e 100644 --- a/src/adcp/reporting/production/_diagnostics.py +++ b/src/adcp/reporting/production/_diagnostics.py @@ -54,10 +54,10 @@ def _worker_stopped(*, boundary: _WorkerBoundary) -> None: "failed", "protected", "held", - "parked", + "deferred", + "stuck", "skipped_unconfigured", - "backed_off", - "stalled", + "overdue", } ) diff --git a/src/adcp/reporting/production/service.py b/src/adcp/reporting/production/service.py index c859338089..fbbbf61d69 100644 --- a/src/adcp/reporting/production/service.py +++ b/src/adcp/reporting/production/service.py @@ -763,13 +763,16 @@ async def _maintain(self) -> None: # is visible instead of looking like a healthy idle worker. pending = { key: counts[key] - for key in ("protected", "held", "parked", "skipped_unconfigured", "backed_off") + for key in ("protected", "held", "deferred", "skipped_unconfigured") if counts.get(key) } if pending: _maintenance_pending(operation=name, counts=pending) - if counts.get("stalled"): - _maintenance_stalled(operation=name, counts={"stalled": counts["stalled"]}) + # Work nobody is reaching: intents expired past the overdue threshold, or periods that + # keep failing (five or more attempts). The same signals the JavaScript SDK reports. + stalled = {key: counts[key] for key in ("overdue", "stuck") if counts.get(key)} + if stalled: + _maintenance_stalled(operation=name, counts=stalled) async def _run_notifications(self) -> None: from adcp.reporting.production.notifications import notification_turn @@ -879,10 +882,10 @@ def _counts(result: Any) -> dict[str, int]: "failed", "protected", "held", - "parked", + "deferred", + "stuck", "skipped_unconfigured", - "backed_off", - "stalled", + "overdue", ): value = getattr(result, name, None) if isinstance(value, (tuple, list)): diff --git a/tests/conformance/reporting/test_reporting_change_feed_pg.py b/tests/conformance/reporting/test_reporting_change_feed_pg.py index cf9fa8d5cf..8b2f74c6e9 100644 --- a/tests/conformance/reporting/test_reporting_change_feed_pg.py +++ b/tests/conformance/reporting/test_reporting_change_feed_pg.py @@ -257,27 +257,132 @@ async def test_pages_cross_99_to_100_in_numeric_order_on_both_feeds() -> None: assert seen == list(range(95, 131)), (account, seen) -async def test_account_readers_do_not_rely_on_the_account_lock_to_see_changes_in_order() -> None: - """Two writers that do not share a lock (for example two SDKs on one account) can commit - out of ``seq`` order; a reader must not skip the slower one's change for good.""" +# -- account feed ordering, ported from the JavaScript SDK (adcp-client #3228) --------------- + +INSERT_CHANGE = ( + "INSERT INTO adcp_reporting_changes (account_id, record_kind, record_id, obligation_id)" + " VALUES ('acct_hol_feed', 'revision', %s, 'robl_hol_feed')" +) + + +def ids(page: Any) -> list[str]: + return [record.record_id for record in page.records] + + +async def committed(pool: Any, record_id: str) -> None: + async with pool.connection() as connection: + await connection.execute(INSERT_CHANGE, (record_id,)) + + +async def until(read: Any, expected: list[str]) -> Any: + """Other tests share the cluster, so an unrelated older transaction can briefly hold a page + back: positive reads poll. The assertions that a page is held back do not need it.""" + import asyncio + + for _ in range(200): + page = await read() + if ids(page) == expected: + return page + await asyncio.sleep(0.05) + return page + + +async def test_a_lower_seq_that_commits_after_a_higher_one_is_never_passed_over() -> None: async with isolated_reporting_pool() as pool: store = await feed_store(pool) - insert = ( - "INSERT INTO adcp_reporting_changes (account_id, record_kind, record_id, obligation_id)" - " VALUES ('acct_a', 'revision', %s, 'obl_a')" - ) + start = await store.changes_after(account_id="acct_hol_feed") slow = await pool.getconn() try: - await slow.execute(insert, ("slow",)) # seq 1, still in flight - async with pool.connection() as fast: - await fast.execute(insert, ("fast",)) # seq 2, commits first - page = await store.changes_after(account_id="acct_a") - # seq 2 is committed but must wait for seq 1: reading past it would skip seq 1. - assert [record.record_id for record in page.records] == [] + await slow.execute(INSERT_CHANGE, ("rrev_low",)) # the lower seq, commits last + await committed(pool, "rrev_high") # a higher seq, committed already + during = await store.changes_after(account_id="acct_hol_feed", cursor=start.cursor) + assert ids(during) == [], "the page stops before the unfinished transaction" + assert during.cursor == start.cursor, "the cursor does not move past it" await slow.commit() finally: await pool.putconn(slow) - page = await store.changes_after(account_id="acct_a") - assert [record.record_id for record in page.records] == ["slow", "fast"] - resumed = await store.changes_after(account_id="acct_a", cursor=page.cursor) - assert resumed.records == () + after = await until( + lambda: store.changes_after(account_id="acct_hol_feed", cursor=start.cursor), + ["rrev_low", "rrev_high"], + ) + assert ids(after) == ["rrev_low", "rrev_high"] + + +async def test_a_held_back_change_is_never_skipped_when_a_later_one_passes_a_plain_xid_filter() -> ( + None +): + async with isolated_reporting_pool() as pool: + store = await feed_store(pool) + start = await store.changes_after(account_id="acct_hol_feed") + early = await pool.getconn() + blocker = await pool.getconn() + try: + # xid order: early < blocker < the change inserted next. + await early.execute("SELECT pg_current_xact_id()") + await blocker.execute("SELECT pg_current_xact_id()") + await committed(pool, "rrev_first") # lower seq, but a transaction after `blocker` + await early.execute(INSERT_CHANGE, ("rrev_second",)) # higher seq, xid before `blocker` + await early.commit() + # `blocker` is the oldest transaction in flight, so rrev_first is held back while + # rrev_second sits below it. Filtering on xid alone would return rrev_second and a + # cursor past rrev_first, which would then never be seen. + during = await store.changes_after(account_id="acct_hol_feed", cursor=start.cursor) + assert ids(during) == [] + assert during.cursor == start.cursor, "the cursor does not move past the held change" + await blocker.commit() + finally: + await pool.putconn(early) + await pool.putconn(blocker) + after = await until( + lambda: store.changes_after(account_id="acct_hol_feed", cursor=start.cursor), + ["rrev_first", "rrev_second"], + ) + assert ids(after) == ["rrev_first", "rrev_second"] + + +async def test_a_committed_prefix_is_returned_and_the_cursor_stops_before_the_first_in_flight() -> ( + None +): + async with isolated_reporting_pool() as pool: + store = await feed_store(pool) + start = await store.changes_after(account_id="acct_hol_feed") + await committed(pool, "rrev_prefix_a") + opened = await pool.getconn() + try: + await opened.execute(INSERT_CHANGE, ("rrev_prefix_b",)) # in flight + await committed(pool, "rrev_prefix_c") # committed after it + during = await until( + lambda: store.changes_after(account_id="acct_hol_feed", cursor=start.cursor), + ["rrev_prefix_a"], + ) + assert ids(during) == ["rrev_prefix_a"], "truncated, not filtered" + await opened.commit() + rest = await until( + lambda: store.changes_after(account_id="acct_hol_feed", cursor=during.cursor), + ["rrev_prefix_b", "rrev_prefix_c"], + ) + assert ids(rest) == ["rrev_prefix_b", "rrev_prefix_c"] + finally: + await pool.putconn(opened) + + +async def test_the_account_feed_query_is_served_by_the_account_seq_index() -> None: + from adcp.reporting.ledger.change_feed import _page_query + + async with isolated_reporting_pool() as pool: + await feed_store(pool) + async with pool.connection() as connection: + await connection.execute( + "INSERT INTO adcp_reporting_changes (account_id, record_kind, record_id," + " obligation_id) SELECT 'acct_filler_' || n, 'revision', 'rrev_filler_' || n," + " 'robl_filler' FROM generate_series(1, 2000) AS n" + ) + await connection.execute("ANALYZE adcp_reporting_changes") + # The very query the store runs for an account page, planned with its parameters. + plan = await ( + await connection.execute( + "EXPLAIN " + _page_query(account=True), + ("acct_hol_feed", 0, None, None, 500), + ) + ).fetchall() + assert "adcp_reporting_changes_account" in "\n".join(row[0] for row in plan) diff --git a/tests/conformance/reporting/test_reporting_period_retirement_pg.py b/tests/conformance/reporting/test_reporting_period_retirement_pg.py index 0e19b7d3e5..814228a9b6 100644 --- a/tests/conformance/reporting/test_reporting_period_retirement_pg.py +++ b/tests/conformance/reporting/test_reporting_period_retirement_pg.py @@ -25,7 +25,7 @@ async def make_due(pool: Any) -> None: """Let every attempt backoff elapse, as waiting would.""" async with pool.connection() as connection: await connection.execute( - "UPDATE adcp_reporting_period_tombstones SET next_attempt_at = clock_timestamp()" + "UPDATE adcp_reporting_period_tombstones SET next_attempt_at = NULL" ) @@ -173,7 +173,7 @@ async def test_a_failed_external_delete_leaves_the_period_retiring_and_resumes( assert len(list_objects(tmp_path / "rows")) == 1 # The failed period backs off instead of retrying on every pass. - assert stuck.failed and (await store.retire_expired_periods()).parked == 1 + assert stuck.failed and (await store.retire_expired_periods()).deferred == 1 await make_due(pool) resumed = await store.retire_expired_periods() @@ -329,12 +329,18 @@ async def test_protected_periods_back_off_and_never_starve_fresh_ones() -> None: assert seen_protected == [protected.reporting_obligation_id] remaining = await fetch_all( pool, - "SELECT reporting_obligation_id, state, attempts, last_outcome," + "SELECT reporting_obligation_id, state, attempts, last_failure," " next_attempt_at > clock_timestamp() FROM adcp_reporting_period_tombstones" " ORDER BY state", ) - assert (protected.reporting_obligation_id, "retiring", 1, "protected", True) in remaining - assert (await store.retire_expired_periods(limit=1)).parked == 1 + assert ( + protected.reporting_obligation_id, + "retiring", + 1, + "RECORDS_PROTECTED", + True, + ) in remaining + assert (await store.retire_expired_periods(limit=1)).deferred == 1 async def test_the_backoff_grows_with_each_attempt_and_the_period_is_retried_once_due() -> None: @@ -351,12 +357,12 @@ async def state() -> tuple[int, float]: return attempts, float(seconds) first_attempts, first_wait = await state() - assert first_attempts == 1 and 0 < first_wait <= 300 + assert first_attempts == 1 and 30 < first_wait <= 60 # the first backoff is a minute await make_due(pool) again = await store.retire_expired_periods(limit=5) assert again.protected == (protected.reporting_obligation_id,) second_attempts, second_wait = await state() - assert second_attempts == 2 and second_wait > 300 # 10 minutes after two attempts + assert second_attempts == 2 and 90 < second_wait <= 120 # then it doubles async def test_held_periods_are_counted_not_silently_dropped() -> None: @@ -451,7 +457,7 @@ async def test_an_earlier_tombstone_table_gains_the_backoff_columns_in_place() - " period_end, state, revision_count, adjustment_count)" " VALUES ('rpo_old', 'a', 'c', 'd', 1, now(), now(), 'retiring', 0, 0)" ) - for column in ("attempts", "next_attempt_at", "last_outcome"): + for column in ("attempts", "next_attempt_at", "last_failure"): await connection.execute( f"ALTER TABLE adcp_reporting_period_tombstones DROP COLUMN {column}" # noqa: S608 ) @@ -459,6 +465,106 @@ async def test_an_earlier_tombstone_table_gains_the_backoff_columns_in_place() - await store.create_schema() assert await fetch_all( pool, - "SELECT attempts, last_outcome, next_attempt_at <= clock_timestamp()" + "SELECT attempts, last_failure, next_attempt_at IS NULL" " FROM adcp_reporting_period_tombstones", ) == [(0, None, True)] + + +# -- head-of-line parity with the JavaScript SDK (adcp-client #3228) ------------------------- + + +async def object_period(store: PgReportingLedgerStore, pool: Any, account: str) -> Any: + config = configuration(account) + await store.put_configuration(config) + obligation = await store.commit_obligation(obligation_for(config)) + await lease(pool) + rows = many_rows(10) + revision = typed_revision(obligation, rows, suffix=account) + await store.stage_revision_rows(revision, rows) + await store.commit_revision(revision, rows) + return obligation + + +def without_binding(configured: Any, pool: Any) -> PgReportingLedgerStore: + """A host that no longer configures the binding: deleting the period's objects fails.""" + return PgReportingLedgerStore( + pool=pool, row_storage=type(configured)(deployment_namespace="test"), change_feed=True + ) + + +async def wait_seconds(pool: Any, obligation_id: str) -> float: + ((seconds,),) = await fetch_all( + pool, + "SELECT EXTRACT(EPOCH FROM next_attempt_at - clock_timestamp())" + " FROM adcp_reporting_period_tombstones WHERE reporting_obligation_id = %s", + (obligation_id,), + ) + return float(seconds) + + +async def test_backoff_doubles_to_six_hours_and_a_persistent_failure_is_reported( + tmp_path: Path, +) -> None: + async with isolated_reporting_pool() as pool: + configured = options(tmp_path) + store = PgReportingLedgerStore(pool=pool, row_storage=configured, change_feed=True) + await store.create_schema() + period = await object_period(store, pool, "acct_a1") + await age(pool, days=500) + broken = without_binding(configured, pool) + for attempt in range(1, 6): + result = await broken.retire_expired_periods() + assert result.failed == (period.reporting_obligation_id,) + expected = 60 * 2 ** (attempt - 1) + seconds = await wait_seconds(pool, period.reporting_obligation_id) + assert expected - 30 < seconds <= expected, (attempt, seconds) + # Four failures are not yet persistent. + assert len(result.stuck) == (1 if attempt >= 5 else 0) + await make_due(pool) + assert result.stuck == ((period.reporting_obligation_id, 5, "STATE_UNAVAILABLE"),) + + # The cap. + async with pool.connection() as connection: + await connection.execute("UPDATE adcp_reporting_period_tombstones SET attempts = 40") + await broken.retire_expired_periods() + capped = await wait_seconds(pool, period.reporting_obligation_id) + assert 6 * 3600 - 30 < capped <= 6 * 3600 + + +async def test_with_only_retries_ready_the_cap_does_not_slow_the_drain(tmp_path: Path) -> None: + async with isolated_reporting_pool() as pool: + configured = options(tmp_path) + store = PgReportingLedgerStore(pool=pool, row_storage=configured, change_feed=True) + await store.create_schema() + for account in ("acct_a1", "acct_a2", "acct_a3"): + await object_period(store, pool, account) + await age(pool, days=500) + failed = await without_binding(configured, pool).retire_expired_periods(limit=3) + assert len(failed.failed) == 3 + await make_due(pool) + # Three retries are ready and nothing else is eligible: both slots go to retries. + result = await store.retire_expired_periods(limit=2) + assert (result.retired, result.failed) == (2, ()) + + +async def test_fresh_periods_keep_a_share_when_failing_periods_are_ready_to_retry( + tmp_path: Path, +) -> None: + async with isolated_reporting_pool() as pool: + configured = options(tmp_path) + store = PgReportingLedgerStore(pool=pool, row_storage=configured, change_feed=True) + await store.create_schema() + first = await object_period(store, pool, "acct_a1") + await object_period(store, pool, "acct_a2") + await age(pool, days=500) + failed = await without_binding(configured, pool).retire_expired_periods(limit=2) + assert len(failed.failed) == 2 + await make_due(pool) + fresh = await object_period(store, pool, "acct_a3") + await age(pool, days=500) # the fresh period is expired too + + # Two failing retries are ready, but they may take only half the pass: one retry (the + # oldest with the fewest attempts) and the fresh period share it. This host cannot + # delete, so both attempts fail, which shows who was selected. + result = await without_binding(configured, pool).retire_expired_periods(limit=2) + assert result.failed == (first.reporting_obligation_id, fresh.reporting_obligation_id) diff --git a/tests/conformance/reporting/test_reporting_row_retention_pg.py b/tests/conformance/reporting/test_reporting_row_retention_pg.py index f3bff153bf..6b219eaf56 100644 --- a/tests/conformance/reporting/test_reporting_row_retention_pg.py +++ b/tests/conformance/reporting/test_reporting_row_retention_pg.py @@ -372,84 +372,218 @@ async def test_a_failed_sweep_reports_its_stable_cause(tmp_path: Path) -> None: ] -async def test_intents_that_keep_failing_back_off_and_never_starve_the_rest(tmp_path: Path) -> None: - async with isolated_reporting_pool() as pool: - store = PgReportingLedgerStore(pool=pool, row_storage=options(tmp_path)) - await store.create_schema() - obligation = await seeded(store) - await lease(pool) - revisions = [ - await staged_revision(store, obligation, f"r{index}", many_rows(10 + index)) - for index in range(4) - ] - bad, good = revisions[:3], revisions[3] - async with pool.connection() as connection: - for age, revision in enumerate([*bad, good]): - # The failing intents are the oldest, so oldest-first selection picks them first. - await connection.execute( - "UPDATE adcp_reporting_row_write_intents SET expires_at =" - " clock_timestamp() - make_interval(secs => %s) WHERE row_set_id = %s", - (3600 - age * 60, revision.reporting_revision_id), - ) - for number, revision in enumerate(bad): - await connection.execute( - "UPDATE adcp_reporting_row_write_intents SET created_objects = %s::jsonb" - " WHERE row_set_id = %s", - ( - json.dumps( - [{"objectKey": f"other/tenant/{number}", "nativeVersion": "1:2:3:4"}] - ), - revision.reporting_revision_id, - ), - ) - # Two slots per pass: before the backoff the three failing intents filled them forever. - swept = 0 - for _ in range(3): - swept += (await store.sweep_row_write_intents(limit=2)).swept - assert swept == 1, "the healthy intent must be swept despite the failing ones" - assert await fetch_all( - pool, "SELECT count(*), min(attempts) FROM adcp_reporting_row_sweep_backoff" - ) == [(3, 1)] - idle = await store.sweep_row_write_intents(limit=2) - assert (idle.swept, idle.failed, idle.backed_off) == (0, 0, 3) - # Once a backoff elapses the intent is retried, and its next wait is longer. - async with pool.connection() as connection: +# -- head-of-line parity with the JavaScript SDK (adcp-client #3228) ------------------------- + + +class SweepHarness: + """Intents inserted directly, with provider deletes that fail for chosen keys.""" + + def __init__(self, pool: Any, store: PgReportingLedgerStore, failing: set[str]) -> None: + self.pool = pool + self.store = store + self.failing = failing + storage = store._row_storage + assert storage is not None + self.namespace = storage.installation_identity[1] + + def key(self, name: str) -> str: + return f"adcp-rows/{self.namespace}/hol/{name}.jsonl" + + async def add( + self, + row_set_id: str, + *, + binding: str = "reports", + objects: tuple[str, ...] = (), + expired_seconds: int = 3600, + state: str = "open", + ) -> None: + created = [{"objectKey": self.key(name), "nativeVersion": "v1"} for name in objects] + async with self.pool.connection() as connection: await connection.execute( - "UPDATE adcp_reporting_row_sweep_backoff SET next_attempt_at = clock_timestamp()" + "INSERT INTO adcp_reporting_row_write_intents (row_binding_id, account_id," + " row_set_id, content_sha256, state, owner_token, created_objects, expires_at)" + " VALUES (%s, 'acct_hol', %s, %s, %s, 'owner', %s::jsonb," + " clock_timestamp() - make_interval(secs => %s))", + (binding, row_set_id, "d" * 64, state, json.dumps(created), expired_seconds), ) - retried = await store.sweep_row_write_intents(limit=10) - assert retried.failed == 3 - assert await fetch_all( - pool, "SELECT min(attempts) FROM adcp_reporting_row_sweep_backoff" - ) == [(2,)] - -async def test_intents_nobody_handles_are_reported_as_skipped_and_then_stalled( - tmp_path: Path, -) -> None: - async with isolated_reporting_pool() as pool: - configured = options(tmp_path) - store = PgReportingLedgerStore(pool=pool, row_storage=configured) - await store.create_schema() - obligation = await seeded(store) - await lease(pool) - await staged_revision(store, obligation, "orphan", many_rows(10)) - # A host that no longer configures the binding cannot sweep: it counts, never errors. - without = PgReportingLedgerStore( - pool=pool, row_storage=type(configured)(deployment_namespace="test") + async def row(self, row_set_id: str) -> Any: + rows = await fetch_all( + self.pool, + "SELECT state, sweep_attempts, next_sweep_at FROM adcp_reporting_row_write_intents" + " WHERE row_set_id = %s", + (row_set_id,), ) - async with pool.connection() as connection: + return rows[0] if rows else None + + async def clear_backoff(self) -> None: + async with self.pool.connection() as connection: await connection.execute( - "UPDATE adcp_reporting_row_write_intents" - " SET expires_at = clock_timestamp() - INTERVAL '2 hours'" + "UPDATE adcp_reporting_row_write_intents SET next_sweep_at = NULL" ) - recent = await without.sweep_row_write_intents() - assert (recent.skipped_unconfigured, recent.stalled, recent.failed) == (1, 0, 0) - # Expired for much longer than any sweep interval: nobody is handling it. + + async def sweep(self, **kwargs: Any) -> tuple[int, int, int, int, int, int]: + result = await self.store.sweep_row_write_intents(**kwargs) + return ( + result.swept, + result.objects_deleted, + result.failed, + result.skipped_unconfigured, + result.deferred, + result.overdue, + ) + + +@pytest.fixture +async def harness(tmp_path: Path) -> Any: + from dataclasses import replace + + failing: set[str] = set() + inner = create_filesystem_reporting_row_object_provider_v1(roots={"rows": tmp_path / "rows"}) + + class Failing: + name = inner.name + ranged_reads = inner.ranged_reads + + def validate_location(self, location: Any) -> None: + inner.validate_location(location) + + async def probe(self, *args: Any, **kwargs: Any) -> None: + await inner.probe(*args, **kwargs) + + async def put_if_absent(self, put: Any, context: Any) -> Any: + return await inner.put_if_absent(put, context) + + async def get(self, get: Any, context: Any) -> Any: + return await inner.get(get, context) + + async def delete(self, delete: Any, context: Any) -> Any: + if delete.key in failing: + raise RuntimeError("provider unavailable") + return await inner.delete(delete, context) + + async with isolated_reporting_pool() as pool: + store = PgReportingLedgerStore( + pool=pool, row_storage=replace(options(tmp_path), providers={"filesystem": Failing()}) + ) + await store.create_schema() + # A binding another host configured and this one does not. async with pool.connection() as connection: await connection.execute( - "UPDATE adcp_reporting_row_write_intents" - " SET expires_at = clock_timestamp() - INTERVAL '3 days'" + "INSERT INTO adcp_reporting_row_bindings (row_binding_id, kind, provider," + " identity_config, identity_sha256, namespace_key)" + " VALUES ('ghost', 'object', 'filesystem', '{}', %s, %s)", + ("e" * 64, "f" * 64), ) - stale = await without.sweep_row_write_intents() - assert (stale.skipped_unconfigured, stale.stalled) == (1, 1) + yield SweepHarness(pool, store, failing) + + +async def test_with_limit_one_a_permanently_failing_intent_does_not_block_an_eligible_one( + harness: SweepHarness, +) -> None: + harness.failing.add(harness.key("failing")) + await harness.add("rrev_failing", objects=("failing",), expired_seconds=3 * 3600) + await harness.add("rrev_healthy", objects=("healthy",), expired_seconds=3600) + + # The oldest intent is tried first and fails. + assert await harness.sweep(limit=1) == (0, 0, 1, 0, 1, 0) + state, attempts, next_sweep_at = await harness.row("rrev_failing") + assert attempts == 1 and next_sweep_at is not None + # It backs off, so the healthy one is swept. + assert await harness.sweep(limit=1) == (1, 1, 0, 0, 1, 0) + assert await harness.row("rrev_healthy") is None + # Not retried before its backoff elapses; once the provider recovers it is swept. + assert await harness.sweep(limit=1) == (0, 0, 0, 0, 1, 0) + harness.failing.clear() + await harness.clear_backoff() + assert await harness.sweep(limit=1) == (1, 1, 0, 0, 0, 0) + assert await harness.row("rrev_failing") is None + + +async def test_a_retry_never_takes_the_slot_of_a_fresh_intent(harness: SweepHarness) -> None: + harness.failing.add(harness.key("retry_first")) + await harness.add("rrev_retry_first", objects=("retry_first",), expired_seconds=5 * 3600) + await harness.sweep(limit=1) + await harness.clear_backoff() + await harness.add("rrev_fresh_after", objects=("fresh_after",), expired_seconds=3600) + # The failed intent is ready again and older, but the fresh one goes first. + result = await harness.sweep(limit=1) + assert result[0] == 1 + assert await harness.row("rrev_fresh_after") is None + assert await harness.row("rrev_retry_first") is not None + + +async def test_unconfigured_bindings_are_skipped_and_counted_unless_there_is_nothing_to_delete( + harness: SweepHarness, +) -> None: + await harness.add( + "rrev_ghost", binding="ghost", objects=("ghost_object",), expired_seconds=3 * 86400 + ) + # Nothing to delete means no binding is needed. + await harness.add("rrev_ghost_empty", binding="ghost", expired_seconds=7200) + await harness.add("rrev_local", objects=("local",), expired_seconds=3600) + + # swept, objects_deleted, failed, skipped_unconfigured, deferred, overdue + assert await harness.sweep(limit=10) == (2, 1, 0, 1, 0, 1) + skipped = await harness.row("rrev_ghost") + assert skipped == ("open", 0, None), "left untouched for a host that configures the binding" + + +async def test_an_unconfigured_binding_at_the_head_of_the_queue_does_not_take_the_slot( + harness: SweepHarness, +) -> None: + await harness.add( + "rrev_ghost_head", binding="ghost", objects=("ghost_head",), expired_seconds=3 * 86400 + ) + await harness.add("rrev_local_next", objects=("local_next",), expired_seconds=3600) + result = await harness.sweep(limit=1) + assert result[0] == 1 and result[3] == 1 + assert await harness.row("rrev_local_next") is None + + +async def test_a_sweeping_intent_backs_off_like_an_open_one(harness: SweepHarness) -> None: + harness.failing.add(harness.key("sweeping")) + await harness.add( + "rrev_sweeping", objects=("sweeping",), expired_seconds=7200, state="sweeping" + ) + await harness.add("rrev_after_sweeping", objects=("after",), expired_seconds=3600) + assert (await harness.sweep(limit=1))[2] == 1 + assert (await harness.sweep(limit=1))[0] == 1 + assert await harness.row("rrev_after_sweeping") is None + + +async def test_overdue_also_counts_a_configured_intent_that_keeps_failing( + harness: SweepHarness, +) -> None: + harness.failing.add(harness.key("provider_down")) + await harness.add("rrev_provider_down", objects=("provider_down",), expired_seconds=2 * 86400) + assert (await harness.sweep())[2] == 1 + # Backing off, still unswept after the threshold: deferred and overdue, not skipped, because + # this host configures the binding and the provider is the fault. + assert await harness.sweep() == (0, 0, 0, 0, 1, 1) + + +async def test_intents_expired_far_longer_than_the_sweep_interval_are_flagged( + harness: SweepHarness, +) -> None: + await harness.add("rrev_recent", binding="ghost", objects=("recent",), expired_seconds=7200) + assert (await harness.sweep())[5] == 0 + assert (await harness.sweep(overdue_after_seconds=3600))[5] == 1 + with pytest.raises(ValueError): + await harness.store.sweep_row_write_intents(overdue_after_seconds=0) + + +async def test_an_earlier_intent_table_gains_the_sweep_backoff_columns_in_place( + harness: SweepHarness, +) -> None: + async with harness.pool.connection() as connection: + await connection.execute( + "ALTER TABLE adcp_reporting_row_write_intents DROP COLUMN sweep_attempts," + " DROP COLUMN next_sweep_at" + ) + await harness.store.create_schema() + await harness.store.create_schema() + await harness.store.ready_row_storage() # the catalog check accepts the upgraded table + await harness.add("rrev_after_upgrade", objects=("x",), expired_seconds=10) + assert await harness.row("rrev_after_upgrade") == ("open", 0, None) diff --git a/tests/test_reporting_production_maintenance.py b/tests/test_reporting_production_maintenance.py index 7df170e778..e4237ff3e4 100644 --- a/tests/test_reporting_production_maintenance.py +++ b/tests/test_reporting_production_maintenance.py @@ -125,10 +125,10 @@ async def test_protected_held_parked_and_skipped_work_is_logged_and_reported( failed=(), protected=("rpo_a", "rpo_b"), held=3, - parked=1, + deferred=1, skipped_unconfigured=4, - backed_off=5, - stalled=0, + stuck=(("rpo_stuck", 6, "STATE_UNAVAILABLE"),), + overdue=0, ) worker = service(store) with caplog.at_level(logging.INFO, logger="adcp.reporting.production"): @@ -143,11 +143,12 @@ async def test_protected_held_parked_and_skipped_work_is_logged_and_reported( } one = pending[0] # Integer counters only: no obligation or account identifiers reach the log. - assert (one.protected, one.held, one.parked) == (2, 3, 1) - assert (one.skipped_unconfigured, one.backed_off) == (4, 5) + assert (one.protected, one.held, one.deferred) == (2, 3, 1) + assert one.skipped_unconfigured == 4 assert all("rpo_" not in r.getMessage() for r in pending) # The same counters are available to health checks and dashboards. assert worker.maintenance_report["period_retirement"]["protected"] == 2 + assert worker.maintenance_report["period_retirement"]["stuck"] == 1 assert worker.maintenance_report["intent_sweep"]["skipped_unconfigured"] == 4 assert not [ r for r in caplog.records if getattr(r, "code", "") == "REPORTING_MAINTENANCE_FAILED" @@ -158,13 +159,14 @@ async def test_work_nobody_is_handling_is_warned_about(caplog: pytest.LogCapture from types import SimpleNamespace store = Store(rows=True, feed=False) - store.report = SimpleNamespace(failed=(), stalled=7) + store.report = SimpleNamespace(failed=(), overdue=7, stuck=(("rpo_a", 5, "X"),)) with caplog.at_level(logging.INFO, logger="adcp.reporting.production"): await service(store)._maintain() stalled = [ r for r in caplog.records if getattr(r, "code", "") == "REPORTING_MAINTENANCE_STALLED" ] - assert stalled and all(r.levelno == logging.WARNING and r.stalled == 7 for r in stalled) + assert stalled and all(r.levelno == logging.WARNING and r.overdue == 7 for r in stalled) + assert all(r.stuck == 1 for r in stalled) async def test_a_quiet_pass_logs_nothing_and_still_records_its_counters(