aiecs 1.5.1__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 (302) hide show
  1. aiecs/__init__.py +72 -0
  2. aiecs/__main__.py +41 -0
  3. aiecs/aiecs_client.py +469 -0
  4. aiecs/application/__init__.py +10 -0
  5. aiecs/application/executors/__init__.py +10 -0
  6. aiecs/application/executors/operation_executor.py +363 -0
  7. aiecs/application/knowledge_graph/__init__.py +7 -0
  8. aiecs/application/knowledge_graph/builder/__init__.py +37 -0
  9. aiecs/application/knowledge_graph/builder/document_builder.py +375 -0
  10. aiecs/application/knowledge_graph/builder/graph_builder.py +356 -0
  11. aiecs/application/knowledge_graph/builder/schema_mapping.py +531 -0
  12. aiecs/application/knowledge_graph/builder/structured_pipeline.py +443 -0
  13. aiecs/application/knowledge_graph/builder/text_chunker.py +319 -0
  14. aiecs/application/knowledge_graph/extractors/__init__.py +27 -0
  15. aiecs/application/knowledge_graph/extractors/base.py +100 -0
  16. aiecs/application/knowledge_graph/extractors/llm_entity_extractor.py +327 -0
  17. aiecs/application/knowledge_graph/extractors/llm_relation_extractor.py +349 -0
  18. aiecs/application/knowledge_graph/extractors/ner_entity_extractor.py +244 -0
  19. aiecs/application/knowledge_graph/fusion/__init__.py +23 -0
  20. aiecs/application/knowledge_graph/fusion/entity_deduplicator.py +387 -0
  21. aiecs/application/knowledge_graph/fusion/entity_linker.py +343 -0
  22. aiecs/application/knowledge_graph/fusion/knowledge_fusion.py +580 -0
  23. aiecs/application/knowledge_graph/fusion/relation_deduplicator.py +189 -0
  24. aiecs/application/knowledge_graph/pattern_matching/__init__.py +21 -0
  25. aiecs/application/knowledge_graph/pattern_matching/pattern_matcher.py +344 -0
  26. aiecs/application/knowledge_graph/pattern_matching/query_executor.py +378 -0
  27. aiecs/application/knowledge_graph/profiling/__init__.py +12 -0
  28. aiecs/application/knowledge_graph/profiling/query_plan_visualizer.py +199 -0
  29. aiecs/application/knowledge_graph/profiling/query_profiler.py +223 -0
  30. aiecs/application/knowledge_graph/reasoning/__init__.py +27 -0
  31. aiecs/application/knowledge_graph/reasoning/evidence_synthesis.py +347 -0
  32. aiecs/application/knowledge_graph/reasoning/inference_engine.py +504 -0
  33. aiecs/application/knowledge_graph/reasoning/logic_form_parser.py +167 -0
  34. aiecs/application/knowledge_graph/reasoning/logic_parser/__init__.py +79 -0
  35. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_builder.py +513 -0
  36. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_nodes.py +630 -0
  37. aiecs/application/knowledge_graph/reasoning/logic_parser/ast_validator.py +654 -0
  38. aiecs/application/knowledge_graph/reasoning/logic_parser/error_handler.py +477 -0
  39. aiecs/application/knowledge_graph/reasoning/logic_parser/parser.py +390 -0
  40. aiecs/application/knowledge_graph/reasoning/logic_parser/query_context.py +217 -0
  41. aiecs/application/knowledge_graph/reasoning/logic_query_integration.py +169 -0
  42. aiecs/application/knowledge_graph/reasoning/query_planner.py +872 -0
  43. aiecs/application/knowledge_graph/reasoning/reasoning_engine.py +554 -0
  44. aiecs/application/knowledge_graph/retrieval/__init__.py +19 -0
  45. aiecs/application/knowledge_graph/retrieval/retrieval_strategies.py +596 -0
  46. aiecs/application/knowledge_graph/search/__init__.py +59 -0
  47. aiecs/application/knowledge_graph/search/hybrid_search.py +423 -0
  48. aiecs/application/knowledge_graph/search/reranker.py +295 -0
  49. aiecs/application/knowledge_graph/search/reranker_strategies.py +553 -0
  50. aiecs/application/knowledge_graph/search/text_similarity.py +398 -0
  51. aiecs/application/knowledge_graph/traversal/__init__.py +15 -0
  52. aiecs/application/knowledge_graph/traversal/enhanced_traversal.py +329 -0
  53. aiecs/application/knowledge_graph/traversal/path_scorer.py +269 -0
  54. aiecs/application/knowledge_graph/validators/__init__.py +13 -0
  55. aiecs/application/knowledge_graph/validators/relation_validator.py +189 -0
  56. aiecs/application/knowledge_graph/visualization/__init__.py +11 -0
  57. aiecs/application/knowledge_graph/visualization/graph_visualizer.py +321 -0
  58. aiecs/common/__init__.py +9 -0
  59. aiecs/common/knowledge_graph/__init__.py +17 -0
  60. aiecs/common/knowledge_graph/runnable.py +484 -0
  61. aiecs/config/__init__.py +16 -0
  62. aiecs/config/config.py +498 -0
  63. aiecs/config/graph_config.py +137 -0
  64. aiecs/config/registry.py +23 -0
  65. aiecs/core/__init__.py +46 -0
  66. aiecs/core/interface/__init__.py +34 -0
  67. aiecs/core/interface/execution_interface.py +152 -0
  68. aiecs/core/interface/storage_interface.py +171 -0
  69. aiecs/domain/__init__.py +289 -0
  70. aiecs/domain/agent/__init__.py +189 -0
  71. aiecs/domain/agent/base_agent.py +697 -0
  72. aiecs/domain/agent/exceptions.py +103 -0
  73. aiecs/domain/agent/graph_aware_mixin.py +559 -0
  74. aiecs/domain/agent/hybrid_agent.py +490 -0
  75. aiecs/domain/agent/integration/__init__.py +26 -0
  76. aiecs/domain/agent/integration/context_compressor.py +222 -0
  77. aiecs/domain/agent/integration/context_engine_adapter.py +252 -0
  78. aiecs/domain/agent/integration/retry_policy.py +219 -0
  79. aiecs/domain/agent/integration/role_config.py +213 -0
  80. aiecs/domain/agent/knowledge_aware_agent.py +646 -0
  81. aiecs/domain/agent/lifecycle.py +296 -0
  82. aiecs/domain/agent/llm_agent.py +300 -0
  83. aiecs/domain/agent/memory/__init__.py +12 -0
  84. aiecs/domain/agent/memory/conversation.py +197 -0
  85. aiecs/domain/agent/migration/__init__.py +14 -0
  86. aiecs/domain/agent/migration/conversion.py +160 -0
  87. aiecs/domain/agent/migration/legacy_wrapper.py +90 -0
  88. aiecs/domain/agent/models.py +317 -0
  89. aiecs/domain/agent/observability.py +407 -0
  90. aiecs/domain/agent/persistence.py +289 -0
  91. aiecs/domain/agent/prompts/__init__.py +29 -0
  92. aiecs/domain/agent/prompts/builder.py +161 -0
  93. aiecs/domain/agent/prompts/formatters.py +189 -0
  94. aiecs/domain/agent/prompts/template.py +255 -0
  95. aiecs/domain/agent/registry.py +260 -0
  96. aiecs/domain/agent/tool_agent.py +257 -0
  97. aiecs/domain/agent/tools/__init__.py +12 -0
  98. aiecs/domain/agent/tools/schema_generator.py +221 -0
  99. aiecs/domain/community/__init__.py +155 -0
  100. aiecs/domain/community/agent_adapter.py +477 -0
  101. aiecs/domain/community/analytics.py +481 -0
  102. aiecs/domain/community/collaborative_workflow.py +642 -0
  103. aiecs/domain/community/communication_hub.py +645 -0
  104. aiecs/domain/community/community_builder.py +320 -0
  105. aiecs/domain/community/community_integration.py +800 -0
  106. aiecs/domain/community/community_manager.py +813 -0
  107. aiecs/domain/community/decision_engine.py +879 -0
  108. aiecs/domain/community/exceptions.py +225 -0
  109. aiecs/domain/community/models/__init__.py +33 -0
  110. aiecs/domain/community/models/community_models.py +268 -0
  111. aiecs/domain/community/resource_manager.py +457 -0
  112. aiecs/domain/community/shared_context_manager.py +603 -0
  113. aiecs/domain/context/__init__.py +58 -0
  114. aiecs/domain/context/context_engine.py +989 -0
  115. aiecs/domain/context/conversation_models.py +354 -0
  116. aiecs/domain/context/graph_memory.py +467 -0
  117. aiecs/domain/execution/__init__.py +12 -0
  118. aiecs/domain/execution/model.py +57 -0
  119. aiecs/domain/knowledge_graph/__init__.py +19 -0
  120. aiecs/domain/knowledge_graph/models/__init__.py +52 -0
  121. aiecs/domain/knowledge_graph/models/entity.py +130 -0
  122. aiecs/domain/knowledge_graph/models/evidence.py +194 -0
  123. aiecs/domain/knowledge_graph/models/inference_rule.py +186 -0
  124. aiecs/domain/knowledge_graph/models/path.py +179 -0
  125. aiecs/domain/knowledge_graph/models/path_pattern.py +173 -0
  126. aiecs/domain/knowledge_graph/models/query.py +272 -0
  127. aiecs/domain/knowledge_graph/models/query_plan.py +187 -0
  128. aiecs/domain/knowledge_graph/models/relation.py +136 -0
  129. aiecs/domain/knowledge_graph/schema/__init__.py +23 -0
  130. aiecs/domain/knowledge_graph/schema/entity_type.py +135 -0
  131. aiecs/domain/knowledge_graph/schema/graph_schema.py +271 -0
  132. aiecs/domain/knowledge_graph/schema/property_schema.py +155 -0
  133. aiecs/domain/knowledge_graph/schema/relation_type.py +171 -0
  134. aiecs/domain/knowledge_graph/schema/schema_manager.py +496 -0
  135. aiecs/domain/knowledge_graph/schema/type_enums.py +205 -0
  136. aiecs/domain/task/__init__.py +13 -0
  137. aiecs/domain/task/dsl_processor.py +613 -0
  138. aiecs/domain/task/model.py +62 -0
  139. aiecs/domain/task/task_context.py +268 -0
  140. aiecs/infrastructure/__init__.py +24 -0
  141. aiecs/infrastructure/graph_storage/__init__.py +11 -0
  142. aiecs/infrastructure/graph_storage/base.py +601 -0
  143. aiecs/infrastructure/graph_storage/batch_operations.py +449 -0
  144. aiecs/infrastructure/graph_storage/cache.py +429 -0
  145. aiecs/infrastructure/graph_storage/distributed.py +226 -0
  146. aiecs/infrastructure/graph_storage/error_handling.py +390 -0
  147. aiecs/infrastructure/graph_storage/graceful_degradation.py +306 -0
  148. aiecs/infrastructure/graph_storage/health_checks.py +378 -0
  149. aiecs/infrastructure/graph_storage/in_memory.py +514 -0
  150. aiecs/infrastructure/graph_storage/index_optimization.py +483 -0
  151. aiecs/infrastructure/graph_storage/lazy_loading.py +410 -0
  152. aiecs/infrastructure/graph_storage/metrics.py +357 -0
  153. aiecs/infrastructure/graph_storage/migration.py +413 -0
  154. aiecs/infrastructure/graph_storage/pagination.py +471 -0
  155. aiecs/infrastructure/graph_storage/performance_monitoring.py +466 -0
  156. aiecs/infrastructure/graph_storage/postgres.py +871 -0
  157. aiecs/infrastructure/graph_storage/query_optimizer.py +635 -0
  158. aiecs/infrastructure/graph_storage/schema_cache.py +290 -0
  159. aiecs/infrastructure/graph_storage/sqlite.py +623 -0
  160. aiecs/infrastructure/graph_storage/streaming.py +495 -0
  161. aiecs/infrastructure/messaging/__init__.py +13 -0
  162. aiecs/infrastructure/messaging/celery_task_manager.py +383 -0
  163. aiecs/infrastructure/messaging/websocket_manager.py +298 -0
  164. aiecs/infrastructure/monitoring/__init__.py +34 -0
  165. aiecs/infrastructure/monitoring/executor_metrics.py +174 -0
  166. aiecs/infrastructure/monitoring/global_metrics_manager.py +213 -0
  167. aiecs/infrastructure/monitoring/structured_logger.py +48 -0
  168. aiecs/infrastructure/monitoring/tracing_manager.py +410 -0
  169. aiecs/infrastructure/persistence/__init__.py +24 -0
  170. aiecs/infrastructure/persistence/context_engine_client.py +187 -0
  171. aiecs/infrastructure/persistence/database_manager.py +333 -0
  172. aiecs/infrastructure/persistence/file_storage.py +754 -0
  173. aiecs/infrastructure/persistence/redis_client.py +220 -0
  174. aiecs/llm/__init__.py +86 -0
  175. aiecs/llm/callbacks/__init__.py +11 -0
  176. aiecs/llm/callbacks/custom_callbacks.py +264 -0
  177. aiecs/llm/client_factory.py +420 -0
  178. aiecs/llm/clients/__init__.py +33 -0
  179. aiecs/llm/clients/base_client.py +193 -0
  180. aiecs/llm/clients/googleai_client.py +181 -0
  181. aiecs/llm/clients/openai_client.py +131 -0
  182. aiecs/llm/clients/vertex_client.py +437 -0
  183. aiecs/llm/clients/xai_client.py +184 -0
  184. aiecs/llm/config/__init__.py +51 -0
  185. aiecs/llm/config/config_loader.py +275 -0
  186. aiecs/llm/config/config_validator.py +236 -0
  187. aiecs/llm/config/model_config.py +151 -0
  188. aiecs/llm/utils/__init__.py +10 -0
  189. aiecs/llm/utils/validate_config.py +91 -0
  190. aiecs/main.py +363 -0
  191. aiecs/scripts/__init__.py +3 -0
  192. aiecs/scripts/aid/VERSION_MANAGEMENT.md +97 -0
  193. aiecs/scripts/aid/__init__.py +19 -0
  194. aiecs/scripts/aid/version_manager.py +215 -0
  195. aiecs/scripts/dependance_check/DEPENDENCY_SYSTEM_SUMMARY.md +242 -0
  196. aiecs/scripts/dependance_check/README_DEPENDENCY_CHECKER.md +310 -0
  197. aiecs/scripts/dependance_check/__init__.py +17 -0
  198. aiecs/scripts/dependance_check/dependency_checker.py +938 -0
  199. aiecs/scripts/dependance_check/dependency_fixer.py +391 -0
  200. aiecs/scripts/dependance_check/download_nlp_data.py +396 -0
  201. aiecs/scripts/dependance_check/quick_dependency_check.py +270 -0
  202. aiecs/scripts/dependance_check/setup_nlp_data.sh +217 -0
  203. aiecs/scripts/dependance_patch/__init__.py +7 -0
  204. aiecs/scripts/dependance_patch/fix_weasel/README_WEASEL_PATCH.md +126 -0
  205. aiecs/scripts/dependance_patch/fix_weasel/__init__.py +11 -0
  206. aiecs/scripts/dependance_patch/fix_weasel/fix_weasel_validator.py +128 -0
  207. aiecs/scripts/dependance_patch/fix_weasel/fix_weasel_validator.sh +82 -0
  208. aiecs/scripts/dependance_patch/fix_weasel/patch_weasel_library.sh +188 -0
  209. aiecs/scripts/dependance_patch/fix_weasel/run_weasel_patch.sh +41 -0
  210. aiecs/scripts/tools_develop/README.md +449 -0
  211. aiecs/scripts/tools_develop/TOOL_AUTO_DISCOVERY.md +234 -0
  212. aiecs/scripts/tools_develop/__init__.py +21 -0
  213. aiecs/scripts/tools_develop/check_type_annotations.py +259 -0
  214. aiecs/scripts/tools_develop/validate_tool_schemas.py +422 -0
  215. aiecs/scripts/tools_develop/verify_tools.py +356 -0
  216. aiecs/tasks/__init__.py +1 -0
  217. aiecs/tasks/worker.py +172 -0
  218. aiecs/tools/__init__.py +299 -0
  219. aiecs/tools/apisource/__init__.py +99 -0
  220. aiecs/tools/apisource/intelligence/__init__.py +19 -0
  221. aiecs/tools/apisource/intelligence/data_fusion.py +381 -0
  222. aiecs/tools/apisource/intelligence/query_analyzer.py +413 -0
  223. aiecs/tools/apisource/intelligence/search_enhancer.py +388 -0
  224. aiecs/tools/apisource/monitoring/__init__.py +9 -0
  225. aiecs/tools/apisource/monitoring/metrics.py +303 -0
  226. aiecs/tools/apisource/providers/__init__.py +115 -0
  227. aiecs/tools/apisource/providers/base.py +664 -0
  228. aiecs/tools/apisource/providers/census.py +401 -0
  229. aiecs/tools/apisource/providers/fred.py +564 -0
  230. aiecs/tools/apisource/providers/newsapi.py +412 -0
  231. aiecs/tools/apisource/providers/worldbank.py +357 -0
  232. aiecs/tools/apisource/reliability/__init__.py +12 -0
  233. aiecs/tools/apisource/reliability/error_handler.py +375 -0
  234. aiecs/tools/apisource/reliability/fallback_strategy.py +391 -0
  235. aiecs/tools/apisource/tool.py +850 -0
  236. aiecs/tools/apisource/utils/__init__.py +9 -0
  237. aiecs/tools/apisource/utils/validators.py +338 -0
  238. aiecs/tools/base_tool.py +201 -0
  239. aiecs/tools/docs/__init__.py +121 -0
  240. aiecs/tools/docs/ai_document_orchestrator.py +599 -0
  241. aiecs/tools/docs/ai_document_writer_orchestrator.py +2403 -0
  242. aiecs/tools/docs/content_insertion_tool.py +1333 -0
  243. aiecs/tools/docs/document_creator_tool.py +1317 -0
  244. aiecs/tools/docs/document_layout_tool.py +1166 -0
  245. aiecs/tools/docs/document_parser_tool.py +994 -0
  246. aiecs/tools/docs/document_writer_tool.py +1818 -0
  247. aiecs/tools/knowledge_graph/__init__.py +17 -0
  248. aiecs/tools/knowledge_graph/graph_reasoning_tool.py +734 -0
  249. aiecs/tools/knowledge_graph/graph_search_tool.py +923 -0
  250. aiecs/tools/knowledge_graph/kg_builder_tool.py +476 -0
  251. aiecs/tools/langchain_adapter.py +542 -0
  252. aiecs/tools/schema_generator.py +275 -0
  253. aiecs/tools/search_tool/__init__.py +100 -0
  254. aiecs/tools/search_tool/analyzers.py +589 -0
  255. aiecs/tools/search_tool/cache.py +260 -0
  256. aiecs/tools/search_tool/constants.py +128 -0
  257. aiecs/tools/search_tool/context.py +216 -0
  258. aiecs/tools/search_tool/core.py +749 -0
  259. aiecs/tools/search_tool/deduplicator.py +123 -0
  260. aiecs/tools/search_tool/error_handler.py +271 -0
  261. aiecs/tools/search_tool/metrics.py +371 -0
  262. aiecs/tools/search_tool/rate_limiter.py +178 -0
  263. aiecs/tools/search_tool/schemas.py +277 -0
  264. aiecs/tools/statistics/__init__.py +80 -0
  265. aiecs/tools/statistics/ai_data_analysis_orchestrator.py +643 -0
  266. aiecs/tools/statistics/ai_insight_generator_tool.py +505 -0
  267. aiecs/tools/statistics/ai_report_orchestrator_tool.py +694 -0
  268. aiecs/tools/statistics/data_loader_tool.py +564 -0
  269. aiecs/tools/statistics/data_profiler_tool.py +658 -0
  270. aiecs/tools/statistics/data_transformer_tool.py +573 -0
  271. aiecs/tools/statistics/data_visualizer_tool.py +495 -0
  272. aiecs/tools/statistics/model_trainer_tool.py +487 -0
  273. aiecs/tools/statistics/statistical_analyzer_tool.py +459 -0
  274. aiecs/tools/task_tools/__init__.py +86 -0
  275. aiecs/tools/task_tools/chart_tool.py +732 -0
  276. aiecs/tools/task_tools/classfire_tool.py +922 -0
  277. aiecs/tools/task_tools/image_tool.py +447 -0
  278. aiecs/tools/task_tools/office_tool.py +684 -0
  279. aiecs/tools/task_tools/pandas_tool.py +635 -0
  280. aiecs/tools/task_tools/report_tool.py +635 -0
  281. aiecs/tools/task_tools/research_tool.py +392 -0
  282. aiecs/tools/task_tools/scraper_tool.py +715 -0
  283. aiecs/tools/task_tools/stats_tool.py +688 -0
  284. aiecs/tools/temp_file_manager.py +130 -0
  285. aiecs/tools/tool_executor/__init__.py +37 -0
  286. aiecs/tools/tool_executor/tool_executor.py +881 -0
  287. aiecs/utils/LLM_output_structor.py +445 -0
  288. aiecs/utils/__init__.py +34 -0
  289. aiecs/utils/base_callback.py +47 -0
  290. aiecs/utils/cache_provider.py +695 -0
  291. aiecs/utils/execution_utils.py +184 -0
  292. aiecs/utils/logging.py +1 -0
  293. aiecs/utils/prompt_loader.py +14 -0
  294. aiecs/utils/token_usage_repository.py +323 -0
  295. aiecs/ws/__init__.py +0 -0
  296. aiecs/ws/socket_server.py +52 -0
  297. aiecs-1.5.1.dist-info/METADATA +608 -0
  298. aiecs-1.5.1.dist-info/RECORD +302 -0
  299. aiecs-1.5.1.dist-info/WHEEL +5 -0
  300. aiecs-1.5.1.dist-info/entry_points.txt +10 -0
  301. aiecs-1.5.1.dist-info/licenses/LICENSE +225 -0
  302. aiecs-1.5.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,378 @@
1
+ """
2
+ Health Checks for Graph Storage Backends
3
+
4
+ Provides health check endpoints and monitoring for graph storage backends,
5
+ enabling production-ready health monitoring and alerting.
6
+ """
7
+
8
+ import logging
9
+ import asyncio
10
+ from typing import Dict, Any, Optional, List
11
+ from dataclasses import dataclass
12
+ from enum import Enum
13
+ from datetime import datetime, timedelta
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class HealthStatus(str, Enum):
19
+ """Health check status"""
20
+
21
+ HEALTHY = "healthy"
22
+ DEGRADED = "degraded"
23
+ UNHEALTHY = "unhealthy"
24
+ UNKNOWN = "unknown"
25
+
26
+
27
+ @dataclass
28
+ class HealthCheckResult:
29
+ """
30
+ Result of a health check
31
+
32
+ Example:
33
+ ```python
34
+ result = HealthCheckResult(
35
+ status=HealthStatus.HEALTHY,
36
+ message="All checks passed",
37
+ response_time_ms=12.5,
38
+ details={"connection_pool": "ok", "query_test": "ok"}
39
+ )
40
+ ```
41
+ """
42
+
43
+ status: HealthStatus
44
+ message: str
45
+ response_time_ms: float = 0.0
46
+ timestamp: datetime = None
47
+ details: Dict[str, Any] = None
48
+ error: Optional[str] = None
49
+
50
+ def __post_init__(self):
51
+ if self.timestamp is None:
52
+ self.timestamp = datetime.utcnow()
53
+ if self.details is None:
54
+ self.details = {}
55
+
56
+ def to_dict(self) -> Dict[str, Any]:
57
+ """Convert to dictionary"""
58
+ return {
59
+ "status": self.status.value,
60
+ "message": self.message,
61
+ "response_time_ms": round(self.response_time_ms, 2),
62
+ "timestamp": self.timestamp.isoformat(),
63
+ "details": self.details,
64
+ "error": self.error,
65
+ }
66
+
67
+ def is_healthy(self) -> bool:
68
+ """Check if status is healthy"""
69
+ return self.status == HealthStatus.HEALTHY
70
+
71
+
72
+ class HealthChecker:
73
+ """
74
+ Health checker for graph storage backends
75
+
76
+ Performs comprehensive health checks including:
77
+ - Connection availability
78
+ - Query execution
79
+ - Response time
80
+ - Resource availability
81
+
82
+ Example:
83
+ ```python
84
+ checker = HealthChecker(store)
85
+ result = await checker.check_health()
86
+
87
+ if result.is_healthy():
88
+ print("Store is healthy")
89
+ else:
90
+ print(f"Store is {result.status}: {result.message}")
91
+ ```
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ store: Any,
97
+ timeout_seconds: float = 5.0,
98
+ query_timeout_ms: float = 1000.0,
99
+ ):
100
+ """
101
+ Initialize health checker
102
+
103
+ Args:
104
+ store: Graph store instance
105
+ timeout_seconds: Overall health check timeout
106
+ query_timeout_ms: Query execution timeout
107
+ """
108
+ self.store = store
109
+ self.timeout_seconds = timeout_seconds
110
+ self.query_timeout_ms = query_timeout_ms
111
+
112
+ async def check_health(self) -> HealthCheckResult:
113
+ """
114
+ Perform comprehensive health check
115
+
116
+ Returns:
117
+ HealthCheckResult with status and details
118
+ """
119
+ start_time = asyncio.get_event_loop().time()
120
+ details = {}
121
+ errors = []
122
+
123
+ try:
124
+ # Check 1: Store initialization
125
+ if not hasattr(self.store, "_is_initialized") or not self.store._is_initialized:
126
+ return HealthCheckResult(
127
+ status=HealthStatus.UNHEALTHY,
128
+ message="Store not initialized",
129
+ response_time_ms=0.0,
130
+ error="Store not initialized",
131
+ )
132
+ details["initialized"] = True
133
+
134
+ # Check 2: Connection availability
135
+ connection_ok = await self._check_connection()
136
+ details["connection"] = "ok" if connection_ok else "failed"
137
+ if not connection_ok:
138
+ errors.append("Connection check failed")
139
+
140
+ # Check 3: Query execution
141
+ query_ok = await self._check_query_execution()
142
+ details["query_execution"] = "ok" if query_ok else "failed"
143
+ if not query_ok:
144
+ errors.append("Query execution failed")
145
+
146
+ # Check 4: Response time
147
+ response_time = await self._check_response_time()
148
+ details["response_time_ms"] = response_time
149
+ if response_time > self.query_timeout_ms:
150
+ errors.append(f"Response time too high: {response_time}ms")
151
+
152
+ # Check 5: Resource availability (if applicable)
153
+ if hasattr(self.store, "pool"):
154
+ pool_ok = await self._check_connection_pool()
155
+ details["connection_pool"] = "ok" if pool_ok else "degraded"
156
+ if not pool_ok:
157
+ errors.append("Connection pool issues")
158
+
159
+ # Determine status
160
+ if errors:
161
+ if len(errors) >= 2:
162
+ status = HealthStatus.UNHEALTHY
163
+ else:
164
+ status = HealthStatus.DEGRADED
165
+ message = "; ".join(errors)
166
+ else:
167
+ status = HealthStatus.HEALTHY
168
+ message = "All health checks passed"
169
+
170
+ response_time_ms = (asyncio.get_event_loop().time() - start_time) * 1000
171
+
172
+ return HealthCheckResult(
173
+ status=status,
174
+ message=message,
175
+ response_time_ms=response_time_ms,
176
+ details=details,
177
+ )
178
+
179
+ except Exception as e:
180
+ response_time_ms = (asyncio.get_event_loop().time() - start_time) * 1000
181
+ logger.error(f"Health check failed: {e}", exc_info=True)
182
+
183
+ return HealthCheckResult(
184
+ status=HealthStatus.UNHEALTHY,
185
+ message=f"Health check exception: {str(e)}",
186
+ response_time_ms=response_time_ms,
187
+ error=str(e),
188
+ details=details,
189
+ )
190
+
191
+ async def _check_connection(self) -> bool:
192
+ """Check if connection is available"""
193
+ try:
194
+ # Try a simple operation
195
+ if hasattr(self.store, "get_stats"):
196
+ await asyncio.wait_for(self.store.get_stats(), timeout=self.timeout_seconds)
197
+ return True
198
+ return False
199
+ except Exception as e:
200
+ logger.debug(f"Connection check failed: {e}")
201
+ return False
202
+
203
+ async def _check_query_execution(self) -> bool:
204
+ """Check if queries can be executed"""
205
+ try:
206
+ # Try a simple query (get_stats or similar)
207
+ if hasattr(self.store, "get_stats"):
208
+ await asyncio.wait_for(self.store.get_stats(), timeout=self.timeout_seconds)
209
+ return True
210
+ return False
211
+ except Exception as e:
212
+ logger.debug(f"Query execution check failed: {e}")
213
+ return False
214
+
215
+ async def _check_response_time(self) -> float:
216
+ """Check average response time"""
217
+ try:
218
+ times = []
219
+ for _ in range(3):
220
+ start = asyncio.get_event_loop().time()
221
+ if hasattr(self.store, "get_stats"):
222
+ await self.store.get_stats()
223
+ elapsed = (asyncio.get_event_loop().time() - start) * 1000
224
+ times.append(elapsed)
225
+
226
+ return sum(times) / len(times) if times else 0.0
227
+ except Exception:
228
+ return float("inf")
229
+
230
+ async def _check_connection_pool(self) -> bool:
231
+ """Check connection pool health"""
232
+ try:
233
+ if hasattr(self.store, "pool"):
234
+ pool = self.store.pool
235
+
236
+ # Check pool size
237
+ if hasattr(pool, "get_size"):
238
+ size = pool.get_size()
239
+ free = pool.get_idle_size()
240
+
241
+ # Pool is healthy if not completely exhausted
242
+ return free > 0 or size < pool.get_max_size()
243
+
244
+ # If we can't check, assume OK
245
+ return True
246
+ return True
247
+ except Exception:
248
+ return False
249
+
250
+ async def check_liveness(self) -> bool:
251
+ """
252
+ Quick liveness check (faster than full health check)
253
+
254
+ Returns:
255
+ True if store is alive, False otherwise
256
+ """
257
+ try:
258
+ if hasattr(self.store, "get_stats"):
259
+ await asyncio.wait_for(self.store.get_stats(), timeout=1.0)
260
+ return True
261
+ return False
262
+ except Exception:
263
+ return False
264
+
265
+ async def check_readiness(self) -> bool:
266
+ """
267
+ Readiness check (can handle requests)
268
+
269
+ Returns:
270
+ True if store is ready, False otherwise
271
+ """
272
+ result = await self.check_health()
273
+ return result.status in [HealthStatus.HEALTHY, HealthStatus.DEGRADED]
274
+
275
+
276
+ class HealthMonitor:
277
+ """
278
+ Continuous health monitoring
279
+
280
+ Monitors health status over time and tracks metrics.
281
+
282
+ Example:
283
+ ```python
284
+ monitor = HealthMonitor(checker, interval_seconds=30)
285
+ await monitor.start()
286
+
287
+ # Get current status
288
+ status = monitor.get_current_status()
289
+
290
+ # Get health history
291
+ history = monitor.get_health_history()
292
+ ```
293
+ """
294
+
295
+ def __init__(self, checker: HealthChecker, interval_seconds: float = 30.0):
296
+ """
297
+ Initialize health monitor
298
+
299
+ Args:
300
+ checker: Health checker instance
301
+ interval_seconds: Check interval in seconds
302
+ """
303
+ self.checker = checker
304
+ self.interval_seconds = interval_seconds
305
+ self.health_history: List[HealthCheckResult] = []
306
+ self.max_history = 100
307
+ self._monitoring = False
308
+ self._task = None
309
+
310
+ async def start(self) -> None:
311
+ """Start continuous monitoring"""
312
+ if self._monitoring:
313
+ return
314
+
315
+ self._monitoring = True
316
+ self._task = asyncio.create_task(self._monitor_loop())
317
+ logger.info("Health monitoring started")
318
+
319
+ async def stop(self) -> None:
320
+ """Stop continuous monitoring"""
321
+ self._monitoring = False
322
+ if self._task:
323
+ self._task.cancel()
324
+ try:
325
+ await self._task
326
+ except asyncio.CancelledError:
327
+ pass
328
+ logger.info("Health monitoring stopped")
329
+
330
+ async def _monitor_loop(self) -> None:
331
+ """Monitoring loop"""
332
+ while self._monitoring:
333
+ try:
334
+ result = await self.checker.check_health()
335
+ self.health_history.append(result)
336
+
337
+ # Keep only recent history
338
+ if len(self.health_history) > self.max_history:
339
+ self.health_history.pop(0)
340
+
341
+ # Log unhealthy status
342
+ if not result.is_healthy():
343
+ logger.warning(f"Health check failed: {result.status} - {result.message}")
344
+
345
+ await asyncio.sleep(self.interval_seconds)
346
+ except asyncio.CancelledError:
347
+ break
348
+ except Exception as e:
349
+ logger.error(f"Health monitoring error: {e}", exc_info=True)
350
+ await asyncio.sleep(self.interval_seconds)
351
+
352
+ def get_current_status(self) -> Optional[HealthCheckResult]:
353
+ """Get most recent health check result"""
354
+ return self.health_history[-1] if self.health_history else None
355
+
356
+ def get_health_history(self, limit: int = 10) -> List[HealthCheckResult]:
357
+ """Get recent health check history"""
358
+ return self.health_history[-limit:]
359
+
360
+ def get_uptime_percentage(self, window_minutes: int = 60) -> float:
361
+ """
362
+ Calculate uptime percentage over time window
363
+
364
+ Args:
365
+ window_minutes: Time window in minutes
366
+
367
+ Returns:
368
+ Uptime percentage (0-100)
369
+ """
370
+ cutoff = datetime.utcnow() - timedelta(minutes=window_minutes)
371
+
372
+ recent = [r for r in self.health_history if r.timestamp >= cutoff]
373
+
374
+ if not recent:
375
+ return 0.0
376
+
377
+ healthy_count = sum(1 for r in recent if r.is_healthy())
378
+ return (healthy_count / len(recent)) * 100.0