Skip to content

Commit 17e1b35

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 17e1b35

1 file changed

Lines changed: 60 additions & 7 deletions

File tree

statemachine/signature.py

Lines changed: 60 additions & 7 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
@@ -95,8 +142,7 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
95142
elif param.name in kwargs:
96143
if param.kind == Parameter.POSITIONAL_ONLY:
97144
msg = (
98-
"{arg!r} parameter is positional only, "
99-
"but was passed as a keyword"
145+
"{arg!r} parameter is positional only, but was passed as a keyword"
100146
)
101147
msg = msg.format(arg=param.name)
102148
raise TypeError(msg) from None
@@ -141,12 +187,14 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
141187
values = [arg_val]
142188
values.extend(arg_vals)
143189
arguments[param.name] = tuple(values)
190+
param_names_used.append(param.name)
144191
break
145192

146193
if param.name in kwargs and param.kind != Parameter.POSITIONAL_ONLY:
147194
arguments[param.name] = kwargs.pop(param.name)
148195
else:
149196
arguments[param.name] = arg_val
197+
param_names_used.append(param.name)
150198

151199
# Now, we iterate through the remaining parameters to process
152200
# keyword arguments
@@ -172,14 +220,19 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
172220
# arguments.
173221
pass
174222
else:
175-
arguments[param_name] = arg_val #
223+
arguments[param_name] = arg_val
224+
param_names_used.append(param_name)
176225

177226
if kwargs:
178227
if kwargs_param is not None:
179228
# Process our '**kwargs'-like parameter
180-
arguments[kwargs_param.name] = kwargs # type: ignore [assignment]
229+
arguments[kwargs_param.name] = kwargs # type: ignore[assignment]
230+
kwargs_param_name = kwargs_param.name
181231
else:
182232
# 'ignoring we got an unexpected keyword argument'
183233
pass
184234

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

0 commit comments

Comments
 (0)