mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(cache): invalidate configured registry instances on replacement (#4363)
## Description
CacheOptimizerRegistry caches explicit configurations under
registration-plus-config-ID keys, but register(override=True) and
unregister only removed the unconfigured registration-name key. Reusing
a CacheConfig after replacing a plugin therefore returned the previous
optimizer implementation; unregister/re-register also resurrected an old
instance.
This fixes that lifecycle invariant: every cached configuration belongs
to the current registration. Existing references already held by callers
remain unchanged; subsequent registry lookups resolve the replacement.
Found through source inspection; no matching existing issue or fix found
in class-name issue/PR searches or the broader optimizer/override PR
search. Base e995eb9f1d.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
## Changes Made
- Use structured private cache keys containing the exact registration
name and optional config identity.
- Invalidate all configurations for that exact registration on
override/unregister without discarding unrelated registrations.
- Add lifecycle regression coverage for OSS/enterprise registrations,
override/re-register, default/two explicit configurations,
unrelated-cache preservation, and subsequent cache reuse.
## Testing
- [x] Regression and adjacent cache tests pass.
- [x] Changed-file Ruff lint and formatting pass.
- [x] Standalone reproduction with actual built-in optimizers passed.
- [ ] Full repository tests, native/provider qualification, and static
type checking completed.
### Test Output
The four new parameterized lifecycle cases fail against the original
implementation:
```text
python -m pytest tests/test_cache/test_registry.py -k replacing_registration -q -o addopts=''
4 failed, 14 deselected in 0.62s
```
After the fix:
```text
python -m pytest tests/test_cache/ -q -rs -o addopts=''
300 passed, 3 skipped in 2.50s
ruff check headroom/cache/registry.py tests/test_cache/test_registry.py
All checks passed!
ruff format --check headroom/cache/registry.py tests/test_cache/test_registry.py
2 files already formatted
git diff --check
exit 0
```
## Real Behavior Proof
- Environment: Linux, CPython 3.12.14; the actual public registry and
built-in Anthropic/OpenAI optimizer classes. No mocked optimizer,
provider connection, model, or credential.
- Exact command / steps: Ran the following standalone script outside
pytest with PYTHONPATH=. against the original and patched checkouts:
```python
from headroom.cache import AnthropicCacheOptimizer, CacheConfig, OpenAICacheOptimizer
from headroom.cache.registry import CacheOptimizerRegistry
name = "registry-lifecycle-repro"
config = CacheConfig()
try:
CacheOptimizerRegistry.register(name, AnthropicCacheOptimizer)
original = CacheOptimizerRegistry.get(name, config=config)
print("Original implementation:", original.provider, original.strategy.value)
CacheOptimizerRegistry.register(name, OpenAICacheOptimizer, override=True)
replacement = CacheOptimizerRegistry.get(name, config=config)
assert isinstance(replacement, OpenAICacheOptimizer), type(replacement).__name__
assert replacement is not original
print("After override:", replacement.provider, replacement.strategy.value)
CacheOptimizerRegistry.unregister(name)
assert replacement not in CacheOptimizerRegistry._instances.values()
CacheOptimizerRegistry.register(name, AnthropicCacheOptimizer)
restored = CacheOptimizerRegistry.get(name, config=config)
assert isinstance(restored, AnthropicCacheOptimizer), type(restored).__name__
assert restored is not original
print("After unregister/re-register:", restored.provider, restored.strategy.value)
assert CacheOptimizerRegistry.get(name, config=config) is restored
print("Repeated lookups still reuse the current implementation: PASS")
finally:
CacheOptimizerRegistry.unregister(name)
```
- Observed result: On the original implementation, the override
assertion raises AssertionError: AnthropicCacheOptimizer. On the patch,
both replacement paths select the correct actual optimizer strategy and
repeated lookups reuse the new instance:
```text
Original implementation: anthropic explicit_breakpoints
After override: openai prefix_stabilization
After unregister/re-register: anthropic explicit_breakpoints
Repeated lookups still reuse the current implementation: PASS
```
- Not tested: Live provider requests, full repository test suite, native
Rust build, static type checking, concurrent register/get calls. Three
optional cache tests skipped because spaCy/sentence-transformers are not
installed. This does not add thread-safety guarantees.
## Runtime Rollout Safety
- Rollout-managed feature(s): None; registry correctness fix.
- Minimum rollout channel: Normal release after maintainer review and
qualification.
- Stable/default behavior changed: Only cache invalidation on explicit
registration replacement/removal. Cached get behavior is unchanged while
the registration is stable.
- Kill switch / disable path: No new flag; the existing cached=False
argument bypasses registry instance reuse.
- Unsafe override required: No. register(override=True) is the existing
explicit replacement API, not a rollout override.
- Qualification impact: Full cache tests and actual registry lifecycle
proof pass; full/native/provider qualification remains outstanding.
- Rollback path: Revert this commit. No persisted data migration or
dependency changes.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
Ready for human review. The current PR delta was re-reviewed with AI
assistance after upstream main was synchronized; the contributor patch
is unchanged. Historical tests and reviewer-reported checks remain
scoped as documented below; this is not a claim of
full-suite/native/provider qualification or merge approval.
## Checklist
- [x] Regression cases fail before the fix and pass after it.
- [x] Changed files follow lint and formatting rules.
- [x] CHANGELOG.md was not edited.
- [ ] Full repository qualification completed.
## Additional Notes
Implemented and tested with OpenAI AI assistance. The checked test items
describe verification that was executed, not a claim that the
publication owner personally ran it. No public API signature changes;
_instances remains private and in-memory.
---------
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
JerrettDavis
parent
b1aaf5b366
commit
1bcdca2d9d
Vendored
+12
-5
@@ -31,7 +31,14 @@ class CacheOptimizerRegistry:
|
||||
"""
|
||||
|
||||
_optimizers: dict[str, type[BaseCacheOptimizer]] = {}
|
||||
_instances: dict[str, BaseCacheOptimizer] = {}
|
||||
_instances: dict[tuple[str, int | None], BaseCacheOptimizer] = {}
|
||||
|
||||
@classmethod
|
||||
def _invalidate_instances(cls, name: str) -> None:
|
||||
"""Discard every configuration cached for this exact registration."""
|
||||
for key in list(cls._instances):
|
||||
if key[0] == name:
|
||||
del cls._instances[key]
|
||||
|
||||
@classmethod
|
||||
def register(
|
||||
@@ -57,8 +64,8 @@ class CacheOptimizerRegistry:
|
||||
f"Optimizer '{name}' already registered. Use override=True to replace."
|
||||
)
|
||||
cls._optimizers[name] = optimizer_class
|
||||
# Clear cached instance if exists
|
||||
cls._instances.pop(name, None)
|
||||
# Configured instances must not outlive their registered implementation.
|
||||
cls._invalidate_instances(name)
|
||||
|
||||
@classmethod
|
||||
def unregister(cls, name: str) -> None:
|
||||
@@ -69,7 +76,7 @@ class CacheOptimizerRegistry:
|
||||
name: Name to unregister
|
||||
"""
|
||||
cls._optimizers.pop(name, None)
|
||||
cls._instances.pop(name, None)
|
||||
cls._invalidate_instances(name)
|
||||
|
||||
@classmethod
|
||||
def get(
|
||||
@@ -109,7 +116,7 @@ class CacheOptimizerRegistry:
|
||||
raise KeyError(f"No optimizer registered for '{key}'. Available: {available}")
|
||||
|
||||
# Return cached instance if requested
|
||||
cache_key = f"{key}:{id(config)}" if config else key
|
||||
cache_key = (key, id(config) if config is not None else None)
|
||||
if cached and cache_key in cls._instances:
|
||||
return cls._instances[cache_key]
|
||||
|
||||
|
||||
@@ -101,6 +101,43 @@ class TestCacheOptimizerRegistry:
|
||||
with pytest.raises(KeyError):
|
||||
CacheOptimizerRegistry.get("unknown-provider")
|
||||
|
||||
@pytest.mark.parametrize("tier", ["oss", "enterprise"])
|
||||
@pytest.mark.parametrize("replacement", ["override", "reregister"])
|
||||
def test_replacing_registration_invalidates_all_configurations(
|
||||
self, monkeypatch, tier, replacement
|
||||
):
|
||||
monkeypatch.setattr(CacheOptimizerRegistry, "_optimizers", {})
|
||||
monkeypatch.setattr(CacheOptimizerRegistry, "_instances", {})
|
||||
|
||||
class ReplacementOptimizer(MockOptimizer):
|
||||
pass
|
||||
|
||||
name = "plugin" if tier == "oss" else "plugin-enterprise"
|
||||
CacheOptimizerRegistry.register(name, MockOptimizer)
|
||||
configs = [None, CacheConfig(), CacheConfig(min_cacheable_tokens=2048)]
|
||||
old_instances = [
|
||||
CacheOptimizerRegistry.get("plugin", tier=tier, config=config) for config in configs
|
||||
]
|
||||
neighbor = f"{name}-neighbor"
|
||||
CacheOptimizerRegistry.register(neighbor, MockOptimizer)
|
||||
unrelated = CacheOptimizerRegistry.get(neighbor, config=configs[1])
|
||||
|
||||
if replacement == "reregister":
|
||||
CacheOptimizerRegistry.unregister(name)
|
||||
assert not any(
|
||||
instance in CacheOptimizerRegistry._instances.values() for instance in old_instances
|
||||
)
|
||||
CacheOptimizerRegistry.register(name, ReplacementOptimizer)
|
||||
else:
|
||||
CacheOptimizerRegistry.register(name, ReplacementOptimizer, override=True)
|
||||
|
||||
for config, old in zip(configs, old_instances):
|
||||
new = CacheOptimizerRegistry.get("plugin", tier=tier, config=config)
|
||||
assert isinstance(new, ReplacementOptimizer)
|
||||
assert new is not old
|
||||
assert CacheOptimizerRegistry.get("plugin", tier=tier, config=config) is new
|
||||
assert CacheOptimizerRegistry.get(neighbor, config=configs[1]) is unrelated
|
||||
|
||||
def test_list_providers(self):
|
||||
"""Test listing providers."""
|
||||
providers = CacheOptimizerRegistry.list_providers()
|
||||
|
||||
Reference in New Issue
Block a user