Commit Graph
3 Commits
Author SHA1 Message Date
xiaoheiai4719-collabandJerrettDavis 1bcdca2d9d 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>
2026-10-28 21:16:56 -05:00
chopratejas e4a41faa33 Fix all ruff lint and format errors for CI
- Fix E402: Move module-level imports to top of file
- Fix F401: Add noqa for availability check imports
- Fix F402: Rename loop variables shadowing imports
- Fix E722: Replace bare except with except Exception
- Fix B904: Add exception chaining (from e)
- Fix F811: Remove duplicate imports
- Fix B027: Add noqa for empty close() method
- Fix E741: Rename ambiguous variable l -> label
- Fix I001: Import sorting issues
- Apply ruff format to all 106 files

All 902 tests pass.
2026-01-10 15:33:44 -08:00
chopratejas 7a05808e0f Add cache optimization module with scalable dynamic content detection
Implements a comprehensive cache optimization layer for LLM providers:

- Provider-specific optimizers (Anthropic, OpenAI, Google) with distinct
  caching strategies: explicit breakpoints, prefix stabilization, and
  CachedContent API respectively

- Scalable dynamic content detector using three strategies:
  1. Structural detection: "Label: value" patterns (language-agnostic)
  2. Entropy-based detection: high-entropy strings (IDs, tokens, hashes)
  3. Universal patterns: ISO 8601, UUIDs, JWTs, hex hashes

- NO hardcoded locale-specific patterns (no month names, etc.)

- Semantic caching layer with LRU eviction and TTL support

- Plugin registry for provider selection and custom optimizers

- 131 tests, real-world benchmarks showing 20-55% compression at <0.3ms
2026-01-07 14:07:49 -08:00