Serialize syncs of the same account, item or family

GF
3d ago
+657-36

Summary

Before: Syncable#sync_later only dedupes against syncs younger than Sync::VISIBLE_FOR (5 minutes), and nothing stops two SyncJobs for the same record from running at the same time. When a sync runs longer than that (initial imports, investment accounts, slow providers) and another sync is requested (auto-sync, manual sync, nightly sync, an edit), a second sync is created and picked up by another worker. Both balance and holding materializers then write the same account: their upserts and purges interleave and the last writer wins. The account shows wrong or missing balances until the next clean sync.

After: syncs of the same account, item or family run one after another. Syncs of different records still run in parallel. A sync that has to wait is kept and runs as soon as the other one finishes, and later requests join it instead of queueing more full syncs.

How

  • Sync#perform wraps start, sync and finalize in a non-blocking, session-level Postgres advisory lock keyed on sync:<type>:<id>, using the same key scheme as GenerateInsightsJob, Financekit::Downstream and DemoFamilyRefreshJob. The lock is released in ensure. The lock query bypasses the query cache, because jobs run with it on and a cached false would keep the sync from ever getting the lock.
  • If the lock is held, perform raises Sync::ConcurrentSyncError before start!. The sync stays pending, and SyncJob retries it every 30 seconds with the same arguments (including balances_only).
  • New Sync.joinable scope: the visible syncs, plus older pending syncs whose job stamped the new syncs.last_attempted_at column within the last 5 minutes. sync_later joins such a sync (widening its window) instead of creating another one. A pending sync whose job was lost stops being joinable after 5 minutes, so the next request enqueues a fresh sync. The visible scope and the UI are unchanged.
  • A sync that has waited for more than an hour writes a DebugLogEntry (category sync, level warn, IDs only) about once an hour, so a hung holder shows up in the debug log.

Why an advisory lock and not a status check

An earlier attempt, #3871, deferred overlapping requests based on the syncing status of another row. A status row survives a crashed or killed worker and would block the record until SyncCleanerJob marks it stale after 24 hours. A session-level advisory lock is released by Postgres as soon as the worker's connection goes away. The lock never blocks (pg_try_advisory_lock), so a parent and its children cannot deadlock: children run in their own jobs under their own keys, and the lock is re-entrant on the same connection.

Connection pooling assumption

Session-level advisory locks need the job to keep the same database session for the whole sync. That holds for direct Postgres connections and for PgBouncer in session mode. PgBouncer in transaction mode would break it, but it would equally break the session-level advisory locks the app already relies on (GenerateInsightsJob, Financekit::Downstream, RecurringTransaction::Pipeline, DemoFamilyRefreshJob), so this PR does not add a new requirement. perform does not run inside a transaction, which is why a transaction-level lock is not an option.

Why unlimited retries

retry_on Sync::ConcurrentSyncError, attempts: :unlimited keeps a requested sync from being dropped while another one holds the lock. It is bounded in practice: perform returns without raising as soon as the sync is no longer pending (completed elsewhere, cancelled, or marked stale by SyncCleanerJob after STALE_AFTER = 24 hours), and the retry chain ends there. That is at most about 2,880 cheap attempts in the worst case of a hung holder, and that case is reported through the hourly DebugLogEntry. A fixed limit like the 20 attempts used for Rule::Runner::LockBusy would silently drop a sync that waits behind a long initial import.

Side effects

  • A family sync stays "syncing" until its delayed children have run.
  • Demo::Generator calls sync.perform inline; it would raise Sync::ConcurrentSyncError if a worker were syncing the same record at that moment.
  • Self-hosting: one nullable column (syncs.last_attempted_at), nothing to configure.

Testing

  • test/models/sync_test.rb: a real second Postgres session holds the lock (the test transaction pins one connection, and advisory locks are re-entrant per session, so a second worker is simulated with a raw PG connection). Covers: no run while another session holds the lock (sync stays pending), run after release and lock freed afterwards, lock freed after a failed sync, different syncables do not block each other, sync_later joins an old pending sync that is still retrying, and does not join one whose job stopped retrying.
  • test/jobs/sync_job_test.rb: re-enqueue with the same arguments, last_attempted_at heartbeat, long-wait reporting thresholds.
  • All nine new tests fail on main (1 failure, 8 errors) and pass with the change.
  • Migrate, rollback, migrate on a database loaded from main's schema; the resulting schema.rb matches.
  • Full bin/rails test in CI green; rubocop and brakeman clean.

Summary by CodeRabbit

  • Bug Fixes
    • Syncs for the same item are less likely to run concurrently, reducing the risk of conflicting updates.
    • If a sync is already in progress, the request is retried automatically instead of failing immediately.
    • Recently attempted pending syncs can be reused, while stale pending syncs no longer prevent a new sync from being scheduled.
    • Long-running waits for a sync are reported periodically rather than on every retry.
    • Balances-only requests are kept separate from other pending syncs.