Skip to content

Commit 06fbe8b

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 06fbe8b

1 file changed

Lines changed: 56 additions & 5 deletions

File tree

statemachine/signature.py

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
from types import MethodType
88
from typing import Any
99

10+
BindCacheKey = tuple[int, frozenset[str]]
11+
BindTemplate = tuple[tuple[str, ...], str | None]
12+
1013

1114
def _make_key(method):
1215
method = method.func if isinstance(method, partial) else method
@@ -44,6 +47,11 @@ def cached_function(cls, method):
4447

4548
class SignatureAdapter(Signature):
4649
is_coroutine: bool = False
50+
_bind_cache: dict[BindCacheKey, BindTemplate]
51+
52+
def __init__(self, *args, **kwargs):
53+
super().__init__(*args, **kwargs)
54+
self._bind_cache = {}
4755

4856
@classmethod
4957
@signature_cache
@@ -60,19 +68,53 @@ def from_callable(cls, method):
6068
adapter.is_coroutine = iscoroutinefunction(method)
6169
return adapter
6270

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

72113
parameters = iter(self.parameters.values())
73114
arg_vals = iter(args)
74115
parameters_ex: Any = ()
75116
kwargs_param = None
117+
kwargs_param_name: str | None = None
76118

77119
while True:
78120
# Let's iterate through the positional arguments and corresponding
@@ -141,12 +183,14 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
141183
values = [arg_val]
142184
values.extend(arg_vals)
143185
arguments[param.name] = tuple(values)
186+
param_names_used.append(param.name)
144187
break
145188

146189
if param.name in kwargs and param.kind != Parameter.POSITIONAL_ONLY:
147190
arguments[param.name] = kwargs.pop(param.name)
148191
else:
149192
arguments[param.name] = arg_val
193+
param_names_used.append(param.name)
150194

151195
# Now, we iterate through the remaining parameters to process
152196
# keyword arguments
@@ -172,14 +216,21 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
172216
# arguments.
173217
pass
174218
else:
175-
arguments[param_name] = arg_val #
219+
arguments[param_name] = arg_val
220+
param_names_used.append(param_name)
176221

177222
if kwargs:
178223
if kwargs_param is not None:
179224
# Process our '**kwargs'-like parameter
180-
arguments[kwargs_param.name] = kwargs # type: ignore [assignment]
225+
arguments[kwargs_param.name] = kwargs # type: ignore[assignment]
226+
kwargs_param_name = kwargs_param.name
181227
else:
182228
# 'ignoring we got an unexpected keyword argument'
183229
pass
184230

185-
return BoundArguments(self, arguments) # type: ignore [arg-type]
231+
template: BindTemplate = (tuple(param_names_used), kwargs_param_name)
232+
self._bind_cache[cache_key] = template
233+
234+
return BoundArguments(self, arguments) # type: ignore[arg-type]
235+
236+

0 commit comments

Comments
 (0)