Skip to content

fix(agenda): correct off-by-one error in returnNextConcurrencyFreeJob#39830

Open
Jashk120 wants to merge 2 commits into
RocketChat:developfrom
Jashk120:fix/agenda-queue-off-by-one
Open

fix(agenda): correct off-by-one error in returnNextConcurrencyFreeJob#39830
Jashk120 wants to merge 2 commits into
RocketChat:developfrom
Jashk120:fix/agenda-queue-off-by-one

Conversation

@Jashk120
Copy link
Copy Markdown

@Jashk120 Jashk120 commented Mar 24, 2026

Proposed changes

returnNextConcurrencyFreeJob in JobProcessingQueue.ts used next > 0 as the loop condition, which caused index 0 to never be evaluated. If the only concurrency-free job happened to be at position 0 in the queue, the loop would exit without finding it. In a scenario where all jobs except the one at index 0 are at their concurrency limit, the wrong job would be returned.

Fixed by changing next > 0 to next >= 0 so all queue positions are evaluated.

Issue(s)

No existing issue — bug found by code review.

Steps to test or reproduce

  1. Fill the queue with multiple jobs where all except the job at index 0 are at concurrency limit
  2. Call returnNextConcurrencyFreeJob — before fix it skips index 0 and returns the wrong job

Summary by CodeRabbit

  • Bug Fixes
    • Job scheduler now correctly includes the first queue item when scanning for available work, improving selection accuracy.
    • When no eligible job is found, the scheduler gracefully exits without attempting invalid access, preventing runtime errors.

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented Mar 24, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Mar 24, 2026

⚠️ No Changeset found

Latest commit: b8319a9

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
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 24, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 84f789d5-561c-4a64-b78a-32e76565fa44

📥 Commits

Reviewing files that changed from the base of the PR and between ed6ca9a and b8319a9.

📒 Files selected for processing (2)
  • packages/agenda/src/Agenda.ts
  • packages/agenda/src/JobProcessingQueue.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/agenda/src/JobProcessingQueue.ts
📜 Recent review details
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • packages/agenda/src/Agenda.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: smirk-dev
Repo: RocketChat/Rocket.Chat PR: 39625
File: apps/meteor/app/api/server/v1/push.ts:85-97
Timestamp: 2026-03-14T14:58:58.834Z
Learning: In RocketChat/Rocket.Chat, the `push.token` POST/DELETE endpoints in `apps/meteor/app/api/server/v1/push.ts` were already migrated to the chained router API pattern on `develop` prior to PR `#39625`. `cleanTokenResult` (which strips `authToken` and returns `PushTokenResult`) and `isPushTokenPOSTProps`/`isPushTokenDELETEProps` validators already exist on `develop`. PR `#39625` only migrates `push.get` and `push.info` to the chained pattern. Do not flag `cleanTokenResult` or `PushTokenResult` as newly introduced behavior-breaking changes when reviewing this PR.
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 39677
File: packages/models/src/helpers/omnichannel/agentStatus.ts:10-29
Timestamp: 2026-03-16T22:56:54.500Z
Learning: In `packages/models/src/helpers/omnichannel/agentStatus.ts` (PR `#39677`), the `queryStatusAgentOnline` function intentionally omits the `$or` offline-status guard for non-bot agents when `isLivechatEnabledWhenAgentIdle === true`. This is by design: the setting `Livechat_enabled_when_agent_idle` (`accept_chats_when_agent_idle`) means agents should receive chats even when idle/offline, so the offline filter must be removed in that path. Bots are always status-agnostic and are always included regardless of their online/offline status. Do not flag this as a bug.
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/agenda/src/Agenda.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/agenda/src/Agenda.ts
🔇 Additional comments (1)
packages/agenda/src/Agenda.ts (1)

909-911: Correct undefined-guard for queue selection result.

Line 909 now properly handles the Job | undefined contract and prevents dereferencing job.attrs when no concurrency-free job is available.


Walkthrough

Changed returnNextConcurrencyFreeJob to return Job | undefined and updated its backward-scan loop from next > 0 to next >= 0. Agenda._jobProcessing() now handles a missing job by returning early when returnNextConcurrencyFreeJob yields undefined.

Changes

Cohort / File(s) Summary
Queue Processing
packages/agenda/src/JobProcessingQueue.ts
Changed return type of returnNextConcurrencyFreeJob to `Job
Job Scheduler
packages/agenda/src/Agenda.ts
Updated _jobProcessing() to handle undefined from returnNextConcurrencyFreeJob by exiting early before accessing job properties (e.g., job.attrs.nextRunAt).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

type: bug

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing an off-by-one error in the loop condition of returnNextConcurrencyFreeJob that prevented index 0 from being evaluated.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@Jashk120 Jashk120 force-pushed the fix/agenda-queue-off-by-one branch from 09b06e5 to ed6ca9a Compare March 24, 2026 05:21
@Jashk120 Jashk120 marked this pull request as ready for review March 24, 2026 05:21
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 1 file

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/agenda/src/JobProcessingQueue.ts">

<violation number="1" location="packages/agenda/src/JobProcessingQueue.ts:63">
P1: `returnNextConcurrencyFreeJob` can return `undefined` (when all jobs are concurrency-blocked) but is typed as `Job`, and callers dereference it unguarded.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread packages/agenda/src/JobProcessingQueue.ts
Copy link
Copy Markdown
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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/agenda/src/JobProcessingQueue.ts (1)

61-71: ⚠️ Potential issue | 🔴 Critical

Return type mismatch and missing null check cause NPE at call site.

The method's return type Job doesn't account for the scenario where no job with available concurrency is found. When the loop completes without breaking (all jobs at concurrency limit), next becomes -1, and this._queue[-1] returns undefined. The call site at Agenda.ts:909 accesses job.attrs.nextRunAt without checking if job is defined, resulting in a crash.

  • Update return type to Job | undefined
  • Add guard: if (next < 0) return undefined;
  • Update call site to handle undefined: if (!job || !job.attrs.nextRunAt) return;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/agenda/src/JobProcessingQueue.ts` around lines 61 - 71, The method
returnNextConcurrencyFreeJob currently assumes a Job is always found; change its
signature to return Job | undefined, add a guard after the loop (if next < 0)
return undefined to avoid indexing this._queue[-1], and keep locating the method
by name returnNextConcurrencyFreeJob and the _queue/agendaDefinitions usage;
then update the call site that uses its result (the variable named job which
later reads job.attrs.nextRunAt) to handle undefined (e.g., if (!job ||
!job.attrs.nextRunAt) return) so callers won’t dereference undefined.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@packages/agenda/src/JobProcessingQueue.ts`:
- Around line 61-71: The method returnNextConcurrencyFreeJob currently assumes a
Job is always found; change its signature to return Job | undefined, add a guard
after the loop (if next < 0) return undefined to avoid indexing this._queue[-1],
and keep locating the method by name returnNextConcurrencyFreeJob and the
_queue/agendaDefinitions usage; then update the call site that uses its result
(the variable named job which later reads job.attrs.nextRunAt) to handle
undefined (e.g., if (!job || !job.attrs.nextRunAt) return) so callers won’t
dereference undefined.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 597bc627-d2d8-48a0-970b-c40d43c96ee0

📥 Commits

Reviewing files that changed from the base of the PR and between 1dbfce4 and ed6ca9a.

📒 Files selected for processing (1)
  • packages/agenda/src/JobProcessingQueue.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • packages/agenda/src/JobProcessingQueue.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: smirk-dev
Repo: RocketChat/Rocket.Chat PR: 39625
File: apps/meteor/app/api/server/v1/push.ts:85-97
Timestamp: 2026-03-14T14:58:58.834Z
Learning: In RocketChat/Rocket.Chat, the `push.token` POST/DELETE endpoints in `apps/meteor/app/api/server/v1/push.ts` were already migrated to the chained router API pattern on `develop` prior to PR `#39625`. `cleanTokenResult` (which strips `authToken` and returns `PushTokenResult`) and `isPushTokenPOSTProps`/`isPushTokenDELETEProps` validators already exist on `develop`. PR `#39625` only migrates `push.get` and `push.info` to the chained pattern. Do not flag `cleanTokenResult` or `PushTokenResult` as newly introduced behavior-breaking changes when reviewing this PR.
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/agenda/src/JobProcessingQueue.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/agenda/src/JobProcessingQueue.ts

@coderabbitai coderabbitai Bot removed the type: bug label Mar 24, 2026
@Jashk120
Copy link
Copy Markdown
Author

@cubic-dev-ai @coderabbitai

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 24, 2026

@Jashk120 Hi! It looks like you've tagged me — happy to help! Would you like me to:

  • 🔍 Review the PR – I can perform a full review of the changes in this pull request.
  • Answer a question – Let me know if you have any specific questions about the code or the fix.

Just let me know how I can assist! 😊


🧠 Learnings used
Learnt from: smirk-dev
Repo: RocketChat/Rocket.Chat PR: 39625
File: apps/meteor/app/api/server/v1/push.ts:85-97
Timestamp: 2026-03-14T14:58:58.834Z
Learning: In RocketChat/Rocket.Chat, the `push.token` POST/DELETE endpoints in `apps/meteor/app/api/server/v1/push.ts` were already migrated to the chained router API pattern on `develop` prior to PR `#39625`. `cleanTokenResult` (which strips `authToken` and returns `PushTokenResult`) and `isPushTokenPOSTProps`/`isPushTokenDELETEProps` validators already exist on `develop`. PR `#39625` only migrates `push.get` and `push.info` to the chained pattern. Do not flag `cleanTokenResult` or `PushTokenResult` as newly introduced behavior-breaking changes when reviewing this PR.

Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 39677
File: packages/models/src/helpers/omnichannel/agentStatus.ts:10-29
Timestamp: 2026-03-16T22:56:54.500Z
Learning: In `packages/models/src/helpers/omnichannel/agentStatus.ts` (PR `#39677`), the `queryStatusAgentOnline` function intentionally omits the `$or` offline-status guard for non-bot agents when `isLivechatEnabledWhenAgentIdle === true`. This is by design: the setting `Livechat_enabled_when_agent_idle` (`accept_chats_when_agent_idle`) means agents should receive chats even when idle/offline, so the offline filter must be removed in that path. Bots are always status-agnostic and are always included regardless of their online/offline status. Do not flag this as a bug.
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@cubic-dev-ai
Copy link
Copy Markdown
Contributor

cubic-dev-ai Bot commented Mar 24, 2026

@cubic-dev-ai @coderabbitai

@Jashk120 I have started the AI code review. It will take a few minutes to complete.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

No issues found across 2 files

@Jashk120
Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 24, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant