Skip to content

⚡ Bolt: optimize get_consumption and combine_consumption#178

Open
Moohan wants to merge 1 commit intomainfrom
bolt-performance-optimizations-5119408834053835043
Open

⚡ Bolt: optimize get_consumption and combine_consumption#178
Moohan wants to merge 1 commit intomainfrom
bolt-performance-optimizations-5119408834053835043

Conversation

@Moohan
Copy link
Copy Markdown
Owner

@Moohan Moohan commented Mar 7, 2026

This PR implements two performance optimizations for the octopusR package:

  1. Avoid Redundant API Calls: The internal get_meter_details() function was automatically calling get_meter_gsp() (a network request) even when the GSP information wasn't needed. get_consumption() now skips this, reducing network overhead by one request per call when meter details are not provided.
  2. Vectorized NA Handling: In combine_consumption(), ifelse() was used to replace NA values with 0. This has been replaced with logical indexing (x[is.na(x)] <- 0), which is measurably faster and more memory-efficient.

Benchmarking Results:

  • API Call Reduction: get_meter_gsp calls reduced from 1 to 0 during get_consumption() execution.
  • combine_consumption Optimization:
    • Before: Median 4.43ms, 10.71MB allocation.
    • After: Median 1.3ms, 3.13MB allocation (~3.4x faster, ~3.4x less RAM).

Tests were run locally using testthat::test_local() and all 64 tests passed.


PR created automatically by Jules for task 5119408834053835043 started by @Moohan

Summary by Sourcery

Optimize meter detail retrieval and consumption combination performance while adding internal documentation for a past optimization decision.

Enhancements:

  • Add an include_gsp flag to meter detail retrieval to optionally skip fetching Grid Supply Point data when not required.
  • Streamline NA replacement in combined consumption data by using direct indexing instead of conditional evaluation for better performance.

Documentation:

  • Document the rationale and action taken to avoid redundant GSP API calls in an internal Bolt note.

Summary by CodeRabbit

  • Performance Improvements

    • Optimised meter detail retrieval by eliminating unnecessary network requests when Grid Supply Point lookups are not required, reducing overhead in consumption data calls by up to 50%.
  • New Features

    • Added configurable option to skip Grid Supply Point lookups during meter detail retrieval.

- Reduced API overhead in `get_consumption` by skipping redundant GSP lookup in `get_meter_details`.
- Replaced `ifelse` with logical indexing in `combine_consumption` for better performance and reduced memory allocation.
- Updated documentation and internal type handling for GSP.
- Added architectural learning to `.jules/bolt.md`.

Co-authored-by: Moohan <5982260+Moohan@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Mar 7, 2026

Reviewer's Guide

Introduces an optional include_gsp flag to avoid unnecessary GSP lookups when fetching meter details for get_consumption, and optimizes combine_consumption NA handling by replacing ifelse-based replacement with in-place, vectorized assignment; also records the optimization in the .jules/bolt.md metadata file.

Sequence diagram for get_consumption and conditional GSP lookup

sequenceDiagram
  participant Client
  participant get_consumption
  participant get_meter_details
  participant get_meter_gsp

  Client->>get_consumption: get_consumption(meter_type, direction, mpan_mprn, serial_number)
  alt mpan_mprn_or_serial_missing
    get_consumption->>get_meter_details: get_meter_details(meter_type, direction, include_gsp = FALSE)
    get_meter_details-->>get_consumption: meter_details(type, mpan_mprn, serial_number, gsp = NA)
  else mpan_mprn_and_serial_provided
    get_consumption-->>Client: consumption_data
  end
  get_consumption-->>Client: consumption_data

  %% Example of other callers that still request GSP
  rect rgb(230,230,230)
    participant OtherCaller
    OtherCaller->>get_meter_details: get_meter_details(meter_type = electricity, direction, include_gsp = TRUE)
    alt electricity_and_include_gsp_true
      get_meter_details->>get_meter_gsp: get_meter_gsp(mpan_mprn)
      get_meter_gsp-->>get_meter_details: gsp
      get_meter_details-->>OtherCaller: meter_details(type, mpan_mprn, serial_number, gsp)
    else gas_or_include_gsp_false
      get_meter_details-->>OtherCaller: meter_details(type, mpan_mprn, serial_number, gsp = NA)
    end
  end
Loading

Class diagram for updated meter and consumption helpers

classDiagram
  class get_consumption {
    get_consumption(meter_type, direction, mpan_mprn, serial_number)
  }

  class get_meter_details {
    get_meter_details(meter_type, direction, include_gsp)
  }

  class get_meter_gsp {
    get_meter_gsp(mpan)
  }

  class combine_consumption {
    combine_consumption(consumption_import, consumption_export, ...)
  }

  get_consumption --> get_meter_details : obtains_meter_details
  get_meter_details --> get_meter_gsp : optional_gsp_lookup
  combine_consumption ..> get_consumption : postprocesses_results

  class MeterDetails {
    type
    mpan_mprn
    serial_number
    direction
    gsp
  }

  get_meter_details ..> MeterDetails : constructs
Loading

File-Level Changes

Change Details Files
Make GSP lookup optional in get_meter_details and disable it for get_consumption to avoid redundant API calls.
  • Extend get_meter_details signature with an include_gsp logical parameter defaulting to TRUE and document it in the roxygen block.
  • Refactor GSP calculation to initialize meter_gsp as NA_character_ and only call get_meter_gsp for electricity meters when include_gsp is TRUE.
  • Update get_consumption to request meter details with include_gsp = FALSE when it auto-fetches meter data, preserving existing behavior when meter details are supplied explicitly.
R/meter_details.R
R/get_consumption.R
Optimize combine_consumption NA-to-zero handling using in-place vectorized assignment instead of ifelse.
  • Replace ifelse-based NA replacement for import_consumption and export_consumption with direct assignment from the _import/_export columns followed by in-place NA replacement via logical indexing.
  • Keep the subsequent cleanup of the original consumption_import and consumption_export columns unchanged.
R/meter_details.R
Document the performance optimization as a Bolt note for future reference.
  • Add a new .jules/bolt.md entry describing the redundant GSP API call issue and the include_gsp solution.
.jules/bolt.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 7, 2026

Walkthrough

This pull request introduces an include_gsp parameter to get_meter_details() that allows conditional skipping of the Grid Supply Point network call. The get_consumption() function is updated to explicitly set include_gsp = FALSE when retrieving meter details, reducing unnecessary overhead.

Changes

Cohort / File(s) Summary
Documentation
.jules/bolt.md
Documents the new include_gsp parameter and notes that previous behaviour caused 50% increase in request overhead for consumption calls without provided meter details.
Consumption Logic
R/get_consumption.R
Updated get_meter_details() call to use named arguments and explicitly set include_gsp = FALSE when meter details are retrieved due to missing MPAN/MPRN or serial number.
Meter Details Implementation
R/meter_details.R
Added include_gsp parameter (default TRUE) with conditional GSP retrieval logic—GSP is only fetched when meter type is electricity and include_gsp = TRUE. Simplified NA handling in consume_consumption flow for import/export data.

Sequence Diagram

sequenceDiagram
    participant Client
    participant get_consumption
    participant get_meter_details
    participant get_meter_gsp

    Client->>get_consumption: get_consumption()
    
    alt meter_details provided
        get_consumption->>Client: return data
    else meter_details missing
        get_consumption->>get_meter_details: include_gsp = FALSE
        
        alt meter_type == electricity && include_gsp == TRUE
            get_meter_details->>get_meter_gsp: fetch GSP
            get_meter_gsp-->>get_meter_details: return GSP
        else skip GSP retrieval
            get_meter_details->>get_meter_details: set GSP = NA
        end
        
        get_meter_details-->>get_consumption: return meter details
        get_consumption->>Client: return data
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

🚥 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 clearly summarises the main changes: optimizations to get_consumption and combine_consumption functions with specific performance improvements.
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 unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bolt-performance-optimizations-5119408834053835043

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

@sourcery-ai sourcery-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.

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.jules/bolt.md:
- Line 1: Add a top-level H1 heading as the very first line of the
.jules/bolt.md note to satisfy markdownlint MD041; keep the existing body (the
2025-05-15 note about get_meter_details, get_meter_gsp, get_consumption and the
new include_gsp parameter) unchanged and simply prepend a single H1 line (e.g.,
a concise title referencing the date/subject) so the file begins with an H1
before the current content.

In `@R/meter_details.R`:
- Around line 330-334: Add a regression test that covers the asymmetric-interval
merge case where merge(..., all = TRUE) produces NA on one side so the
zero-filling logic for result$import_consumption and result$export_consumption
is exercised; create a new test in tests/testthat (e.g.
test-combine_consumption-asymmetric.R) that builds two series with non-aligned
intervals (one has an interval the other lacks), calls the combine function used
in meter_details.R (the code path touching
result$import_consumption/result$export_consumption), and asserts that NA gaps
are replaced with 0 rather than left as NA, matching the existing
populated-series expectations.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: a803809b-b844-46b5-ae16-015fb736934f

📥 Commits

Reviewing files that changed from the base of the PR and between 74f7003 and 20af0be.

📒 Files selected for processing (3)
  • .jules/bolt.md
  • R/get_consumption.R
  • R/meter_details.R

@@ -0,0 +1 @@
## 2025-05-15 - Redundant GSP API call in get_consumption **Learning:** The internal `get_meter_details()` function was automatically calling `get_meter_gsp()` which makes a network request to retrieve Grid Supply Point info. This info is not needed for `get_consumption()`, leading to a 50% increase in request overhead for every consumption call when meter details aren't provided. **Action:** Added an `include_gsp` parameter to `get_meter_details()` to allow skipping this call when the data is not required.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add a top-level heading to satisfy markdownlint.

The file currently starts with body content, which triggers MD041. A single H1 at the top fixes the warning and makes the note easier to scan.

📝 Proposed fix
-## 2025-05-15 - Redundant GSP API call in get_consumption **Learning:** The internal `get_meter_details()` function was automatically calling `get_meter_gsp()` which makes a network request to retrieve Grid Supply Point info. This info is not needed for `get_consumption()`, leading to a 50% increase in request overhead for every consumption call when meter details aren't provided. **Action:** Added an `include_gsp` parameter to `get_meter_details()` to allow skipping this call when the data is not required.
+# Bolt learnings
+
+## 2025-05-15 - Redundant GSP API call in `get_consumption`
+
+**Learning:** The internal `get_meter_details()` function was automatically calling `get_meter_gsp()`, which makes a network request to retrieve Grid Supply Point info. This info is not needed for `get_consumption()`, leading to a 50% increase in request overhead for every consumption call when meter details are not provided.
+
+**Action:** Added an `include_gsp` parameter to `get_meter_details()` to allow skipping this call when the data is not required.
📝 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
## 2025-05-15 - Redundant GSP API call in get_consumption **Learning:** The internal `get_meter_details()` function was automatically calling `get_meter_gsp()` which makes a network request to retrieve Grid Supply Point info. This info is not needed for `get_consumption()`, leading to a 50% increase in request overhead for every consumption call when meter details aren't provided. **Action:** Added an `include_gsp` parameter to `get_meter_details()` to allow skipping this call when the data is not required.
# Bolt learnings
## 2025-05-15 - Redundant GSP API call in `get_consumption`
**Learning:** The internal `get_meter_details()` function was automatically calling `get_meter_gsp()`, which makes a network request to retrieve Grid Supply Point info. This info is not needed for `get_consumption()`, leading to a 50% increase in request overhead for every consumption call when meter details are not provided.
**Action:** Added an `include_gsp` parameter to `get_meter_details()` to allow skipping this call when the data is not required.
🧰 Tools
🪛 markdownlint-cli2 (0.21.0)

[warning] 1-1: First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)

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

In @.jules/bolt.md at line 1, Add a top-level H1 heading as the very first line
of the .jules/bolt.md note to satisfy markdownlint MD041; keep the existing body
(the 2025-05-15 note about get_meter_details, get_meter_gsp, get_consumption and
the new include_gsp parameter) unchanged and simply prepend a single H1 line
(e.g., a concise title referencing the date/subject) so the file begins with an
H1 before the current content.

Comment on lines +330 to +334
result$import_consumption <- result$consumption_import
result$import_consumption[is.na(result$import_consumption)] <- 0

result$export_consumption <- result$consumption_export
result$export_consumption[is.na(result$export_consumption)] <- 0
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Add a regression test for zero-filled merge gaps.

This path only sees NAs when merge(..., all = TRUE) produces intervals present on one side but not the other, and the existing tests/testthat/test-combine_consumption.R:22-75 cases only cover fully populated series. Please add an asymmetric-interval test so this optimisation keeps the intended behaviour pinned down.

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

In `@R/meter_details.R` around lines 330 - 334, Add a regression test that covers
the asymmetric-interval merge case where merge(..., all = TRUE) produces NA on
one side so the zero-filling logic for result$import_consumption and
result$export_consumption is exercised; create a new test in tests/testthat
(e.g. test-combine_consumption-asymmetric.R) that builds two series with
non-aligned intervals (one has an interval the other lacks), calls the combine
function used in meter_details.R (the code path touching
result$import_consumption/result$export_consumption), and asserts that NA gaps
are replaced with 0 rather than left as NA, matching the existing
populated-series expectations.

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