improvement(db): tag advisory lock statements by caller

Merged
WA
1mo ago
+294-110

Summary

  • Every transaction-scoped advisory lock in apps/sim ran the same statement, SELECT pg_advisory_xact_lock(hashtextextended($1, 0)), so query insights showed all lock waits as one fingerprint with no way to tell which caller was waiting
  • New acquireAdvisoryXactLock(tx, tag, key) and tryAcquireAdvisoryXactLock(tx, tag, key) in lib/db/advisory-locks.ts issue the same call with a trailing SQLCommenter tag (/*lock='<family>'*/), which PlanetScale query tags can filter on. The tag must be a static snake_case identifier, so it can't break out of the comment
  • About 45 call sites now go through the helper, each tagged with its lock family (user_table_rows_pos, organization_membership, usage_log_event, …). Keys, lock types, timeouts, and transaction boundaries are unchanged
  • Left alone: statements whose SQL text is already unique (packages/db locks, the file-search dispatch generate_series claim) and one untyped repair script

Type of Change

  • Improvement

Testing

  • New lib/db/advisory-locks.integration.ts (real Postgres):
    • the same key blocks and releases on commit; a different key doesn't block
    • the try variant returns false while held
    • the tag reaches the server (checked through pg_stat_activity)
    • an unsafe tag is rejected
  • Each test goes red when its guarantee is broken
  • Type-check, lint, check:audits, and unit tests for every changed file pass

Checklist

  • Code follows project style guidelines
  • Self-reviewed my changes
  • Tests added/updated and passing
  • No new warnings introduced
  • I confirm that I have read and agree to the terms outlined in the Contributor License Agreement (CLA)