Skip to content

Fix redis worker debounce #1966

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

Merged
merged 5 commits into from
Apr 22, 2025
Merged

Fix redis worker debounce #1966

merged 5 commits into from
Apr 22, 2025

Conversation

matt-aitken
Copy link
Member

@matt-aitken matt-aitken commented Apr 22, 2025

When using the "debounce" pattern with our (internal) Redis worker it was possible that we acked a job by mistake.

Example sequence:

  1. Add a job with id: "job-a"
  2. While that is running, add another id: "job-a" but with availableAt in the future.
  3. The first instance of the job completes before the availableAt
  4. We ack() the job id, before the new one starts.

This means that second one will never execute. This is a race condition.

This fix means that we will only ack an item if the item in the queue has the same deduplicationKey, i.e. is the exact same item. So if you've added another item with the same id we won't ack it.

Summary by CodeRabbit

  • New Features
    • Introduced a deduplication key mechanism for queue items, improving reliability when processing and acknowledging jobs.
  • Bug Fixes
    • Enhanced queue cleanup to ensure completed jobs are properly removed from both present and future queues.
  • Tests
    • Added integration tests for job deduplication, scheduling, and queue cleanup to verify correct behavior in various scenarios.

Copy link

changeset-bot bot commented Apr 22, 2025

⚠️ No Changeset found

Latest commit: be02fe6

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.

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

Copy link
Contributor

coderabbitai bot commented Apr 22, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce a deduplication key mechanism to the Redis-based queue system. Queue items now include an optional deduplicationKey, generated upon enqueueing and propagated through dequeueing, job handling, and acknowledgment steps. The acknowledgment logic in both the queue and Redis command interface was updated to validate this key, ensuring only the intended job instance is acknowledged and removed. The worker's job handler and processing logic were extended to handle and forward the deduplication key. Additionally, new integration tests were added to verify deduplication, job replacement, and queue cleanup behaviors, including scenarios that highlight known issues with job scheduling and removal.

Changes

File(s) Change Summary
packages/redis-worker/src/queue.ts Added optional deduplicationKey to queue item types; updated enqueue, dequeue, and ack methods to handle this key; enhanced Redis command interface and logic for deduplication validation.
packages/redis-worker/src/worker.ts Extended job handler and processing logic to accept and propagate deduplicationKey; updated acknowledgment calls.
packages/redis-worker/src/worker.test.ts Added integration tests for deduplication, job replacement, and queue cleanup; included tests for known scheduling issues.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Client
    participant Queue
    participant Redis
    participant Worker
    participant JobHandler

    Client->>Queue: enqueue(job)
    Queue->>Redis: Store job with deduplicationKey
    Worker->>Queue: dequeue()
    Queue->>Redis: Fetch job with deduplicationKey
    Queue->>Worker: Return job, deduplicationKey
    Worker->>JobHandler: process(job, deduplicationKey)
    JobHandler-->>Worker: Complete
    Worker->>Queue: ack(jobId, deduplicationKey)
    Queue->>Redis: ackItem(jobId, deduplicationKey)
    Redis-->>Queue: Validate & remove if deduplicationKey matches

Poem

In the warren of code, a key now appears,
Deduplication magic to calm our queue fears.
With nanoid in paw, each job gets its mark,
So rabbits can hop without missing the spark.
Tests leap and they bound, confirming the way—
The queue’s never cleaner at the end of the day!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72cbabe and be02fe6.

📒 Files selected for processing (2)
  • packages/redis-worker/src/queue.ts (8 hunks)
  • packages/redis-worker/src/worker.test.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Sorry, something went wrong.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
packages/redis-worker/src/worker.ts (1)

349-377: 🛠️ Refactor suggestion

ack() wrapper now bypasses the deduplication check

Inside processItem() you correctly call this.queue.ack(id, deduplicationKey), but the public Worker.ack() helper (lines 281‑287, unchanged) still invokes this.queue.ack(id) without the key. Any external user of worker.ack() (or future internal use) will wipe out a newer job with the same ID.

Either:

  1. Add an overload that requires the key, or
  2. Deprecate/remove the wrapper and expose queue.ack directly, or
  3. Forward an optional parameter:
- ack(id: string) {
+ ack(id: string, deduplicationKey?: string) {-   this.queue.ack(id);
+   this.queue.ack(id, deduplicationKey ?? "");
 }
🧹 Nitpick comments (1)
packages/redis-worker/src/worker.test.ts (1)

428-437: Stale comment may confuse future readers

The inline note “These assertions should fail – demonstrating the bug” is no longer accurate after the deduplication fix; the assertions are expected to pass. Please update or remove the comment to reflect the current intent, otherwise newcomers may treat a CI‑green run as suspicious.

- // These assertions should fail - demonstrating the bug
- // The second job should run …
+ // These assertions confirm that the second job is processed
+ // after the first one completes, validating the debounce fix.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2c19693 and 72cbabe.

📒 Files selected for processing (3)
  • packages/redis-worker/src/queue.ts (8 hunks)
  • packages/redis-worker/src/worker.test.ts (1 hunks)
  • packages/redis-worker/src/worker.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/redis-worker/src/worker.ts (1)
packages/redis-worker/src/queue.ts (1)
  • AnyQueueItem (33-41)
packages/redis-worker/src/worker.test.ts (1)
internal-packages/testcontainers/src/index.ts (1)
  • redisTest (128-128)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines 380 to +408
this.redis.defineCommand("ackItem", {
numberOfKeys: 2,
lua: `
local queue = KEYS[1]
local items = KEYS[2]
local queueKey = KEYS[1]
local itemsKey = KEYS[2]
local id = ARGV[1]
local deduplicationKey = ARGV[2]

redis.call('ZREM', queue, id)
redis.call('HDEL', items, id)
-- Get the item from the hash
local item = redis.call('HGET', itemsKey, id)
if not item then
return -1
end

-- Only check deduplicationKey if a non-empty one was passed in
if deduplicationKey and deduplicationKey ~= "" then
local success, parsed = pcall(cjson.decode, item)
if success then
if parsed.deduplicationKey and parsed.deduplicationKey ~= deduplicationKey then
return 0
end
end
end

-- Remove from sorted set and hash
redis.call('ZREM', queueKey, id)
redis.call('HDEL', itemsKey, id)
return 1
`,
`,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Lua script: avoid false‑positives when no deduplicationKey is stored

If the stored item predates this feature it will have no deduplicationKey.
When an old item is replaced by a new one with a key while another worker still holds the old key (""), the current logic bypasses the check (deduplicationKey argument is empty) and deletes the new item – re‑introducing the race.

Guard by returning 0 whenever the stored item has a key but none is supplied:

- if deduplicationKey and deduplicationKey ~= "" then
+ if deduplicationKey == nil or deduplicationKey == "" then
+   local parsed = cjson.decode(item)
+   if parsed.deduplicationKey then
+     return 0
+   end
+ else
   -- existing path

This keeps backward‑compatibility (old items without a key are still ACKed) while protecting new ones.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 208 to 217
async ack(id: string, deduplicationKey?: string): Promise<void> {
try {
await this.redis.ackItem(`queue`, `items`, id);
const result = await this.redis.ackItem(`queue`, `items`, id, deduplicationKey ?? "");
if (result === 0) {
this.logger.error(`SimpleQueue ${this.name}.ack(): ack operation returned 0`, {
queue: this.name,
id,
deduplicationKey,
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Escalate ACK mismatches instead of silently logging them

ack() only logs when the Lua script returns 0 (deduplication‑key mismatch) or -1 (item missing) but still resolves void.
Call‑sites (e.g. Worker.processItem) will therefore treat the job as successfully acknowledged even though it remains in Redis, leading to:

  • the job becoming “stuck” until TTL‑cleanup or a manual redrive
  • misleading success metrics / traces

Consider propagating the return value (or throwing) so that the caller can retry, reschedule or surface an error.

- const result = await this.redis.ackItem(...);
- if (result === 0) {
-   this.logger.error(/* … */);
- }
+ const result = await this.redis.ackItem(...);
+ if (result <= 0) {
+   throw new Error(
+     `ACK failed for id=${id} (result=${result}, dedupKey=${deduplicationKey ?? "∅"})`
+   );
+ }
📝 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
async ack(id: string, deduplicationKey?: string): Promise<void> {
try {
await this.redis.ackItem(`queue`, `items`, id);
const result = await this.redis.ackItem(`queue`, `items`, id, deduplicationKey ?? "");
if (result === 0) {
this.logger.error(`SimpleQueue ${this.name}.ack(): ack operation returned 0`, {
queue: this.name,
id,
deduplicationKey,
});
}
async ack(id: string, deduplicationKey?: string): Promise<void> {
try {
const result = await this.redis.ackItem(`queue`, `items`, id, deduplicationKey ?? "");
if (result <= 0) {
throw new Error(
`ACK failed for id=${id} (result=${result}, dedupKey=${deduplicationKey ?? "∅"})`
);
}
// …rest of the logic…

@matt-aitken matt-aitken merged commit e379fc1 into main Apr 22, 2025
10 of 11 checks passed
@matt-aitken matt-aitken deleted the fix-redis-worker-debounce branch April 22, 2025 14:24
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.

None yet

2 participants