Skip to content

Fix stale bindings from DynamicKeyBindings when ids are reused - #2166

Open
hailsaturn wants to merge 3 commits into
prompt-toolkit:mainfrom
hailsaturn:fix-dynamic-keybindings-version
Open

hailsaturn wants to merge 3 commits into
prompt-toolkit:mainfrom
hailsaturn:fix-dynamic-keybindings-version

Conversation

@hailsaturn

Copy link
Copy Markdown

Summary

Fix cache invalidation for DynamicKeyBindings when its callback returns a different KeyBindings object with the same id() and _version as a previously returned object.

Fixes #2165

DynamicKeyBindings now tracks a counter that increments whenever the callback returns a different object (checked with is), and reports (counter, key_bindings._version) instead of using id(). See #2165 for more detail.

An unused variable _last_child_version was also removed from the DynamicKeyBindings constructor. Also, _bindings2 is initialised so the first call has something to compare against.

Testing

Since the issue depends on the allocator, a regression test in tests/test_key_binding.py patches id to always return 0. This forces the id() collision behaviour and verifies that successive dynamic bindings are not served from a stale cache.

The added regression test fails on main and passes with this change.

The existing full suite, ruff check, ruff format --check and mypy --strict all pass.

Previously DynamicKeyBindings used (id(kb), kb._version) for its version. Since id(kb) can be reused if kb is freed, it is possible for different objects with the same number of bindings to produce an identical version and _MergedKeyBindings was serving the stale bindings. The fix instead tracks a counter that increases whenever the callback returns a different object.
@hailsaturn hailsaturn changed the title Fix dynamic keybindings version Fix stale bindings from DynamicKeyBindings when ids are reused Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DynamicKeyBindings._version can collide for distinct KeyBindings instances, causing stale bindings

1 participant