← Back to Pull requests

fix(store-client): never advance the PostgreSQL resume position past an unverified event #2250

Closed
unknown closed this pull request without merging on Nov 04, 2026 08:46 UTC
View on GitHub
unknown unknown commented on Nov 03, 2026 03:09 UTC
Author

Summary

Fixes #2249.

The PostgreSQL change-stream watcher could save a resume position ahead of the event it acknowledged, so a restart silently skipped events.

  • MarkProcessed: it looks up changed_at only when the ack is ahead of the read position (lastEventID), because only then is the timestamp used. If that lookup fails, it returns a wrapped error before marking rows processed or saving a position, and never substitutes time.Now(). Acks at or behind the read position skip the lookup and behave exactly as on main, even if the row was purged.

  • convertOldTokenToTimestamp (legacy eventID-only tokens): both lookups retry transient errors with capped exponential backoff and jitter (max 30s) until they succeed, find no row, or the context is cancelled. If conversion still fails, the id is cleared to (zero, 0) so the stream replays and advances. It never stays at (zero, old id), which could resend the same rows forever. Other load errors still start the readers, as on main. A missing legacy row resumes from the smallest changed_at among later ids, with eventID 0 so tied timestamps are included. The warning now logs the old event ID before it is reset.
  • Production changes are confined to changestream.go. There is no schema, token-format, Helm, metric or interface change. ADR-002 and ADR-056 were read: delivery stays resumable and cumulative checkpoint ordering is preserved.

    Behavior change for callers

    MarkProcessed can now return an error where it used to succeed after moving the checkpoint past unread events. Existing caller paths handle it, so no caller changes are needed:

  • The sequential DefaultEventProcessor already stops on MarkProcessed errors through its uncheckpointed-event path, as it does for a failed UPDATE. The component restarts and replays from the unchanged checkpoint.

  • The partitioned processor keeps the pending token and retries it with the next cumulative acknowledgement.

  • fault-remediation propagates the error for controller retry.
  • Purged rows: an ack at or behind the read position no longer looks the row up, so a purged row cannot fail the ack. This includes fault-remediation's retries with the same token. Only an ack ahead of the read position can fail on a missing row. (An earlier revision of this PR claimed a purged row self-heals; review showed that was wrong for same-token retries, and 747534bd fixes it.)

    With a legacy token, Start now waits while the database is unreachable, which is the retry-until-success behavior. All callers call Start synchronously and continue afterwards. Without the database nothing works anyway, so this seemed preferable to falling back to a replay position.

    Known limitations (unchanged by this PR)

  • Start only logs a failed non-legacy resume load, such as a token-query error or a malformed token, and replays from (zero, 0). This is heavy but loses nothing.

  • A row with a smaller id but a later changed_at is redelivered on every poll until a newer row arrives, because advancePosition compares ids only. This is unrelated to this PR and also happens on main. Filed as #2264.

  • If no later rows exist, a missing legacy row still falls back to the current time. Nothing is skipped at that moment, but app-to-database clock skew could matter.

  • saveResumePosition errors are still logged and swallowed.
  • 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)
  • Unit tests: new sqlmock tests TestMarkProcessed_TimestampLookupFailure_PreservesResumePosition (closed connection and missing row) and TestLoadResumePosition_LegacyLookupTransientError_DoesNotAdvance fail on main @ 152425f3 and pass here. Success-path tests were added for both functions.

    Real PostgreSQL 16.15: a disposable container ran a scratch harness that is not committed. It used the provider's own createTables and the real watcher. Each scenario ran on both revisions:

    | Scenario | main @ 152425f3 | This PR |
    |---|---|---|
    | Valid ack saves the row's real changed_at | pass | pass |
    | Ack of a purged row, then restart | returns nil, checkpoint jumps to now, delivers [] (rows 2, 4 lost) | returns error, checkpoint unchanged, delivers [2,4]; a later cumulative ack succeeds |
    | Legacy token, row missing; later rows include a smaller id with a later timestamp and a tie | rows skipped | every later row delivered (replays allowed) |
    | Legacy conversion blocked by a lock, then cancelled | position = now, delivers [] | error, position kept, delivers [10,11,12] after recovery |

    Commands and results:

  • go test -race -count=3 ./pkg/datastore/providers/postgresql/... (macOS): pass.

  • make -C store-client lint-test (macOS): pass.

  • Linux, go test -race -count=1 ./...: store-client pass (780, with six existing database-dependent skips); syslog-health-monitor pass (339, including the boot-ID tests).

  • make lint-test-all (macOS): exits 2 only at the four syslog boot-ID tests. They need Linux /proc/sys/kernel/random/boot_id and pass on Linux, as above. Protobuf, license, module, Renovate, dead-code and unused-code checks pass. The full gate has not passed in a single run, so CI on Linux is the authoritative check.
  • 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

    Bug Fixes
    Resume positions are no longer advanced when event timestamp lookups fail.
    Legacy resume tokens now retry temporary lookup failures and can resume from the earliest remaining event when the original event has expired.
    If no later events remain, legacy tokens fall back to the current time.
    * Resume loading can continue after non-cancellation errors, allowing event replay where possible.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Review follow-up (747534bd, fd305ca2)

    Addresses both review threads. Verified against a disposable PostgreSQL 16 using the real watcher:

  • A purged row acked behind the read position succeeds, including five retries with the same token. All of them failed on cbc43600.

  • A purged row acked ahead of the read position returns an error and writes nothing.

  • A transiently locked legacy lookup retries, then resumes at the real timestamp.

  • After a cancelled conversion, the stream delivers [1,2] once and advances. cbc43600 resent them on every poll at (zero, 10).

  • A failed token query and a malformed token still start the readers, as on main.

  • A transient error in the fallback query is retried and recovers.
  • The race suites pass three times on macOS (-race -count=3) and once on Linux. make -C store-client lint-test passes (801 tests). make lint-test-all again fails only at the four macOS-only syslog boot-ID tests. One scenario remains open, the smaller-id redelivery; it behaves identically before and after this PR and is tracked in #2264.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: KaivalyaMDabhadkar Review duration: 1776m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). 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%
    56%
    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 #2250"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% 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: 56.8% · Lower = rushed or shallow review
    56.8%
    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: 22.5% · Safe to merge
    22.5%