exonware-xwlazy 0.1.0.11__py3-none-any.whl → 0.1.0.19__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. exonware/__init__.py +22 -0
  2. exonware/xwlazy/__init__.py +0 -0
  3. exonware/xwlazy/common/__init__.py +47 -0
  4. exonware/xwlazy/common/base.py +58 -0
  5. exonware/xwlazy/common/cache.py +506 -0
  6. exonware/xwlazy/common/logger.py +268 -0
  7. exonware/xwlazy/common/services/__init__.py +72 -0
  8. exonware/xwlazy/common/services/dependency_mapper.py +234 -0
  9. exonware/xwlazy/common/services/install_async_utils.py +169 -0
  10. exonware/xwlazy/common/services/install_cache_utils.py +257 -0
  11. exonware/xwlazy/common/services/keyword_detection.py +292 -0
  12. exonware/xwlazy/common/services/spec_cache.py +173 -0
  13. exonware/xwlazy/common/strategies/__init__.py +28 -0
  14. exonware/xwlazy/common/strategies/caching_dict.py +45 -0
  15. exonware/xwlazy/common/strategies/caching_installation.py +89 -0
  16. exonware/xwlazy/common/strategies/caching_lfu.py +67 -0
  17. exonware/xwlazy/common/strategies/caching_lru.py +64 -0
  18. exonware/xwlazy/common/strategies/caching_multitier.py +60 -0
  19. exonware/xwlazy/common/strategies/caching_ttl.py +60 -0
  20. {xwlazy/lazy → exonware/xwlazy}/config.py +52 -20
  21. exonware/xwlazy/contracts.py +1410 -0
  22. exonware/xwlazy/defs.py +397 -0
  23. xwlazy/lazy/lazy_errors.py → exonware/xwlazy/errors.py +21 -8
  24. exonware/xwlazy/facade.py +1049 -0
  25. exonware/xwlazy/module/__init__.py +18 -0
  26. exonware/xwlazy/module/base.py +569 -0
  27. exonware/xwlazy/module/data.py +17 -0
  28. exonware/xwlazy/module/facade.py +247 -0
  29. exonware/xwlazy/module/importer_engine.py +2161 -0
  30. exonware/xwlazy/module/strategies/__init__.py +22 -0
  31. exonware/xwlazy/module/strategies/module_helper_lazy.py +94 -0
  32. exonware/xwlazy/module/strategies/module_helper_simple.py +66 -0
  33. exonware/xwlazy/module/strategies/module_manager_advanced.py +112 -0
  34. exonware/xwlazy/module/strategies/module_manager_simple.py +96 -0
  35. exonware/xwlazy/package/__init__.py +18 -0
  36. exonware/xwlazy/package/base.py +807 -0
  37. xwlazy/lazy/host_conf.py → exonware/xwlazy/package/conf.py +62 -10
  38. exonware/xwlazy/package/data.py +17 -0
  39. exonware/xwlazy/package/facade.py +481 -0
  40. exonware/xwlazy/package/services/__init__.py +84 -0
  41. exonware/xwlazy/package/services/async_install_handle.py +89 -0
  42. exonware/xwlazy/package/services/config_manager.py +246 -0
  43. exonware/xwlazy/package/services/discovery.py +374 -0
  44. {xwlazy/lazy → exonware/xwlazy/package/services}/host_packages.py +43 -16
  45. exonware/xwlazy/package/services/install_async.py +278 -0
  46. exonware/xwlazy/package/services/install_cache.py +146 -0
  47. exonware/xwlazy/package/services/install_interactive.py +60 -0
  48. exonware/xwlazy/package/services/install_policy.py +158 -0
  49. exonware/xwlazy/package/services/install_registry.py +56 -0
  50. exonware/xwlazy/package/services/install_result.py +17 -0
  51. exonware/xwlazy/package/services/install_sbom.py +154 -0
  52. exonware/xwlazy/package/services/install_utils.py +83 -0
  53. exonware/xwlazy/package/services/installer_engine.py +408 -0
  54. exonware/xwlazy/package/services/lazy_installer.py +720 -0
  55. {xwlazy/lazy → exonware/xwlazy/package/services}/manifest.py +42 -25
  56. exonware/xwlazy/package/services/strategy_registry.py +188 -0
  57. exonware/xwlazy/package/strategies/__init__.py +57 -0
  58. exonware/xwlazy/package/strategies/package_discovery_file.py +130 -0
  59. exonware/xwlazy/package/strategies/package_discovery_hybrid.py +85 -0
  60. exonware/xwlazy/package/strategies/package_discovery_manifest.py +102 -0
  61. exonware/xwlazy/package/strategies/package_execution_async.py +114 -0
  62. exonware/xwlazy/package/strategies/package_execution_cached.py +91 -0
  63. exonware/xwlazy/package/strategies/package_execution_pip.py +100 -0
  64. exonware/xwlazy/package/strategies/package_execution_wheel.py +107 -0
  65. exonware/xwlazy/package/strategies/package_mapping_discovery_first.py +101 -0
  66. exonware/xwlazy/package/strategies/package_mapping_hybrid.py +106 -0
  67. exonware/xwlazy/package/strategies/package_mapping_manifest_first.py +101 -0
  68. exonware/xwlazy/package/strategies/package_policy_allow_list.py +58 -0
  69. exonware/xwlazy/package/strategies/package_policy_deny_list.py +58 -0
  70. exonware/xwlazy/package/strategies/package_policy_permissive.py +47 -0
  71. exonware/xwlazy/package/strategies/package_timing_clean.py +68 -0
  72. exonware/xwlazy/package/strategies/package_timing_full.py +67 -0
  73. exonware/xwlazy/package/strategies/package_timing_smart.py +69 -0
  74. exonware/xwlazy/package/strategies/package_timing_temporary.py +67 -0
  75. exonware/xwlazy/runtime/__init__.py +18 -0
  76. exonware/xwlazy/runtime/adaptive_learner.py +131 -0
  77. exonware/xwlazy/runtime/base.py +276 -0
  78. exonware/xwlazy/runtime/facade.py +95 -0
  79. exonware/xwlazy/runtime/intelligent_selector.py +173 -0
  80. exonware/xwlazy/runtime/metrics.py +64 -0
  81. exonware/xwlazy/runtime/performance.py +39 -0
  82. exonware/xwlazy/version.py +2 -2
  83. {exonware_xwlazy-0.1.0.11.dist-info → exonware_xwlazy-0.1.0.19.dist-info}/METADATA +86 -10
  84. exonware_xwlazy-0.1.0.19.dist-info/RECORD +87 -0
  85. exonware_xwlazy-0.1.0.11.dist-info/RECORD +0 -20
  86. xwlazy/__init__.py +0 -34
  87. xwlazy/lazy/__init__.py +0 -301
  88. xwlazy/lazy/bootstrap.py +0 -106
  89. xwlazy/lazy/lazy_base.py +0 -465
  90. xwlazy/lazy/lazy_contracts.py +0 -290
  91. xwlazy/lazy/lazy_core.py +0 -3727
  92. xwlazy/lazy/logging_utils.py +0 -194
  93. xwlazy/version.py +0 -77
  94. /xwlazy/lazy/lazy_state.py → /exonware/xwlazy/common/services/state_manager.py +0 -0
  95. {exonware_xwlazy-0.1.0.11.dist-info → exonware_xwlazy-0.1.0.19.dist-info}/WHEEL +0 -0
  96. {exonware_xwlazy-0.1.0.11.dist-info → exonware_xwlazy-0.1.0.19.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,276 @@
1
+ """
2
+ #exonware/xwlazy/src/exonware/xwlazy/runtime/base.py
3
+
4
+ Company: eXonware.com
5
+ Author: Eng. Muhammad AlShehri
6
+ Email: connect@exonware.com
7
+ Version: 0.1.0.19
8
+ Generation Date: 10-Oct-2025
9
+
10
+ Abstract Base Class for Runtime Services
11
+
12
+ This module defines the abstract base class for runtime services.
13
+ """
14
+
15
+ import threading
16
+ from abc import ABC, abstractmethod
17
+ from typing import Dict, List, Optional, Any, Tuple
18
+
19
+ from ..contracts import (
20
+ IRuntime,
21
+ )
22
+
23
+
24
+ # =============================================================================
25
+ # ABSTRACT RUNTIME (Unified - Merges all runtime services)
26
+ # =============================================================================
27
+
28
+ class ARuntimeHelper(IRuntime, ABC):
29
+ """
30
+ Unified abstract base for runtime services.
31
+
32
+ Merges functionality from all runtime service interfaces.
33
+ Provides runtime services for state management, learning, monitoring, and caching.
34
+
35
+ This abstract class combines:
36
+ - State management (persistent state for lazy installation)
37
+ - Adaptive learning (learning import patterns and optimizing loading)
38
+ - Intelligent selection (selecting optimal modes based on load characteristics)
39
+ - Metrics collection (collecting and aggregating performance metrics)
40
+ - Performance monitoring (monitoring lazy loading performance)
41
+ - Multi-tier caching (L1/L2/L3 caching)
42
+ - Registry (managing instances by key)
43
+ """
44
+
45
+ __slots__ = (
46
+ # From IStateManager
47
+ '_manual_state', '_auto_state',
48
+ # From IMetricsCollector
49
+ '_metrics',
50
+ # From IPerformanceMonitor
51
+ '_load_times', '_access_counts',
52
+ # From IMultiTierCache
53
+ '_l1_cache', '_l2_cache', '_l3_cache',
54
+ # From IRegistry
55
+ '_registry',
56
+ # Common
57
+ '_lock'
58
+ )
59
+
60
+ def __init__(self):
61
+ """Initialize unified runtime services."""
62
+ # From IStateManager
63
+ self._manual_state: Optional[bool] = None
64
+ self._auto_state: Optional[bool] = None
65
+
66
+ # From IMetricsCollector
67
+ self._metrics: Dict[str, List[float]] = {}
68
+
69
+ # From IPerformanceMonitor
70
+ self._load_times: Dict[str, List[float]] = {}
71
+ self._access_counts: Dict[str, int] = {}
72
+
73
+ # From IMultiTierCache
74
+ self._l1_cache: Dict[str, Any] = {}
75
+ self._l2_cache: Dict[str, Any] = {}
76
+ self._l3_cache: Dict[str, Any] = {}
77
+
78
+ # From IRegistry
79
+ self._registry: Dict[str, Any] = {}
80
+
81
+ # Common
82
+ self._lock = threading.RLock()
83
+
84
+ # ========================================================================
85
+ # State Management Methods (from IStateManager)
86
+ # ========================================================================
87
+
88
+ def get_manual_state(self) -> Optional[bool]:
89
+ """Get manual state override (from IStateManager)."""
90
+ return self._manual_state
91
+
92
+ def set_manual_state(self, value: Optional[bool]) -> None:
93
+ """Set manual state override (from IStateManager)."""
94
+ with self._lock:
95
+ self._manual_state = value
96
+
97
+ def get_cached_auto_state(self) -> Optional[bool]:
98
+ """Get cached auto-detected state (from IStateManager)."""
99
+ return self._auto_state
100
+
101
+ def set_auto_state(self, value: Optional[bool]) -> None:
102
+ """Set cached auto-detected state (from IStateManager)."""
103
+ with self._lock:
104
+ self._auto_state = value
105
+
106
+ # ========================================================================
107
+ # Adaptive Learning Methods (from IAdaptiveLearner)
108
+ # ========================================================================
109
+
110
+ @abstractmethod
111
+ def record_import(self, module_name: str, import_time: float) -> None:
112
+ """Record an import event (from IAdaptiveLearner)."""
113
+ pass
114
+
115
+ @abstractmethod
116
+ def predict_next_imports(self, current_module: str, count: int = 3) -> List[str]:
117
+ """Predict next likely imports based on patterns (from IAdaptiveLearner)."""
118
+ pass
119
+
120
+ @abstractmethod
121
+ def get_module_score(self, module_name: str) -> float:
122
+ """Get priority score for a module (from IAdaptiveLearner)."""
123
+ pass
124
+
125
+ # ========================================================================
126
+ # Intelligent Selection Methods (from IIntelligentSelector)
127
+ # ========================================================================
128
+
129
+ @abstractmethod
130
+ def detect_load_level(
131
+ self,
132
+ module_count: int = 0,
133
+ total_import_time: float = 0.0,
134
+ import_count: int = 0,
135
+ memory_usage_mb: float = 0.0
136
+ ) -> Any:
137
+ """Detect current load level (from IIntelligentSelector)."""
138
+ pass
139
+
140
+ @abstractmethod
141
+ def get_optimal_mode(self, load_level: Any) -> Tuple[Any, Any]:
142
+ """Get optimal mode for a load level (from IIntelligentSelector)."""
143
+ pass
144
+
145
+ @abstractmethod
146
+ def update_mode_map(self, mode_map: Dict[Any, Tuple[Any, Any]]) -> None:
147
+ """Update mode mapping with benchmark results (from IIntelligentSelector)."""
148
+ pass
149
+
150
+ # ========================================================================
151
+ # Metrics Collection Methods (from IMetricsCollector)
152
+ # ========================================================================
153
+
154
+ def record_metric(self, name: str, value: float, timestamp: Optional[Any] = None) -> None:
155
+ """Record a metric value (from IMetricsCollector)."""
156
+ with self._lock:
157
+ if name not in self._metrics:
158
+ self._metrics[name] = []
159
+ self._metrics[name].append(value)
160
+
161
+ @abstractmethod
162
+ def get_metric_stats(self, name: str) -> Dict[str, Any]:
163
+ """Get statistics for a metric (from IMetricsCollector)."""
164
+ pass
165
+
166
+ @abstractmethod
167
+ def get_all_stats(self) -> Dict[str, Dict[str, Any]]:
168
+ """Get statistics for all metrics (from IMetricsCollector)."""
169
+ pass
170
+
171
+ def clear_metrics(self) -> None:
172
+ """Clear all collected metrics (from IMetricsCollector)."""
173
+ with self._lock:
174
+ self._metrics.clear()
175
+
176
+ # ========================================================================
177
+ # Performance Monitoring Methods (from IPerformanceMonitor)
178
+ # ========================================================================
179
+
180
+ def record_load_time(self, module: str, load_time: float) -> None:
181
+ """Record module load time (from IPerformanceMonitor)."""
182
+ with self._lock:
183
+ if module not in self._load_times:
184
+ self._load_times[module] = []
185
+ self._load_times[module].append(load_time)
186
+
187
+ def record_access(self, module: str) -> None:
188
+ """Record module access (from IPerformanceMonitor)."""
189
+ with self._lock:
190
+ self._access_counts[module] = self._access_counts.get(module, 0) + 1
191
+
192
+ @abstractmethod
193
+ def get_performance_stats(self) -> Dict[str, Any]:
194
+ """Get performance statistics (from IPerformanceMonitor)."""
195
+ pass
196
+
197
+ # ========================================================================
198
+ # Multi-Tier Cache Methods (from IMultiTierCache)
199
+ # ========================================================================
200
+
201
+ def get_multi_tier_cached(self, key: str) -> Optional[Any]:
202
+ """Get value from cache (L1 -> L2 -> L3) (from IMultiTierCache)."""
203
+ with self._lock:
204
+ # Check L1 first
205
+ if key in self._l1_cache:
206
+ return self._l1_cache[key]
207
+ # Check L2
208
+ if key in self._l2_cache:
209
+ value = self._l2_cache[key]
210
+ # Promote to L1
211
+ self._l1_cache[key] = value
212
+ return value
213
+ # Check L3
214
+ if key in self._l3_cache:
215
+ value = self._l3_cache[key]
216
+ # Promote to L2
217
+ self._l2_cache[key] = value
218
+ return value
219
+ return None
220
+
221
+ def set_multi_tier_cached(self, key: str, value: Any) -> None:
222
+ """Set value in cache (L1 and L2) (from IMultiTierCache)."""
223
+ with self._lock:
224
+ self._l1_cache[key] = value
225
+ self._l2_cache[key] = value
226
+
227
+ def clear_multi_tier_cache(self) -> None:
228
+ """Clear all cache tiers (from IMultiTierCache)."""
229
+ with self._lock:
230
+ self._l1_cache.clear()
231
+ self._l2_cache.clear()
232
+ self._l3_cache.clear()
233
+
234
+ @abstractmethod
235
+ def shutdown_multi_tier_cache(self) -> None:
236
+ """Shutdown cache (flush L2, cleanup threads) (from IMultiTierCache)."""
237
+ pass
238
+
239
+ # Alias method for backward compatibility
240
+ def shutdown_cache(self) -> None:
241
+ """Alias for shutdown_multi_tier_cache (backward compatibility)."""
242
+ self.shutdown_multi_tier_cache()
243
+
244
+ # ========================================================================
245
+ # Registry Methods (from IRegistry)
246
+ # ========================================================================
247
+
248
+ def get_instance(self, key: str) -> Any:
249
+ """Get instance by key (from IRegistry)."""
250
+ with self._lock:
251
+ return self._registry.get(key)
252
+
253
+ def register(self, key: str, instance: Any) -> None:
254
+ """Register an instance (from IRegistry)."""
255
+ with self._lock:
256
+ self._registry[key] = instance
257
+
258
+ def unregister(self, key: str) -> None:
259
+ """Unregister an instance (from IRegistry)."""
260
+ with self._lock:
261
+ self._registry.pop(key, None)
262
+
263
+ def has_key(self, key: str) -> bool:
264
+ """Check if key is registered (from IRegistry)."""
265
+ with self._lock:
266
+ return key in self._registry
267
+
268
+
269
+ # =============================================================================
270
+ # EXPORT ALL
271
+ # =============================================================================
272
+
273
+ __all__ = [
274
+ 'ARuntimeHelper',
275
+ ]
276
+
@@ -0,0 +1,95 @@
1
+ """
2
+ Runtime Services Facade
3
+
4
+ Main facade: XWRuntimeHelper extends ARuntimeHelper
5
+ Provides concrete implementation for all runtime services.
6
+ """
7
+
8
+ from typing import Dict, List, Optional, Tuple, Any
9
+ from .base import ARuntimeHelper
10
+ from ..defs import LazyLoadMode, LazyInstallMode
11
+
12
+
13
+ class XWRuntimeHelper(ARuntimeHelper):
14
+ """
15
+ Concrete implementation of ARuntimeHelper.
16
+
17
+ Provides runtime services for state management, learning, monitoring, and caching.
18
+ """
19
+
20
+ def __init__(self):
21
+ """Initialize XW runtime services."""
22
+ super().__init__()
23
+
24
+ # Abstract methods from ARuntime that need implementation
25
+ def record_import(self, module_name: str, import_time: float) -> None:
26
+ """Record an import event."""
27
+ # TODO: Implement import recording
28
+ pass
29
+
30
+ def predict_next_imports(self, current_module: str, count: int = 3) -> List[str]:
31
+ """Predict next likely imports based on patterns."""
32
+ # TODO: Implement prediction logic
33
+ return []
34
+
35
+ def get_module_score(self, module_name: str) -> float:
36
+ """Get priority score for a module."""
37
+ # TODO: Implement scoring logic
38
+ return 0.0
39
+
40
+ def detect_load_level(
41
+ self,
42
+ module_count: int = 0,
43
+ total_import_time: float = 0.0,
44
+ import_count: int = 0,
45
+ memory_usage_mb: float = 0.0
46
+ ):
47
+ """Detect current load level."""
48
+ # TODO: Implement load level detection
49
+ from .intelligent_selector import LoadLevel
50
+ return LoadLevel.LIGHT
51
+
52
+ def get_optimal_mode(self, load_level) -> Tuple[LazyLoadMode, LazyInstallMode]:
53
+ """Get optimal mode for a load level."""
54
+ # TODO: Implement mode selection
55
+ return LazyLoadMode.AUTO, LazyInstallMode.SMART
56
+
57
+ def update_mode_map(self, mode_map: Dict[Any, Tuple[LazyLoadMode, LazyInstallMode]]) -> None:
58
+ """Update mode mapping with benchmark results."""
59
+ # TODO: Implement mode map update
60
+ pass
61
+
62
+ def get_metric_stats(self, name: str) -> Dict[str, Any]:
63
+ """Get statistics for a metric."""
64
+ with self._lock:
65
+ values = self._metrics.get(name, [])
66
+ if not values:
67
+ return {'count': 0, 'total': 0.0, 'average': 0.0, 'min': 0.0, 'max': 0.0}
68
+ return {
69
+ 'count': len(values),
70
+ 'total': sum(values),
71
+ 'average': sum(values) / len(values),
72
+ 'min': min(values),
73
+ 'max': max(values)
74
+ }
75
+
76
+ def get_all_stats(self) -> Dict[str, Dict[str, Any]]:
77
+ """Get statistics for all metrics."""
78
+ with self._lock:
79
+ return {name: self.get_metric_stats(name) for name in self._metrics.keys()}
80
+
81
+ def get_performance_stats(self) -> Dict[str, Any]:
82
+ """Get performance statistics."""
83
+ with self._lock:
84
+ return {
85
+ 'load_times': {k: {'count': len(v), 'total': sum(v), 'average': sum(v) / len(v) if v else 0.0}
86
+ for k, v in self._load_times.items()},
87
+ 'access_counts': self._access_counts.copy(),
88
+ 'memory_usage': 0.0 # TODO: Implement memory usage tracking
89
+ }
90
+
91
+ def shutdown_multi_tier_cache(self) -> None:
92
+ """Shutdown cache (flush L2, cleanup threads)."""
93
+ # TODO: Implement cache shutdown
94
+ pass
95
+
@@ -0,0 +1,173 @@
1
+ """
2
+ #exonware/xwlazy/src/exonware/xwlazy/loading/intelligent_utils.py
3
+
4
+ Intelligent mode utilities for automatic mode switching.
5
+
6
+ Company: eXonware.com
7
+ Author: Eng. Muhammad AlShehri
8
+ Email: connect@exonware.com
9
+ Version: 0.1.0.19
10
+ Generation Date: 19-Nov-2025
11
+
12
+ This module provides intelligent mode switching based on load level.
13
+ """
14
+
15
+ from typing import Dict, Tuple, Optional
16
+
17
+ from ..defs import LazyLoadMode, LazyInstallMode, LoadLevel
18
+
19
+ # Lazy import to avoid circular dependency
20
+ logger = None
21
+
22
+ def _get_logger():
23
+ """Get logger (lazy import to avoid circular dependency)."""
24
+ global logger
25
+ if logger is None:
26
+ from ..common.logger import get_logger
27
+ logger = get_logger("xwlazy.loading.intelligent")
28
+ return logger
29
+
30
+
31
+ # Optimal mode mappings based on benchmark results (updated from consistency test)
32
+ # Format: {LoadLevel: (LazyLoadMode, LazyInstallMode)}
33
+ # Updated: 2025-11-19 - Based on 20-iteration consistency test averages
34
+ # Light: ultra+full (0.568ms avg), Medium: hyperparallel+full (5.134ms avg)
35
+ # Heavy: preload+size_aware (18.475ms avg), Enterprise: preload+full (44.742ms avg)
36
+ INTELLIGENT_MODE_MAP: Dict[LoadLevel, Tuple[LazyLoadMode, LazyInstallMode]] = {
37
+ LoadLevel.LIGHT: (LazyLoadMode.ULTRA, LazyInstallMode.FULL), # Winner: 0.568ms avg (±26.1% CV)
38
+ LoadLevel.MEDIUM: (LazyLoadMode.HYPERPARALLEL, LazyInstallMode.FULL), # Winner: 5.134ms avg (±4.7% CV)
39
+ LoadLevel.HEAVY: (LazyLoadMode.PRELOAD, LazyInstallMode.SIZE_AWARE), # Winner: 18.475ms avg (±10.2% CV)
40
+ LoadLevel.ENTERPRISE: (LazyLoadMode.PRELOAD, LazyInstallMode.FULL), # Winner: 44.742ms avg (±1.5% CV)
41
+ }
42
+
43
+
44
+ class IntelligentModeSelector:
45
+ """Selects optimal mode based on current load characteristics."""
46
+
47
+ def __init__(self, mode_map: Optional[Dict[LoadLevel, Tuple[LazyLoadMode, LazyInstallMode]]] = None):
48
+ """
49
+ Initialize intelligent mode selector.
50
+
51
+ Args:
52
+ mode_map: Custom mode mapping (defaults to INTELLIGENT_MODE_MAP)
53
+ """
54
+ self._mode_map = mode_map or INTELLIGENT_MODE_MAP.copy()
55
+ self._current_load_level: Optional[LoadLevel] = None
56
+ self._module_count = 0
57
+ self._total_import_time = 0.0
58
+ self._import_count = 0
59
+
60
+ def update_mode_map(self, mode_map: Dict[LoadLevel, Tuple[LazyLoadMode, LazyInstallMode]]) -> None:
61
+ """Update the mode mapping with benchmark results."""
62
+ self._mode_map = mode_map.copy()
63
+ _get_logger().info(f"Updated INTELLIGENT mode mapping: {mode_map}")
64
+
65
+ def detect_load_level(
66
+ self,
67
+ module_count: int = 0,
68
+ total_import_time: float = 0.0,
69
+ import_count: int = 0,
70
+ memory_usage_mb: float = 0.0
71
+ ) -> LoadLevel:
72
+ """
73
+ Detect current load level based on system characteristics.
74
+
75
+ Args:
76
+ module_count: Number of modules loaded
77
+ total_import_time: Total time spent on imports (seconds)
78
+ import_count: Number of imports performed
79
+ memory_usage_mb: Current memory usage in MB
80
+
81
+ Returns:
82
+ Detected LoadLevel
83
+ """
84
+ # Update internal state
85
+ self._module_count = module_count
86
+ self._total_import_time = total_import_time
87
+ self._import_count = import_count
88
+
89
+ # Simple heuristics based on module count and import patterns
90
+ # These thresholds can be tuned based on actual usage patterns
91
+
92
+ if import_count == 0:
93
+ # Initial state - default to light
94
+ self._current_load_level = LoadLevel.LIGHT
95
+ elif module_count < 5 and import_count < 10:
96
+ # Light load: few modules, few imports
97
+ self._current_load_level = LoadLevel.LIGHT
98
+ elif module_count < 20 and import_count < 50:
99
+ # Medium load: moderate number of modules/imports
100
+ self._current_load_level = LoadLevel.MEDIUM
101
+ elif module_count < 100 and import_count < 200:
102
+ # Heavy load: many modules, many imports
103
+ self._current_load_level = LoadLevel.HEAVY
104
+ else:
105
+ # Enterprise load: very large scale
106
+ self._current_load_level = LoadLevel.ENTERPRISE
107
+
108
+ # Override based on memory usage if significant
109
+ if memory_usage_mb > 300:
110
+ self._current_load_level = LoadLevel.ENTERPRISE
111
+ elif memory_usage_mb > 150:
112
+ self._current_load_level = LoadLevel.HEAVY
113
+
114
+ return self._current_load_level
115
+
116
+ def get_optimal_mode(self, load_level: Optional[LoadLevel] = None) -> Tuple[LazyLoadMode, LazyInstallMode]:
117
+ """
118
+ Get optimal mode combination for given load level.
119
+
120
+ Args:
121
+ load_level: Load level (if None, uses detected level)
122
+
123
+ Returns:
124
+ Tuple of (LazyLoadMode, LazyInstallMode)
125
+ """
126
+ if load_level is None:
127
+ load_level = self._current_load_level or LoadLevel.LIGHT
128
+
129
+ optimal = self._mode_map.get(load_level)
130
+ if optimal is None:
131
+ # Fallback to default
132
+ _get_logger().warning(f"No optimal mode found for {load_level}, using default")
133
+ optimal = (LazyLoadMode.AUTO, LazyInstallMode.SMART)
134
+
135
+ return optimal
136
+
137
+ def should_switch_mode(
138
+ self,
139
+ current_mode: Tuple[LazyLoadMode, LazyInstallMode],
140
+ detected_level: LoadLevel
141
+ ) -> bool:
142
+ """
143
+ Determine if mode should be switched based on detected load level.
144
+
145
+ Args:
146
+ current_mode: Current (load_mode, install_mode) tuple
147
+ detected_level: Detected load level
148
+
149
+ Returns:
150
+ True if mode should be switched
151
+ """
152
+ optimal_mode = self.get_optimal_mode(detected_level)
153
+ return current_mode != optimal_mode
154
+
155
+ def get_stats(self) -> Dict:
156
+ """Get intelligent mode statistics."""
157
+ return {
158
+ 'current_load_level': self._current_load_level.value if self._current_load_level else None,
159
+ 'module_count': self._module_count,
160
+ 'import_count': self._import_count,
161
+ 'total_import_time': self._total_import_time,
162
+ 'mode_map': {
163
+ level.value: {
164
+ 'load_mode': mode[0].value,
165
+ 'install_mode': mode[1].value
166
+ }
167
+ for level, mode in self._mode_map.items()
168
+ }
169
+ }
170
+
171
+
172
+ __all__ = ['LoadLevel', 'INTELLIGENT_MODE_MAP', 'IntelligentModeSelector']
173
+
@@ -0,0 +1,64 @@
1
+ """
2
+ Performance metrics tracking for lazy loading system.
3
+
4
+ This module provides utilities for tracking and aggregating performance metrics.
5
+ """
6
+
7
+ from typing import Dict, Any, List, Optional
8
+ from datetime import datetime
9
+ from collections import defaultdict
10
+
11
+
12
+ class MetricsCollector:
13
+ """Collects and aggregates performance metrics."""
14
+
15
+ def __init__(self):
16
+ """Initialize metrics collector."""
17
+ self._metrics: Dict[str, List[float]] = defaultdict(list)
18
+ self._counts: Dict[str, int] = defaultdict(int)
19
+ self._timestamps: Dict[str, List[datetime]] = defaultdict(list)
20
+
21
+ def record_metric(self, name: str, value: float, timestamp: Optional[datetime] = None) -> None:
22
+ """Record a metric value."""
23
+ self._metrics[name].append(value)
24
+ self._counts[name] += 1
25
+ if timestamp is None:
26
+ timestamp = datetime.now()
27
+ self._timestamps[name].append(timestamp)
28
+
29
+ def get_metric_stats(self, name: str) -> Dict[str, Any]:
30
+ """Get statistics for a specific metric."""
31
+ values = self._metrics.get(name, [])
32
+ if not values:
33
+ return {}
34
+
35
+ return {
36
+ 'count': len(values),
37
+ 'total': sum(values),
38
+ 'average': sum(values) / len(values),
39
+ 'min': min(values),
40
+ 'max': max(values),
41
+ }
42
+
43
+ def get_all_stats(self) -> Dict[str, Dict[str, Any]]:
44
+ """Get statistics for all metrics."""
45
+ return {name: self.get_metric_stats(name) for name in self._metrics.keys()}
46
+
47
+ def clear(self) -> None:
48
+ """Clear all collected metrics."""
49
+ self._metrics.clear()
50
+ self._counts.clear()
51
+ self._timestamps.clear()
52
+
53
+
54
+ # Global metrics collector instance
55
+ _global_metrics = MetricsCollector()
56
+
57
+
58
+ def get_metrics_collector() -> MetricsCollector:
59
+ """Get the global metrics collector instance."""
60
+ return _global_metrics
61
+
62
+
63
+ __all__ = ['MetricsCollector', 'get_metrics_collector']
64
+
@@ -0,0 +1,39 @@
1
+ """
2
+ Performance monitoring for lazy loading system.
3
+
4
+ This module contains LazyPerformanceMonitor extracted from lazy_core.py Section 4.
5
+ """
6
+
7
+ from typing import Dict, Any
8
+
9
+
10
+ class LazyPerformanceMonitor:
11
+ """Performance monitor for lazy loading operations."""
12
+
13
+ __slots__ = ('_load_times', '_access_counts', '_memory_usage')
14
+
15
+ def __init__(self):
16
+ """Initialize performance monitor."""
17
+ self._load_times: Dict[str, float] = {}
18
+ self._access_counts: Dict[str, int] = {}
19
+ self._memory_usage: Dict[str, Any] = {}
20
+
21
+ def record_load_time(self, module: str, load_time: float) -> None:
22
+ """Record module load time."""
23
+ self._load_times[module] = load_time
24
+
25
+ def record_access(self, module: str) -> None:
26
+ """Record module access."""
27
+ self._access_counts[module] = self._access_counts.get(module, 0) + 1
28
+
29
+ def get_stats(self) -> Dict[str, Any]:
30
+ """Get performance statistics."""
31
+ return {
32
+ 'load_times': self._load_times.copy(),
33
+ 'access_counts': self._access_counts.copy(),
34
+ 'memory_usage': self._memory_usage.copy()
35
+ }
36
+
37
+
38
+ __all__ = ['LazyPerformanceMonitor']
39
+
@@ -14,13 +14,13 @@ All version references should import from this module to ensure consistency.
14
14
  # =============================================================================
15
15
 
16
16
  # Main version - update this to change version across entire project
17
- __version__ = "0.1.0.16"
17
+ __version__ = "0.1.0.19"
18
18
 
19
19
  # Version components for programmatic access
20
20
  VERSION_MAJOR = 0
21
21
  VERSION_MINOR = 1
22
22
  VERSION_PATCH = 0
23
- VERSION_BUILD = 16 # Set to None for releases, or build number for dev builds
23
+ VERSION_BUILD = 19 # Set to None for releases, or build number for dev builds
24
24
 
25
25
  # Version metadata
26
26
  VERSION_SUFFIX = "" # e.g., "dev", "alpha", "beta", "rc1"