-
Notifications
You must be signed in to change notification settings - Fork 514
[Fix] recover stale external db requests #1428
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nams1570
wants to merge
1
commit into
dev
Choose a base branch
from
inspect-stuck-db-sync-req
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+156
−20
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| import { globalPrismaClient } from "@/prisma-client"; | ||
| import { globalPrismaClient, retryTransaction } from "@/prisma-client"; | ||
| import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors"; | ||
|
|
||
| const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; | ||
|
|
@@ -41,3 +41,102 @@ export async function enqueueExternalDbSyncBatch(tenancyIds: string[]): Promise< | |
| ON CONFLICT ("deduplicationKey") WHERE "startedFulfillingAt" IS NULL DO NOTHING | ||
| `; | ||
| } | ||
|
|
||
| export type RecoverStaleResult = { resetIds: string[], deletedIds: string[] }; | ||
|
|
||
| // Recovers OutgoingRequest rows that were claimed (startedFulfillingAt set) | ||
| // but never deleted — typically because the poller died mid-iteration. We | ||
| // can't naively reset every stale row because the partial unique index | ||
| // `OutgoingRequest_deduplicationKey_pending_key` would reject any reset that | ||
| // produces a duplicate among rows where startedFulfillingAt IS NULL. | ||
| // | ||
| // Per stale row: | ||
| // - dedup key is NULL -> reset (NULLs don't enter the index) | ||
| // - any active sibling exists for the -> delete (the active sibling already | ||
| // same key (pending OR fresh-in-flight) represents the work; resetting would | ||
| // create concurrent duplicate work) | ||
| // - shares key with other stale rows -> reset the oldest, delete the rest | ||
| // - otherwise -> reset | ||
| // | ||
| // "Active sibling" includes both pending rows and rows currently being processed | ||
| // by another poller invocation — we don't want recovery to spawn a parallel | ||
| // sync alongside an already-in-flight one for the same tenancy. | ||
| // | ||
| // Concurrency notes (READ COMMITTED): | ||
| // - Mutation CTEs repeat the staleness predicate so EvalPlanQual skips rows | ||
| // another transaction reset/deleted/re-claimed during the lock wait — | ||
| // otherwise we could clobber a freshly-claimed row back to pending. | ||
| // - A concurrent sequencer INSERT for the same key between our EXISTS check | ||
| // and UPDATE raises P2010 (SQLSTATE 23505). The poller call site catches | ||
| // it so the rest of the iteration keeps processing; the next cron tick | ||
| // re-runs recovery on a fresh snapshot. | ||
| export async function recoverStaleOutgoingRequests(staleThresholdMs: number): Promise<RecoverStaleResult> { | ||
| type Row = { action: "reset" | "delete", id: string }; | ||
| const rows = await retryTransaction(globalPrismaClient, async (tx) => { | ||
| return await tx.$queryRaw<Row[]>` | ||
| WITH stale AS ( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| SELECT | ||
| o."id", | ||
| CASE | ||
| WHEN o."deduplicationKey" IS NULL THEN 'reset'::text | ||
| WHEN EXISTS ( | ||
| SELECT 1 FROM "OutgoingRequest" p | ||
| WHERE p."deduplicationKey" = o."deduplicationKey" | ||
| AND ( | ||
| p."startedFulfillingAt" IS NULL | ||
| OR p."startedFulfillingAt" >= NOW() - ${staleThresholdMs} * INTERVAL '1 millisecond' | ||
| ) | ||
| ) THEN 'delete'::text | ||
| WHEN ROW_NUMBER() OVER ( | ||
| PARTITION BY o."deduplicationKey" | ||
| ORDER BY o."createdAt" ASC, o."id" ASC | ||
| ) = 1 THEN 'reset'::text | ||
| ELSE 'delete'::text | ||
| END AS action | ||
| FROM "OutgoingRequest" o | ||
| WHERE o."startedFulfillingAt" IS NOT NULL | ||
| AND o."startedFulfillingAt" < NOW() - ${staleThresholdMs} * INTERVAL '1 millisecond' | ||
| -- Drain oldest first; LIMIT caps each call so a backlog can't blow | ||
| -- up one transaction. Subsequent poll iterations mop up the rest. | ||
| ORDER BY o."startedFulfillingAt" ASC, o."id" ASC | ||
| LIMIT 100 | ||
| ), | ||
| -- Both mutation CTEs repeat the staleness predicate so that under | ||
| -- READ COMMITTED, EvalPlanQual re-evaluates against the latest row | ||
| -- version after any lock wait and skips rows that are no longer stale | ||
| -- (because a concurrent recovery reset/deleted them or a poller | ||
| -- re-claimed the row in the gap). | ||
| deleted AS ( | ||
| DELETE FROM "OutgoingRequest" o | ||
| USING stale s | ||
| WHERE o."id" = s."id" | ||
| AND s.action = 'delete' | ||
| AND o."startedFulfillingAt" IS NOT NULL | ||
| AND o."startedFulfillingAt" < NOW() - ${staleThresholdMs} * INTERVAL '1 millisecond' | ||
| RETURNING o."id" | ||
| ), | ||
| reset AS ( | ||
| UPDATE "OutgoingRequest" o | ||
| SET "startedFulfillingAt" = NULL | ||
| FROM stale s | ||
| WHERE o."id" = s."id" | ||
| AND s.action = 'reset' | ||
| AND o."startedFulfillingAt" IS NOT NULL | ||
| AND o."startedFulfillingAt" < NOW() - ${staleThresholdMs} * INTERVAL '1 millisecond' | ||
| RETURNING o."id" | ||
| ) | ||
| -- Read from the mutation CTEs (not from the planning CTE) so the counts | ||
| -- reflect rows that actually changed. Under concurrent recovery this | ||
| -- matters: a row that was deleted/reset by another transaction between | ||
| -- snapshot and execution would still appear in the planning CTE but | ||
| -- not in the mutation CTEs. | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| SELECT 'reset'::text AS action, "id" FROM reset | ||
| UNION ALL | ||
| SELECT 'delete'::text AS action, "id" FROM deleted | ||
| `; | ||
| }); | ||
| return { | ||
| resetIds: rows.filter(r => r.action === "reset").map(r => r.id), | ||
| deletedIds: rows.filter(r => r.action === "delete").map(r => r.id), | ||
| }; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Multiple near-identical error events emitted per poller run when handling stale requests, causing error monitoring spam