Skip to content

Commit 277271d

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 277271d

1 file changed

Lines changed: 63 additions & 7 deletions

File tree

statemachine/signature.py

Lines changed: 63 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,56 @@ 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+
95+
for i, name in enumerate(param_names):
96+
if i < len(args):
97+
arguments[name] = args[i]
98+
else:
99+
arguments[name] = kwargs.get(name)
100+
101+
if kwargs_param_name is not None:
102+
arguments[kwargs_param_name] = kwargs
103+
104+
return BoundArguments(self, arguments) # type: ignore[arg-type]
105+
106+
def _full_bind( # noqa: C901
107+
self,
108+
cache_key: BindCacheKey,
109+
*args: Any,
110+
**kwargs: Any,
111+
) -> BoundArguments:
64112
"""Get a BoundArguments object, that maps the passed `args`
65113
and `kwargs` to the function's signature. It avoids to raise `TypeError`
66114
trying to fill all the required arguments and ignoring the unknown ones.
67115
68116
Adapted from the internal `inspect.Signature._bind`.
69117
"""
70-
arguments = {}
118+
arguments: dict[str, Any] = {}
119+
param_names_used: list[str] = []
71120

72121
parameters = iter(self.parameters.values())
73122
arg_vals = iter(args)
74123
parameters_ex: Any = ()
75124
kwargs_param = None
125+
kwargs_param_name: str | None = None
76126

77127
while True:
78128
# Let's iterate through the positional arguments and corresponding
@@ -95,8 +145,7 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
95145
elif param.name in kwargs:
96146
if param.kind == Parameter.POSITIONAL_ONLY:
97147
msg = (
98-
"{arg!r} parameter is positional only, "
99-
"but was passed as a keyword"
148+
"{arg!r} parameter is positional only, but was passed as a keyword"
100149
)
101150
msg = msg.format(arg=param.name)
102151
raise TypeError(msg) from None
@@ -141,12 +190,14 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
141190
values = [arg_val]
142191
values.extend(arg_vals)
143192
arguments[param.name] = tuple(values)
193+
param_names_used.append(param.name)
144194
break
145195

146196
if param.name in kwargs and param.kind != Parameter.POSITIONAL_ONLY:
147197
arguments[param.name] = kwargs.pop(param.name)
148198
else:
149199
arguments[param.name] = arg_val
200+
param_names_used.append(param.name)
150201

151202
# Now, we iterate through the remaining parameters to process
152203
# keyword arguments
@@ -172,14 +223,19 @@ def bind_expected(self, *args: Any, **kwargs: Any) -> BoundArguments: # noqa: C
172223
# arguments.
173224
pass
174225
else:
175-
arguments[param_name] = arg_val #
226+
arguments[param_name] = arg_val
227+
param_names_used.append(param_name)
176228

177229
if kwargs:
178230
if kwargs_param is not None:
179231
# Process our '**kwargs'-like parameter
180-
arguments[kwargs_param.name] = kwargs # type: ignore [assignment]
232+
arguments[kwargs_param.name] = kwargs # type: ignore[assignment]
233+
kwargs_param_name = kwargs_param.name
181234
else:
182235
# 'ignoring we got an unexpected keyword argument'
183236
pass
184237

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

0 commit comments

Comments
 (0)