add cache to optimize type checking #2737
Open
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.
What does this PR do?
Context
Jira ticket
The
validate_and_convert_types
function was causing severe performance degradation whencheck_return_type=True
, resulting in 5.0x slowdown for API calls.Root Cause: Exponential validation overhead due to deeply nested API responses. A single dashboard response triggered 108,516+ validation calls with recursive validation of the same nested structures repeatedly.
Failed Optimization Attempts
Early Exit Strategies: Primitive type checks, inheritance checks, and exact type matching were ineffective because inputs were raw JSON data requiring conversion to typed models, not already-typed instances.
The core issue was that we couldn't avoid the validation work through early exits, but we could avoid repeating identical validation work through caching.
Changes
ApiClient-Level Validation Cache
Cache Infrastructure: Added
_validation_cache
toApiClient.__init__()
with configurable size limit (default: 1000 entries)Cache Integration: Modified
ApiClient.deserialize()
to pass cache tovalidate_and_convert_types()
Validation Function Updates: Added
request_cache
parameter throughout validation call chain with_make_hashable()
helper for unhashable typesGentle FIFO Memory Management: When cache is full, evict 25% of entries while keeping 75% most recent
Design Decisions:
Tests
Performance Test Setup
Using the exact reproduction case from the original issue:
Performance Results:
Additional Notes
Review checklist
Please check relevant items below:
This PR includes all newly recorded cassettes for any modified tests.
This PR does not rely on API client schema changes.
Or, this PR relies on API schema changes and this is a Draft PR to include tests for that new functionality.