feat(relay): delete a user's relay data when Clerk deletes the user #42285
Mergedjuliusmarmingemerged 9 commits into
main fromrefs/pull/42285/headmerged by juliusmarminge View on GitHubPushed352794c
- @@ -0,0 +111,21 @@111+ }112+ calls.push(`select ${name} ${params(condition).join(",")}`);113+ return calls.some((call) => call.startsWith("deprovision")) &&114+ name === "relay_managed_endpoint_allocations"115+ ? []116+ : (selects[name] ?? []);117+ }),118+ }),119+ }),120+ delete: (table: Table) => ({121+ where: (condition: SQL | undefined) =>122+ Effect.sync(() => {123+ calls.push(`delete ${getTableName(table)} ${params(condition).join(",")}`);124+ }),125+ }),126+ } as unknown as RelayDb.RelayDb["Service"];127+128+ return Effect.gen(function* () {129+ const accounts = yield* AccountDeletion.AccountDeletion;130+ yield* accounts.deleteAccount({ userId: "user_1" });131+ expect(calls.filter((call) => !call.startsWith("select"))).toEqual([@@ -0,0 +74,21 @@74+ .from(relayEnvironmentLinks)75+ .where(eq(relayEnvironmentLinks.userId, userId)),76+ db77+ .select({ environmentId: relayManagedEndpointAllocations.environmentId })78+ .from(relayManagedEndpointAllocations)79+ .where(eq(relayManagedEndpointAllocations.userId, userId)),80+ ]).pipe(81+ Effect.map((rows) => [...new Set(rows.flat().map((row) => row.environmentId))]),82+ Effect.mapError(fail("list-environments")),83+ );84+85+ // Revoke, clear held webhooks, and delete each Cloudflare tunnel and DNS record before86+ // dropping rows, so no live tunnel is left without the allocation that tracks it.87+ yield* Effect.forEach(88+ environmentIds,89+ (environmentId) =>90+ unlinkEnvironmentRecord({91+ userId,92+ environmentId,93+ managedEndpointNamespace: config.managedEndpointNamespace,94+ }).pipe(Effect.provideContext(unlinkContext)),@@ -0,0 +82,21 @@82+ Effect.mapError(fail("list-environments")),83+ );84+85+ // Revoke, clear held webhooks, and delete each Cloudflare tunnel and DNS record before86+ // dropping rows, so no live tunnel is left without the allocation that tracks it.87+ yield* Effect.forEach(88+ environmentIds,89+ (environmentId) =>90+ unlinkEnvironmentRecord({91+ userId,92+ environmentId,93+ managedEndpointNamespace: config.managedEndpointNamespace,94+ }).pipe(Effect.provideContext(unlinkContext)),95+ { discard: true },96+ ).pipe(Effect.mapError(fail("deprovision")));97+ const remainingAllocations = yield* db98+ .select({ environmentId: relayManagedEndpointAllocations.environmentId })99+ .from(relayManagedEndpointAllocations)100+ .where(eq(relayManagedEndpointAllocations.userId, userId))101+ .pipe(Effect.mapError(fail("deprovision")));102+ if (remainingAllocations.length > 0) {@@ -0,0 +99,21 @@99+ .from(relayManagedEndpointAllocations)100+ .where(eq(relayManagedEndpointAllocations.userId, userId))101+ .pipe(Effect.mapError(fail("deprovision")));102+ if (remainingAllocations.length > 0) {103+ return yield* fail("deprovision")(104+ new Error(`${remainingAllocations.length} managed tunnel(s) still allocated`),105+ );106+ }107+108+ yield* transactions109+ .withTransaction(110+ Effect.gen(function* () {111+ yield* db.delete(relayEnvironmentLinks).where(eq(relayEnvironmentLinks.userId, userId));112+ // Environment-scoped rows go only when no other account still links the environment.113+ const stillLinked =114+ environmentIds.length === 0115+ ? []116+ : yield* db117+ .select({ environmentId: relayEnvironmentLinks.environmentId })118+ .from(relayEnvironmentLinks)119+ .where(inArray(relayEnvironmentLinks.environmentId, environmentIds));
Pushede588069
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -0,0 +186,21 @@186+ yield* db187+ .insert(relayAccountDeletions)188+ .values({ userId: input.userId, requestedAt: now })189+ .onConflictDoNothing()190+ .pipe(191+ Effect.mapError(192+ (cause) =>193+ new AccountDeletionFailed({ userId: input.userId, stage: "record-request", cause }),194+ ),195+ );196+ });197+198+ const processPending = Effect.gen(function* () {199+ const settledBefore = DateTime.formatIso(200+ DateTime.subtractDuration(yield* DateTime.now, DELETION_SETTLE),201+ );202+ const pending = yield* db203+ .select()204+ .from(relayAccountDeletions)205+ .orderBy(relayAccountDeletions.requestedAt)206+ .limit(PENDING_BATCH_SIZE)
Pushed29b30f4
- @@ -13,3 +13,4 @@1313 **Push delivery failing:** Inspect `relay.apns_deliveries.process_signed_job` or `relay.fcm.process` errors—an expired APNs key or FCM service account fails every job.1414 **Traffic dropped:** Check `https://relay.t3.codes/health` first.1515 **Tunnel cleanup stopped / deletions failing:** Check `relay.managed_endpoint_reaper.sweep` spans and Cloudflare API errors. To pause cleanup during an incident, set `RELAY_TUNNEL_CLEANUP_MODE=off` and redeploy the relay (see [Managed tunnel cleanup rollout](./03_release.md#managed-tunnel-cleanup-rollout)).16+**Account deletions failing:** A Clerk account deletion keeps failing. `select * from relay_account_deletions order by attempts desc` shows which, and the failed `relay.account_deletion.delete_account` span under each `relay.account_deletion.process_pending` sweep names the stage (usually Cloudflare tunnel teardown). The row stays and retries every 5 minutes until it succeeds.@@ -0,0 +161,21 @@161+ for (const identity of identities) {162+ const sameIdentity = (163+ table:164+ | typeof relayEnvironmentLinks165+ | typeof relayEnvironmentCredentials166+ | typeof relayAgentActivityRows,167+ ) =>168+ and(169+ eq(table.environmentId, identity.environmentId),170+ eq(table.environmentPublicKey, identity.environmentPublicKey),171+ );172+ const stillLinked = yield* db173+ .select({ environmentId: relayEnvironmentLinks.environmentId })174+ .from(relayEnvironmentLinks)175+ .where(sameIdentity(relayEnvironmentLinks))176+ .limit(1);177+ if (stillLinked.length > 0) continue;178+ yield* db179+ .delete(relayEnvironmentCredentials)180+ .where(sameIdentity(relayEnvironmentCredentials));181+ yield* db.delete(relayAgentActivityRows).where(sameIdentity(relayAgentActivityRows));@@ -208,3 +208,12 @@208208 rangeMinutes: 30,209209 triggerFromNRuns: 2,210210 },211+ {212+ id: "RelayAccountDeletionFailingMonitor",213+ // Pages because a stuck deletion is a privacy request we have accepted and not carried out.214+ severity: "page",215+ name: "T3 Connect relay: account deletions failing",216+ description:217+ "Failed account deletion passes in 2 h. The cron retries every 5 min, so one stuck deletion fails 24 times in 2 h; a one-off Cloudflare blip fails once or twice. Healthy: 0. Pending rows and their attempts are in relay_account_deletions.",218+ query: (dataset) =>219+ `['${dataset}']\n| where name == "relay.account_deletion.process_pending"\n| summarize failed = sum(toint(['attributes.custom']['relay.account_deletion.failed']))`,
Pushed5624890
Pushed2975050
- @@ -48,3 +48,6 @@48484949 Use Clerk's allowlist or Restricted mode for new sign-ups (an enabled empty allowlist blocks all sign-ups). Ban the account in Clerk to revoke existing sessions.505051+### Account deletion webhook52+53+Under Clerk **Webhooks**, add an endpoint at `https://<relay domain>/v1/webhooks/clerk` subscribed to `user.deleted`, and set its signing secret as `CLERK_WEBHOOK_SIGNING_SECRET` on the relay. Deleting a user in Clerk then records the deletion, and the relay's five-minute cron tears down their managed tunnels and deletes their relay rows, retrying until a pass succeeds after the user's relay tokens have expired. Each deletion is a row in `relay_account_deletions`: pending while `completed_at` is null (`attempts` climbing means it keeps failing), then kept as the record of which account was deleted and when. After restoring the relay database from a backup, set `completed_at` back to null on every row so the restored data is deleted again. Without the secret the route answers 404.
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Other scenarios#
All 64 scenario measurements match
main.All 64 scenario measurements
short turn resumeWebSocket decodedshort turn resumeWebSocket messageslong turn running, cold openHTTP decodedlong turn running, cold openrowslong turn running, history pageHTTP decodedlong turn running, history pagerowslong turn finished, cold openHTTP decodedlong turn finished, cold openrowslong turn finished, socket cold openWebSocket decodedlong turn finished, socket cold openWebSocket messageslong turn finished, socket cold openrowslong turn finished, work pageHTTP decodedlong turn finished, work pagerowsidle thread resumeWebSocket decodedidle thread resumeWebSocket messagesfleet shell snapshotHTTP decodedfleet shell snapshotrowsfleet shell subscribeWebSocket decodedfleet shell subscribeWebSocket messagesfleet shell resume checkHTTP decodedfleet shell resume checkrowsstale shell reloadHTTP decodedstale shell reloadrowsstale shell resumeWebSocket decodedstale shell resumeWebSocket messagesstale todo list cold openHTTP decodedstale todo list cold openrowsstale todo list cold opennodesstale todo list cold opensubagentsstale todo list cold openplansstale todo list cold openproviderTurnsstale todo list cold opencheckpointsshort turn resumeWebSocket decodedshort turn resumeWebSocket messageslong turn running, cold openHTTP decodedlong turn running, cold openrowslong turn running, history pageHTTP decodedlong turn running, history pagerowslong turn finished, cold openHTTP decodedlong turn finished, cold openrowslong turn finished, socket cold openWebSocket decodedlong turn finished, socket cold openWebSocket messageslong turn finished, socket cold openrowslong turn finished, work pageHTTP decodedlong turn finished, work pagerowsidle thread resumeWebSocket decodedidle thread resumeWebSocket messagesfleet shell snapshotHTTP decodedfleet shell snapshotrowsfleet shell subscribeWebSocket decodedfleet shell subscribeWebSocket messagesfleet shell resume checkHTTP decodedfleet shell resume checkrowsstale shell reloadHTTP decodedstale shell reloadrowsstale shell resumeWebSocket decodedstale shell resumeWebSocket messagesstale todo list cold openHTTP decodedstale todo list cold openrowsstale todo list cold opennodesstale todo list cold opensubagentsstale todo list cold openplansstale todo list cold openproviderTurnsstale todo list cold opencheckpointsBaseline:
f99ef08· PR result:c10e42b· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.