Skip to content

fix(agenda): clear failReason and failedAt on successful job completion#39758

Open
Jashk120 wants to merge 2 commits into
RocketChat:developfrom
Jashk120:fix/agenda-clear-failreason-on-success-v2
Open

fix(agenda): clear failReason and failedAt on successful job completion#39758
Jashk120 wants to merge 2 commits into
RocketChat:developfrom
Jashk120:fix/agenda-clear-failreason-on-success-v2

Conversation

@Jashk120
Copy link
Copy Markdown

@Jashk120 Jashk120 commented Mar 20, 2026

Proposed changes

failReason and failedAt fields are never cleared when a job runs successfully
after a previous failure. This causes stale failure data to persist indefinitely
in rocketchat_cron.

Two changes:

  1. Job.ts — clear failReason and failedAt in the success path of jobCallback
  2. Agenda.ts — filter undefined values from $set into $unset in _updateJob
    so MongoDB actually removes the fields instead of ignoring them

Issue(s)

Closes #39755

Steps to test

  1. Manually set failReason and failedAt on a job document in rocketchat_cron
  2. Wait for the job to run successfully on next scheduled execution
  3. Verify both fields are removed from the document
    Steps to test or reproduce

Before fix — job with lastFinishedAt set still showing stale failReason:

{
    "_id": "69b96a5e22a18cc50365c72c",
    "name": "UserDataDownload",
    "lastRunAt": "2026-03-20T05:10:00.000Z",
    "lastFinishedAt": "2026-03-20T05:10:00.004Z",
    "failReason": "Got Stuck",
    "failedAt": "2026-03-20T05:10:00.004Z"
}

After fix — both fields cleared after successful run:

{
    "_id": "69b96a5e22a18cc50365c72c",
    "name": "UserDataDownload",
    "lastRunAt": "2026-03-20T05:38:00.001Z",
    "lastFinishedAt": "2026-03-20T05:38:00.004Z"

}

Summary by CodeRabbit

  • Bug Fixes
    • Jobs now clear previous failure details when they finish successfully, preventing stale error information from persisting.
    • Job completion timestamps are updated reliably on success.
    • Updates to job properties now only write defined changes to the database and explicitly remove select fields when unset, avoiding accidental persistence of undefined values.

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented Mar 20, 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 20, 2026

⚠️ No Changeset found

Latest commit: d16188f

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 20, 2026

Walkthrough

Clears stale failure fields on successful job completion and refactors how job updates are sent to MongoDB: _updateJob now builds $set and $unset maps from props, and successful job completion now clears failReason and failedAt while updating lastFinishedAt.

Changes

Cohort / File(s) Summary
MongoDB Update Operator Handling
packages/agenda/src/Agenda.ts
Refactored _updateJob to iterate props and produce separate $set entries for defined values and $unset entries for a restricted set of keys when values are undefined; only include $set/$unset when non-empty (prevents persisting undefined to MongoDB).
Job Success State Reset
packages/agenda/src/Job.ts
On successful job callback (no err), clears attrs.failReason and attrs.failedAt (sets to undefined) and updates lastFinishedAt; failure path still calls this.fail(err).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: clearing failReason and failedAt fields on successful job completion, which is the core objective of the PR.
Linked Issues check ✅ Passed The PR implementation directly addresses issue #39755 by clearing failure fields on success in Job.ts and handling undefined values with $unset in Agenda.ts.
Out of Scope Changes check ✅ Passed All changes are focused on resolving the linked issue; no out-of-scope modifications detected in the affected files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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.

Tip

CodeRabbit can scan for known vulnerabilities in your dependencies using OSV Scanner.

OSV Scanner will automatically detect and report security vulnerabilities in your project's dependencies. No additional configuration is required.

@Jashk120 Jashk120 force-pushed the fix/agenda-clear-failreason-on-success-v2 branch from 1eb1337 to b4e02ea Compare March 20, 2026 07:30
@Jashk120 Jashk120 marked this pull request as ready for review March 20, 2026 07:32
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

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/agenda/src/Agenda.ts (1)

495-496: Remove the new implementation comment.

The code is already self-explanatory here. As per coding guidelines, "Avoid code comments in the implementation".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/agenda/src/Agenda.ts` around lines 495 - 496, Remove the redundant
implementation comment that precedes the debug call; delete the line "// Update
the job and process the resulting data" so only the debug statement debug('job
already has _id, calling findOneAndUpdate() using _id as query'); remains in the
method where job update is handled (around the code using findOneAndUpdate in
Agenda.ts).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/agenda/src/Agenda.ts`:
- Around line 483-493: The loop over Object.entries(props) is unconditionally
turning any undefined prop into an $unset, which will mistakenly remove fields
like lastRunAt set temporarily by repeatEvery(..., { skipImmediate: true });
change the logic in the block that builds $set/$unset (the code using props,
$set, $unset, update) to only unset the specific failure-related fields
(failReason and failedAt) or use an explicit delete-list instead of unsetting
every undefined prop; locate the builder that iterates props (the for (const
[key, value] of Object.entries(props)) block) and replace the unconditional
undefined => $unset behavior with either (a) only add key to $unset if key is in
['failReason','failedAt'] and value === undefined, or (b) maintain an explicit
array of keysToRemove and only unset those keys when present.

---

Nitpick comments:
In `@packages/agenda/src/Agenda.ts`:
- Around line 495-496: Remove the redundant implementation comment that precedes
the debug call; delete the line "// Update the job and process the resulting
data" so only the debug statement debug('job already has _id, calling
findOneAndUpdate() using _id as query'); remains in the method where job update
is handled (around the code using findOneAndUpdate in Agenda.ts).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 903604b2-795c-48e5-bd61-23e017a7b5d6

📥 Commits

Reviewing files that changed from the base of the PR and between 8fe10c0 and b4e02ea.

📒 Files selected for processing (2)
  • packages/agenda/src/Agenda.ts
  • packages/agenda/src/Job.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/Job.ts
  • 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: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.
📚 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/Job.ts
  • 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/Job.ts
  • packages/agenda/src/Agenda.ts
🔇 Additional comments (1)
packages/agenda/src/Job.ts (1)

209-211: Success-path cleanup looks right.

This clears the stale failure markers before persisting, so a recovered job no longer carries failReason/failedAt into later runs.

Comment thread packages/agenda/src/Agenda.ts Outdated
@coderabbitai coderabbitai Bot removed the type: bug label Mar 20, 2026
@Jashk120 Jashk120 marked this pull request as draft March 22, 2026 05:57
@Jashk120 Jashk120 marked this pull request as ready for review March 22, 2026 06:08
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

@cubic-dev-ai @coderabbitai review

@cubic-dev-ai
Copy link
Copy Markdown
Contributor

cubic-dev-ai Bot commented Mar 24, 2026

@cubic-dev-ai @coderabbitai review

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 24, 2026

@Jashk120 Sure! I'll review the changes in PR #39758 now.


🧠 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.
✅ 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.

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

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.

FailReason and FailedAt not cleared after successful job completion

1 participant