Skip to content

Commit 66bc139

Browse files
author
rodrigo.nogueira
committed
## Description
The `signature_adapter` causes significant overhead in hot transition paths due to repeated signature binding on every callback invocation. This PR implements caching for `bind_expected()` to avoid recomputing argument bindings when the kwargs pattern is unchanged. ## Root Cause The `SignatureAdapter.bind_expected()` method iterates through all parameters and matches them against the provided kwargs on every invocation. In typical state machine usage, callbacks are invoked repeatedly with the same kwargs keys (e.g., `source`, `target`, `event`), making this repeated computation wasteful. ## Fix Added a per-instance cache (`_bind_cache`) to `SignatureAdapter` that stores "binding templates" based on the arguments structure: - **Cache key**: `(len(args), frozenset(kwargs.keys()))` - **Cache value**: A template of which parameters to extract - **Fast path**: On cache hit, extract arguments directly using the template (~1 µs) - **Slow path**: First call computes full binding and stores template (~2 µs) This approach preserves **full Dependency Injection functionality** - callbacks still receive correctly filtered arguments (`source`, `target`, etc.). ## Performance When measuring `bind_expected()` in isolation: - **Cached**: 0.86 µs/call - **Uncached**: 2.12 µs/call - **Improvement**: ~59% This is consistent with the ~30% end-to-end improvement reported in #548, as binding is one of several components in a full transition. ## Testing All existing tests pass (328 passed, 9 xfailed). Fixes #548
1 parent 9a089ed commit 66bc139

1 file changed

Lines changed: 61 additions & 5 deletions

File tree

statemachine/signature.py

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import annotations
2+
13
from functools import partial
24
from inspect import BoundArguments
35
from inspect import Parameter
@@ -6,6 +8,12 @@
68
from itertools import chain
79
from types import MethodType
810
from typing import Any
11+
from typing import FrozenSet
12+
from typing import Optional
13+
from typing import Tuple
14+
15+
BindCacheKey = Tuple[int, FrozenSet[str]]
16+
BindTemplate = Tuple[Tuple[str, ...], Optional[str]] # noqa: UP007
917

1018

1119
def _make_key(method):
@@ -44,6 +52,11 @@ def cached_function(cls, method):
4452

4553
class SignatureAdapter(Signature):
4654
is_coroutine: bool = False
55+
_bind_cache: dict[BindCacheKey, BindTemplate]
56+
57+
def __init__(self, *args, **kwargs):
58+
super().__init__(*args, **kwargs)
59+
self._bind_cache = {}
4760

4861
@classmethod
4962
@signature_cache
@@ -60,19 +73,53 @@ def from_callable(cls, method):
6073
adapter.is_coroutine = iscoroutinefunction(method)
6174
return adapter
6275

63-
def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C901
76+
def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments:
77+
cache_key: BindCacheKey = (len(args), frozenset(kwargs.keys()))
78+
template = self._bind_cache.get(cache_key)
79+
80+
if template is not None:
81+
return self._fast_bind(args, kwargs, template)
82+
83+
result = self._full_bind(cache_key, *args, **kwargs)
84+
return result
85+
86+
def _fast_bind(
87+
self,
88+
args: tuple[Any, ...],
89+
kwargs: dict[str, Any],
90+
template: BindTemplate,
91+
) -> BoundArguments:
92+
param_names, kwargs_param_name = template
93+
arguments: dict[str, Any] = {}
94+
for i, name in enumerate(param_names):
95+
if i < len(args):
96+
arguments[name] = args[i]
97+
elif name in kwargs:
98+
arguments[name] = kwargs[name]
99+
if kwargs_param_name is not None:
100+
arguments[kwargs_param_name] = kwargs
101+
return BoundArguments(self, arguments) # type: ignore[arg-type]
102+
103+
def _full_bind( # noqa: C901
104+
self,
105+
cache_key: BindCacheKey,
106+
*args: Any,
107+
**kwargs: Any,
108+
) -> BoundArguments:
64109
"""Get a BoundArguments object, that maps the passed `args`
65110
and `kwargs` to the function's signature. It avoids to raise `TypeError`
66111
trying to fill all the required arguments and ignoring the unknown ones.
67112
68113
Adapted from the internal `inspect.Signature._bind`.
69114
"""
70-
arguments = {}
115+
arguments: dict[str, Any] = {}
116+
param_names_used: list[str] = []
71117

72118
parameters = iter(self.parameters.values())
73119
arg_vals = iter(args)
74120
parameters_ex: Any = ()
75121
kwargs_param = None
122+
kwargs_param_name: str | None = None
76123

77124
while True:
78125
# Let's iterate through the positional arguments and corresponding
@@ -141,12 +188,14 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
141188
values = [arg_val]
142189
values.extend(arg_vals)
143190
arguments[param.name] = tuple(values)
191+
param_names_used.append(param.name)
144192
break
145193

146194
if param.name in kwargs and param.kind != Parameter.POSITIONAL_ONLY:
147195
arguments[param.name] = kwargs.pop(param.name)
148196
else:
149197
arguments[param.name] = arg_val
198+
param_names_used.append(param.name)
150199

151200
# Now, we iterate through the remaining parameters to process
152201
# keyword arguments
@@ -172,14 +221,21 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
172221
# arguments.
173222
pass
174223
else:
175-
arguments[param_name] = arg_val #
224+
arguments[param_name] = arg_val
225+
param_names_used.append(param_name)
176226

177227
if kwargs:
178228
if kwargs_param is not None:
179229
# Process our '**kwargs'-like parameter
180-
arguments[kwargs_param.name] = kwargs # type: ignore [assignment]
230+
arguments[kwargs_param.name] = kwargs # type: ignore[assignment]
231+
kwargs_param_name = kwargs_param.name
181232
else:
182233
# 'ignoring we got an unexpected keyword argument'
183234
pass
184235

185-
return BoundArguments(self, arguments) # type: ignore [arg-type]
236+
template: BindTemplate = (tuple(param_names_used), kwargs_param_name)
237+
self._bind_cache[cache_key] = template
238+
239+
return BoundArguments(self, arguments) # type: ignore[arg-type]
240+
241+

0 commit comments

Comments
 (0)