Skip to content

Conversation

@spsancti
Copy link
Contributor

@spsancti spsancti commented Aug 27, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved stability of predictive rate calculations by fixing indexing and boundary handling.
    • Prevented rare underflow and divide-by-zero errors in edge cases.
    • Ensured consistent results with sparse or degenerate measurement data (returns safe defaults instead of erratic values).
    • Made overshoot adjustment more robust when rates are extremely low.
    • Overall, delivers more reliable and predictable behavior in rate-dependent features.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 27, 2025

Walkthrough

Implements defensive fixes and indexing corrections in src/display/core/predictive.h. getRate adds a cutoff boundary check, corrects accumulation loop indexing, guards against tiny variance and non-positive slopes, and returns 0.0 for degenerate cases. getOvershootAdjustMillis caches rate and avoids division by near-zero. No API changes.

Changes

Cohort / File(s) Summary
Predictive rate and overshoot safeguards
src/display/core/predictive.h
getRate: add cutoff boundary check (prevent underflow), fix accumulation loop to use j, guard against tiny tdev2 (< 1e-10) and non-positive slope, return 0.0 for degenerate data. getOvershootAdjustMillis: cache local rate, return 0.0 if rate < 1e-10 to avoid division by zero. No signature/API changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Caller
  participant Pred as Predictive
  Caller->>Pred: getOvershootAdjustMillis(params)
  rect rgb(230,245,255)
    note over Pred: compute local rate and guard early
    Pred->>Pred: getRate(measurements, cutoff)
    alt stop index underflow risk
      note right of Pred: while (i > 0 && measurementTimes[i-1] > cutoff)
    end
    alt tiny variance (tdev2 < 1e-10)
      Pred-->>Pred: return 0.0 (degenerate)
    else alt non-positive slope
      Pred-->>Pred: return 0.0 (non-positive volume)
    end
  end
  alt rate < 1e-10
    Pred-->>Caller: 0.0 (avoid division)
  else
    Pred-->>Caller: overshootMillis (uses cached rate)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibble numbers, whiskers quick and keen,
Fixed the loops where bounds were unseen.
No tiny variances bring panic or shame,
Zero‑guards keep divisions tame.
Carrots counted, predictions serene. 🥕

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 895f02e and ce01772.

📒 Files selected for processing (1)
  • src/display/core/predictive.h (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/display/core/predictive.h
⏰ 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). (2)
  • GitHub Check: deploy
  • GitHub Check: test
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • 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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@sonarqubecloud
Copy link

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

Caution

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

⚠️ Outside diff range comments (1)
src/display/core/predictive.h (1)

4-5: Include what you use.

This header uses std::vector and std::pow but doesn’t include their headers. Avoid relying on transitive includes.

 #include <Arduino.h>
+#include <vector>
+#include <cmath>
🧹 Nitpick comments (4)
src/display/core/predictive.h (4)

45-47: Indexing fix is correct; avoid pow in the hot loop.

Use precomputed deltas and multiplication to reduce floating-point overhead on MCU targets.

-            tdev_vdev += (measurementTimes[j] - t_mean) * (measurements[j] - v_mean);
-            tdev2 += pow(measurementTimes[j] - t_mean, 2.0);
+            const double dt = measurementTimes[j] - t_mean;
+            const double dv = measurements[j] - v_mean;
+            tdev_vdev += dt * dv;
+            tdev2 += dt * dt;

48-53: Near-zero denominator guard is good; name the threshold.

Minor: give the magic number a name for readability and easier tuning.

-        // Prevent division by zero
-        if (tdev2 < 1e-10) {
+        // Prevent division by near-zero denominator (units: ms^2)
+        constexpr double kTdev2Epsilon = 1e-10;
+        if (tdev2 < kTdev2Epsilon) {
             return 0.0;
         }

54-56: Comment mismatch on units.

The code returns volume/ms; the comment suggests seconds. Align the comment to avoid confusion.

-        double volumePerMilliSecond = tdev_vdev / tdev2;              // the slope (volume per millisecond) of the linear best fit
-        return volumePerMilliSecond > 0 ? volumePerMilliSecond : 0.0; // return 0 if it is not positive, convert to seconds
+        double volumePerMilliSecond = tdev_vdev / tdev2;              // slope (volume per millisecond) of the linear best fit
+        return volumePerMilliSecond > 0 ? volumePerMilliSecond : 0.0; // return 0 if it is not positive (units: volume/ms)

62-70: Division-by-zero guard is correct; clarify negative overshoot behavior.

If actual < expected, result is negative ms. Is that intended? Consider clamping to 0 for “overshoot” semantics.

         double rate = getRate(measurementTimes.back());
         
         // Prevent division by zero
         if (rate < 1e-10) {
             return 0.0;
         }
-        
-        return overshoot / rate;
+        // If actual <= expected, there is no overshoot to adjust.
+        if (overshoot <= 0.0) {
+            return 0.0;
+        }
+        return overshoot / rate;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f62c2e5 and 895f02e.

📒 Files selected for processing (1)
  • src/display/core/predictive.h (3 hunks)
⏰ 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). (2)
  • GitHub Check: deploy
  • GitHub Check: test
🔇 Additional comments (1)
src/display/core/predictive.h (1)

25-27: Good underflow safeguard in cutoff scan.

The added i > 0 guard prevents size_t wraparound and out-of-bounds access when the window excludes all points. LGTM.

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.

1 participant