Skip to content

fix(platform): retire the schedules and rows of deleted organizations - #3550

Merged
yannickmonney merged 2 commits into
mainfrom
fix/trigger-scan-skips-deleted-orgs
Sep 27, 2026
Merged

yannickmonney merged 2 commits into
mainfrom
fix/trigger-scan-skips-deleted-orgs

Conversation

@yannickmonney

Copy link
Copy Markdown
Contributor

Summary

Organization deletions before #3240 (0.5.0–0.5.8) removed a few tables and left every other org-keyed app row behind. That included the organization's automations and their enabled schedules. The minutely scan kept claiming each due occurrence and started a run for an organization that no longer existed, and it would do so indefinitely (#3022). This PR fixes it in two layers:

  1. The scan never runs a schedule of a deleted organization (backend/domains/automations/triggers.ts).
    • Each row the scan reads now carries an orgMissing flag (NOT EXISTS "organization").
    • Such a schedule is skipped before anything else is read (no claim, no run).
    • Each page disables the skipped schedules with one conditional UPDATE … SET enabled = false. The write re-checks that the row is still enabled and the organization still missing, and it returns the rows it changed.
    • One summary line per scan names what that write disabled.
    • It is logged exactly once: a disabled schedule never enters a page again, and an overlapping scan that lost the write reports nothing.
    • ScheduleScanResult.orphaned counts them.
  2. Migration 0125_rows_of_deleted_organizations.sql removes what those deletions left behind. It works the way the teardown cascade does:
    • It walks the same catalog as listOrgOwnedTables: every app base table with an org_id column.
    • It deletes child tables before the tables they reference. The order is byte order ("C"), and on the real schema it is identical to orderChildrenFirst's (checked on a scratch copy).
    • It keeps ORG_TEARDOWN_KEEPS (audit_logs, audit_chain_heads, audit_integrity_progress, organization_tombstones).
    • A row is stranded when no "organization" row carries its org_id.
    • It is guarded with to_regclass('"organization"') for a fresh database, the 0120 pattern. App migrations run before Better Auth creates its tables.
    • It is idempotent and safe during a rolling deploy. Triggers are deleted before the runs they reference, so a claim the old image's scan makes during the migration is waited for, and its run is deleted too.

backend/MIGRATION.md (organizations row) and tests/manual/reference/automation.md (a new automated row) record both.

Closes #3022

Decisions for the reviewer

  • A deleted organization under an active legal hold keeps every row. The teardown has refused to delete a held organization since 0.5.8 (fix(platform): atomic hold-aware org deletion, immutable slug #3162). Legal holds exist since 0.5.0, though, so on 0.5.0–0.5.7 an organization could be deleted while held, and the rows it left are exactly what the hold preserves. A released hold does not count. Such an organization's schedules are still disabled by the scan. Its rows stay until someone releases the hold. If you would rather delete held rows as well, it is one NOT EXISTS clause to drop.
  • The keep list is written into the migration, because a shipped migration is frozen. It matches ORG_TEARDOWN_KEEPS as of this PR.
  • Migration number. 0123 is taken on main (feat(platform): fan out @mentions in task descriptions #3519) and 0124 is claimed by the open feat(platform): pause a schedule after five permanent failures in a row #3533 (refactor(platform): drop the retired sandbox tables #3532 also still claims 0123), so this PR takes 0125. Please re-check at merge time. The integration lane finds the file by its slug, so renumbering needs no code change.
  • Cost. The migration runs one DELETE per org-keyed table (96 today), each an anti-join against "organization", which means a sequential pass over the large tables. This is a one-time cost at the boot that applies it, the same kind of cost as the 0076/0077 dedups.
  • org_id holds only organization ids. Before relying on "no organization row means stranded", I swept every write into the 96 tables, in current code and in all v0.5.x tags. Every INSERT binds org_id to an organization id resolved from a session, REST key, token or existing row. No table is deployment-wide, and no migration seeds rows.

Verification

  • bunx vitest run --project server on triggers.scan.test.ts, triggers.webhook.test.ts, backend/jobs/ and backend/domains/organizations/: 12 files, 95 tests passed. After rebasing onto the current main, the scan, webhook and organizations files passed again: 5 files, 68 tests. The two new scan cases and the updated result shapes fail against the unfixed scan (5 of 10 red).
  • bunx oxlint --type-aware and oxfmt --check on the changed TypeScript files: clean. Opengrep (tools/opengrep/run.sh) on the changed files: 0 findings. bun run lint:manual: ok.
  • Scoped tsc over the changed files (except the 54k-line integration-check.ts, whose only change is two imports and two lane entries): exit 0.
  • The migration applies cleanly to a fresh database after every other migration, where the guard returns early. The harness's boot migrations exercise the same path on each run. Applied twice to a seeded scratch database: live org untouched, dead org removed except the ledger, held org kept, released-hold org removed, second pass unchanged.
  • Real Postgres (local; no CI workflow runs backend:integration). Two new lanes, both registered:
    • checkDeletedOrgSchedules: a deployed, due schedule of a non-existent organization
      • starts no run and ends up disabled;
      • is not claimed (the cursor is unmoved and no skip is stamped);
      • is named in one line across two scans;
      • does not stop the live schedule beside it from being claimed.
    • checkOrphanedOrgRowsBackfill: re-applies the file inside a rolled-back transaction. At boot the guard returns before any DELETE, so this lane is the only place the DELETEs run. Results:
      • the dead organization's rows are gone, across a cascade (a table with no org id), SET NULL and NO ACTION foreign key;
      • the audit row and the tombstone stay;
      • a held dead organization and the live organization keep every row;
      • a second pass changes nothing.
    • ITEST_LANES=checkAutomations,checkAutomationTriggerDelivery,checkDeletedOrgSchedules,checkOrphanedOrgRowsBackfill: 36/36 checks passed across 4/4 lanes. This filtered run includes the existing fairness (205 schedules), overlapping-scan and schedule-fire probes.
    • Regression proof: with only triggers.ts reverted, checkDeletedOrgSchedules reads runs=1 (want 0), enabled=true (want false), claimed=true.
  • Pre-existing, not from this branch: checkOrganizationLifecycle fails 6 checks with the same output on origin/main. The lane renames org A to "Life A renamed" and later confirms the deletion with "Life A", so the teardown answers 400 ORG_CONFIRM_NAME_MISMATCH, and every check after it that assumes the deletion happened fails. It needs its own fix.

Not in scope

  • Slug-keyed leftovers of pre-fix(platform): complete organization removal and member credential paths #3240 deletions (knowledge corpus rows, blobs, the config tree). They live outside the app database, and a new organization may have taken the same slug since.
  • app_realtime.outbox. The teardown clears it, but listOrgOwnedTables does not walk it, and hints older than an hour are reclaimed anyway.
  • The webhook and event doors. Their trigger rows go with the cascade and this backfill, and neither can fire without an outside caller or an event in that organization.

A deletion before 0.5.9 (#3240) left every automation row of the
organization behind, and the minutely scan went on claiming and starting
a run for each due occurrence of its enabled schedules — for a tenant
that no longer existed, forever.

Each page row of the scan now says whether an `organization` row still
carries its org id. A schedule whose organization is gone is never
claimed: the page disables it with one conditional UPDATE (still
enabled, organization still missing, re-checked at the write) and the
scan names what that write disabled in one line. A disabled schedule
never enters a page again, and an overlapping scan that lost the write
reports nothing, so each one is logged exactly once. `orphaned` counts
them on the scan result.

Proved on real Postgres by `checkDeletedOrgSchedules`: a deployed, due
schedule of a non-existent organization starts no run, ends up disabled
and unclaimed, is named in one line across two scans, and the live
schedule beside it is still claimed. Without the fix the same lane reads
runs=1, enabled=true.

Refs #3022
Until #3240 (0.5.9) deleting an organization removed a handful of tables
and left every other org-keyed app row behind. Migration 0125 removes
them the way the teardown cascade would have: the same catalog walk
`listOrgOwnedTables` does (every app base table with an org_id column),
child tables before the tables they reference, in the byte order
`orderChildrenFirst` sorts by, and the governance ledger kept
(`ORG_TEARDOWN_KEEPS`: audit_logs, audit_chain_heads,
audit_integrity_progress, organization_tombstones).

A row is stranded when no "organization" row carries its org_id. A
deleted organization with an active legal hold keeps every row: the
teardown refuses such a deletion since 0.5.8 (#3162), but on 0.5.0–0.5.7
an organization could be deleted under a hold. Guarded for a fresh
database (app migrations run before Better Auth creates its tables),
idempotent, and rolling-deploy safe.

At boot on a fresh database the guard returns before any DELETE, so
`checkOrphanedOrgRowsBackfill` re-applies the file over a planted
fixture inside a rolled-back transaction: the dead organization's rows
go along a cascade, SET NULL and NO ACTION foreign key, the audit row
and tombstone stay, a held dead organization and the live one keep
every row, and a second pass changes nothing. The ledger rows in
backend/MIGRATION.md and the manual automation register record it.

Closes #3022
@yannickmonney
yannickmonney merged commit 227f545 into main Sep 27, 2026
50 checks passed
@yannickmonney
yannickmonney deleted the fix/trigger-scan-skips-deleted-orgs branch September 27, 2026 21:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: deleting an organization leaves its automation schedule triggers enabled — the minutely scan then crashes in orgSlugFromId forever

1 participant