Files
accounted/supabase/migrations/20260807151000_journal_entry_lines_account_id_index.sql
Mattsson bd7a423b86 fix(sandbox): fit the nightly cleanup inside PostgREST's 8s session cap (#1451)
* fix(sandbox): fit the nightly cleanup inside PostgREST's 8s session cap

Follow-up to #1449. Profiling the repaired teardown on prod puts one
sandbox user at ~3s (the auth.users delete fans out over ~250 FK triggers;
FK indexes were tried inside an aborted transaction and do not help), while
every PostgREST session inherits authenticator's statement_timeout = 8s.
The nightly RPC call therefore times out and ROLLS BACK wholesale: a second
silent-failure mode for the same cron.

- cleanup_expired_sandbox_users gets a function-local statement_timeout of
  290s (same sanctioned pattern as undo_sie_import, 20260702154500) via
  migration 20260807150000.
- The cron route bounds each night to 60 users (~180s), exports
  maxDuration = 300, and the backlog drains over a few nights.
- Tests: route asserts the bounded rpc call and the maxDuration budget; the
  pg suite pins proconfig containing statement_timeout=290s.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): index journal_entry_lines.account_id (chart-account cascade seq-scans 730k rows)

Caught live during the backlog purge: DELETE FROM auth.users cascades chart_of_accounts deletion, whose ON DELETE SET NULL fires an unindexed UPDATE over journal_entry_lines per account (~37 per sandbox company). This is the bulk of the ~3s per-user teardown cost.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-07 14:37:28 +02:00

12 lines
683 B
SQL

-- journal_entry_lines.account_id (FK to chart_of_accounts, ON DELETE SET
-- NULL) has no index, while account_number, journal_entry_id, cost_center,
-- project and the dimension bags all do. Deleting a chart account therefore
-- seq-scans all ~730k journal_entry_lines rows per account; sandbox teardown
-- deletes ~37 chart accounts per company, which is where most of its ~3s
-- per-user cost goes (caught live: the backlog purge timed out inside
-- "UPDATE ONLY journal_entry_lines SET account_id = NULL WHERE account_id =
-- $1" cascading from DELETE FROM auth.users).
CREATE INDEX IF NOT EXISTS idx_journal_entry_lines_account_id
ON public.journal_entry_lines (account_id);