Skip to content

[ISSUE #6541] [Enhancement✨] StatsItem to use TimeUtils.current_millis for timestamp generation#6576

Merged
mxsm merged 1 commit intomxsm:mainfrom
pranshu314:refactor/use_current_millis
Feb 28, 2026
Merged

[ISSUE #6541] [Enhancement✨] StatsItem to use TimeUtils.current_millis for timestamp generation#6576
mxsm merged 1 commit intomxsm:mainfrom
pranshu314:refactor/use_current_millis

Conversation

@pranshu314
Copy link
Contributor

@pranshu314 pranshu314 commented Feb 28, 2026

Which Issue(s) This PR Fixes(Closes)

Brief Description

  • use TimeUtils::current_millis in stats_item

How Did You Test This Change?

  • Verified the application builds successfully using cargo build
  • Confirmed optimized production build using cargo build --release
  • Ran the full test suite with cargo test (cargo test -p rocketmq_common)
  • Ensured all existing tests passed without failures or regressions

Summary by CodeRabbit

  • Refactor
    • Standardized internal time tracking mechanisms to use a centralized time utility across statistics components, improving code consistency and maintainability without affecting public APIs.

use TimeUtils::current_millis in stats_item
@rocketmq-rust-bot
Copy link
Collaborator

🔊@pranshu314 🚀Thanks for your contribution🎉!

💡CodeRabbit(AI) will review your code first🔥!

Note

🚨The code review suggestions from CodeRabbit are to be used as a reference only, and the PR submitter can decide whether to make changes based on their own judgment. Ultimately, the project management personnel will conduct the final code review💥.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 28, 2026

Walkthrough

Refactored stats_item.rs to centralize timestamp generation by replacing all SystemTime-based wall-clock computations with TimeUtils.current_millis(). This affects timestamp initialization, updates in add methods, and CallSnapshot entry generation throughout the module.

Changes

Cohort / File(s) Summary
Time Source Consolidation
rocketmq-common/src/common/stats/stats_item.rs
Replaced SystemTime-based timestamp computations with centralized TimeUtils.current_millis() across initialization, updates, and snapshot generation. Added current_millis import and updated compute functions (compute_next_minutes_time_millis, compute_next_hour_time_millis, compute_next_morning_time_millis) to use unified time source.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Timestamps once scattered like clover in spring,
Now unified, oh what a harmonious thing!
From SystemTime's chaos to TimeUtils bright,
The stats now measure with centralized light.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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: replacing time acquisition logic in StatsItem with TimeUtils.current_millis for centralized timestamp generation.
Linked Issues check ✅ Passed The pull request fully implements the objective from issue #6541 by replacing all SystemTime-based time acquisition in stats_item.rs with TimeUtils.current_millis.
Out of Scope Changes check ✅ Passed All changes are scoped to stats_item.rs and directly address the objective of centralizing timestamp generation using TimeUtils.current_millis; no unrelated modifications detected.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Caution

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

⚠️ Outside diff range comments (1)
rocketmq-common/src/common/stats/stats_item.rs (1)

86-93: ⚠️ Potential issue | 🟡 Minor

Documentation is inconsistent with new initialization behavior.

The doc comment states "A value of 0 means the item has never been written to," but last_update_timestamp is now initialized to current_millis() (line 47), so it will never be 0 for a newly constructed item. The documentation should be updated to reflect the new semantics.

📝 Proposed doc update
     /// Returns the wall-clock timestamp (milliseconds since UNIX epoch) of the last
-    /// [`add`](Self::add) or [`increment`](Self::increment) call.
-    ///
-    /// A value of `0` means the item has never been written to.
+    /// [`add`](Self::add) or [`increment`](Self::increment) call, or the creation
+    /// time if the item has never been written to.
     #[inline]
     pub fn get_last_update_timestamp(&self) -> u64 {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rocketmq-common/src/common/stats/stats_item.rs` around lines 86 - 93, The doc
comment for get_last_update_timestamp is out of date because
last_update_timestamp is initialized to current_millis() (so a newly constructed
StatsItem will not return 0); update the documentation on
get_last_update_timestamp (and any related doc on initialization) to state that
it returns the wall-clock timestamp of the last add/increment or the creation
time (initialized to current_millis()), and remove or change the sentence
claiming "A value of `0` means the item has never been written to" to reflect
the new semantics of last_update_timestamp.
🧹 Nitpick comments (1)
rocketmq-common/src/common/stats/stats_item.rs (1)

156-159: Consider caching current_millis() to ensure consistent timestamps.

When the list is empty, current_millis() is called twice (lines 157 and 159), which can introduce a minor timing drift between the backdated and current snapshots. Storing the value once would ensure the time difference is exactly the intended offset.

♻️ Proposed refactor
     pub fn sampling_in_seconds_internal(
         cs_list: &Mutex<LinkedList<CallSnapshot>>,
         current_value: u64,
         current_times: u64,
     ) {
         let mut cs_list = cs_list.lock();
+        let now = current_millis();
         if cs_list.is_empty() {
-            cs_list.push_back(CallSnapshot::new(current_millis() - 10 * 1000, 0, 0));
+            cs_list.push_back(CallSnapshot::new(now - 10 * 1000, 0, 0));
         }
-        cs_list.push_back(CallSnapshot::new(current_millis(), current_times, current_value));
+        cs_list.push_back(CallSnapshot::new(now, current_times, current_value));
         if cs_list.len() > 7 {
             cs_list.pop_front();
         }
     }

The same pattern applies to sampling_in_minutes (lines 168-170) and sampling_in_hour (lines 179-181).

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

In `@rocketmq-common/src/common/stats/stats_item.rs` around lines 156 - 159, Cache
the timestamp once instead of calling current_millis() repeatedly so the
backdated and current CallSnapshot use the exact intended offsets: capture let
now = current_millis() and use now and now - 10 * 1000 when creating
CallSnapshot entries for cs_list in the block shown, and apply the same change
where sampling_in_minutes and sampling_in_hour build their snapshots; update
usages of CallSnapshot::new(...) to use the cached now variable to ensure
consistent timestamps.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@rocketmq-common/src/common/stats/stats_item.rs`:
- Around line 19-21: Remove the now-unused import "use std::time::SystemTime;"
from the top of stats_item.rs (the code now uses current_millis via use
crate::TimeUtils::current_millis;), search for any remaining references to
SystemTime in the same file and delete them if none exist, then run cargo
check/cargo build to ensure no other usages remain.

---

Outside diff comments:
In `@rocketmq-common/src/common/stats/stats_item.rs`:
- Around line 86-93: The doc comment for get_last_update_timestamp is out of
date because last_update_timestamp is initialized to current_millis() (so a
newly constructed StatsItem will not return 0); update the documentation on
get_last_update_timestamp (and any related doc on initialization) to state that
it returns the wall-clock timestamp of the last add/increment or the creation
time (initialized to current_millis()), and remove or change the sentence
claiming "A value of `0` means the item has never been written to" to reflect
the new semantics of last_update_timestamp.

---

Nitpick comments:
In `@rocketmq-common/src/common/stats/stats_item.rs`:
- Around line 156-159: Cache the timestamp once instead of calling
current_millis() repeatedly so the backdated and current CallSnapshot use the
exact intended offsets: capture let now = current_millis() and use now and now -
10 * 1000 when creating CallSnapshot entries for cs_list in the block shown, and
apply the same change where sampling_in_minutes and sampling_in_hour build their
snapshots; update usages of CallSnapshot::new(...) to use the cached now
variable to ensure consistent timestamps.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cc1652 and 572aa51.

📒 Files selected for processing (1)
  • rocketmq-common/src/common/stats/stats_item.rs

Comment on lines 19 to +21
use std::time::SystemTime;

use crate::TimeUtils::current_millis;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Remove unused SystemTime import.

The std::time::SystemTime import on line 19 is no longer used after refactoring to current_millis(). This dead import should be removed.

🧹 Proposed fix
 use std::fmt;
 use std::sync::atomic::AtomicU64;
 use std::sync::atomic::Ordering;
-use std::time::SystemTime;

 use crate::TimeUtils::current_millis;
📝 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
use std::time::SystemTime;
use crate::TimeUtils::current_millis;
use std::fmt;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use crate::TimeUtils::current_millis;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@rocketmq-common/src/common/stats/stats_item.rs` around lines 19 - 21, Remove
the now-unused import "use std::time::SystemTime;" from the top of stats_item.rs
(the code now uses current_millis via use crate::TimeUtils::current_millis;),
search for any remaining references to SystemTime in the same file and delete
them if none exist, then run cargo check/cargo build to ensure no other usages
remain.

@codecov
Copy link

codecov bot commented Feb 28, 2026

Codecov Report

❌ Patch coverage is 36.36364% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 41.92%. Comparing base (51f5ad7) to head (572aa51).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
rocketmq-common/src/common/stats/stats_item.rs 36.36% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6576      +/-   ##
==========================================
- Coverage   41.96%   41.92%   -0.04%     
==========================================
  Files         954      955       +1     
  Lines      133233   133300      +67     
==========================================
- Hits        55906    55887      -19     
- Misses      77327    77413      +86     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Collaborator

@rocketmq-rust-bot rocketmq-rust-bot left a comment

Choose a reason for hiding this comment

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

LGTM - All CI checks passed ✅

Copy link
Owner

@mxsm mxsm left a comment

Choose a reason for hiding this comment

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

LGTM

@mxsm mxsm merged commit 4effe3c into mxsm:main Feb 28, 2026
10 of 22 checks passed
@rocketmq-rust-bot rocketmq-rust-bot added approved PR has approved and removed ready to review waiting-review waiting review this PR labels Feb 28, 2026
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.

[Enhancement✨] StatsItem to use TimeUtils.current_millis for timestamp generation

4 participants