fix(memory): add thread-safe singleton initialization
- Add threading.Lock with double-check locking to ScopeManager - Add asyncio.Lock with double-check locking to MemoryReflection - Make reset_memory_metrics async with proper locking - Update test fixtures to handle async reset functions 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ Implements pattern detection, success/failure analysis, anomaly detection,
|
||||
and insight generation.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import statistics
|
||||
from collections import Counter, defaultdict
|
||||
@@ -1425,8 +1426,9 @@ class MemoryReflection:
|
||||
)
|
||||
|
||||
|
||||
# Singleton instance
|
||||
# Singleton instance with async-safe initialization
|
||||
_memory_reflection: MemoryReflection | None = None
|
||||
_reflection_lock = asyncio.Lock()
|
||||
|
||||
|
||||
async def get_memory_reflection(
|
||||
@@ -1434,7 +1436,7 @@ async def get_memory_reflection(
|
||||
config: ReflectionConfig | None = None,
|
||||
) -> MemoryReflection:
|
||||
"""
|
||||
Get or create the memory reflection service.
|
||||
Get or create the memory reflection service (async-safe).
|
||||
|
||||
Args:
|
||||
session: Database session
|
||||
@@ -1445,11 +1447,15 @@ async def get_memory_reflection(
|
||||
"""
|
||||
global _memory_reflection
|
||||
if _memory_reflection is None:
|
||||
_memory_reflection = MemoryReflection(session=session, config=config)
|
||||
async with _reflection_lock:
|
||||
# Double-check locking pattern
|
||||
if _memory_reflection is None:
|
||||
_memory_reflection = MemoryReflection(session=session, config=config)
|
||||
return _memory_reflection
|
||||
|
||||
|
||||
def reset_memory_reflection() -> None:
|
||||
"""Reset the memory reflection singleton."""
|
||||
async def reset_memory_reflection() -> None:
|
||||
"""Reset the memory reflection singleton (async-safe)."""
|
||||
global _memory_reflection
|
||||
_memory_reflection = None
|
||||
async with _reflection_lock:
|
||||
_memory_reflection = None
|
||||
|
||||
Reference in New Issue
Block a user