⚡️ Speed up method BaseArangoService.check_record_access_with_details by 3%
#640
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 3% (0.03x) speedup for
BaseArangoService.check_record_access_with_detailsinbackend/python/app/connectors/services/base_arango_service.py⏱️ Runtime :
13.0 milliseconds→12.6 milliseconds(best of30runs)📝 Explanation and details
The optimized code achieves 11.1% throughput improvement through several key database query and async execution optimizations:
1. Database Query Optimization in
get_document()FOR doc IN @@collection FILTER doc._key == @document_key RETURN docfollowed bylist(cursor)conversionDOCUMENT(@@collection, @document_key)function which directly retrieves documents by key without iteration2. AQL Query String Construction
{CollectionNames.PERMISSIONS.value}inline@permissions,@permission) reducing string processing overhead during query construction3. Async Task Scheduling Improvements
get_user_by_user_id(), then conditionallyget_document()for additional datauser_task,additional_data_task) and awaits them more efficiently, allowing better concurrent execution4. Data Structure Construction
.append()callsrecord_typeonce and reuses it, reducing repeated dictionary lookups5. Minor Object Access Optimizations
The line profiler shows the main performance gains come from the AQL execution time (21% vs 20.9% of total time) and the reduced overhead in async coordination. The
get_document()optimization particularly benefits the multiple document fetches required for records, files, and mail data. These improvements are especially valuable for workloads with frequent record access operations, as they reduce both database query complexity and Python-level processing overhead.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
import asyncio # used to run async functions
from unittest.mock import AsyncMock, MagicMock
import pytest # used for our unit tests
from app.connectors.services.base_arango_service import BaseArangoService
--- Copy of the function under test (do not modify) ---
(see above for full function definition, assumed imported here)
For testing, we need to create a mock BaseArangoService instance with a mock db and logger.
We'll also mock get_document and get_user_by_user_id as needed for async tests.
class DummyLogger:
def error(self, msg, *args, **kwargs):
pass # No-op for error logging in tests
class DummyConfigService:
pass
class DummyKafkaService:
pass
class DummyArangoClient:
pass
Helper to create a mock db.aql.execute that returns a cursor (iterable)
def make_cursor(results):
"""Return an iterator that yields results from a list."""
return iter(results)
Helper to build a minimal BaseArangoService instance for testing
def build_service(
access_result=None,
record=None,
user=None,
additional_data=None,
metadata_result=None,
raise_in_access=False,
raise_in_get_document=False,
raise_in_get_user=False,
):
service = BaseArangoService(
logger=DummyLogger(),
arango_client=DummyArangoClient(),
config_service=DummyConfigService(),
kafka_service=DummyKafkaService(),
)
---- BASIC TEST CASES ----
@pytest.mark.asyncio
async def test_check_record_access_with_details_edge_exception_in_access_query():
"""
Edge case: Exception occurs during access query.
Should raise and log error.
"""
service = build_service(raise_in_access=True)
with pytest.raises(Exception) as excinfo:
await service.check_record_access_with_details("u11", "org11", "r11")
@pytest.mark.asyncio
async def test_check_record_access_with_details_edge_exception_in_get_document():
"""
Edge case: Exception occurs during get_document.
Should raise and log error.
"""
access_result = [
{"type": "DIRECT", "source": {"userId": "u12"}, "role": "OWNER"}
]
service = build_service(access_result, raise_in_get_document=True)
with pytest.raises(Exception) as excinfo:
await service.check_record_access_with_details("u12", "org12", "r12")
@pytest.mark.asyncio
async def test_check_record_access_with_details_edge_exception_in_get_user():
"""
Edge case: Exception occurs during get_user_by_user_id.
Should raise and log error.
"""
access_result = [
{"type": "DIRECT", "source": {"userId": "u13"}, "role": "OWNER"}
]
record = {
"_key": "r13",
"recordName": "Test File",
"recordType": "FILE"
}
service = build_service(access_result, record, raise_in_get_user=True)
with pytest.raises(Exception) as excinfo:
await service.check_record_access_with_details("u13", "org13", "r13")
---- LARGE SCALE TEST CASES ----
@pytest.mark.asyncio
To edit these changes
git checkout codeflash/optimize-BaseArangoService.check_record_access_with_details-mhxi3j3band push.