Skip to content

fix(reporting): stop stuck retirements and sweeps blocking the rest; guard the account change feed - #3228

Merged
bokelley merged 3 commits into
mainfrom
bokelley/reporting-retention-head-of-line
Oct 12, 2026
Merged

bokelley merged 3 commits into
mainfrom
bokelley/reporting-retention-head-of-line

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Three robustness fixes for the reporting ledger, found by the Python maintainer's review of the mirrored code (adcp-client-python#1457, comment 6129135604) and verified in JS.

  1. Retirement head-of-line blocking. A retiring tombstone whose external deletes failed on every pass stayed first in retireExpiredPeriods forever, so limit stuck periods starved every eligible one. Tombstones now carry attempts, next_attempt_at and last_failure. A failed attempt backs off (1 minute, doubling, capped at 6 hours) and is skipped until it elapses. Ready retries go ahead of fresh periods for at most ceil(limit / 2) slots and otherwise only fill slots fresh periods leave empty, so a retry backlog still drains at full speed. The result gains deferred (periods backing off) and stuck (up to 20 periods with 5 or more failures, with attempts and cause).
  2. Intent sweep head-of-line blocking. sweepRowWriteIntents has the same backoff (sweep_attempts, next_sweep_at) and takes never-failed intents first. Intents with objects to delete through a binding this host does not configure were previously claimed (state = 'sweeping') and failed with STATE_UNAVAILABLE on every pass; they are now left untouched and counted. Intents with no recorded objects need no binding and are still swept. The result gains skippedUnconfigured, deferred and overdue (expired longer than the new overdueAfterSeconds, default 24 hours, meaning no host is sweeping them and their objects leak). runReportingLedgerMaintenance now reports stuck, deferred, skippedUnconfigured and overdue through onError (ReportingMaintenancePartialFailureError.warnings), not just failed items.
  3. Account change feed. changesAfter({ account_id }) now ends a page before the first change whose xid >= pg_snapshot_xmin(pg_current_snapshot()). This is a prefix truncation, not the WHERE xid < xmin the deployment feed uses: with seq order, a plain filter can hand out a later change while skipping an earlier committed one it excluded (committed seq 1 with a high xid, committed seq 2 with a low xid, an unrelated older transaction open), which would turn the guard into a new permanent skip. The (account_id, seq) index still serves the query (the scan is unchanged; the xid comparison is a selected column). docs/guides/REPORTING-LEDGER.md now states that a ledger database has exactly one writer SDK, and that the guard is defense in depth.

pruneChanges and the consumer holds rely on the same ordering assumption only through recorded_at (30 days by default) and through cursors the feed itself returned, which the truncated pages never advance past an in-flight change; no code change there.

Behaviour change to know about

xmin is cluster-wide: any older open transaction with an assigned xid (another database, an idle-in-transaction session) now holds account pages back until it ends, as it already did for the deployment feed. An empty page can mean caught up or held back, which the guide now says. Because of that, CI runs the files that hold transactions open on purpose or read feeds until empty (reporting-host-reads-pg, reporting-bigquery-sink-pg, reporting-row-retention-pg, reliable-reporting-core-maintenance-pg, and the new reporting-head-of-line-pg) in a serial step.

Migrations

REPORTING_LEDGER_MIGRATION (tombstones) and REPORTING_ROW_STORAGE_MIGRATION (intents) add the new columns. They must be re-applied before upgrading: retention and the upload sweep query the new columns. The adds are guarded on the catalog (as notification-activity does), so a rerun takes no table lock. Verified idempotent over three applications.

Tests

  • test/lib/reporting-head-of-line-pg.test.js (new, PostgreSQL): with limit=1 a permanently failing period / intent does not block an eligible one; first backoff about a minute, doubling per attempt, capped at 6 hours; stuck appears at 5 attempts; the cap leaves fresh periods a slot and a retry-only backlog still drains at full limit; an abort mid-delete records no failure (retire and sweep); retries do not take a fresh intent's slot; unconfigured-binding intents are skipped and counted (including at the head of a limit=1 queue) while empty ones are swept; overdue and its threshold; a sweeping intent backs off. Feed: a lower seq that commits after a higher one is not passed over and the cursor does not move; the xid-vs-seq inversion case that a plain filter would skip; a committed prefix is returned up to the first in-flight change; the executed page query uses the (account_id, seq) index.
  • test/lib/reporting-maintenance-warnings.test.js (new): backlog counts reach report even when nothing failed, and stores without the new fields still work.
  • Existing assertions updated for the new result fields; three bigquery-sink assertions that read the account feed while a deliberate blocker transaction is open now assert it is held back.

Expert review gate

code-reviewer-deep and nodejs-testing-expert ran read-only on the diff. npm run review:codex -- --all --base main ran but the Codex backend timed out ("failed to refresh available models") and produced no findings.

Fixed: lock-free idempotent migration adds; retries backfill unused slots (a lone retry backlog drained at half speed); changeset, code comment and docs no longer claim readers stop depending on lock discipline or that fresh periods always keep a share at limit=1; a zero-failure warning message; the overdue wording; account-feed empty-page ambiguity documented; CI serialization of feed-reading files; tests for abort handling, resume-only drain, cursor assertions, committed-prefix truncation, a spy-coupled index check, unconfigured binding at limit=1, sweeping-state backoff, and ROLLBACK in finally so a failing test cannot leave a transaction holding xmin.

Declined:

  • Degrade to the old SQL when the new columns are missing. Migrations are applied before an upgrade (same as lifecycle_state.failure_count), the changeset says so, and a second code path would be dead weight.
  • Not recording backoff when the cause is an unconfigured binding. A binding removed from configuration is the permanent failure this change exists to back off. A host configured differently can be delayed by up to 6 hours for such a period, which is acceptable under one writer SDK.
  • Backoff for a phase-1 failure (no tombstone exists yet). Phase 1 is a single local transaction; only a database fault fails it, and nothing deterministic does.
  • Dropping deferred / skippedUnconfigured from onError. The task asked for the counts to reach it.
  • A held_back flag on the feed page. Out of scope for this change; the empty-page ambiguity is documented.

🤖 Generated with Claude Code

bokelley and others added 2 commits October 12, 2026 19:12
…guard the account change feed

Retirement and upload sweeps now back off failing items (tombstone attempts /
next_attempt_at, intent sweep_attempts / next_sweep_at; 1 minute doubling to 6
hours), cap retries at half a retirement pass so fresh periods keep a share,
skip intents for bindings the host does not configure, and report stuck,
deferred, skipped-unconfigured and overdue counts through the maintenance
helper. The account change feed ends a page before the first in-flight change,
as the deployment feed does. Documents the one-writer-SDK-per-database rule.

Co-Authored-By: Claude Sonnet <[email protected]>
Lock-free idempotent migration column adds, retries backfill unused slots,
clearer maintenance warnings, abort handling tests, feed prefix test, and
serialize the feed-reading PG test files in CI.

Co-Authored-By: Claude Sonnet <[email protected]>
Comment thread src/lib/reporting/ledger/postgres.ts Resolved

@aao-secretariat aao-secretariat Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ladon verdict: Approve

Approve — head-of-line fix for reporting retention, upload sweeps, and account change feed.

Checked:

  • In-flight guard on the account feed truncates the seq-ordered page at the first xid >= xmin row (postgres.ts:1571) rather than filtering — correct shape, since filtering would hand out a later change while skipping an earlier one. Proven by reporting-head-of-line-pg.test.js:1061.
  • Backoff math (backoffIntervalSql, one-minute doubling capped at six hours), half-the-pass resume cap (limit+1)/2, and abort-not-a-fault handling all check out.
  • Changeset present, minor/additive — correct for the wire impact.
  • Serial CI step for feed-ordering files (xmin is cluster-wide) is the correct operational call.

Medium findings (1):

  • src/lib/reporting/ledger/postgres.ts:2374 — overdue over-counts configured intents this host is retrying, so the "no host is handling them" cause text can misdirect triage; untested for the configured case.

One medium finding, no blocking issues, no escalation trigger (high_risk false, gated_paths false, no team gate, no prior decision). Falls through to row 9 → approve. Worth addressing the overdue count triage wording in a follow-up, but not blocking.

Medium findings

  • src/lib/reporting/ledger/postgres.ts:2374 — overdue count conflates configured-retrying intents with no-host-leaking cause

aao-secretariat[bot]
aao-secretariat Bot previously approved these changes Oct 12, 2026

@aao-secretariat aao-secretariat Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ladon verdict: Approve

Approve — three reporting-ledger robustness fixes with no blocking or medium findings.

What I checked:

  • Account change-feed truncates at the first in_flight row before cursor computation (postgres.ts:1547) and the extra column does not leak on the wire via explicit field mapping (postgres.ts:1552) — witness-not-translator preserved.
  • Retirement tier CASE + ORDER BY tier, resume, attempts, period_end, obligation_id gives fresh periods a share while draining retries; head-of-line backoff logic sound.
  • Phase-1 tombstone commits before external deletes, so first-attempt backoff is never lost.
  • Migration DO-blocks are catalog-guarded and idempotent.
  • Changeset present and correctly minor (additive fields/options/error-param) — changeset-vs-wire-impact satisfied.
  • CI reorg runs each PG test file exactly once with feed-sensitive files serialized.

Decision trace: No critical/high/medium findings (rows 1, 4, 5, 6, 8 don't fire). high_risk is false (rows 3, 5 don't fire). gated_paths is false, so row 2 does not fire despite review_decision: REVIEW_REQUIRED. No no-auto-approve team match (row 7 doesn't fire). Falls through to row 9 → approve.

@bokelley
bokelley enabled auto-merge (squash) October 12, 2026 19:40

@aao-secretariat aao-secretariat Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ladon verdict: Approve

Approve.

This is a subsequent review following a prior approve at head 3f788b3. The delta since then is a single new, test-only addition in test/lib/reporting-head-of-line-pg.test.js (+9 net): a case verifying that overdue also counts a configured intent that keeps failing, alongside deferred. The reviewer verified the assertion against sweepRowWriteIntents backlog semantics — after a configured-binding delete fails and backs off (next_sweep_at = now+60s), the second pass correctly returns deferred:1 + overdue:1 with skippedUnconfigured:0. The assertion matches production semantics, is deterministic, and closes a real coverage gap. No new production code, no changeset concern (test-only), no witness/translator or transport-client issues.

No critical/high/medium findings. gated_paths is false (so row 2 does not apply despite review_decision=REVIEW_REQUIRED). high_risk is false. No author team gate. Rows 1–8 do not fire; falls through to row 9 → approve.

@bokelley
bokelley merged commit aba77ed into main Oct 12, 2026
42 checks passed
@bokelley
bokelley deleted the bokelley/reporting-retention-head-of-line branch October 12, 2026 20:01
bokelley added a commit that referenced this pull request Oct 15, 2026
* feat(reporting): order the account change feed by (xid, seq)

The account feed ordered by seq and cut each page before the first in-flight
change, which depends on lock discipline (#3228). Order it by (xid, seq) behind
xid < pg_snapshot_xmin(...), as the deployment-wide feed does, and drop the
truncation guard.

- Account cursors carry xid. A seq-only cursor from before is mapped to a
  position that skips nothing (the smaller of the oldest later change's xid and
  the snapshot's xmin) and upgraded; it fails with CURSOR_EXPIRED if a change
  with a higher seq was pruned.
- The account horizon gains (xid, seq) columns, the consumer table's check
  constraint is replaced, and (account_id, xid, seq) is indexed.
- pruneChanges, retireExpiredPeriods and compaction holds use (xid, seq) for
  account consumers; pre-upgrade rows hold by seq.

Closes #3283

Co-Authored-By: Claude Sonnet <[email protected]>

* fix(reporting): address review of the account feed (xid, seq) change

- pruneChanges takes victims in (xid, seq) order, so a limited batch cannot leave a retained change below the account horizon.
- Cursor seq and xid are range-checked, so out-of-range values fail as INVALID_INPUT.
- A NULL-xid consumer row is replaced only by a cursor whose seq is not behind.
- Document mixed-fleet maintenance, rollback and concurrent index creation.
- Tests: minimal redelivery of a mapped legacy cursor, exact mapped values, prune batching, concurrent migration appliers, compaction hold in (xid, seq) order, legacy cursor save against a new-format row.

Co-Authored-By: Claude Sonnet <[email protected]>

---------

Co-authored-by: Claude Sonnet <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant