Skip to content

fix(run-engine): heartbeat batch items so slow ones are not run twice - #4569

Open
matt-aitken wants to merge 1 commit into
mainfrom
fix/batch-item-heartbeat
Open

fix(run-engine): heartbeat batch items so slow ones are not run twice#4569
matt-aitken wants to merge 1 commit into
mainfrom
fix/batch-item-heartbeat

Conversation

@matt-aitken

Copy link
Copy Markdown
Member

Summary

A batch item whose callback ran longer than the visibility timeout was reclaimed and handed to a second consumer while the first was still working on it. Both consumers created a run for the same item, and the redelivery could then be dropped, leaving the batch short of its expected count and never finalizing.

Items are now heartbeated for as long as their callback runs, so a slow item stays owned by the consumer running it.

Detail

Nothing was extending the deadline: an item was claimed with a fixed 60s lease and the lease was never renewed, so exceeding it guaranteed redelivery regardless of whether the consumer was healthy.

Each beat extends by a full visibility timeout while the tick stays at a third of it. Extending by only the tick interval would leave the deadline lapsing briefly on every cycle, which a reclaim scan can land in. The timeout is configurable so this is testable in reasonable time.

If a beat reports the in-flight entry is gone, the item has been reclaimed and the consumer discards its result instead of completing over the new owner. Worth being precise about what that buys: it is best effort, not a fence. The in-flight member is keyed only by message and queue id, so once another consumer re-claims the item the member exists again and this consumer's beats succeed. It closes the window where the item is back on the queue and unclaimed; a real fence needs a per-claim token in the member.

The regression test runs an item slower than the timeout across two consumers and asserts it executes once. Without the heartbeat it fails with the item having run twice.

A claimed item stayed invisible for a fixed 60s and was never heartbeated, so any
item whose callback ran longer than that was reclaimed and handed to a second
consumer while the first was still working on it. Both consumers created a run for
the same item, and the redelivery could then be dropped, leaving the batch short of
its expected count.

Items are now heartbeated for as long as their callback runs. Each beat extends by
a full visibility timeout while the tick stays at a third of it, so a slow beat has
margin rather than lapsing the deadline. The timeout is configurable so the
behaviour is testable.

If a beat reports the in-flight entry is gone the item was reclaimed, and the
consumer discards its result rather than completing over the new owner. That is a
best-effort signal, not a fence: the in-flight member carries no per-claim token,
so once another consumer re-claims the item this consumer's beats succeed again.
@changeset-bot

changeset-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 5ecb968

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 Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

BatchQueue now accepts a configurable visibility timeout with a 60-second default. It derives a heartbeat interval and passes both values to FairQueue. During callback execution, BatchQueue renews the message lease. If lease ownership is lost, it discards the callback result and skips completion and result recording. An integration test verifies that a long-running item is not redelivered.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description clearly explains the issue, implementation, limitation, and regression test, but it omits most template sections and the issue reference. Add the required Closes # reference, checklist, Testing, Changelog, and Screenshots sections, and complete each applicable item.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: adding heartbeats to prevent duplicate processing of slow batch items.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/batch-item-heartbeat

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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ff6a7503-66a9-440c-9b5b-9bd4a7140e7c

📥 Commits

Reviewing files that changed from the base of the PR and between 8819e25 and 5ecb968.

📒 Files selected for processing (3)
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • GitHub Check: audit
  • GitHub Check: code-quality / code-quality
  • GitHub Check: audit
  • GitHub Check: 🔍 What moved
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

**/*.{ts,tsx}: Prefer static imports over dynamic import(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from @trigger.dev/sdk; never use @trigger.dev/sdk/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use vitest for all tests in the Trigger.dev repository

**/*.{test,spec}.{ts,tsx}: Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.
Place test files next to the source files they test.

Files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
internal-packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For internal packages, use typecheck for verification and never use build as the correctness check.

Files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
🧠 Learnings (12)
📚 Learning: 2026-03-03T13:07:27.810Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3166
File: internal-packages/run-engine/src/batch-queue/tests/index.test.ts:711-713
Timestamp: 2026-03-03T13:07:27.810Z
Learning: In test files under internal-packages/run-engine/src/batch-queue/tests, prefer asserting using toBeGreaterThanOrEqual for rate limiter behavior when the consumer loop may call the limiter during empty polls as well as during actual processing. This avoids flaky failures due to strict equality, while still validating expected non-decreasing behavior.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
  • internal-packages/run-engine/src/batch-queue/index.ts
  • internal-packages/run-engine/src/batch-queue/types.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.

Applied to files:

  • internal-packages/run-engine/src/batch-queue/tests/index.test.ts
🔇 Additional comments (2)
internal-packages/run-engine/src/batch-queue/index.ts (1)

62-64: LGTM!

Also applies to: 73-74

internal-packages/run-engine/src/batch-queue/tests/index.test.ts (1)

957-1007: LGTM!

Comment on lines +103 to +104
this.visibilityTimeoutMs = options.visibilityTimeoutMs ?? BATCH_ITEM_VISIBILITY_TIMEOUT_MS;
this.heartbeatIntervalMs = Math.max(50, Math.floor(this.visibilityTimeoutMs / 3));

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the visibility-timeout contract.

For a timeout below 50 ms, the first heartbeat occurs after the lease expires. Values near 50 ms also have no scheduling margin. This can reclaim an active item and cause duplicate processing.

  • internal-packages/run-engine/src/batch-queue/index.ts#L103-L104: Reject non-finite or too-small values, or derive a heartbeat interval that always occurs safely before expiry.
  • internal-packages/run-engine/src/batch-queue/types.ts#L217-L222: Document the accepted minimum timeout.
📍 Affects 2 files
  • internal-packages/run-engine/src/batch-queue/index.ts#L103-L104 (this comment)
  • internal-packages/run-engine/src/batch-queue/types.ts#L217-L222

Comment on lines +164 to +165
visibilityTimeoutMs: this.visibilityTimeoutMs,
heartbeatIntervalMs: this.visibilityTimeoutMs,

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Pass the derived heartbeat interval to FairQueue.

Line 165 passes this.visibilityTimeoutMs as heartbeatIntervalMs. This bypasses the one-third interval derived on Line 104. FairQueue can then heartbeat at the lease deadline instead of before it.

Proposed fix
-      heartbeatIntervalMs: this.visibilityTimeoutMs,
+      heartbeatIntervalMs: this.heartbeatIntervalMs,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
visibilityTimeoutMs: this.visibilityTimeoutMs,
heartbeatIntervalMs: this.visibilityTimeoutMs,
visibilityTimeoutMs: this.visibilityTimeoutMs,
heartbeatIntervalMs: this.heartbeatIntervalMs,

Comment on lines +776 to +798
): { stop: () => void; lostLease: () => boolean } {
let lostLease = false;

const interval = setInterval(() => {
this.fairQueue
.heartbeatMessage(messageId, queueId)
.then((stillOwned) => {
if (!stillOwned) {
lostLease = true;
}
})
.catch((error) => {
this.logger.debug("Batch item heartbeat failed", {
messageId,
queueId,
error: error instanceof Error ? error.message : String(error),
});
});
}, this.heartbeatIntervalMs);

interval.unref?.();

return { stop: () => clearInterval(interval), lostLease: () => lostLease };

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Wait for active heartbeats and handle lease loss for callback errors.

stop() only clears the interval. A heartbeatMessage() call already in flight can set lostLease after Line 892. Also, a rejected callback skips the lease check and enters failMessage or failure recording. Both paths can mutate a message after another consumer reclaimed it.

  • internal-packages/run-engine/src/batch-queue/index.ts#L776-L798: Make stop() await or serialize active heartbeat requests before it returns.
  • internal-packages/run-engine/src/batch-queue/index.ts#L869-L900: Capture both callback results and callback errors. After awaiting heartbeat shutdown, discard either outcome when lostLease() is true.
📍 Affects 1 file
  • internal-packages/run-engine/src/batch-queue/index.ts#L776-L798 (this comment)
  • internal-packages/run-engine/src/batch-queue/index.ts#L869-L900

@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 3 potential issues.

Open in Devin Review

Comment on lines +779 to +798
const interval = setInterval(() => {
this.fairQueue
.heartbeatMessage(messageId, queueId)
.then((stillOwned) => {
if (!stillOwned) {
lostLease = true;
}
})
.catch((error) => {
this.logger.debug("Batch item heartbeat failed", {
messageId,
queueId,
error: error instanceof Error ? error.message : String(error),
});
});
}, this.heartbeatIntervalMs);

interval.unref?.();

return { stop: () => clearInterval(interval), lostLease: () => lostLease };

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.

🟡 A batch item whose processing hangs forever now blocks its batch from ever finishing

The item is kept permanently invisible by an unbounded keep-alive timer (setInterval at internal-packages/run-engine/src/batch-queue/index.ts:779-794) that runs for as long as the callback runs, so a callback that never returns stops the item from ever being retried and the batch never completes.

Impact: If a single item's processing stalls indefinitely (e.g. a hung network/database call), the whole batch stays stuck forever instead of recovering by retrying that item.

Why the safety net disappeared: extension has no upper bound

Before this change, a claimed message had a fixed 60s lease; if the consumer stopped making progress the reclaim loop (packages/redis-worker/src/fair-queue/visibility.ts:393) put the message back on the queue and another consumer eventually processed it, letting the batch finish.

Now #startHeartbeat extends the deadline by a full visibilityTimeoutMs every visibilityTimeoutMs/3 (internal-packages/run-engine/src/batch-queue/index.ts:773-799) and only stops in the finally after the callback settles (index.ts:888-890). A callback that never settles (no timeout in processItemCallback) keeps beating forever, so the item is never reclaimed, never redelivered, processedCount never reaches meta.runCount, and #finalizeBatch is never called.

A common mitigation is capping the total heartbeat lifetime (e.g. stop extending after N × visibility timeout, or after a configured max processing duration) so a genuinely stuck consumer still yields the item.

Prompt for agents
In internal-packages/run-engine/src/batch-queue/index.ts, #startHeartbeat extends a batch item's visibility deadline indefinitely for as long as the process-item callback is pending. Previously a stuck consumer would simply let the lease lapse and the FairQueue reclaim loop would redeliver the item, so the batch could still finish. With unbounded heartbeating, a callback that never settles keeps the item invisible forever and the batch's processed count never reaches runCount, so the batch never finalizes. Consider bounding how long an item may be heartbeated (e.g. a maxProcessingDurationMs option, or stop after N extensions) and letting the item lapse back to the queue past that bound, so a hung consumer cannot wedge a batch permanently.
Open in Devin Review

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

Comment on lines +892 to +900
if (heartbeat.lostLease()) {
this.logger.warn("Discarding batch item result, another consumer now owns it", {
batchId,
itemIndex,
messageId,
attempt,
});
return;
}

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.

🟡 An item taken over by another worker can still be marked permanently failed by the old worker

When processing throws, the code records a permanent failure and re-queues the item (failMessage/recordFailure in the catch block at internal-packages/run-engine/src/batch-queue/index.ts:892-899 is only applied to the success path), so an item that another worker has already taken over and succeeded on can be reported as failed.

Impact: A batch can report an item as failed even though a run for it was created successfully, and the created run is missing from the batch's results.

Asymmetric ownership check between the result path and the throw path

After the callback resolves, the code checks heartbeat.lostLease() and discards the result (internal-packages/run-engine/src/batch-queue/index.ts:892-900). If the callback instead throws, control jumps straight to the outer catch (see internal-packages/run-engine/src/batch-queue/index.ts:996 onwards) with no lostLease() check, so this consumer calls fairQueue.failMessage(...) (re-queuing a message now owned by someone else) or completionTracker.recordFailure(...).

recordFailure and recordSuccess are idempotent on itemIndex (internal-packages/run-engine/src/batch-queue/completionTracker.ts:329-351), so whichever lands first wins. If the stale consumer's failure lands first, the new owner's recordSuccess becomes a no-op: the batch counts the item as failed and the successfully created run never appears in runIds.

Applying the same lostLease() guard at the top of the catch block (before scheduling retry/recording failure) would close this.

Prompt for agents
In internal-packages/run-engine/src/batch-queue/index.ts #handleMessage, the new heartbeat lost-lease guard is only applied when the process-item callback resolves. When the callback throws, the outer catch block calls fairQueue.failMessage (re-queueing a message another consumer now owns) or completionTracker.recordFailure without checking heartbeat.lostLease(). Because recordSuccess/recordFailure are idempotent per itemIndex, a stale consumer's failure record can win the race against the new owner's success record, causing the batch to report a failure for an item whose run was actually created. Consider hoisting the heartbeat handle so the catch path can consult lostLease() and bail out the same way the success path does.
Open in Devin Review

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

Comment on lines +62 to +63
/** How long a claimed batch item stays invisible before the reclaim loop takes it back. */
const BATCH_ITEM_VISIBILITY_TIMEOUT_MS = 60_000;

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.

🔍 No .server-changes entry for a user-visible batch fix

CONTRIBUTING.md / AGENTS.md ask for a .server-changes/ file for server-only PRs (apps/webapp/, apps/supervisor/, "etc."). This PR touches only internal-packages/run-engine, which the table does not name explicitly, and repo history is mixed for run-engine-only PRs (some include one, some do not). Given the fix is user-visible (duplicate runs / batches that never finalize), a .server-changes/ note with area: webapp, type: fix would likely be expected here.

Open in 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.

1 participant