Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Dec 19, 2025

📄 8% (0.08x) speedup for OneNoteDataSource.me_onenote_notebooks_sections_delete_pages_content in backend/python/app/sources/external/microsoft/one_note/one_note.py

⏱️ Runtime : 365 microseconds 340 microseconds (best of 5 runs)

📝 Explanation and details

The optimization achieves a 7% runtime improvement by reducing unnecessary object instantiation and attribute assignments through more efficient parameter handling.

Key optimizations:

  1. Conditional object creation: Instead of always creating a RequestConfiguration object for query parameters (line showing 157μs in original), the optimized version uses a dictionary to collect parameters first and only instantiates RequestConfiguration when parameters are actually present. This eliminates object creation overhead in the common case where no query parameters are specified.

  2. Batch parameter assignment: Rather than setting each parameter individually on the RequestConfiguration object through multiple attribute assignments, parameters are collected in a dictionary and then applied using setattr() in a loop. This reduces the number of individual attribute access operations.

  3. Defensive copying: Added headers.copy() to prevent mutation of input parameters while maintaining the same functional behavior.

Performance impact: The line profiler shows the original version spent 13.1% of total time (157μs) just instantiating the query parameters RequestConfiguration object on every call. The optimized version reduces this overhead by only creating the object when needed and using more efficient batch assignment.

Test case benefits: The optimization is particularly effective for test cases with minimal or no query parameters (like the basic delete operations), where the unnecessary object instantiation is completely avoided. For parameter-heavy operations, the batch assignment approach still provides modest improvements.

The throughput remains constant at 560 operations/second, indicating the optimization doesn't change the fundamental async operation characteristics but reduces per-call overhead, making it beneficial for high-frequency OneNote API operations.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 129 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 92.9%
🌀 Generated Regression Tests and Runtime
import asyncio  # used to run async functions

# Dummy logger
from typing import Optional

import pytest  # used for our unit tests
from app.sources.external.microsoft.one_note.one_note import OneNoteDataSource

# --- Minimal stubs for dependencies (so tests run without real MS Graph) ---


class OneNoteResponse:
    def __init__(self, success: bool, data=None, error: Optional[str] = None):
        self.success = success
        self.data = data
        self.error = error


class DummyDeleteEndpoint:
    """Simulates the .delete() async method of the endpoint."""

    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self._response = response
        self._should_raise = should_raise
        self._raise_exc = raise_exc

    async def delete(self, request_configuration=None):
        if self._should_raise:
            raise self._raise_exc or Exception("Simulated API error")
        return self._response


class DummyPages:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self._response = response
        self._should_raise = should_raise
        self._raise_exc = raise_exc

    def by_onenote_page_id(self, onenotePage_id):
        return DummyDeleteEndpoint(self._response, self._should_raise, self._raise_exc)


class DummySections:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self._response = response
        self._should_raise = should_raise
        self._raise_exc = raise_exc

    def by_onenote_section_id(self, onenoteSection_id):
        return DummyPages(self._response, self._should_raise, self._raise_exc)


class DummyNotebooks:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self._response = response
        self._should_raise = should_raise
        self._raise_exc = raise_exc

    def by_notebook_id(self, notebook_id):
        return DummySections(self._response, self._should_raise, self._raise_exc)


class DummyMe:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self.onenote = DummyOnenote(response, should_raise, raise_exc)


class DummyOnenote:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self.notebooks = DummyNotebooks(response, should_raise, raise_exc)


class DummyGraphServiceClient:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self.me = DummyMe(response, should_raise, raise_exc)


class DummyMSGraphClient:
    def __init__(self, response=None, should_raise=False, raise_exc=None):
        self._response = response
        self._should_raise = should_raise
        self._raise_exc = raise_exc

    def get_client(self):
        return self

    def get_ms_graph_service_client(self):
        return DummyGraphServiceClient(
            self._response, self._should_raise, self._raise_exc
        )


# --- TESTS ---

# BASIC TEST CASES


@pytest.mark.asyncio
async def test_delete_pages_content_success_with_all_args():
    """Test successful delete with all optional arguments provided."""
    dummy_response = object()
    client = DummyMSGraphClient(response=dummy_response)
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="notebookA",
        onenoteSection_id="sectionA",
        onenotePage_id="pageA",
        If_Match="etag123",
        select=["id", "title"],
        expand=["parentNotebook"],
        filter="title eq 'Test'",
        orderby="title",
        search="keyword",
        top=5,
        skip=2,
        headers={"Custom-Header": "value"},
    )


@pytest.mark.asyncio
async def test_delete_pages_content_returns_error_object():
    """Test when the API returns an object with an 'error' attribute."""

    class ErrorObj:
        def __init__(self):
            self.error = "Simulated error"

    error_obj = ErrorObj()
    client = DummyMSGraphClient(response=error_obj)
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="n", onenoteSection_id="s", onenotePage_id="p"
    )


@pytest.mark.asyncio
async def test_delete_pages_content_returns_error_dict_str():
    """Test when the API returns a dict with an 'error' key that is a string."""
    error_dict = {"error": "Some error string"}
    client = DummyMSGraphClient(response=error_dict)
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="n", onenoteSection_id="s", onenotePage_id="p"
    )


@pytest.mark.asyncio
async def test_delete_pages_content_returns_error_code_message():
    """Test when the API returns an object with code and message attributes."""

    class ErrorObj:
        def __init__(self):
            self.code = "500"
            self.message = "Internal Server Error"

    error_obj = ErrorObj()
    client = DummyMSGraphClient(response=error_obj)
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="n", onenoteSection_id="s", onenotePage_id="p"
    )


# EDGE TEST CASES


@pytest.mark.asyncio
async def test_delete_pages_content_none_response():
    """Test when the API returns None."""
    client = DummyMSGraphClient(response=None)
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="n", onenoteSection_id="s", onenotePage_id="p"
    )


@pytest.mark.asyncio
async def test_delete_pages_content_api_raises_exception():
    """Test when the API raises an exception (simulate network or server error)."""
    client = DummyMSGraphClient(
        should_raise=True, raise_exc=RuntimeError("API failure!")
    )
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="n", onenoteSection_id="s", onenotePage_id="p"
    )


@pytest.mark.asyncio
async def test_delete_pages_content_invalid_client():
    """Test that constructor raises ValueError if client lacks 'me'."""

    class BadClient:
        def get_client(self):
            return self

        def get_ms_graph_service_client(self):
            return object()  # no 'me'

    with pytest.raises(ValueError):
        OneNoteDataSource(BadClient())


@pytest.mark.asyncio
async def test_delete_pages_content_concurrent_execution():
    """Test concurrent execution of multiple delete operations."""
    dummy_response1 = object()
    dummy_response2 = object()
    client1 = DummyMSGraphClient(response=dummy_response1)
    client2 = DummyMSGraphClient(response=dummy_response2)
    ds1 = OneNoteDataSource(client1)
    ds2 = OneNoteDataSource(client2)
    # Run two deletes concurrently
    results = await asyncio.gather(
        ds1.me_onenote_notebooks_sections_delete_pages_content(
            notebook_id="n1", onenoteSection_id="s1", onenotePage_id="p1"
        ),
        ds2.me_onenote_notebooks_sections_delete_pages_content(
            notebook_id="n2", onenoteSection_id="s2", onenotePage_id="p2"
        ),
    )


@pytest.mark.asyncio
async def test_delete_pages_content_with_kwargs():
    """Test passing additional kwargs does not break the function."""
    dummy_response = object()
    client = DummyMSGraphClient(response=dummy_response)
    ds = OneNoteDataSource(client)
    res = await ds.me_onenote_notebooks_sections_delete_pages_content(
        notebook_id="notebookX",
        onenoteSection_id="sectionX",
        onenotePage_id="pageX",
        custom_param="foo",
    )


# LARGE SCALE TEST CASES


@pytest.mark.asyncio
async def test_delete_pages_content_many_concurrent():
    """Test many concurrent delete operations for scalability."""
    dummy_response = object()
    client = DummyMSGraphClient(response=dummy_response)
    ds = OneNoteDataSource(client)
    # Launch 20 concurrent deletes
    tasks = [
        ds.me_onenote_notebooks_sections_delete_pages_content(
            notebook_id=f"nb{i}", onenoteSection_id=f"sec{i}", onenotePage_id=f"pg{i}"
        )
        for i in range(20)
    ]
    results = await asyncio.gather(*tasks)


@pytest.mark.asyncio
async def test_OneNoteDataSource_me_onenote_notebooks_sections_delete_pages_content_throughput_high_volume():
    """Throughput: Test function under sustained high-volume concurrent load."""
    dummy_response = object()
    client = DummyMSGraphClient(response=dummy_response)
    ds = OneNoteDataSource(client)
    # Simulate 50 concurrent deletes (bounded to avoid resource exhaustion)
    tasks = [
        ds.me_onenote_notebooks_sections_delete_pages_content(
            notebook_id=f"nb{i}", onenoteSection_id=f"sec{i}", onenotePage_id=f"pg{i}"
        )
        for i in range(50)
    ]
    results = await asyncio.gather(*tasks)


# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

To edit these changes git checkout codeflash/optimize-OneNoteDataSource.me_onenote_notebooks_sections_delete_pages_content-mjckhz3e and push.

Codeflash Static Badge

…_content

The optimization achieves a **7% runtime improvement** by reducing unnecessary object instantiation and attribute assignments through more efficient parameter handling.

**Key optimizations:**

1. **Conditional object creation**: Instead of always creating a `RequestConfiguration` object for query parameters (line showing 157μs in original), the optimized version uses a dictionary to collect parameters first and only instantiates `RequestConfiguration` when parameters are actually present. This eliminates object creation overhead in the common case where no query parameters are specified.

2. **Batch parameter assignment**: Rather than setting each parameter individually on the `RequestConfiguration` object through multiple attribute assignments, parameters are collected in a dictionary and then applied using `setattr()` in a loop. This reduces the number of individual attribute access operations.

3. **Defensive copying**: Added `headers.copy()` to prevent mutation of input parameters while maintaining the same functional behavior.

**Performance impact**: The line profiler shows the original version spent 13.1% of total time (157μs) just instantiating the query parameters `RequestConfiguration` object on every call. The optimized version reduces this overhead by only creating the object when needed and using more efficient batch assignment.

**Test case benefits**: The optimization is particularly effective for test cases with minimal or no query parameters (like the basic delete operations), where the unnecessary object instantiation is completely avoided. For parameter-heavy operations, the batch assignment approach still provides modest improvements.

The throughput remains constant at 560 operations/second, indicating the optimization doesn't change the fundamental async operation characteristics but reduces per-call overhead, making it beneficial for high-frequency OneNote API operations.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 December 19, 2025 07:48
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: Medium Optimization Quality according to Codeflash labels Dec 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: Medium Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant