Skip to content

add cron job tracking model#322

Open
satish2025-crew wants to merge 4 commits intotrunkfrom
868hqn90h
Open

add cron job tracking model#322
satish2025-crew wants to merge 4 commits intotrunkfrom
868hqn90h

Conversation

@satish2025-crew
Copy link
Copy Markdown
Contributor

@satish2025-crew satish2025-crew commented Mar 11, 2026

https://app.clickup.com/t/868hqn90h

Summary by CodeRabbit

  • New Features
    • Added job run tracking to monitor scheduled job executions, capturing status, timing, and error details; supports filtering by job, status, time ranges, and ordered queries.
  • Tests
    • Added comprehensive tests covering tracking data, filtering, ordering, time-range queries, and combined query behaviors.

@satish2025-crew satish2025-crew added enhancement New feature or request cr-124 CR-124 Hub 24Hr retry labels Mar 11, 2026
@satish2025-crew satish2025-crew requested a review from vkghub March 11, 2026 13:26
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 11, 2026

📝 Walkthrough

Walkthrough

Adds a new Mongoid model CronJobRun to record scheduled job executions (fields: job_name, started_at, ended_at, status, error_message) and multiple status/time query scopes, plus an RSpec suite exercising fields, scopes, ordering, and scope chaining.

Changes

Cohort / File(s) Summary
CronJobRun model
app/models/cron_job_run.rb
Introduces CronJobRun (Mongoid::Document, Mongoid::Timestamps) with fields: job_name (String), started_at (DateTime), ended_at (DateTime), status (Symbol), error_message (String). Adds scopes: recent, for_job(name), failed, running, succeeded, past_hour, past_day, on_date(date), date_range(from, to).
Model specs
spec/models/cron_job_run_spec.rb
Adds RSpec tests validating field types, scope behavior (ordering, inclusion), time-bounded queries, and scope chaining with seeded sample records.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 I hop through timestamps with whiskers so keen,
I log every start, every end, every scene,
Statuses, errors tucked snug in a row,
Scopes help me find them where cron breezes blow. 🥕

🚥 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 pull request title 'add cron job tracking model' directly and accurately summarizes the main change: adding a new CronJobRun model for tracking cron job executions.
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.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 868hqn90h

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.

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: 4

🧹 Nitpick comments (1)
app/models/cron_job_run.rb (1)

7-15: Add validations for the core tracking fields.

Right now callers can persist blank job_name, nil started_at, or arbitrary status values. That will make these records much less reliable for the indexed lookups and status scopes this model is introducing.

💡 Suggested change
   field :jobs_succeeded, type: Integer, default: 0
   field :jobs_failed, type: Integer, default: 0
   field :metadata, type: Hash, default: {}
+
+  VALID_STATUSES = %i[running failed succeeded].freeze
+
+  validates :job_name, :started_at, :status, presence: true
+  validates :status, inclusion: { in: VALID_STATUSES }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/models/cron_job_run.rb` around lines 7 - 15, CronJobRun allows blank or
invalid core fields; add ActiveModel validations on the model: validate presence
(and not blank) of job_name and started_at, validate presence of status plus
inclusion in a defined set (e.g. define STATUS_VALUES constant and use validates
:status, inclusion: { in: STATUS_VALUES }), and add numeric/non-negative checks
for jobs_processed, jobs_succeeded, and jobs_failed (e.g.
validates_numericality_of ..., greater_than_or_equal_to: 0). Update the
CronJobRun model to include these validations so indexed lookups and status
scopes only store valid records.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/models/cron_job_run.rb`:
- Line 3: Add a top-level documentation comment for the CronJobRun class (class
CronJobRun) describing its responsibility and usage, or suppress the
Style/Documentation cop for this class by adding the appropriate RuboCop
directive above the class (e.g., # rubocop:disable Style/Documentation) if
documentation is intentionally omitted; update only the class declaration area
so CI no longer fails on the top-level documentation rule.
- Around line 28-41: The record method currently creates a CronJobRun and yields
it but never finalizes successful runs; change it so that after yielding
(whether the block raises or not) the record is updated with ended_at and the
appropriate status: on normal completion set status to :succeeded and ended_at
to DateTime.now, and on exception (rescue StandardError => e) keep the existing
behavior that sets status :failed, error_message and ended_at; implement this by
wrapping the yield in begin...rescue...ensure or using an ensure block that
updates run when present, referencing the existing class method
CronJobRun.record, the local run variable, and the create!/yield flow so callers
no longer must manually mark success.
- Line 26: Remove the redundant .freeze on the JOB_RETRY_FAILED_VLP constant in
the CronJobRun class: because the file has # frozen_string_literal: true, change
the constant declaration from JOB_RETRY_FAILED_VLP =
'retry_failed_vlp_jobs'.freeze to simply JOB_RETRY_FAILED_VLP =
'retry_failed_vlp_jobs' (update the declaration where the constant is defined).

In `@spec/models/cron_job_run_spec.rb`:
- Line 121: The example block passed to
described_class.record(CronJobRun::JOB_RETRY_FAILED_VLP) declares an unused
block parameter `run`, causing Lint/UnusedBlockArgument; remove the unused
parameter by changing the block from `do |run| ... end` to `do ... end` (i.e.,
drop `|run|`) wherever this invocation appears so the test no longer defines an
unused variable.

---

Nitpick comments:
In `@app/models/cron_job_run.rb`:
- Around line 7-15: CronJobRun allows blank or invalid core fields; add
ActiveModel validations on the model: validate presence (and not blank) of
job_name and started_at, validate presence of status plus inclusion in a defined
set (e.g. define STATUS_VALUES constant and use validates :status, inclusion: {
in: STATUS_VALUES }), and add numeric/non-negative checks for jobs_processed,
jobs_succeeded, and jobs_failed (e.g. validates_numericality_of ...,
greater_than_or_equal_to: 0). Update the CronJobRun model to include these
validations so indexed lookups and status scopes only store valid records.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a35b952f-267c-4da2-a7ba-4538060ffc55

📥 Commits

Reviewing files that changed from the base of the PR and between e1ac410 and 454c1aa.

📒 Files selected for processing (2)
  • app/models/cron_job_run.rb
  • spec/models/cron_job_run_spec.rb

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.

🧹 Nitpick comments (2)
app/models/cron_job_run.rb (2)

12-12: Consider validating status against allowed values.

Without validation, invalid status symbols can be persisted, potentially breaking reporting and scope queries.

💡 Suggested addition
   field :status, type: Symbol        # :running, :succeeded, or :failed
   field :error_message, type: String # Set when status is :failed
 
+  STATUSES = %i[running succeeded failed].freeze
+  validates :status, inclusion: { in: STATUSES }, allow_nil: true
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/models/cron_job_run.rb` at line 12, Add a strict validation for the
status field in the CronJobRun model: define a constant (e.g., STATUSES =
[:running, :succeeded, :failed]) and add validates :status, inclusion: { in:
STATUSES } so only those symbols can be persisted; update any code that sets or
queries status to use CronJobRun::STATUSES (or the constant values) to avoid
hardcoded strings/symbol mismatches.

9-13: Consider adding an index on job_name and started_at.

Queries will frequently filter by job_name and sort/filter by started_at. Without indexes, performance will degrade as the collection grows.

💡 Suggested addition
   field :error_message, type: String # Set when status is :failed
 
+  index({ job_name: 1, started_at: -1 })
+  index({ started_at: -1 })
+
   scope :recent, -> { order(started_at: :desc) }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/models/cron_job_run.rb` around lines 9 - 13, Add database indexes to the
CronJobRun model to speed queries that filter by job_name and sort/filter by
started_at: add a single-field index on job_name and a compound index on
{job_name, started_at} (started_at descending if you usually sort newest-first)
in the model definition so queries against the job_name and started_at fields
(field names: job_name, started_at; model: CronJobRun) use indexed lookups and
avoid full collection scans.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@app/models/cron_job_run.rb`:
- Line 12: Add a strict validation for the status field in the CronJobRun model:
define a constant (e.g., STATUSES = [:running, :succeeded, :failed]) and add
validates :status, inclusion: { in: STATUSES } so only those symbols can be
persisted; update any code that sets or queries status to use
CronJobRun::STATUSES (or the constant values) to avoid hardcoded strings/symbol
mismatches.
- Around line 9-13: Add database indexes to the CronJobRun model to speed
queries that filter by job_name and sort/filter by started_at: add a
single-field index on job_name and a compound index on {job_name, started_at}
(started_at descending if you usually sort newest-first) in the model definition
so queries against the job_name and started_at fields (field names: job_name,
started_at; model: CronJobRun) use indexed lookups and avoid full collection
scans.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8a5bf417-ddfd-44f2-99af-1e5bc288b5c3

📥 Commits

Reviewing files that changed from the base of the PR and between 454c1aa and c82c131.

📒 Files selected for processing (2)
  • app/models/cron_job_run.rb
  • spec/models/cron_job_run_spec.rb

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.

🧹 Nitpick comments (1)
spec/models/cron_job_run_spec.rb (1)

96-100: Consider using the record's actual timestamp for more robust date comparison.

The target_date is computed independently from when run2 was created. If the test crosses a midnight boundary (e.g., slow CI run), the dates could theoretically differ.

💡 More robust approach
     describe '.on_date' do
       it 'returns runs started on the given date' do
-        target_date = 23.hours.ago.to_date
+        target_date = run2.started_at.to_date
         expect(described_class.on_date(target_date).to_a).to contain_exactly(run2)
       end
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@spec/models/cron_job_run_spec.rb` around lines 96 - 100, The test computes
target_date independently which can diverge from run2's actual timestamp; change
target_date to derive from the fixture's timestamp (e.g. use
run2.started_at.to_date or run2.created_at.to_date) so the expectation calls
described_class.on_date(target_date) use the record's real date, ensuring the
spec is robust across midnight boundaries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@spec/models/cron_job_run_spec.rb`:
- Around line 96-100: The test computes target_date independently which can
diverge from run2's actual timestamp; change target_date to derive from the
fixture's timestamp (e.g. use run2.started_at.to_date or
run2.created_at.to_date) so the expectation calls
described_class.on_date(target_date) use the record's real date, ensuring the
spec is robust across midnight boundaries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 30e9097f-4b53-4e23-8b90-e6d726e2e7a9

📥 Commits

Reviewing files that changed from the base of the PR and between c82c131 and 97f5005.

📒 Files selected for processing (1)
  • spec/models/cron_job_run_spec.rb

@saikumar9 saikumar9 enabled auto-merge (squash) March 18, 2026 13:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cr-124 CR-124 Hub 24Hr retry enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants