~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Enhance notification system: Add per-user rate limiting and improve documentation
tombii3a1a75721ed1
diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.mdindex 2f056a1345..aaa0f184b6 100644--- a/docs/NOTIFICATIONS.md+++ b/docs/NOTIFICATIONS.md@@ -40,8 +40,10 @@ Notifications are configured per-user via the settings system:- `notifications.on_auth_issue` - Enable notifications for authentication failures (default: false)### Rate Limiting Settings-- `notifications.rate_limit_per_hour` - Max notifications per hour per user-- `notifications.rate_limit_per_day` - Max notifications per day per user+- `notifications.rate_limit_per_hour` - Max notifications per hour (per user, default: 10)+- `notifications.rate_limit_per_day` - Max notifications per day (per user, default: 50)++**Per-User Rate Limiting**: Each user can configure their own rate limits via their settings. Rate limits are enforced independently per user, so one user hitting their limit does not affect other users. This ensures fair resource allocation in multi-user deployments.**Note on Multi-Worker Deployments**: The current rate limiting implementation uses in-memory storage and is process-local. In multi-worker deployments (e.g., gunicorn with multiple workers), each worker process maintains its own rate limit counters. This means a user could potentially send up to `N × max_per_hour` notifications (where N = number of workers) by distributing requests across different workers. For single-worker deployments (the default for LDR), this is not a concern. If you're running a multi-worker production deployment, consider monitoring notification volumes or implementing Redis-based rate limiting.@@ -80,8 +82,11 @@ Use the test function to verify notification configuration:```pythonfrom local_deep_research.notifications.manager import NotificationManager-# Create manager with empty settings (testing doesn't need settings)-notification_manager = NotificationManager(settings_snapshot={})+# Create manager for testing (user_id is required)+notification_manager = NotificationManager(+ settings_snapshot={},+ user_id="test_user"+)# Test a service URLresult = notification_manager.test_service("discord://webhook_id/webhook_token")@@ -101,19 +106,26 @@ from local_deep_research.settings import SettingsManagerfrom local_deep_research.database.session_context import get_user_db_session# Get settings snapshot+username = "your_username"with get_user_db_session(username, password) as session:settings_manager = SettingsManager(session)settings_snapshot = settings_manager.get_settings_snapshot()-# Create notification manager and send-notification_manager = NotificationManager(settings_snapshot=settings_snapshot)+# Create notification manager with user_id for per-user rate limiting+notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot,+ user_id=username # Enables per-user rate limit configuration+)++# Send notification (user_id already set in manager)notification_manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context={"query": "...", "summary": "...", "url": "/research/123"},- user_id="username")```+**Important**: The `user_id` parameter is **required** when creating a `NotificationManager`. This ensures the user's configured rate limits from their settings are properly applied and enforces per-user isolation.+### Building Full URLsUse `build_notification_url()` to convert relative paths to full URLs for clickable links in notifications.@@ -138,9 +150,10 @@ The system fetches service URLs from user settings when needed, rather than main### Performance Optimizations- **Temporary Apprise Instances**: Temporary Apprise instances are created for each send operation and automatically garbage collected by Python. This simple approach avoids memory management complexity.-- **Shared Rate Limiter**: A single rate limiter instance is shared across all NotificationManager instances to correctly enforce per-user rate limits.+- **Shared Rate Limiter with Per-User Limits**: A single rate limiter instance is shared across all NotificationManager instances for efficiency, while maintaining separate rate limit configurations and counters for each user. This provides both memory efficiency (~24 bytes per user for limit storage) and proper per-user isolation.- **Thread-Safe**: The rate limiter uses threading locks for safe concurrent access within a single process.- **Exponential Backoff Retry**: Failed notifications are retried up to 3 times with exponential backoff (0.5s → 1.0s → 2.0s) to handle transient network issues.+- **Dynamic Limit Updates**: User rate limits can be updated at runtime when creating a new NotificationManager instance with updated settings.## Thread Safety & Background Tasks@@ -150,7 +163,7 @@ The notification system is designed to work safely from background threads (e.g.**Key Principle**: Capture settings once with a database session, then pass the snapshot (not the session) to `NotificationManager`.-- ✅ **Correct**: `NotificationManager(settings_snapshot=settings_snapshot)`+- ✅ **Correct**: `NotificationManager(settings_snapshot=settings_snapshot, user_id=username)`- ❌ **Wrong**: `NotificationManager(session=session)` - Not thread-safe!See the source code in `web/queue/processor_v2.py` and `error_handling/error_reporter.py` for implementation examples.@@ -169,10 +182,56 @@ Use `force=True` parameter to bypass rate limits and disabled settings for critiEach event type can be individually enabled/disabled via settings (see Event-Specific Settings above).+### Per-User Rate Limiting++The notification system supports independent rate limiting for each user:++**How It Works:**+- Each user configures their own rate limits via settings (e.g., `notifications.rate_limit_per_hour`)+- Rate limits are enforced per-user, not globally+- One user hitting their limit does not affect other users+- Rate limits can be different for each user based on their settings++**Example:**+```python+# User A with conservative limits (5/hour)+snapshot_a = {"notifications.rate_limit_per_hour": 5}+manager_a = NotificationManager(snapshot_a, user_id="user_a")++# User B with generous limits (20/hour)+snapshot_b = {"notifications.rate_limit_per_hour": 20}+manager_b = NotificationManager(snapshot_b, user_id="user_b")++# User A can send 5 notifications per hour+# User B can send 20 notifications per hour+# They don't interfere with each other+```++**Technical Details:**+- The rate limiter maintains separate counters for each user+- Each user's limits are stored in memory (~24 bytes per user)+- Limits can be updated dynamically by creating a new NotificationManager for that user+- The `user_id` parameter is required when creating a NotificationManager+### Rate Limit HandlingRate limit exceptions (`RateLimitError`) can be caught and handled gracefully. See `notifications/exceptions.py` for available exception types.+**Example:**+```python+from local_deep_research.notifications.exceptions import RateLimitError++try:+ notification_manager.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context=context,+ )+except RateLimitError as e:+ # The manager already knows the user_id from initialization+ logger.warning(f"Rate limit exceeded: {e}")+ # Handle rate limit (e.g., queue for later, notify user)+```+## Troubleshooting### Notifications Not Sending@@ -189,8 +248,9 @@ Rate limit exceptions (`RateLimitError`) can be caught and handled gracefully. S- **Fix**: Configure service URL in settings dashboard or via API**Issue**: "Rate limit exceeded"-- **Cause**: User has sent too many notifications within the time window-- **Fix**: Wait for rate limit window to expire, or use `force=True` for critical notifications+- **Cause**: User has sent too many notifications within their configured time window (hourly or daily limit)+- **Fix**: Wait for rate limit window to expire (1 hour for hourly, 1 day for daily), adjust rate limit settings, or use `force=True` for critical notifications+- **Note**: Rate limits are enforced per-user, so this only affects the specific user who exceeded their limit**Issue**: "Failed to send notification after 3 attempts"- **Cause**: Service is unreachable or credentials are invaliddiff --git a/docs/NOTIFICATION_FLOW.md b/docs/NOTIFICATION_FLOW.mdindex 77cdbf4d73..5241515765 100644--- a/docs/NOTIFICATION_FLOW.md+++ b/docs/NOTIFICATION_FLOW.md@@ -86,9 +86,10 @@ def _send_research_notification(research = session.query(ResearchHistory).filter_by(id=research_id).first()if research:- # Create notification manager with settings snapshot+ # Create notification manager with settings snapshot and user_idnotification_manager = NotificationManager(- settings_snapshot=settings_snapshot+ settings_snapshot=settings_snapshot,+ user_id=username # Enables per-user rate limiting)# Build full URL for notification@@ -105,11 +106,10 @@ def _send_research_notification("url": full_url, # Full clickable URL}- # Send notification+ # Send notification (user_id already set in manager init)result = notification_manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context=context,- user_id=username,)```@@ -157,14 +157,17 @@ def send_notification(**Settings Checked (from `settings_snapshot`):**1. **`notifications.on_research_completed`** - Is this event type enabled? (default: False for most events)-2. **Rate limits** - Check shared rate limiter (per-user):- - `notifications.rate_limit_per_hour` (default: 10)- - `notifications.rate_limit_per_day` (default: 50)+2. **Per-User Rate Limits** - Check shared rate limiter with user-specific limits:+ - `notifications.rate_limit_per_hour` (default: 10) - Configured per user+ - `notifications.rate_limit_per_day` (default: 50) - Configured per user+ - Each user has independent rate limit counters3. **`notifications.service_url`** - Comma-separated list of Apprise URLs (required)**Key Points:**- All settings come from `settings_snapshot` (captured earlier)-- Rate limiter is **shared singleton** across all NotificationManager instances+- Rate limiter is **shared singleton** with per-user limits and counters+- Each user's rate limits are configured independently when `NotificationManager` is created with `user_id`+- One user hitting their rate limit does NOT affect other users- `force=False` by default (respects settings and rate limits)### 6. NotificationService Formats Message (`service.py:198-235`)@@ -324,7 +327,10 @@ settings_snapshot = settings_manager.get_settings_snapshot()# Returns dict like: {"notifications.service_url": "...", "notifications.on_research_completed": True, ...}# 2. Pass to NotificationManager (thread-safe - no session!)-notification_manager = NotificationManager(settings_snapshot=settings_snapshot)+notification_manager = NotificationManager(+ settings_snapshot=settings_snapshot,+ user_id=username+)# 3. NotificationManager reads from snapshotdef _get_setting(self, key: str, default: Any = None) -> Any:@@ -339,14 +345,20 @@ def _get_setting(self, key: str, default: Any = None) -> Any:## Rate Limiting-**Implementation:** In-memory, per-user, shared singleton+**Implementation:** In-memory, per-user limits and counters, shared singleton```pythonclass RateLimiter:_lock = threading.Lock()+ _user_limits: Dict[str, tuple[int, int]] = {} # user_id -> (max_per_hour, max_per_day)_hourly_counts: Dict[str, deque] = {} # user_id -> timestamps_daily_counts: Dict[str, deque] = {} # user_id -> timestamps+ def set_user_limits(self, user_id: str, max_per_hour: int, max_per_day: int):+ """Configure rate limits for a specific user."""+ with self._lock:+ self._user_limits[user_id] = (max_per_hour, max_per_day)+def allow(self, user_id: str) -> bool:with self._lock: # Thread-safenow = datetime.now(timezone.utc)@@ -354,10 +366,15 @@ class RateLimiter:# Clean old entries (> 1 hour, > 1 day)self._clean_old_entries(user_id, now)- # Check limits- if len(self._hourly_counts[user_id]) >= self.max_per_hour:+ # Get user-specific limits or defaults+ max_per_hour, max_per_day = self._user_limits.get(+ user_id, (self.max_per_hour, self.max_per_day)+ )++ # Check limits using user-specific values+ if len(self._hourly_counts[user_id]) >= max_per_hour:return False- if len(self._daily_counts[user_id]) >= self.max_per_day:+ if len(self._daily_counts[user_id]) >= max_per_day:return False# Record this notification@@ -367,28 +384,38 @@ class RateLimiter:return True```-**Shared Singleton Pattern:**+**Shared Singleton Pattern with Per-User Configuration:**```pythonclass NotificationManager:_shared_rate_limiter: Optional["RateLimiter"] = None_rate_limiter_lock = threading.Lock()- def __init__(self, settings_snapshot: Dict[str, Any]):+ def __init__(self, settings_snapshot: Dict[str, Any], user_id: str):with NotificationManager._rate_limiter_lock:if NotificationManager._shared_rate_limiter is None:+ # Create shared rate limiter with defaultsNotificationManager._shared_rate_limiter = RateLimiter(max_per_hour=settings_snapshot.get("notifications.rate_limit_per_hour", 10),max_per_day=settings_snapshot.get("notifications.rate_limit_per_day", 50),)+self._rate_limiter = NotificationManager._shared_rate_limiter++ # Configure per-user limits (user_id is required)+ max_per_hour = settings_snapshot.get("notifications.rate_limit_per_hour", 10)+ max_per_day = settings_snapshot.get("notifications.rate_limit_per_day", 50)+ self._rate_limiter.set_user_limits(user_id, max_per_hour, max_per_day)```**Key Points:**-- One rate limiter instance across all NotificationManager instances-- Ensures per-user limits are enforced correctly-- Thread-safe with `threading.Lock()`-- Automatic cleanup of old entries-- Periodic cleanup of inactive users (every 24 hours)+- **One rate limiter instance** across all NotificationManager instances (singleton)+- **Per-user rate limits**: Each user can have different limits based on their settings+- **Per-user counters**: Each user has independent notification counters+- **User isolation**: One user hitting their limit does NOT affect others+- **Thread-safe** with `threading.Lock()` for all operations+- **Automatic cleanup** of old entries (> 1 hour, > 1 day)+- **Periodic cleanup** of inactive users (every 24 hours)+- **Memory efficient**: ~24 bytes per user for limit storage## Configuration@@ -407,9 +434,9 @@ notifications.on_subscription_error = False # Default: Falsenotifications.on_api_quota_warning = False # Default: Falsenotifications.on_auth_issue = False # Default: False-# Rate limits (per-user)-notifications.rate_limit_per_hour = 10 # Max notifications per hour-notifications.rate_limit_per_day = 50 # Max notifications per day+# Rate limits (per-user, configured independently for each user)+notifications.rate_limit_per_hour = 10 # Max notifications per hour (per user)+notifications.rate_limit_per_day = 50 # Max notifications per day (per user)# URL configuration (for clickable links)app.external_url = "https://ldr.example.com" # Preferred@@ -423,8 +450,11 @@ app.port = 5000```pythonfrom local_deep_research.notifications.manager import NotificationManager-# Create manager with empty settings (testing doesn't need settings)-notification_manager = NotificationManager(settings_snapshot={})+# Create manager with settings and required user_id+notification_manager = NotificationManager(+ settings_snapshot={},+ user_id="test_user" # Required for per-user rate limiting+)# Test a service URLresult = notification_manager.test_service("discord://webhook_id/webhook_token")@@ -440,11 +470,11 @@ try:notification_manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context=context,- user_id="test_user")except RateLimitError as e:logger.warning(f"Rate limit exceeded: {e}")# Notification not sent, user needs to wait+ # Note: This only affects the user that the manager was created for```### Send Failure (After 3 Retries)@@ -496,17 +526,16 @@ ResearchHistory.query.filter_by(id=research_id).first() → research details↓build_notification_url() → full_url↓-NotificationManager(settings_snapshot=settings_snapshot)+NotificationManager(settings_snapshot=settings_snapshot, user_id=username)↓notification_manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,- context={query, research_id, summary, url},- user_id=username+ context={query, research_id, summary, url})↓[NotificationManager]├─ Check: notifications.on_research_completed- ├─ Check: Rate limiter (hourly/daily)+ ├─ Check: Per-user rate limiter (hourly/daily)└─ Get: notifications.service_url↓NotificationService.send_event(event_type, context, service_urls)@@ -533,13 +562,14 @@ Apprise.notify(title=title, body=body)## Key Design Decisions1. **Settings Snapshot Pattern**: Avoids thread-safety issues with database sessions-2. **Shared Rate Limiter**: Single instance ensures correct per-user enforcement-3. **Temporary Apprise Instances**: Created per-send and automatically garbage collected-4. **Exponential Backoff**: 3 retry attempts with increasing delays (0.5s → 1.0s → 2.0s)-5. **Encrypted Storage**: Service URLs stored encrypted in per-user SQLCipher database-6. **URL Masking**: Credentials hidden in logs (e.g., `discord://webhook_id/***`)-7. **No Session in Manager**: NotificationManager never receives database session (thread-safe)-8. **Error Sanitization**: Error messages sanitized in notifications to prevent information exposure+2. **Shared Rate Limiter with Per-User Limits**: Single rate limiter instance ensures correct per-user enforcement while maintaining separate limits and counters for each user+3. **User Isolation**: Each user's rate limits are independent - one user hitting their limit does not affect others+4. **Temporary Apprise Instances**: Created per-send and automatically garbage collected+5. **Exponential Backoff**: 3 retry attempts with increasing delays (0.5s → 1.0s → 2.0s)+6. **Encrypted Storage**: Service URLs stored encrypted in per-user SQLCipher database+7. **URL Masking**: Credentials hidden in logs (e.g., `discord://webhook_id/***`)+8. **No Session in Manager**: NotificationManager never receives database session (thread-safe)+9. **Error Sanitization**: Error messages sanitized in notifications to prevent information exposure## Additional Notification Events@@ -584,4 +614,4 @@ Run notification tests:pdm run python -m pytest tests/notifications/ -v```-All 91 tests passing ✓+All 98 tests passing ✓ (including 7 new per-user rate limiting tests)diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.pyindex 3107a5dc17..e161ce813d 100644--- a/src/local_deep_research/error_handling/error_reporter.py+++ b/src/local_deep_research/error_handling/error_reporter.py@@ -283,7 +283,7 @@ class ErrorReporter:settings_snapshot = settings_manager.get_settings_snapshot()notification_manager = NotificationManager(- settings_snapshot=settings_snapshot+ settings_snapshot=settings_snapshot, user_id=username)# Determine event type and build context@@ -323,7 +323,6 @@ class ErrorReporter:notification_manager.send_notification(event_type=event_type,context=notification_context,- user_id=username,)except Exception as e:diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex df73d0691f..4688fc35ad 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -22,6 +22,30 @@ class NotificationManager:This manager is designed to be used from background threads (e.g., queueprocessors) by passing a settings_snapshot dictionary captured from themain thread.++ **Per-User Rate Limiting:**+ The rate limiter is shared across ALL NotificationManager instances as a+ singleton, but supports per-user rate limit configuration. Each user has+ their own rate limits based on their settings, which are configured when+ the NotificationManager is initialized with the required user_id parameter.++ **How It Works:**+ - The first NotificationManager instance creates the shared RateLimiter+ with default limits+ - Each instance configures user-specific limits by passing user_id to __init__+ - The rate limiter maintains separate counters and limits for each user+ - Users are completely isolated - one user's limit doesn't affect others++ Example:+ >>> # User A with conservative limits+ >>> snapshot_a = {"notifications.rate_limit_per_hour": 5}+ >>> manager_a = NotificationManager(snapshot_a, user_id="user_a")+ >>> # ✅ user_a gets 5/hour+ >>>+ >>> # User B with generous limits (doesn't affect User A!)+ >>> snapshot_b = {"notifications.rate_limit_per_hour": 20}+ >>> manager_b = NotificationManager(snapshot_b, user_id="user_b")+ >>> # ✅ user_b gets 20/hour, user_a still has 5/hour"""# Shared rate limiter instance across all NotificationManager instances@@ -30,7 +54,7 @@ class NotificationManager:_shared_rate_limiter: Optional["RateLimiter"] = None_rate_limiter_lock = threading.Lock()- def __init__(self, settings_snapshot: Dict[str, Any]):+ def __init__(self, settings_snapshot: Dict[str, Any], user_id: str):"""Initialize the notification manager.@@ -39,6 +63,8 @@ class NotificationManager:from SettingsManager.get_settings_snapshot().This allows thread-safe access to user settingsfrom background threads.+ user_id: User identifier for per-user rate limiting. The rate limits+ from settings_snapshot will be configured for this user.Example:>>> # In main thread with database session@@ -46,33 +72,61 @@ class NotificationManager:>>> snapshot = settings_manager.get_settings_snapshot()>>>>>> # In background thread (thread-safe)- >>> notification_manager = NotificationManager(snapshot)+ >>> notification_manager = NotificationManager(+ ... settings_snapshot=snapshot,+ ... user_id="user123"+ ... )>>> notification_manager.send_notification(...)"""# Store settings snapshot for thread-safe accessself._settings_snapshot = settings_snapshot+ self._user_id = user_idself.service = NotificationService()# Initialize shared rate limiter on first use+ # The shared rate limiter now supports per-user limits, so each user's+ # settings are respected regardless of initialization order.with NotificationManager._rate_limiter_lock:if NotificationManager._shared_rate_limiter is None:- # Get rate limit settings from snapshot- max_per_hour = self._get_setting(+ # Create shared rate limiter with default limits+ # (individual users can have different limits)+ default_max_per_hour = self._get_setting("notifications.rate_limit_per_hour", default=10)- max_per_day = self._get_setting(+ default_max_per_day = self._get_setting("notifications.rate_limit_per_day", default=50)+ logger.info(+ f"Initializing shared rate limiter with defaults: "+ f"{default_max_per_hour}/hour, {default_max_per_day}/day"+ )+NotificationManager._shared_rate_limiter = RateLimiter(- max_per_hour=max_per_hour,- max_per_day=max_per_day,+ max_per_hour=default_max_per_hour,+ max_per_day=default_max_per_day,)# Use the shared instanceself._rate_limiter = NotificationManager._shared_rate_limiter+ # Configure per-user rate limits+ max_per_hour = self._get_setting(+ "notifications.rate_limit_per_hour", default=10+ )+ max_per_day = self._get_setting(+ "notifications.rate_limit_per_day", default=50+ )++ self._rate_limiter.set_user_limits(+ user_id, max_per_hour, max_per_day+ )+ logger.debug(+ f"Configured rate limits for user {user_id}: "+ f"{max_per_hour}/hour, {max_per_day}/day"+ )+def _get_setting(self, key: str, default: Any = None) -> Any:"""Get a setting value from snapshot.@@ -90,16 +144,17 @@ class NotificationManager:self,event_type: EventType,context: Dict[str, Any],- user_id: Optional[str] = None,force: bool = False,) -> bool:"""Send a notification for an event.+ Uses the user_id that was provided during initialization for+ rate limiting and user preferences.+Args:event_type: Type of eventcontext: Context data for the notification- user_id: User ID (for rate limiting and preferences)force: If True, bypass rate limitingReturns:@@ -110,30 +165,33 @@ class NotificationManager:"""try:logger.debug(- f"Sending notification: event_type={event_type.value}, user_id={user_id}, force={force}"+ f"Sending notification: event_type={event_type.value}, "+ f"user_id={self._user_id}, force={force}")logger.debug(f"Context keys: {list(context.keys())}")# Check if notifications are enabled for this event type- should_notify = self._should_notify(event_type, user_id)+ should_notify = self._should_notify(event_type)logger.debug(- f"Notification enabled check for {event_type.value}: {should_notify}"+ f"Notification enabled check for {event_type.value}: "+ f"{should_notify}")if not force and not should_notify:logger.debug(- f"Notifications disabled for event type: {event_type.value} (user: {user_id})"+ f"Notifications disabled for event type: "+ f"{event_type.value} (user: {self._user_id})")return False- # Check rate limit- rate_limit_ok = self._rate_limiter.allow(user_id or "default")+ # Check rate limit using the manager's user_id+ rate_limit_ok = self._rate_limiter.allow(self._user_id)logger.debug(- f"Rate limit check for {user_id or 'default'}: {rate_limit_ok}"+ f"Rate limit check for {self._user_id}: {rate_limit_ok}")if not force and not rate_limit_ok:- logger.warning(f"Rate limit exceeded for user {user_id}")+ logger.warning(f"Rate limit exceeded for user {self._user_id}")raise RateLimitError("Notification rate limit exceeded. ""Please wait before sending more notifications."@@ -146,7 +204,8 @@ class NotificationManager:if not service_urls or not service_urls.strip():logger.debug(- f"No notification service URLs configured for user {user_id}"+ f"No notification service URLs configured for user "+ f"{self._user_id}")return False@@ -158,23 +217,26 @@ class NotificationManager:# Log to database if enabledif result:- self._log_notification(event_type, context, user_id)+ self._log_notification(event_type, context)logger.info(- f"Notification sent: {event_type.value} to user {user_id}"+ f"Notification sent: {event_type.value} to user "+ f"{self._user_id}")else:logger.warning(- f"Notification failed: {event_type.value} to user {user_id}"+ f"Notification failed: {event_type.value} to user "+ f"{self._user_id}")return resultexcept RateLimitError:- logger.warning(f"Rate limit error for user {user_id}")+ logger.warning(f"Rate limit error for user {self._user_id}")raiseexcept Exception as e:logger.exception(- f"Error sending notification for {event_type.value} to user {user_id}: {e}"+ f"Error sending notification for {event_type.value} to user "+ f"{self._user_id}: {e}")return False@@ -190,17 +252,15 @@ class NotificationManager:"""return self.service.test_service(url)- def _should_notify(- self,- event_type: EventType,- user_id: Optional[str] = None,- ) -> bool:+ def _should_notify(self, event_type: EventType) -> bool:"""Check if notifications should be sent for this event type.+ Uses the manager's settings snapshot to determine if the event type+ is enabled for the user.+Args:event_type: Event type to check- user_id: User IDReturns:True if notifications should be sent@@ -218,18 +278,16 @@ class NotificationManager:return Falsedef _log_notification(- self,- event_type: EventType,- context: Dict[str, Any],- user_id: Optional[str] = None,+ self, event_type: EventType, context: Dict[str, Any]) -> None:"""Log a sent notification (simplified logging to application logs only).+ Uses the manager's user_id for logging.+Args:event_type: Event typecontext: Notification context- user_id: User ID"""try:title = (@@ -238,7 +296,8 @@ class NotificationManager:or "Unknown")logger.info(- f"Notification sent: {event_type.value} - {title} (user: {user_id or 'unknown'})"+ f"Notification sent: {event_type.value} - {title} "+ f"(user: {self._user_id})")except Exception as e:logger.debug(f"Failed to log notification: {e}")@@ -246,25 +305,44 @@ class NotificationManager:class RateLimiter:"""- Simple in-memory rate limiter for notifications.+ Simple in-memory rate limiter for notifications with per-user limit support.- Note: This implementation stores rate limits in memory only, which means+ This rate limiter tracks notification counts per user and enforces+ configurable rate limits. Each user can have their own rate limits,+ which are stored separately from the notification counts.++ **Per-User Limits:**+ Rate limits can be configured per-user using `set_user_limits()`.+ If no user-specific limits are set, the default limits (passed to+ __init__) are used.++ **Memory Storage:**+ This implementation stores rate limits in memory only, which meanslimits are reset when the server restarts. This is acceptable for normalusers since they cannot restart the server. If an admin restarts the server,rate limits reset which is reasonable behavior.- Thread Safety: This implementation is thread-safe using threading.Lock()- for concurrent requests from the same user. However, in a production- environment with multiple worker processes (e.g., gunicorn with multiple- workers), rate limits are not shared across processes.-- **Multi-Worker Limitation**: In multi-worker deployments, each worker- process maintains its own rate limit counters. Users could potentially- bypass rate limits by distributing requests across different workers,- getting up to N × max_per_hour notifications (where N = number of workers).- For single-worker deployments (the default for LDR), this is not a concern.- For production multi-worker deployments, consider implementing Redis-based- rate limiting.+ **Thread Safety:**+ This implementation is thread-safe using threading.Lock() for concurrent+ requests from the same user.++ **Multi-Worker Limitation:**+ In multi-worker deployments, each worker process maintains its own rate+ limit counters. Users could potentially bypass rate limits by distributing+ requests across different workers, getting up to N × max_per_hour+ notifications (where N = number of workers). For single-worker deployments+ (the default for LDR), this is not a concern. For production multi-worker+ deployments, consider implementing Redis-based rate limiting.++ Example:+ >>> limiter = RateLimiter(max_per_hour=10, max_per_day=50)+ >>> # Set custom limits for specific user+ >>> limiter.set_user_limits("user_a", max_per_hour=5, max_per_day=25)+ >>> limiter.set_user_limits("user_b", max_per_hour=20, max_per_day=100)+ >>> # Users get their configured limits+ >>> limiter.allow("user_a") # Limited to 5/hour+ >>> limiter.allow("user_b") # Limited to 20/hour+ >>> limiter.allow("user_c") # Uses defaults: 10/hour"""def __init__(@@ -274,30 +352,83 @@ class RateLimiter:cleanup_interval_hours: int = 24,):"""- Initialize rate limiter.+ Initialize rate limiter with default limits.Args:- max_per_hour: Maximum notifications per hour per user- max_per_day: Maximum notifications per day per user+ max_per_hour: Default maximum notifications per hour per user+ max_per_day: Default maximum notifications per day per usercleanup_interval_hours: How often to run cleanup of inactive users (hours)"""+ # Default limits used when no user-specific limits are setself.max_per_hour = max_per_hourself.max_per_day = max_per_dayself.cleanup_interval_hours = cleanup_interval_hours++ # Per-user rate limit configuration (user_id -> (max_per_hour, max_per_day))+ self._user_limits: Dict[str, tuple[int, int]] = {}++ # Per-user notification countsself._hourly_counts: Dict[str, deque] = {}self._daily_counts: Dict[str, deque] = {}+self._last_cleanup = datetime.now(timezone.utc)- self._lock = threading.Lock() # Add thread safety+ self._lock = threading.Lock() # Thread safety for all operations++ def set_user_limits(+ self, user_id: str, max_per_hour: int, max_per_day: int+ ) -> None:+ """+ Set rate limits for a specific user.++ This allows each user to have their own rate limit configuration.+ If not set, the user will use the default limits passed to __init__.++ Args:+ user_id: User identifier+ max_per_hour: Maximum notifications per hour for this user+ max_per_day: Maximum notifications per day for this user++ Example:+ >>> limiter = RateLimiter(max_per_hour=10, max_per_day=50)+ >>> limiter.set_user_limits("power_user", max_per_hour=20, max_per_day=100)+ >>> limiter.set_user_limits("limited_user", max_per_hour=5, max_per_day=25)+ """+ with self._lock:+ self._user_limits[user_id] = (max_per_hour, max_per_day)+ logger.debug(+ f"Set rate limits for user {user_id}: "+ f"{max_per_hour}/hour, {max_per_day}/day"+ )++ def get_user_limits(self, user_id: str) -> tuple[int, int]:+ """+ Get the effective rate limits for a user.++ Returns the user-specific limits if set, otherwise returns defaults.++ Args:+ user_id: User identifier++ Returns:+ Tuple of (max_per_hour, max_per_day)+ """+ with self._lock:+ return self._user_limits.get(+ user_id, (self.max_per_hour, self.max_per_day)+ )def allow(self, user_id: str) -> bool:"""Check if a notification is allowed for a user.+ Uses per-user rate limits if configured via set_user_limits(),+ otherwise uses the default limits from __init__.+Args:user_id: User identifierReturns:- True if notification is allowed+ True if notification is allowed, False if rate limit exceeded"""with self._lock:now = datetime.now(timezone.utc)@@ -313,21 +444,26 @@ class RateLimiter:# Clean old entriesself._clean_old_entries(user_id, now)+ # Get user-specific limits or defaults+ max_per_hour, max_per_day = self._user_limits.get(+ user_id, (self.max_per_hour, self.max_per_day)+ )+# Check limitshourly_count = len(self._hourly_counts[user_id])daily_count = len(self._daily_counts[user_id])- if hourly_count >= self.max_per_hour:+ if hourly_count >= max_per_hour:logger.warning(f"Hourly rate limit exceeded for user {user_id}: "- f"{hourly_count}/{self.max_per_hour}"+ f"{hourly_count}/{max_per_hour}")return False- if daily_count >= self.max_per_day:+ if daily_count >= max_per_day:logger.warning(f"Daily rate limit exceeded for user {user_id}: "- f"{daily_count}/{self.max_per_day}"+ f"{daily_count}/{max_per_day}")return Falsediff --git a/src/local_deep_research/web/queue/manager.py b/src/local_deep_research/web/queue/manager.pyindex 0c9ca40e0c..cb09a3c267 100644--- a/src/local_deep_research/web/queue/manager.py+++ b/src/local_deep_research/web/queue/manager.py@@ -68,7 +68,7 @@ class QueueManager:settings_snapshot = settings_manager.get_settings_snapshot()notification_manager = NotificationManager(- settings_snapshot=settings_snapshot+ settings_snapshot=settings_snapshot, user_id=username)# Build notification context@@ -81,7 +81,6 @@ class QueueManager:notification_manager.send_notification(event_type=EventType.RESEARCH_QUEUED,context=context,- user_id=username,)except Exception as e:logger.debug(f"Failed to send queued notification: {e}")diff --git a/src/local_deep_research/web/queue/processor.py b/src/local_deep_research/web/queue/processor.pyindex e189db61d0..2a4c7c0d4b 100644--- a/src/local_deep_research/web/queue/processor.py+++ b/src/local_deep_research/web/queue/processor.py@@ -587,7 +587,8 @@ class QueueProcessor:# Create notification manager with settings snapshotnotification_manager = NotificationManager(- settings_snapshot=settings_snapshot+ settings_snapshot=settings_snapshot,+ user_id=op_data["username"],)# Build notification context@@ -601,7 +602,6 @@ class QueueProcessor:notification_manager.send_notification(event_type=EventType.RESEARCH_FAILED,context=context,- user_id=op_data["username"],)logger.info(f"Sent failure notification for research {research_id}"diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 15be5a7f54..5da5c4da56 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -408,7 +408,7 @@ class QueueProcessorV2:from ...notifications.url_builder import build_notification_urlnotification_manager = NotificationManager(- settings_snapshot=settings_snapshot+ settings_snapshot=settings_snapshot, user_id=username)# Build context based on event type@@ -460,7 +460,6 @@ class QueueProcessorV2:result = notification_manager.send_notification(event_type=EventType[event_type],context=context,- user_id=username,)logger.info(f"Notification sent, result: {result}")logger.info(@@ -476,7 +475,7 @@ class QueueProcessorV2:from ...notifications.manager import NotificationManagernotification_manager = NotificationManager(- settings_snapshot=settings_snapshot+ settings_snapshot=settings_snapshot, user_id=username)# Build minimal context@@ -499,7 +498,6 @@ class QueueProcessorV2:notification_manager.send_notification(event_type=EventType[event_type],context=context,- user_id=username,)logger.info(f"Sent {event_type.lower()} notification for research "diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.pyindex 5852d51751..f33c1f88f5 100644--- a/tests/notifications/test_manager.py+++ b/tests/notifications/test_manager.py@@ -26,9 +26,12 @@ class TestNotificationManagerInit:"notifications.rate_limit_per_day": 50,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )assert manager._settings_snapshot == snapshot+ assert manager._user_id == "test_user"def test_shared_rate_limiter_singleton(self, mocker):"""Test that rate limiter is shared across instances."""@@ -40,8 +43,12 @@ class TestNotificationManagerInit:"notifications.rate_limit_per_day": 50,}- manager1 = NotificationManager(settings_snapshot=snapshot)- manager2 = NotificationManager(settings_snapshot=snapshot)+ manager1 = NotificationManager(+ settings_snapshot=snapshot, user_id="user1"+ )+ manager2 = NotificationManager(+ settings_snapshot=snapshot, user_id="user2"+ )# Both managers should have the same rate limiter instanceassert manager1._rate_limiter is manager2._rate_limiter@@ -59,7 +66,9 @@ class TestGetSetting:"notifications.service_url": "discord://webhook/token",}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )result = manager._get_setting("notifications.service_url")@@ -68,7 +77,9 @@ class TestGetSetting:def test_get_setting_returns_default(self, mocker):"""Test getting setting returns default when not found."""snapshot = {}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )result = manager._get_setting("notifications.nonexistent", default="default_value"@@ -87,7 +98,9 @@ class TestSendNotification:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )# Mock service.send_eventmanager.service.send_event = mocker.MagicMock(return_value=True)@@ -103,7 +116,6 @@ class TestSendNotification:result = manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context=context,- user_id="test_user",)assert result is True@@ -117,7 +129,9 @@ class TestSendNotification:"notifications.on_research_completed": False, # Disabled}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.send_event = mocker.MagicMock()context = {"query": "Test"}@@ -137,7 +151,9 @@ class TestSendNotification:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.send_event = mocker.MagicMock()context = {"query": "Test"}@@ -157,7 +173,9 @@ class TestSendNotification:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.send_event = mocker.MagicMock()# Mock rate limiter to deny@@ -169,7 +187,6 @@ class TestSendNotification:manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context=context,- user_id="test_user",)manager.service.send_event.assert_not_called()@@ -181,7 +198,9 @@ class TestSendNotification:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.send_event = mocker.MagicMock(return_value=True)# Mock rate limiter to deny, but force should bypass@@ -192,7 +211,6 @@ class TestSendNotification:result = manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context=context,- user_id="test_user",force=True, # Bypass rate limit)@@ -208,7 +226,9 @@ class TestSendNotification:"notifications.on_research_completed": False, # Disabled}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.send_event = mocker.MagicMock(return_value=True)manager._rate_limiter.allow = mocker.MagicMock(return_value=True)@@ -230,7 +250,9 @@ class TestSendNotification:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )# Mock service to failmanager.service.send_event = mocker.MagicMock(return_value=False)@@ -252,7 +274,9 @@ class TestSendNotification:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )# Mock service to raise exceptionmanager.service.send_event = mocker.MagicMock(@@ -280,12 +304,12 @@ class TestShouldNotify:"notifications.on_research_completed": True,}- manager = NotificationManager(settings_snapshot=snapshot)-- result = manager._should_notify(- EventType.RESEARCH_COMPLETED, user_id="test_user"+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user")+ result = manager._should_notify(EventType.RESEARCH_COMPLETED)+assert result is Truedef test_should_notify_disabled(self, mocker):@@ -294,23 +318,23 @@ class TestShouldNotify:"notifications.on_research_completed": False,}- manager = NotificationManager(settings_snapshot=snapshot)-- result = manager._should_notify(- EventType.RESEARCH_COMPLETED, user_id="test_user"+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user")+ result = manager._should_notify(EventType.RESEARCH_COMPLETED)+assert result is Falsedef test_should_notify_default_false(self, mocker):"""Test notification defaults to False when setting missing."""snapshot = {}- manager = NotificationManager(settings_snapshot=snapshot)-- result = manager._should_notify(- EventType.RESEARCH_COMPLETED, user_id="test_user"+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user")+ result = manager._should_notify(EventType.RESEARCH_COMPLETED)+# Default is False for missing settings to avoid infinite loopsassert result is False@@ -321,7 +345,9 @@ class TestTestService:def test_test_service_success(self, mocker):"""Test successful service test."""snapshot = {}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.test_service = mocker.MagicMock(return_value={"success": True}@@ -337,7 +363,9 @@ class TestTestService:def test_test_service_failure(self, mocker):"""Test failed service test."""snapshot = {}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.test_service = mocker.MagicMock(return_value={"success": False, "error": "Connection failed"}@@ -495,7 +523,9 @@ class TestIntegration:}# Create manager with snapshot (no session - thread-safe)- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )# Mock servicemanager.service.send_event = mocker.MagicMock(return_value=True)@@ -510,7 +540,6 @@ class TestIntegration:result = manager.send_notification(event_type=EventType.RESEARCH_COMPLETED,context=context,- user_id="test_user",)assert result is True@@ -530,7 +559,9 @@ class TestIntegration:"notifications.on_subscription_update": False, # Disabled}- manager = NotificationManager(settings_snapshot=snapshot)+ manager = NotificationManager(+ settings_snapshot=snapshot, user_id="test_user"+ )manager.service.send_event = mocker.MagicMock(return_value=True)# Research completed - should send@@ -555,3 +586,181 @@ class TestIntegration:context={"subscription_name": "Test"},)assert result3 is False+++class TestPerUserRateLimiting:+ """Tests for per-user rate limiting functionality."""++ def test_rate_limiter_set_user_limits(self):+ """Test setting per-user rate limits."""+ limiter = RateLimiter(max_per_hour=10, max_per_day=50)++ # Set custom limits for specific users+ limiter.set_user_limits("user_a", max_per_hour=5, max_per_day=25)+ limiter.set_user_limits("user_b", max_per_hour=20, max_per_day=100)++ # Verify limits are set correctly+ assert limiter.get_user_limits("user_a") == (5, 25)+ assert limiter.get_user_limits("user_b") == (20, 100)+ assert limiter.get_user_limits("user_c") == (10, 50) # Uses defaults++ def test_rate_limiter_respects_per_user_limits(self):+ """Test that rate limiter enforces different limits per user."""+ limiter = RateLimiter(max_per_hour=10, max_per_day=50)++ # Set conservative limits for user_a+ limiter.set_user_limits("user_a", max_per_hour=2, max_per_day=5)++ # User A should be limited to 2 per hour+ assert limiter.allow("user_a") is True # 1st+ assert limiter.allow("user_a") is True # 2nd+ assert limiter.allow("user_a") is False # 3rd - exceeds limit++ # User B should use default limits (10 per hour)+ for _ in range(10):+ assert limiter.allow("user_b") is True+ assert limiter.allow("user_b") is False # 11th - exceeds default++ def test_notification_manager_with_user_id(self, mocker):+ """Test NotificationManager configures per-user limits."""+ # Reset shared rate limiter+ NotificationManager._shared_rate_limiter = None++ # User A with conservative limits+ snapshot_a = {+ "notifications.rate_limit_per_hour": 3,+ "notifications.rate_limit_per_day": 10,+ }+ manager_a = NotificationManager(snapshot_a, user_id="user_a")++ # User B with generous limits+ snapshot_b = {+ "notifications.rate_limit_per_hour": 15,+ "notifications.rate_limit_per_day": 50,+ }+ manager_b = NotificationManager(snapshot_b, user_id="user_b")++ # Verify both users have the same rate limiter instance (singleton)+ assert manager_a._rate_limiter is manager_b._rate_limiter++ # Verify per-user limits are configured correctly+ limiter = manager_a._rate_limiter+ assert limiter.get_user_limits("user_a") == (3, 10)+ assert limiter.get_user_limits("user_b") == (15, 50)++ def test_per_user_limits_isolation(self, mocker):+ """Test that users don't interfere with each other's limits."""+ # Reset shared rate limiter+ NotificationManager._shared_rate_limiter = None++ # Create managers for two users+ snapshot_a = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ "notifications.rate_limit_per_hour": 2,+ "notifications.rate_limit_per_day": 5,+ }+ manager_a = NotificationManager(snapshot_a, user_id="user_a")++ snapshot_b = {+ "notifications.service_url": "discord://webhook/token",+ "notifications.on_research_completed": True,+ "notifications.rate_limit_per_hour": 5,+ "notifications.rate_limit_per_day": 10,+ }+ manager_b = NotificationManager(snapshot_b, user_id="user_b")++ # Mock service+ manager_a.service.send_event = mocker.MagicMock(return_value=True)+ manager_b.service.send_event = mocker.MagicMock(return_value=True)++ context = {"query": "Test"}++ # User A sends notifications up to their limit (2)+ result1 = manager_a.send_notification(+ EventType.RESEARCH_COMPLETED, context+ )+ assert result1 is True++ result2 = manager_a.send_notification(+ EventType.RESEARCH_COMPLETED, context+ )+ assert result2 is True++ # User A exceeds limit+ with pytest.raises(RateLimitError):+ manager_a.send_notification(EventType.RESEARCH_COMPLETED, context)++ # User B should still be able to send (not affected by User A)+ for _ in range(5): # User B has 5/hour limit+ result = manager_b.send_notification(+ EventType.RESEARCH_COMPLETED, context+ )+ assert result is True++ # User B exceeds their own limit+ with pytest.raises(RateLimitError):+ manager_b.send_notification(EventType.RESEARCH_COMPLETED, context)++ def test_manager_configures_user_limits(self, mocker):+ """Test that manager configures per-user limits on initialization."""+ # Reset shared rate limiter+ NotificationManager._shared_rate_limiter = None++ snapshot = {+ "notifications.rate_limit_per_hour": 7,+ "notifications.rate_limit_per_day": 30,+ }++ # Create manager with user_id+ manager = NotificationManager(snapshot, user_id="some_user")++ # Limiter should be created with defaults from snapshot+ limiter = manager._rate_limiter+ assert limiter.max_per_hour == 7+ assert limiter.max_per_day == 30++ # User-specific limits should be configured+ assert limiter.get_user_limits("some_user") == (7, 30)++ def test_updating_user_limits_after_initialization(self):+ """Test that user limits can be updated after manager creation."""+ # Reset shared rate limiter+ NotificationManager._shared_rate_limiter = None++ # Create manager with initial limits+ snapshot = {+ "notifications.rate_limit_per_hour": 5,+ "notifications.rate_limit_per_day": 20,+ }+ manager = NotificationManager(snapshot, user_id="user_a")++ # Verify initial limits+ assert manager._rate_limiter.get_user_limits("user_a") == (5, 20)++ # Update limits directly on rate limiter+ manager._rate_limiter.set_user_limits(+ "user_a", max_per_hour=10, max_per_day=40+ )++ # Verify limits are updated+ assert manager._rate_limiter.get_user_limits("user_a") == (10, 40)++ def test_multiple_managers_same_user_updates_limits(self):+ """Test that creating multiple managers for same user updates limits."""+ # Reset shared rate limiter+ NotificationManager._shared_rate_limiter = None++ # First manager for user_a with 5/hour+ snapshot1 = {"notifications.rate_limit_per_hour": 5}+ manager1 = NotificationManager(snapshot1, user_id="user_a")++ assert manager1._rate_limiter.get_user_limits("user_a") == (5, 50)++ # Second manager for user_a with 10/hour (should update)+ snapshot2 = {"notifications.rate_limit_per_hour": 10}+ manager2 = NotificationManager(snapshot2, user_id="user_a")++ # Both managers should see the updated limits+ assert manager1._rate_limiter.get_user_limits("user_a") == (10, 50)+ assert manager2._rate_limiter.get_user_limits("user_a") == (10, 50)