← Back to Pull requests

docs(designs): propose ADR-068 bounded retention for the PostgreSQL changelog #2234

Closed
unknown closed this pull request without merging on Nov 03, 2026 09:29 UTC
View on GitHub
unknown unknown commented on Oct 31, 2026 22:55 UTC
Author

Summary

Refs #2170. This proposes ADR-068 for maintainers to decide. It does not implement it.

With the PostgreSQL datastore, nothing deletes from datastore_changelog, so it grows without limit. The report in #2170 shows 42M rows and 90 GB on a ~350-node cluster. The cleanup_changelog() function in docs/postgresql-schema.sql is never called, and the components do not create it.

AGENTS.md asks for an ADR before deleting event-store history on a timer, so this PR proposes the design first. The main points:

  • Deleting by processed is not safe. MarkProcessed marks an id prefix for the whole table, for all consumers. So cleanup_changelog() and the workaround in the issue can delete rows another consumer has not read.

  • The bound is the oldest consumer position, as a (changed_at, id) pair, plus the retention, checked on every deleted row. An id alone is not a position, because the poll orders by (changed_at, id) and ids follow allocation order, not time.

  • Every saved position counts, also a stale one. A token that has not changed for a long time raises an alert, but it is never ignored, because an old last_updated does not prove that a consumer is gone.

  • The cleaner runs in-process through both store and client-factory connections, including platform-connectors-only deployments, one run at a time under its own advisory lock. Each connection owner cancels and waits for its cleaner before closing its pool. Factory connections do not perform schema setup or DDL. It deletes in batches through an index range scan on idx_changelog_resume_all from #2233. It is off by default, with new keys, variables and metrics only.
  • The revised proposal selects a previous-snapshot guard: each run records pg_snapshot_xmin(pg_current_snapshot()) and only uses a horizon observed at least one cleanup interval earlier. A new optional changelog_cleanup_state table shares the full horizon and observation time across owners. The first run seeds it without deleting. Comparisons account for 32-bit row xmin versus xid8; the bounded candidate query checks current row versions after validating the horizon window. No commit-timestamp server setting or older-writer change is required.

    The revision also includes acknowledgment-safe idle checkpoints for healthy quiet consumers, with unchanged consumer interfaces and resume-token fields. Idle advancement now requires a fresh activity inspection with no other open or prepared transactions and no hidden activity, followed by a new read snapshot. Its actual candidate pair must precede the inspection fence, and all handed-out deliveries must be acknowledged. Missing visibility or uncertain timestamp ordering defers idle progress; busy databases can conservatively hold cleanup back. Reader rollout is an explicit prerequisite before enabling cleanup; older readers cannot be identified automatically from the unchanged token format.

    Invalid retention or cleanup settings warn and disable only the cleaner, without failing startup or ingestion. Seven days is 168h; Go does not accept 7d.

    The detailed proposed guard and checkpoint protocol is separate to keep the ADR under the reading limit.

    Alternatives considered: a Helm CronJob, calling cleanup_changelog(), deleting in MarkProcessed, ignoring stale tokens, and partitioning. The open questions for maintainers are in the Notes section: the default, and how to recover from a removed component's token.

    Earlier measurements checked the candidate age-and-position query on PostgreSQL 16 with a 5M-row changelog and idx_changelog_resume_all. These measurements exclude the selected long-transaction guard; they do not validate a complete cleaner:

  • With work to do, the batch query is an index range scan with all three conditions in the index condition, and a 10,000-row batch takes 68 ms.

  • With nothing to delete, it takes 0.12 ms (8 buffers).

  • When the oldest consumer is behind every old row, it reads 4 buffers.

  • In a small table with a token at (10:00, id 200), the pair bound keeps a row at (10:05, id 150) and a young row with id 120. A bound on id alone would delete both.
  • The negative-age review follow-up requires a new short repeatable-read transaction per delete batch, an assigned anchoring xid and the existing validated previous horizon. The guard permits snapshot-visible negative-age versions as well as versions strictly older than the horizon. This prevents a very old frozen prefix from permanently blocking cleanup. Both branches remain behind the retention and consumer-position conditions. Concurrent changes causing serialization failure roll back the entire batch; metrics count committed deletes only. Read committed is not permitted for this predicate.

    Type of Change


  • 🐛 Bug fix

  • ✨ New feature

  • 💥 Breaking change

  • 📚 Documentation

  • 🔧 Refactoring

  • 🔨 Build/CI
  • Component(s) Affected


  • Health Monitor

  • Core Service

  • Fault Management

  • Janitor

  • Deployment/Config

  • API/Interface

  • Preflight

  • Plugins

  • Documentation/CI

  • New Component

  • Multiple Components

  • Other
  • Testing


  • Tests pass locally

  • Manual testing completed

  • No breaking changes (or documented)
  • Final branch sync e2f09ad2 includes main 152425f3 without changing the ADR, protocol or index content. Relative to main this PR still changes only three documentation files. Local links, document lengths and whitespace checks pass. The required full gate on the synced revision again passed protobuf, license, module, Renovate, dead-code and unused-code checks, then stopped at the same four Linux boot-ID tests on macOS (339 tests, four failures). Full local validation remains incomplete; this sync does not claim a new runtime or E2E result.

    Latest revision 6e1681b6 addresses the negative-age concern. On PostgreSQL 16, explicit synthetic old raw-XID cases cover signed-age boundaries and bounded progress through a modeled negative-age prefix. Separate real-row MVCC tests preserve late root/subtransaction/prepared commits and processed updates, exclude a post-snapshot negative-age insert under repeatable read, demonstrate why read committed is unsafe, and verify 40001 rolls back earlier deletes in the same batch. The prefix fixture uses a separate xid column, not physical ancient tuple headers. A live old-tuple/full-wrap acceptance test remains outstanding before release.

    An offline counter-advance fixture failed setup and was abandoned after automatic approval review rejected another retry under the repository retry limit. It is not counted as passing evidence. The ordinary MVCC container was disposed of.

    Documentation links, structure, whitespace and lengths pass (ADR 2,993 words, protocol 1,483). make lint-test-all ran on 6e1681b6: protobuf, license, module, Renovate, dead-code and unused-code checks passed, then the same four Linux boot-ID tests failed on macOS (339 tests, four failures). No assertions were weakened; full local validation is not green. No runtime cleaner or new E2E pass is claimed.

    Earlier documentation revision 82ae888a addresses the late-commit idle-checkpoint finding. A fresh, network-isolated PostgreSQL 16 prototype reproduced the unsafe saved-tail loss, then passed the proposed conservative fence checks for xid-less/read-only writers, prepared transactions, activity-to-prepare transitions, disabled tracking, hidden visibility and a late no-listener commit returned by subsequent polling. This is SQL-prototype evidence; provider acknowledgment bookkeeping, arbitrary database clock-regression handling and full concurrency/restart release tests remain implementation prerequisites. The new protocol explicitly requires timestamp ordering and defers progress when it cannot be established.

    Final ADR/protocol links, structure, whitespace and lengths pass (2,985 / 1,326 words). Ran make lint-test-all on 82ae888a with the corrected isolated tools: protobuf, license, module, Renovate, dead-code and unused-code checks passed; the same four Linux boot-ID syslog tests failed on macOS (339 tests, four failures). No assertions were weakened. The complete local gate is not green. No runtime code or E2E result is claimed by this revision.

    Merge follow-up 71ce3faf brings the branch up to main 6ebbc1bd. The only conflict was the ADR index; both ADR-066 and ADR-068 entries are preserved. The proposal and protocol content are unchanged. Local links, ADR structure, document length, index entries and whitespace checks passed. After correcting the isolated Python tool environment to the current protobuf pin, make lint-test-all passed protobuf, license, module, Renovate, dead-code and unused-code checks, then stopped at the same four Linux boot-ID tests on macOS (339 syslog tests, four failures). No assertions were weakened. Full local validation remains incomplete; E2E was not rerun for this index-only conflict resolution.

    This is a proposed design, not a cleaner implementation. Validation for 0556cc2a:

  • ADR structure, local links, whitespace, and document length passed. ADR: 2,986 words; supporting protocol: 1,028 words.

  • PostgreSQL 16 prototype passed guard warm-up, too-early runs, owner replacement, late top-level/subtransaction/prepared commits, processed updates and VACUUM FREEZE. A later horizon made previously protected rows eligible. Observation times were advanced to model elapsed cleanup intervals.

  • PostgreSQL relative-age checks passed representative low-ID rollover/equality cases and rejected a full-epoch alias. These are not a live-cluster transaction-counter wrap test; release acceptance still requires wraparound coverage.

  • A protected prefix produced no deletion, and the actual materialized-candidate plan returned at most 100 candidates. This checks bounded prototype work, not final million-row guarded-query performance.

  • A repeatable-read empty proof and captured tail left a concurrently committed matching event beyond the saved boundary. Provider in-flight/acknowledgment bookkeeping is specified and remains a future implementation acceptance test.

  • Nine Go duration/parser enablement cases passed: unset, 0, negative, below-minimum, 24h, 168h, 7d, malformed and overflowing. Startup/ingestion behavior is an acceptance requirement, not implemented code tested by this documentation PR.

  • Ran make lint-test-all once in the clean isolated revision checkout. Protobuf, license, module, Renovate, dead-code and unused-code gates passed; it stopped at four syslog tests requiring Linux /proc/sys/kernel/random/boot_id, absent on macOS. That syslog suite passed on Linux in earlier validation. Full local repository validation is not green, and E2E was not rerun for this documentation revision.
  • Earlier chart renders confirmed DaemonSet, central Deployment, and central Deployment-only topologies with store-owning components disabled. Earlier 5M-row candidate-query measurements above exclude the selected guard. No production cleanup, reader bookkeeping, runtime schema migration, Helm value, or dependency change is delivered here. Implementation follows maintainer acceptance and #2233.

    Checklist


  • Self-review completed

  • Documentation updated (if needed)

  • Ready for review
  • <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

    Documentation
    Added a proposed PostgreSQL changelog-retention design and protocol covering cleanup eligibility, bounded deletion, safety safeguards, configuration, metrics, and operational guidance.
    Documented how retention age, saved consumer positions, and a prior-snapshot guard constrain cleanup, and that unsafe or unreadable state can block deletion.
    Noted that cleanup is disabled by default, requires acknowledgment-safe consumers and a specified index, and is not implemented; retention remains a proposal.
    * Added the proposal to the design document index.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Checkpoint verification follow-up (36149d9c..90bb3b6b)

    This addresses CodeRabbit thread 4448095083 with protocol changes only. With retention enabled, MarkProcessed fails closed when changed_at cannot be verified. An empty or incomplete token table no longer authorizes deletion. Every PostgreSQL watcher construction path persists a database-clock start pair before returning a watcher. That covers three constructors through one shared helper. Start and the token schema are unchanged. Legacy-token failures fail closed and never overwrite the existing row. Operator recovery and acceptance cases are documented. The age and previous-snapshot guards are unchanged. Local link, wrapping and whitespace checks pass. The full make lint-test-all gate was not rerun for this documentation-only revision.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: KaivalyaMDabhadkar Review duration: 3514m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #2234"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%