Skip to content

fix(batch): clear idempotency keys pointing at dead runs in batchTrigger - #4913

Closed
itzzdev09 wants to merge 1 commit into
triggerdotdev:mainfrom
itzzdev09:fix/4819-batch-idempotency-dead-runs
Closed

fix(batch): clear idempotency keys pointing at dead runs in batchTrigger#4913
itzzdev09 wants to merge 1 commit into
triggerdotdev:mainfrom
itzzdev09:fix/4819-batch-idempotency-dead-runs

Conversation

@itzzdev09

Copy link
Copy Markdown

Fixes #4819. Reported by @Jaimin2687.

The bug

The single-trigger path clears an idempotency key when the run it points at reached a clearable terminal state — IdempotencyKeyConcern.handleExistingRun guards on shouldIdempotencyKeyBeCleared(existingRun.status). The batch path (batchTriggerV3.server.ts:453) only tested time expiry:

if (cachedRun.idempotencyKeyExpiresAt && cachedRun.idempotencyKeyExpiresAt < new Date()) { ... }
return { id: cachedRun.friendlyId, isCached: true, ... };  // dead run returned here

So batchTrigger with a key pointing at a CRASHED / TIMED_OUT / SYSTEM_FAILURE run returned that run as isCached: true, and kept returning it on every retry.

Why it isn't a one-line check

The batch path had no status to test. findRunsByIdempotencyKeys selected five columns and status was not one of them (PostgresRunStore.ts:1864), and IdempotencyKeyRunMatch agreed. Dropping shouldIdempotencyKeyBeCleared(cachedRun.status) in would not have compiled. Hence three files:

  1. internal-packages/run-store/src/types.tsIdempotencyKeyRunMatch gains status: TaskRunStatus.
  2. internal-packages/run-store/src/PostgresRunStore.ts — the lookup selects "status". delegatingRunStore.ts:439 and runOpsStore.ts:781 both just forward, so no change there.
  3. apps/webapp/app/v3/services/batchTriggerV3.server.ts — the guard becomes keyTimeExpired || shouldIdempotencyKeyBeCleared(cachedRun.status).

Two deliberate choices:

  • Same branch as time expiry, not a separate one. That branch is what adds the run to expiredRunIds, which drives the clearIdempotencyKey call below. A separate branch would mint a fresh run but leave the stale key in place, and the next batch would hit it again.
  • Policy stays in the webapp. shouldIdempotencyKeyBeCleared lives in v3/taskStatus.ts and stays there; the run store just returns one more column. The tradeoff is that the store now carries a field only one caller uses, which seemed better than pushing status policy down into the store.

Notes

  • Added a .server-changes/ entry rather than a changeset: the webapp change is user-facing, and @internal/run-store is private: true, so per CHANGESETS.md no changeset applies.
  • Also gave status to the IdempotencyKeyRunMatch fixture in runOpsStore.shardMap.test.ts so it stays faithful to the type (those rows are cast, so it was not a compile break).

Verification — honest status

  • Static, against this branch: TaskRun.status is a real non-null column (TaskRunStatus @default(PENDING)), so the added SELECT is valid; shouldIdempotencyKeyBeCleared is isFailedRunStatus(status) || status === "EXPIRED", i.e. exactly the six clearable statuses, matching single-trigger; shouldIdempotencyKeyBeCleared was already reachable from ../taskStatus, which batchTriggerV3.server.ts already imports from.
  • Not run locally: the added store-level regression test (PostgresRunStore.findRunsByIdempotencyKeys.test.ts — asserts a CRASHED and an EXECUTING row come back with their statuses) needs the repo's testcontainers/Docker harness, and I could not install the workspace in this environment. It should run in CI, and I'll fix anything that falls out.

Context: a bot opened #4912 for this issue off my analysis in #4819; it was auto-closed by CI within seconds. This is the same fix reworked and submitted properly, with the changeset/server-changes distinction handled and the fixture updated.

🤖 Generated with Claude Code

The single-trigger path clears an idempotency key when the run it points at
reached a clearable terminal state — `IdempotencyKeyConcern.handleExistingRun`
guards on `shouldIdempotencyKeyBeCleared(existingRun.status)`. The batch path
only tested time expiry, so `batchTrigger` with a key pointing at a dead run
returned that FAILED run as `isCached: true`, and kept returning it on every
retry.

The batch path could not make that check: `findRunsByIdempotencyKeys` selected
five columns and `status` was not one of them, so `cachedRun` had no status to
test. The fix spans three files:

- `run-store/types.ts`: `IdempotencyKeyRunMatch` gains `status`.
- `run-store/PostgresRunStore.ts`: the lookup selects `"status"`.
  `delegatingRunStore` and `runOpsStore` forward unchanged.
- `batchTriggerV3.server.ts`: the cached-run guard becomes
  `keyTimeExpired || shouldIdempotencyKeyBeCleared(cachedRun.status)`, in the
  same branch as time expiry so the run lands in `expiredRunIds` and the stale
  key is cleared — otherwise it would survive to the next batch.

Policy stays owned by the webapp (`shouldIdempotencyKeyBeCleared` lives in
`v3/taskStatus.ts`); the store just returns one more column.

Fixes triggerdotdev#4819.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@changeset-bot

changeset-bot Bot commented Sep 9, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 81ebf24

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: eb1536f6-1148-46c0-bc0e-e470945cbcaa

📥 Commits

Reviewing files that changed from the base of the PR and between 6f5c49c and 81ebf24.

📒 Files selected for processing (6)
  • .server-changes/batch-idempotency-dead-runs.md
  • apps/webapp/app/v3/services/batchTriggerV3.server.ts
  • internal-packages/run-store/src/PostgresRunStore.findRunsByIdempotencyKeys.test.ts
  • internal-packages/run-store/src/PostgresRunStore.ts
  • internal-packages/run-store/src/runOpsStore.shardMap.test.ts
  • internal-packages/run-store/src/types.ts

Walkthrough

The run store now returns status from findRunsByIdempotencyKeys and includes it in IdempotencyKeyRunMatch. batchTrigger checks expiration and clearable terminal statuses before reusing cached runs. Invalid matches have their idempotency keys cleared and receive new run IDs. Regression tests cover CRASHED and EXECUTING statuses.

Severity of issue fixed: Medium

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Hi @itzzdev09, thanks for your interest in contributing!

This project requires that pull request authors are vouched, and you are not in the list of vouched users.

This PR will be closed automatically. See https://github.com/triggerdotdev/trigger.dev/blob/main/CONTRIBUTING.md for more details.

@github-actions github-actions Bot closed this Sep 9, 2026

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 potential issue.

Devin Review

const keyTimeExpired =
!!cachedRun.idempotencyKeyExpiresAt && cachedRun.idempotencyKeyExpiresAt < new Date();

if (keyTimeExpired || shouldIdempotencyKeyBeCleared(cachedRun.status)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Large mixed batches omit fresh runs

When live cached items precede dead ones, shouldIdempotencyKeyBeCleared marks only the latter for creation. Job ranges cover newRunCount slots from index zero, not the new runs' positions. New tasks beyond those ranges never run, while the API returns nonexistent run IDs.

Prompt for agents
The new dead-run classification increases newRunCount for selected positions, but the default parallel scheduler in apps/webapp/app/v3/services/batchTriggerV3.server.ts builds contiguous ranges from zero using only newRunCount. Batch runIds still contains every item, including live cached entries. If cached entries occupy early positions, scheduled ranges can end before later fresh entries, so those entries are never processed. Update parallel range construction or item processing so every position containing a non-cached run is covered, while preserving batch item indexes and completion accounting. Add a regression test with more than the async threshold, live cached entries first, and dead idempotent entries later.
Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

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: batchTrigger returns stale failed runs instead of re-triggering when idempotency key points to a dead run

1 participant