⚡️ Speed up function get_validator_usage_attributes
by 23%
#55
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.
📄 23% (0.23x) speedup for
get_validator_usage_attributes
inguardrails/hub_telemetry/hub_tracing.py
⏱️ Runtime :
1.91 milliseconds
→1.55 milliseconds
(best of79
runs)📝 Explanation and details
The optimization adds a specialized fast path for tuple indexing in the
safe_get
function. Instead of always falling back to the expensivesafe_get_with_brackets
function for non-dict containers, the optimized version directly handles tuples with a simpletry/except
block.Key changes:
elif isinstance(container, tuple):
check with directcontainer[key]
accesssafe_get_with_brackets
, which includes debug logging and additional exception handling logicWhy it's faster:
The line profiler shows that
safe_get
was spending 80.7% of its time insafe_get_with_brackets
calls. Sinceargs
is a tuple in the main use case (safe_get(args, 1)
), the optimization eliminates this expensive function call and replaces it with direct tuple indexing, reducing total time from 3.95ms to 2.72ms (31% faster insafe_get
alone).Test case performance:
args
tuples, where the original code unnecessarily called the expensive fallback functionThe optimization is particularly effective for the common telemetry pattern of accessing validator objects from argument tuples.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
test_pytest_testsunit_teststest_guard_log_py_testsintegration_teststest_guard_py_testsunit_testsvalidator__replay_test_0.py::test_guardrails_hub_telemetry_hub_tracing_get_validator_usage_attributes
To edit these changes
git checkout codeflash/optimize-get_validator_usage_attributes-mh1p5ojy
and push.