harborrag-runtime 2.0.0__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 (271) hide show
  1. harborrag_runtime/__init__.py +22 -0
  2. harborrag_runtime/application/README.md +39 -0
  3. harborrag_runtime/application/__init__.py +39 -0
  4. harborrag_runtime/application/chat/__init__.py +7 -0
  5. harborrag_runtime/application/chat/citations.py +149 -0
  6. harborrag_runtime/application/chat/client.py +201 -0
  7. harborrag_runtime/application/chat/completion.py +92 -0
  8. harborrag_runtime/application/chat/completion_request.py +130 -0
  9. harborrag_runtime/application/chat/evidence.py +202 -0
  10. harborrag_runtime/application/chat/options.py +43 -0
  11. harborrag_runtime/application/chat/preparation.py +135 -0
  12. harborrag_runtime/application/chat/presenters.py +130 -0
  13. harborrag_runtime/application/chat/prompting.py +127 -0
  14. harborrag_runtime/application/chat/query_scope.py +146 -0
  15. harborrag_runtime/application/chat/replay.py +141 -0
  16. harborrag_runtime/application/chat/request_filters.py +134 -0
  17. harborrag_runtime/application/chat/retrieval.py +127 -0
  18. harborrag_runtime/application/chat/service.py +371 -0
  19. harborrag_runtime/application/composition/__init__.py +1 -0
  20. harborrag_runtime/application/composition/factories.py +106 -0
  21. harborrag_runtime/application/composition/resources.py +141 -0
  22. harborrag_runtime/application/composition/selection.py +65 -0
  23. harborrag_runtime/application/composition/service.py +550 -0
  24. harborrag_runtime/application/composition/tenant_models.py +45 -0
  25. harborrag_runtime/application/control_plane/__init__.py +1 -0
  26. harborrag_runtime/application/control_plane/active_runs.py +38 -0
  27. harborrag_runtime/application/control_plane/connection_models.py +109 -0
  28. harborrag_runtime/application/control_plane/connection_testing.py +91 -0
  29. harborrag_runtime/application/control_plane/connection_writes.py +227 -0
  30. harborrag_runtime/application/control_plane/connections.py +749 -0
  31. harborrag_runtime/application/control_plane/effect_recovery.py +235 -0
  32. harborrag_runtime/application/control_plane/projects.py +313 -0
  33. harborrag_runtime/application/control_plane/settings_import.py +239 -0
  34. harborrag_runtime/application/control_plane/settings_service.py +233 -0
  35. harborrag_runtime/application/control_plane/tenants.py +55 -0
  36. harborrag_runtime/application/errors.py +110 -0
  37. harborrag_runtime/application/ingestion/__init__.py +1 -0
  38. harborrag_runtime/application/ingestion/client.py +65 -0
  39. harborrag_runtime/application/ingestion/connection_sources.py +96 -0
  40. harborrag_runtime/application/ingestion/direct.py +120 -0
  41. harborrag_runtime/application/ingestion/follower.py +83 -0
  42. harborrag_runtime/application/ingestion/ports.py +174 -0
  43. harborrag_runtime/application/ingestion/progress_bridge.py +221 -0
  44. harborrag_runtime/application/ingestion/retry_selection.py +71 -0
  45. harborrag_runtime/application/ingestion/service.py +564 -0
  46. harborrag_runtime/application/ingestion/starter.py +78 -0
  47. harborrag_runtime/application/memory/__init__.py +21 -0
  48. harborrag_runtime/application/memory/client.py +114 -0
  49. harborrag_runtime/application/memory/composition.py +90 -0
  50. harborrag_runtime/application/memory/context.py +45 -0
  51. harborrag_runtime/application/memory/sessions.py +117 -0
  52. harborrag_runtime/application/ports.py +133 -0
  53. harborrag_runtime/application/retrieval/__init__.py +1 -0
  54. harborrag_runtime/application/retrieval/access.py +26 -0
  55. harborrag_runtime/application/scheduling/service.py +58 -0
  56. harborrag_runtime/application/schemas.py +15 -0
  57. harborrag_runtime/chat/README.md +40 -0
  58. harborrag_runtime/chat/__init__.py +18 -0
  59. harborrag_runtime/chat/composition.py +53 -0
  60. harborrag_runtime/chat/facade.py +46 -0
  61. harborrag_runtime/chat/service.py +183 -0
  62. harborrag_runtime/chat/tenant_clients.py +341 -0
  63. harborrag_runtime/chat/tenant_config.py +235 -0
  64. harborrag_runtime/chat/tenant_models.py +22 -0
  65. harborrag_runtime/composition/__init__.py +5 -0
  66. harborrag_runtime/composition/config_store.py +53 -0
  67. harborrag_runtime/composition/connection_removal.py +120 -0
  68. harborrag_runtime/composition/connection_stores.py +107 -0
  69. harborrag_runtime/composition/control_plane.py +401 -0
  70. harborrag_runtime/composition/mcp_auth.py +39 -0
  71. harborrag_runtime/composition/readers.py +113 -0
  72. harborrag_runtime/composition/resources.py +336 -0
  73. harborrag_runtime/composition/storage_providers.py +113 -0
  74. harborrag_runtime/config/__init__.py +84 -0
  75. harborrag_runtime/config/checkout.py +212 -0
  76. harborrag_runtime/config/chunking.py +167 -0
  77. harborrag_runtime/config/connectors/__init__.py +19 -0
  78. harborrag_runtime/config/connectors/fingerprints.py +54 -0
  79. harborrag_runtime/config/connectors/importing.py +611 -0
  80. harborrag_runtime/config/connectors/loader.py +95 -0
  81. harborrag_runtime/config/connectors/models/__init__.py +30 -0
  82. harborrag_runtime/config/connectors/models/atlassian.py +199 -0
  83. harborrag_runtime/config/connectors/models/builder.py +208 -0
  84. harborrag_runtime/config/connectors/models/common.py +45 -0
  85. harborrag_runtime/config/connectors/models/fields.py +134 -0
  86. harborrag_runtime/config/connectors/models/github.py +143 -0
  87. harborrag_runtime/config/connectors/models/local_file.py +119 -0
  88. harborrag_runtime/config/connectors/models/registry.py +149 -0
  89. harborrag_runtime/config/connectors/models/sharepoint.py +186 -0
  90. harborrag_runtime/config/connectors/models/spec.py +563 -0
  91. harborrag_runtime/config/connectors/parsing.py +275 -0
  92. harborrag_runtime/config/connectors/providers.py +177 -0
  93. harborrag_runtime/config/connectors/schemas.py +215 -0
  94. harborrag_runtime/config/errors.py +26 -0
  95. harborrag_runtime/config/graph_build.py +335 -0
  96. harborrag_runtime/config/graph_build_loading.py +38 -0
  97. harborrag_runtime/config/loading.py +245 -0
  98. harborrag_runtime/config/models.py +95 -0
  99. harborrag_runtime/config/ontology_loading.py +76 -0
  100. harborrag_runtime/config/parsers/__init__.py +19 -0
  101. harborrag_runtime/config/parsers/loader.py +85 -0
  102. harborrag_runtime/config/parsers/parsing.py +285 -0
  103. harborrag_runtime/config/parsers/providers.py +305 -0
  104. harborrag_runtime/config/parsers/schemas.py +614 -0
  105. harborrag_runtime/config/settings.py +378 -0
  106. harborrag_runtime/config/settings_document.py +133 -0
  107. harborrag_runtime/config/temporal.py +331 -0
  108. harborrag_runtime/config/temporal_loading.py +310 -0
  109. harborrag_runtime/config_store/__init__.py +5 -0
  110. harborrag_runtime/config_store/defaults.py +47 -0
  111. harborrag_runtime/config_store/provider.py +153 -0
  112. harborrag_runtime/config_store/run_settings.py +72 -0
  113. harborrag_runtime/connections/__init__.py +27 -0
  114. harborrag_runtime/connections/secrets.py +348 -0
  115. harborrag_runtime/contracts.py +237 -0
  116. harborrag_runtime/document_stage_catalog.py +82 -0
  117. harborrag_runtime/errors.py +64 -0
  118. harborrag_runtime/events/__init__.py +3 -0
  119. harborrag_runtime/events/in_process.py +100 -0
  120. harborrag_runtime/execution/__init__.py +26 -0
  121. harborrag_runtime/execution/contracts.py +32 -0
  122. harborrag_runtime/execution/direct.py +169 -0
  123. harborrag_runtime/execution/gateway.py +97 -0
  124. harborrag_runtime/execution/source_conversion.py +61 -0
  125. harborrag_runtime/execution/source_submission.py +278 -0
  126. harborrag_runtime/execution/submission.py +64 -0
  127. harborrag_runtime/execution/task_registry.py +387 -0
  128. harborrag_runtime/execution/temporal.py +165 -0
  129. harborrag_runtime/ingestion/README.md +79 -0
  130. harborrag_runtime/ingestion/__init__.py +59 -0
  131. harborrag_runtime/ingestion/chunking_profile.py +97 -0
  132. harborrag_runtime/ingestion/composition.py +279 -0
  133. harborrag_runtime/ingestion/connection_checks.py +239 -0
  134. harborrag_runtime/ingestion/connections.py +507 -0
  135. harborrag_runtime/ingestion/document/__init__.py +1 -0
  136. harborrag_runtime/ingestion/document/normalization.py +14 -0
  137. harborrag_runtime/ingestion/document/normalizers/__init__.py +9 -0
  138. harborrag_runtime/ingestion/document/normalizers/builtins.py +39 -0
  139. harborrag_runtime/ingestion/document/normalizers/transform.py +30 -0
  140. harborrag_runtime/ingestion/document/run_tools.py +152 -0
  141. harborrag_runtime/ingestion/failure_classification.py +82 -0
  142. harborrag_runtime/ingestion/field_indexes.py +56 -0
  143. harborrag_runtime/ingestion/maintenance/__init__.py +1 -0
  144. harborrag_runtime/ingestion/maintenance/connection_removal.py +115 -0
  145. harborrag_runtime/ingestion/maintenance/projection_admin.py +180 -0
  146. harborrag_runtime/ingestion/maintenance/relation_repair.py +555 -0
  147. harborrag_runtime/ingestion/maintenance/retention.py +353 -0
  148. harborrag_runtime/ingestion/observability.py +3 -0
  149. harborrag_runtime/ingestion/profiles.py +127 -0
  150. harborrag_runtime/ingestion/runtime_builder.py +339 -0
  151. harborrag_runtime/ingestion/source/__init__.py +1 -0
  152. harborrag_runtime/ingestion/source/descriptor_mapping.py +144 -0
  153. harborrag_runtime/ingestion/source/discovery.py +290 -0
  154. harborrag_runtime/ingestion/source/documents.py +184 -0
  155. harborrag_runtime/ingestion/source/finalization.py +288 -0
  156. harborrag_runtime/ingestion/source/operations.py +175 -0
  157. harborrag_runtime/ingestion/source/plan.py +413 -0
  158. harborrag_runtime/ingestion/source/retry.py +150 -0
  159. harborrag_runtime/ingestion/source/service.py +470 -0
  160. harborrag_runtime/ingestion/source/skips.py +172 -0
  161. harborrag_runtime/ingestion_contracts.py +107 -0
  162. harborrag_runtime/memory/__init__.py +81 -0
  163. harborrag_runtime/memory/access.py +47 -0
  164. harborrag_runtime/memory/administration.py +460 -0
  165. harborrag_runtime/memory/context/__init__.py +5 -0
  166. harborrag_runtime/memory/context/result.py +20 -0
  167. harborrag_runtime/memory/directory.py +166 -0
  168. harborrag_runtime/memory/erasure.py +122 -0
  169. harborrag_runtime/memory/locks.py +170 -0
  170. harborrag_runtime/memory/messages.py +202 -0
  171. harborrag_runtime/memory/presenters.py +117 -0
  172. harborrag_runtime/memory/projects.py +38 -0
  173. harborrag_runtime/memory/tiers/__init__.py +1 -0
  174. harborrag_runtime/memory/tiers/in_memory.py +491 -0
  175. harborrag_runtime/memory/titles.py +32 -0
  176. harborrag_runtime/memory/usage.py +131 -0
  177. harborrag_runtime/observability/__init__.py +1 -0
  178. harborrag_runtime/observability/connector_metrics.py +14 -0
  179. harborrag_runtime/observability/discovery_metrics.py +46 -0
  180. harborrag_runtime/observability/model.py +410 -0
  181. harborrag_runtime/observability/observability_types.py +47 -0
  182. harborrag_runtime/observability/stage_observation.py +96 -0
  183. harborrag_runtime/observability/tool_audit.py +17 -0
  184. harborrag_runtime/plugins.py +56 -0
  185. harborrag_runtime/rate_limiting.py +39 -0
  186. harborrag_runtime/reader_contracts.py +149 -0
  187. harborrag_runtime/retrieval/__init__.py +1 -0
  188. harborrag_runtime/retrieval/composition.py +174 -0
  189. harborrag_runtime/retrieval/facades.py +224 -0
  190. harborrag_runtime/scheduling/__init__.py +48 -0
  191. harborrag_runtime/scheduling/config.py +185 -0
  192. harborrag_runtime/scheduling/errors.py +37 -0
  193. harborrag_runtime/scheduling/models.py +146 -0
  194. harborrag_runtime/scheduling/service.py +297 -0
  195. harborrag_runtime/scheduling/validation.py +213 -0
  196. harborrag_runtime/sdk/__init__.py +86 -0
  197. harborrag_runtime/sdk/configuration.py +44 -0
  198. harborrag_runtime/sdk/facades.py +47 -0
  199. harborrag_runtime/sdk/runtime.py +242 -0
  200. harborrag_runtime/security/__init__.py +1 -0
  201. harborrag_runtime/security/api_key_operations.py +236 -0
  202. harborrag_runtime/serialization.py +35 -0
  203. harborrag_runtime/temporal/__init__.py +19 -0
  204. harborrag_runtime/temporal/activity_observability.py +313 -0
  205. harborrag_runtime/temporal/client.py +580 -0
  206. harborrag_runtime/temporal/connection.py +39 -0
  207. harborrag_runtime/temporal/conversion.py +147 -0
  208. harborrag_runtime/temporal/dispatch.py +38 -0
  209. harborrag_runtime/temporal/document_workflow.py +154 -0
  210. harborrag_runtime/temporal/failure_handling.py +68 -0
  211. harborrag_runtime/temporal/gateway.py +121 -0
  212. harborrag_runtime/temporal/heartbeats.py +67 -0
  213. harborrag_runtime/temporal/identity.py +14 -0
  214. harborrag_runtime/temporal/ingestion_activities.py +435 -0
  215. harborrag_runtime/temporal/maintenance_activities.py +251 -0
  216. harborrag_runtime/temporal/maintenance_schemas.py +88 -0
  217. harborrag_runtime/temporal/optional.py +19 -0
  218. harborrag_runtime/temporal/plan_resolver.py +149 -0
  219. harborrag_runtime/temporal/policies.py +18 -0
  220. harborrag_runtime/temporal/reindex_workflow.py +71 -0
  221. harborrag_runtime/temporal/retry_activities.py +147 -0
  222. harborrag_runtime/temporal/retry_workflow.py +222 -0
  223. harborrag_runtime/temporal/sandbox.py +51 -0
  224. harborrag_runtime/temporal/schedules.py +341 -0
  225. harborrag_runtime/temporal/schemas.py +482 -0
  226. harborrag_runtime/temporal/source_activities.py +590 -0
  227. harborrag_runtime/temporal/source_batch_workflow.py +226 -0
  228. harborrag_runtime/temporal/source_workflow.py +908 -0
  229. harborrag_runtime/temporal/submission.py +23 -0
  230. harborrag_runtime/temporal/worker.py +478 -0
  231. harborrag_runtime/temporal/worker_registry.py +141 -0
  232. harborrag_runtime/temporal_models.py +227 -0
  233. harborrag_runtime/testing/chat_fakes.py +309 -0
  234. harborrag_runtime/testing/chat_service_double.py +126 -0
  235. harborrag_runtime/testing/connection_fakes.py +278 -0
  236. harborrag_runtime/testing/memory_fakes.py +128 -0
  237. harborrag_runtime/topology/__init__.py +1 -0
  238. harborrag_runtime/topology/budgeted_extractor.py +110 -0
  239. harborrag_runtime/topology/chunk_runner.py +41 -0
  240. harborrag_runtime/topology/composition.py +168 -0
  241. harborrag_runtime/topology/configuration.py +126 -0
  242. harborrag_runtime/topology/contextual.py +140 -0
  243. harborrag_runtime/topology/derived.py +238 -0
  244. harborrag_runtime/topology/derived_coverage.py +5 -0
  245. harborrag_runtime/topology/derived_dispatch.py +63 -0
  246. harborrag_runtime/topology/derived_factory.py +175 -0
  247. harborrag_runtime/topology/derived_models.py +251 -0
  248. harborrag_runtime/topology/derived_projection.py +127 -0
  249. harborrag_runtime/topology/description_factory.py +81 -0
  250. harborrag_runtime/topology/embedding_profile.py +85 -0
  251. harborrag_runtime/topology/entity_summary_index.py +304 -0
  252. harborrag_runtime/topology/maintenance.py +126 -0
  253. harborrag_runtime/topology/operations.py +277 -0
  254. harborrag_runtime/topology/parent_materializer.py +167 -0
  255. harborrag_runtime/topology/run_cost.py +43 -0
  256. harborrag_runtime/topology/security_operations.py +46 -0
  257. harborrag_runtime/topology/service.py +349 -0
  258. harborrag_runtime/topology/summary_factory.py +164 -0
  259. harborrag_runtime/topology/summary_inputs.py +129 -0
  260. harborrag_runtime/topology/summary_operations.py +128 -0
  261. harborrag_runtime/topology/summary_policy.py +39 -0
  262. harborrag_runtime/topology/summary_products.py +43 -0
  263. harborrag_runtime/topology/summary_service.py +625 -0
  264. harborrag_runtime/topology/summary_worker.py +129 -0
  265. harborrag_runtime/topology/summary_workflow.py +32 -0
  266. harborrag_runtime/topology/worker.py +101 -0
  267. harborrag_runtime/topology/workflow.py +32 -0
  268. harborrag_runtime-2.0.0.dist-info/METADATA +267 -0
  269. harborrag_runtime-2.0.0.dist-info/RECORD +271 -0
  270. harborrag_runtime-2.0.0.dist-info/WHEEL +4 -0
  271. harborrag_runtime-2.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,23 @@
1
+ """Compatibility construction of Temporal-specific source workflow inputs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from harborrag_core.ingestion.run_contracts import SourceSubmission
6
+ from harborrag_runtime.config.settings import RuntimeSettings
7
+ from harborrag_runtime.execution.gateway import prepare_configured_source_submission
8
+ from harborrag_runtime.ingestion.connections import ResolvedConnection
9
+
10
+ from .gateway import to_temporal_source
11
+ from .schemas import SourceIngestionInput
12
+
13
+
14
+ def build_source_input(
15
+ settings: RuntimeSettings,
16
+ submission: SourceSubmission,
17
+ *,
18
+ connection: ResolvedConnection,
19
+ ) -> SourceIngestionInput:
20
+ """Build the Temporal workflow input for a submission and its resolved connection."""
21
+ return to_temporal_source(
22
+ prepare_configured_source_submission(settings, submission, connection=connection)
23
+ )
@@ -0,0 +1,478 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ import random
6
+ import signal
7
+ from collections.abc import Callable, Coroutine, Sequence
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from datetime import timedelta
10
+ from typing import Any
11
+
12
+ from temporalio.client import Client
13
+ from temporalio.worker import Worker
14
+
15
+ from harborrag_adapters.repositories.object_store import (
16
+ ImmutableArtifactReader,
17
+ ImmutableArtifactWriter,
18
+ )
19
+ from harborrag_core.observability.process_logging import configure_logging
20
+ from harborrag_runtime.config.graph_build import GraphBuildConfig
21
+ from harborrag_runtime.config.settings import RuntimeSettings
22
+ from harborrag_runtime.config.temporal import TemporalRuntimeConfig
23
+ from harborrag_runtime.ingestion import build_ingestion_runtime
24
+ from harborrag_runtime.topology.derived_models import RequestEmbedder
25
+ from harborrag_runtime.topology.summary_factory import SummaryRuntimeFactory
26
+ from harborrag_runtime.topology.summary_worker import serve_summaries
27
+
28
+ from .connection import connect_temporal_client
29
+ from .ingestion_activities import IngestionActivities
30
+ from .maintenance_activities import MaintenanceActivities
31
+ from .sandbox import workflow_sandbox_runner
32
+ from .schedules import TemporalScheduleBackend
33
+ from .worker_registry import (
34
+ validate_worker_registrations,
35
+ worker_registrations,
36
+ )
37
+
38
+ logger = logging.getLogger("harborrag.runtime.temporal.worker")
39
+ TASK_QUEUE_DEPTH_LOOKUP_TIMEOUT_SECONDS = 1.0
40
+ SCHEDULE_METRICS_INTERVAL_SECONDS = 30.0
41
+ FIRST_RETENTION_SWEEP_MAX_DELAY_SECONDS = 60.0
42
+
43
+
44
+ def thread_pool_size(config: TemporalRuntimeConfig) -> int:
45
+ """One thread per activity this process may run at once.
46
+
47
+ Connector loads, parsing, normalization and chunking all run through
48
+ ``asyncio.to_thread``, and a Jira load sleeps in the rate limiter while it
49
+ holds its thread. The default executor has ``cpu_count + 4`` threads (8 on
50
+ a 4-vCPU host), which caps the documents a replica can really progress at
51
+ about eight however many activity slots it has.
52
+ """
53
+
54
+ return config.worker.max_concurrent_activities * len(config.task_queues.as_tuple())
55
+
56
+
57
+ def _size_thread_pool(config: TemporalRuntimeConfig) -> None:
58
+ asyncio.get_running_loop().set_default_executor(
59
+ ThreadPoolExecutor(
60
+ max_workers=thread_pool_size(config), thread_name_prefix="harborrag-activity"
61
+ )
62
+ )
63
+
64
+
65
+ async def run_workers(
66
+ settings: RuntimeSettings,
67
+ *,
68
+ stop_event: asyncio.Event | None = None,
69
+ ) -> None:
70
+ """Run the Postgres-authoritative workflow hierarchy until shutdown."""
71
+
72
+ config = TemporalRuntimeConfig.from_settings(settings)
73
+ _size_thread_pool(config)
74
+ # Establish the control-plane dependency before opening every ingestion
75
+ # repository and connector. This fails fast during Temporal startup or
76
+ # transport errors and avoids expensive start/close churn in restart loops.
77
+ client = await connect_temporal_client(config)
78
+ runtime = build_ingestion_runtime(settings)
79
+ try:
80
+ await runtime.start()
81
+ activities = IngestionActivities(
82
+ runtime,
83
+ temporal_client=client,
84
+ telemetry=runtime.telemetry,
85
+ settings=settings,
86
+ temporal_config=config,
87
+ )
88
+ maintenance = MaintenanceActivities(
89
+ runtime,
90
+ telemetry=runtime.telemetry,
91
+ )
92
+ registrations = worker_registrations(activities, maintenance, config.task_queues)
93
+ validate_worker_registrations(registrations, config.task_queues.as_tuple())
94
+ workers = tuple(
95
+ _build_worker(
96
+ client,
97
+ config,
98
+ task_queue=task_queue,
99
+ workflows=workflows,
100
+ activities=queue_activities,
101
+ )
102
+ for task_queue, workflows, queue_activities in registrations
103
+ )
104
+ await _emit_queue_metrics(runtime.telemetry, client, config)
105
+ logger.info(
106
+ "Temporal ingestion worker polling queues: %s",
107
+ ", ".join(config.task_queues.as_tuple()),
108
+ )
109
+ summary_run = _summary_runner(settings, runtime, client, stop_event)
110
+ retention_run = _retention_runner(settings, runtime, stop_event)
111
+ runs = asyncio.gather(
112
+ *(worker.run() for worker in workers),
113
+ *((summary_run,) if summary_run is not None else ()),
114
+ *((retention_run,) if retention_run is not None else ()),
115
+ )
116
+ metrics_interval = getattr(settings, "schedule_metrics_interval_seconds", 0.0)
117
+ schedule_metrics = (
118
+ asyncio.create_task(
119
+ _schedule_metrics_loop(
120
+ runtime.telemetry, client, config, stop_event, interval=metrics_interval
121
+ )
122
+ )
123
+ if metrics_interval
124
+ else None
125
+ )
126
+ try:
127
+ await _wait_for_shutdown(workers, runs, stop_event=stop_event)
128
+ finally:
129
+ if schedule_metrics is not None:
130
+ schedule_metrics.cancel()
131
+ await asyncio.gather(schedule_metrics, return_exceptions=True)
132
+ finally:
133
+ await runtime.close()
134
+
135
+
136
+ def _retention_runner(
137
+ settings: RuntimeSettings,
138
+ runtime: Any,
139
+ stop_event: asyncio.Event | None,
140
+ ) -> Coroutine[Any, Any, None] | None:
141
+ """Sweep every scope for retired versions past their TTL on a fixed interval."""
142
+
143
+ interval_hours = getattr(settings, "retired_version_purge_interval_hours", 0.0)
144
+ retention = getattr(runtime, "retention", None)
145
+ if not interval_hours or retention is None:
146
+ return None
147
+ return _sweep_retired_versions(
148
+ retention,
149
+ interval_hours * 3600.0,
150
+ stop_event,
151
+ telemetry=getattr(runtime, "telemetry", None),
152
+ )
153
+
154
+
155
+ async def _sweep_retired_versions(
156
+ retention: Any,
157
+ interval_seconds: float,
158
+ stop_event: asyncio.Event | None,
159
+ *,
160
+ telemetry: Any | None = None,
161
+ ) -> None:
162
+ """Sweep soon after start, then every interval.
163
+
164
+ Waiting a full interval first meant a worker restarted more often than the
165
+ interval (daily deploys, spot nodes) never swept at all. The first sweep waits
166
+ a short random delay instead, so replicas started together do not all claim
167
+ the same versions at once.
168
+ """
169
+
170
+ stop = stop_event or asyncio.Event()
171
+ first_delay = min(interval_seconds, FIRST_RETENTION_SWEEP_MAX_DELAY_SECONDS)
172
+ delay = random.uniform(0.0, first_delay) # noqa: S311 - jitter, not security
173
+ while not stop.is_set():
174
+ try:
175
+ await asyncio.wait_for(stop.wait(), timeout=delay)
176
+ return
177
+ except TimeoutError:
178
+ pass
179
+ delay = interval_seconds
180
+ try:
181
+ batch = await _unless_stopped(retention.run_all(), stop)
182
+ except _SweepStopped:
183
+ return
184
+ except Exception as error: # noqa: BLE001 - a failed sweep waits for the next one
185
+ logger.error(
186
+ "Retired version sweep failed error_type=%s",
187
+ type(error).__name__,
188
+ exc_info=True,
189
+ )
190
+ continue
191
+ logger.info(
192
+ "Retired version sweep completed eligible=%d purged=%d skipped=%d failed=%d "
193
+ "deleted_objects=%d backlog=%d",
194
+ batch.eligible,
195
+ batch.purged,
196
+ batch.skipped,
197
+ batch.failed,
198
+ batch.deleted_objects,
199
+ batch.backlog,
200
+ )
201
+ if telemetry is not None:
202
+ telemetry.record_retention_purge(
203
+ purged=batch.purged,
204
+ skipped=batch.skipped,
205
+ failed=batch.failed,
206
+ deleted_objects=batch.deleted_objects,
207
+ backlog=batch.backlog,
208
+ )
209
+
210
+
211
+ class _SweepStopped(Exception):
212
+ """The worker is shutting down while a sweep is running."""
213
+
214
+
215
+ async def _unless_stopped(sweep: Coroutine[Any, Any, Any], stop: asyncio.Event) -> Any:
216
+ """Run one sweep, cancelling it when the worker stops.
217
+
218
+ A sweep drains batches for minutes, and shutdown waits for this loop.
219
+ Cancelling mid-purge is safe: the version stays PURGING under its lease and
220
+ the next sweep, on any worker, resumes it.
221
+ """
222
+
223
+ task = asyncio.ensure_future(sweep)
224
+ stopped = asyncio.ensure_future(stop.wait())
225
+ try:
226
+ await asyncio.wait((task, stopped), return_when=asyncio.FIRST_COMPLETED)
227
+ finally:
228
+ stopped.cancel()
229
+ if not task.done():
230
+ task.cancel()
231
+ await asyncio.gather(stopped, task, return_exceptions=True)
232
+ if task.cancelled():
233
+ raise _SweepStopped
234
+ return task.result()
235
+
236
+
237
+ def _summary_runner(
238
+ settings: RuntimeSettings,
239
+ runtime: Any,
240
+ client: Client,
241
+ stop_event: asyncio.Event | None,
242
+ ) -> Coroutine[Any, Any, None] | None:
243
+ """Attach the optional semantic projection queue to the deployed worker."""
244
+ # Deliberate duck-typing, not a dead guard: a caller may pass any settings
245
+ # object, and one without graph-build configuration skips this queue rather
246
+ # than failing the whole worker over an optional projection.
247
+ if not hasattr(settings, "graph_build_config_path"):
248
+ return None
249
+ graph_build = GraphBuildConfig.from_settings(settings)
250
+ if not graph_build.summarization.enabled:
251
+ return None
252
+ tenants = tuple(tenant.tenant_id for tenant in graph_build.tenants)
253
+ if not tenants:
254
+ logger.warning("Summary projection enabled but no managed tenants are configured")
255
+ return None
256
+ effective = graph_build.effective_settings(settings)
257
+ # The durable worker already owns a connected vector repository and embed
258
+ # client; handing them over is what lets an accepted entity card also become
259
+ # a searchable point here, not only on the standalone summaries CLI. Same
260
+ # duck-typing as above: a partial runtime simply gets cards without search.
261
+ vectors = getattr(runtime, "vector_repository", None)
262
+ embed_client = getattr(runtime, "embed_client", None)
263
+ factory = SummaryRuntimeFactory(
264
+ effective,
265
+ runtime.control,
266
+ ImmutableArtifactReader(runtime.object_store),
267
+ ImmutableArtifactWriter(runtime.object_store),
268
+ vectors,
269
+ RequestEmbedder(embed_client) if embed_client is not None else None,
270
+ )
271
+ logger.info(
272
+ "Temporal summary worker polling queue=%s tenants=%s",
273
+ effective.summary_task_queue,
274
+ ",".join(tenants),
275
+ )
276
+ return serve_summaries(client, factory, tenants, stop_event=stop_event)
277
+
278
+
279
+ def _build_worker(
280
+ client: Client,
281
+ config: TemporalRuntimeConfig,
282
+ *,
283
+ task_queue: str,
284
+ workflows: Sequence[type[Any]] = (),
285
+ activities: Sequence[Callable[..., Any]] = (),
286
+ ) -> Worker:
287
+ """Apply one typed capacity policy to every task-queue worker."""
288
+
289
+ worker = config.worker
290
+ return Worker(
291
+ client,
292
+ task_queue=task_queue,
293
+ workflows=workflows,
294
+ activities=activities,
295
+ workflow_runner=workflow_sandbox_runner(workflows),
296
+ identity=worker.identity,
297
+ max_concurrent_activities=worker.max_concurrent_activities,
298
+ max_concurrent_workflow_tasks=worker.max_concurrent_workflow_tasks,
299
+ max_concurrent_activity_task_polls=(worker.max_concurrent_activity_polls),
300
+ max_concurrent_workflow_task_polls=(worker.max_concurrent_workflow_polls),
301
+ graceful_shutdown_timeout=timedelta(seconds=worker.graceful_shutdown_seconds),
302
+ )
303
+
304
+
305
+ async def _emit_queue_metrics(
306
+ telemetry: Any,
307
+ client: Client,
308
+ config: TemporalRuntimeConfig,
309
+ ) -> None:
310
+ # Runtime-owned telemetry is optional in tests; skip emission when unavailable.
311
+ if telemetry is None:
312
+ return
313
+
314
+ queue_depths = await _describe_task_queue_depths(
315
+ client,
316
+ namespace=config.connection.namespace,
317
+ task_queues=config.task_queues.as_tuple(),
318
+ )
319
+ for queue_name in config.task_queues.as_tuple():
320
+ slots = config.worker.max_concurrent_activities
321
+ telemetry.record_temporal_worker_slots(queue_name, slots)
322
+ depth = queue_depths.get(queue_name)
323
+ telemetry.record_temporal_queue_depth(queue_name, depth)
324
+ telemetry.record_temporal_worker_slot_saturation(queue_name, slots=slots, depth=depth)
325
+
326
+
327
+ async def _schedule_metrics_loop(
328
+ telemetry: Any,
329
+ client: Client,
330
+ config: TemporalRuntimeConfig,
331
+ stop_event: asyncio.Event | None,
332
+ *,
333
+ interval: float = SCHEDULE_METRICS_INTERVAL_SECONDS,
334
+ ) -> None:
335
+ while True:
336
+ try:
337
+ views = await TemporalScheduleBackend(client, config).list_all()
338
+ telemetry.record_schedule_states(
339
+ {
340
+ view.definition.schedule_id: (
341
+ view.definition.paused,
342
+ view.desired_paused,
343
+ view.num_actions_skipped_overlap,
344
+ )
345
+ for view in views
346
+ }
347
+ )
348
+ except asyncio.CancelledError:
349
+ raise
350
+ except Exception:
351
+ logger.exception("Temporal schedule metrics collection failed")
352
+ if stop_event is None:
353
+ await asyncio.sleep(interval)
354
+ else:
355
+ try:
356
+ await asyncio.wait_for(stop_event.wait(), timeout=interval)
357
+ except TimeoutError:
358
+ continue
359
+ return
360
+
361
+
362
+ async def _describe_task_queue_depths(
363
+ client: Client,
364
+ *,
365
+ namespace: str,
366
+ task_queues: tuple[str, ...],
367
+ ) -> dict[str, int]:
368
+ service_client = getattr(client, "service_client", None)
369
+ workflow_service = getattr(service_client, "workflow_service", None)
370
+ if workflow_service is None:
371
+ return {}
372
+
373
+ try:
374
+ from temporalio.api.taskqueue.v1 import TaskQueue
375
+ from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest
376
+ except Exception:
377
+ return {}
378
+
379
+ depths: dict[str, int] = {}
380
+ for queue_name in task_queues:
381
+ try:
382
+ response = await asyncio.wait_for(
383
+ workflow_service.describe_task_queue(
384
+ DescribeTaskQueueRequest(
385
+ namespace=namespace,
386
+ task_queue=TaskQueue(name=queue_name),
387
+ )
388
+ ),
389
+ timeout=TASK_QUEUE_DEPTH_LOOKUP_TIMEOUT_SECONDS,
390
+ )
391
+ except Exception:
392
+ continue
393
+ status = getattr(response, "task_queue_status", None)
394
+ depth: int | None = None
395
+ for field_name in ("approximate_backlog_count", "backlog_count_hint"):
396
+ value = getattr(status, field_name, None) if status is not None else None
397
+ if isinstance(value, int):
398
+ depth = max(0, value)
399
+ break
400
+ if depth is not None:
401
+ depths[queue_name] = depth
402
+ return depths
403
+
404
+
405
+ async def _wait_for_shutdown(
406
+ workers: tuple[Worker, ...],
407
+ runs: asyncio.Future[Any],
408
+ *,
409
+ stop_event: asyncio.Event | None,
410
+ ) -> None:
411
+ stop_task = asyncio.create_task(stop_event.wait()) if stop_event is not None else None
412
+ try:
413
+ if stop_task is None:
414
+ await asyncio.shield(runs)
415
+ else:
416
+ done, _ = await asyncio.wait(
417
+ (runs, stop_task),
418
+ return_when=asyncio.FIRST_COMPLETED,
419
+ )
420
+ if runs in done:
421
+ await runs
422
+ finally:
423
+ if stop_task is not None:
424
+ stop_task.cancel()
425
+ await asyncio.gather(stop_task, return_exceptions=True)
426
+ shutdown_results = await asyncio.gather(
427
+ *(worker.shutdown() for worker in workers),
428
+ return_exceptions=True,
429
+ )
430
+ run_error: BaseException | None = None
431
+ try:
432
+ await asyncio.shield(runs)
433
+ except BaseException as exc: # Preserve cancellation after every worker was stopped.
434
+ run_error = exc
435
+ shutdown_errors = [
436
+ result for result in shutdown_results if isinstance(result, BaseException)
437
+ ]
438
+ if run_error is not None:
439
+ shutdown_errors.append(run_error)
440
+ if shutdown_errors:
441
+ raise BaseExceptionGroup("Temporal worker shutdown failed", shutdown_errors)
442
+
443
+
444
+ def _install_handlers(
445
+ loop: asyncio.AbstractEventLoop,
446
+ stop_event: asyncio.Event,
447
+ ) -> dict[signal.Signals, Any]:
448
+ previous: dict[signal.Signals, Any] = {}
449
+ for process_signal in (signal.SIGINT, signal.SIGTERM):
450
+ try:
451
+ previous[process_signal] = signal.getsignal(process_signal)
452
+ loop.add_signal_handler(process_signal, stop_event.set)
453
+ except (NotImplementedError, RuntimeError, ValueError):
454
+ previous.pop(process_signal, None)
455
+ return previous
456
+
457
+
458
+ def main() -> None:
459
+ configure_logging()
460
+ with asyncio.Runner() as runner:
461
+ loop = runner.get_loop()
462
+ stop_event = asyncio.Event()
463
+ previous = _install_handlers(loop, stop_event)
464
+ try:
465
+ runner.run(
466
+ run_workers(
467
+ RuntimeSettings(),
468
+ stop_event=stop_event,
469
+ )
470
+ )
471
+ finally:
472
+ for process_signal, handler in previous.items():
473
+ loop.remove_signal_handler(process_signal)
474
+ signal.signal(process_signal, handler)
475
+
476
+
477
+ if __name__ == "__main__":
478
+ main()
@@ -0,0 +1,141 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ from harborrag_runtime.document_stage_catalog import DOCUMENT_STAGE_CATALOG
7
+ from harborrag_runtime.temporal_models import TaskQueueConfig
8
+
9
+ from .document_workflow import DocumentIngestionWorkflow
10
+ from .ingestion_activities import IngestionActivities
11
+ from .maintenance_activities import MaintenanceActivities
12
+ from .reindex_workflow import ReindexWorkflow
13
+ from .retry_workflow import DocumentRetryWorkflow, RetryFailuresWorkflow
14
+ from .source_batch_workflow import SourceBatchWorkflow
15
+ from .source_workflow import ScheduledSourceIngestionWorkflow, SourceIngestionWorkflow
16
+
17
+
18
+ def _stage_activities(
19
+ activities: IngestionActivities,
20
+ role: str,
21
+ ) -> tuple[Callable[..., Any], ...]:
22
+ return tuple(
23
+ getattr(activities, stage.method_name)
24
+ for stage in DOCUMENT_STAGE_CATALOG
25
+ if stage.task_queue_role == role
26
+ )
27
+
28
+
29
+ def worker_registrations(
30
+ activities: IngestionActivities,
31
+ maintenance: MaintenanceActivities,
32
+ task_queues: TaskQueueConfig | None = None,
33
+ ) -> tuple[
34
+ tuple[str, tuple[type[Any], ...], tuple[Callable[..., Any], ...]],
35
+ ...,
36
+ ]:
37
+ task_queues = task_queues or TaskQueueConfig()
38
+ return (
39
+ (
40
+ task_queues.discovery,
41
+ (SourceIngestionWorkflow, ScheduledSourceIngestionWorkflow, RetryFailuresWorkflow),
42
+ (
43
+ activities.discover_source_items,
44
+ activities.cancel_source_ingestion,
45
+ activities.close_cancelled_source_execution,
46
+ activities.read_cancelled_source_result,
47
+ activities.pause_source_ingestion,
48
+ activities.resume_source_ingestion,
49
+ activities.pause_workflow_execution,
50
+ activities.pause_batch_execution,
51
+ activities.unpause_workflow_execution,
52
+ activities.record_source_failure,
53
+ activities.finalize_source_ingestion,
54
+ activities.prepare_scheduled_source,
55
+ activities.record_scheduled_run_metrics,
56
+ activities.prepare_retry_failures,
57
+ activities.record_retry_failures_task_failure,
58
+ activities.finalize_retry_failures,
59
+ ),
60
+ ),
61
+ (
62
+ task_queues.transform,
63
+ (
64
+ SourceBatchWorkflow,
65
+ DocumentIngestionWorkflow,
66
+ DocumentRetryWorkflow,
67
+ ),
68
+ _stage_activities(activities, "transform"),
69
+ ),
70
+ (
71
+ task_queues.io,
72
+ (),
73
+ (
74
+ activities.fetch_and_capture_raw,
75
+ activities.record_document_failure,
76
+ activities.retry_document_release,
77
+ activities.record_retry_document_failure,
78
+ )
79
+ + _stage_activities(activities, "io"),
80
+ ),
81
+ (
82
+ task_queues.parser,
83
+ (),
84
+ (activities.parse_and_normalize,),
85
+ ),
86
+ (
87
+ task_queues.model,
88
+ (),
89
+ _stage_activities(activities, "model"),
90
+ ),
91
+ (
92
+ task_queues.index,
93
+ (ReindexWorkflow,),
94
+ (
95
+ *_stage_activities(activities, "index"),
96
+ activities.publish_version,
97
+ maintenance.cleanup_source_projections,
98
+ maintenance.cleanup_reindex_projections,
99
+ maintenance.repair_reindex_relations,
100
+ maintenance.reindex,
101
+ ),
102
+ ),
103
+ )
104
+
105
+
106
+ def validate_worker_registrations(
107
+ registrations: tuple[
108
+ tuple[str, tuple[type[Any], ...], tuple[Callable[..., Any], ...]],
109
+ ...,
110
+ ],
111
+ expected_task_queues: tuple[str, ...] | None = None,
112
+ ) -> None:
113
+ if expected_task_queues is None:
114
+ expected_task_queues = TaskQueueConfig().as_tuple()
115
+ queue_names = tuple(task_queue for task_queue, _, _ in registrations)
116
+ if set(queue_names) != set(expected_task_queues):
117
+ missing = sorted(set(expected_task_queues) - set(queue_names))
118
+ unexpected = sorted(set(queue_names) - set(expected_task_queues))
119
+ raise RuntimeError(
120
+ f"Temporal worker queue registration mismatch missing={missing} unexpected={unexpected}"
121
+ )
122
+
123
+ workflow_names = [
124
+ workflow_type.__name__ for _, workflows, _ in registrations for workflow_type in workflows
125
+ ]
126
+ activity_names = [
127
+ activity_fn.__name__ for _, _, activities in registrations for activity_fn in activities
128
+ ]
129
+
130
+ duplicate_workflows = sorted(
131
+ {name for name in workflow_names if workflow_names.count(name) > 1}
132
+ )
133
+ duplicate_activities = sorted(
134
+ {name for name in activity_names if activity_names.count(name) > 1}
135
+ )
136
+ if duplicate_workflows or duplicate_activities:
137
+ raise RuntimeError(
138
+ "Temporal worker registrations contain duplicates "
139
+ f"duplicate_workflows={duplicate_workflows} "
140
+ f"duplicate_activities={duplicate_activities}"
141
+ )