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,169 @@
1
+ """Inline ingestion executor for the SDK's ``direct`` execution mode.
2
+
3
+ The executor owns one ingestion runtime. A lock serializes its startup, runs
4
+ and shutdown, so a failed start never leaves a half-built runtime in use.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import contextlib
11
+
12
+ from harborrag_core.ingestion import IngestionTaskState
13
+ from harborrag_core.invariants import HarborInvariantError
14
+ from harborrag_runtime.composition.connection_stores import migrate_control_plane
15
+ from harborrag_runtime.config.connectors.importing import import_connectors_once
16
+ from harborrag_runtime.config.settings import RuntimeSettings
17
+ from harborrag_runtime.contracts import IngestionRequest, IngestionResult
18
+ from harborrag_runtime.errors import WorkflowRunAlreadyStartedError
19
+ from harborrag_runtime.execution.source_conversion import to_source_request
20
+ from harborrag_runtime.execution.submission import (
21
+ build_ingestion_input,
22
+ resolve_request_connection,
23
+ )
24
+ from harborrag_runtime.ingestion.composition import IngestionRuntime
25
+ from harborrag_runtime.ingestion.runtime_builder import build_ingestion_runtime
26
+
27
+ _TERMINAL_TASK_STATES = frozenset(
28
+ {
29
+ IngestionTaskState.COMPLETED,
30
+ IngestionTaskState.PARTIAL,
31
+ IngestionTaskState.FAILED,
32
+ IngestionTaskState.CANCELLED,
33
+ }
34
+ )
35
+
36
+
37
+ class DirectIngestionExecutor:
38
+ """Run source ingestion inline through the production use-case graph.
39
+
40
+ Args:
41
+ settings: Runtime settings the ingestion runtime is built from.
42
+ """
43
+
44
+ def __init__(self, settings: RuntimeSettings) -> None:
45
+ self._settings = settings
46
+ self._runtime: IngestionRuntime | None = None
47
+ self._runtime_started = False
48
+ self._lifecycle_lock = asyncio.Lock()
49
+ self._imported = False
50
+
51
+ async def start(self) -> None:
52
+ """Build and start the ingestion runtime unless it is already running."""
53
+ async with self._lifecycle_lock:
54
+ if self._runtime_started:
55
+ return
56
+ await self._rebuild_runtime()
57
+ await self._connect_runtime()
58
+
59
+ async def run(self, request: IngestionRequest) -> IngestionResult:
60
+ """Run one ingestion in this process and return its outcome.
61
+
62
+ Without ``start``, the runtime is built for this run. If resolving the
63
+ connection or building the connector then fails, that runtime is closed
64
+ and the original error is raised. A ``ConnectionNotFoundError`` or
65
+ ``ConnectorConfigurationError`` passes through, and
66
+ ``WorkflowRunAlreadyStartedError`` means the run ID belongs to a finished run.
67
+
68
+ Args:
69
+ request: The run to execute.
70
+
71
+ Returns:
72
+ The run's final counts, including the items it skipped.
73
+ """
74
+ async with self._lifecycle_lock:
75
+ fresh = not self._runtime_started
76
+ if fresh:
77
+ await self._rebuild_runtime()
78
+ runtime = self._runtime
79
+ if runtime is None or runtime.connection_resolver is None:
80
+ raise HarborInvariantError("self._runtime must not be None here")
81
+ try:
82
+ await self._import_connectors_once(runtime)
83
+ connection = await resolve_request_connection(runtime.connection_resolver, request)
84
+ source = build_ingestion_input(self._settings, request, connection=connection)
85
+ connector = await runtime.connector(
86
+ tenant_id=source.tenant_id,
87
+ task_id=source.task_id,
88
+ configuration_fingerprint=source.configuration_fingerprint,
89
+ run_settings=source.run_settings,
90
+ )
91
+ except Exception:
92
+ if fresh:
93
+ with contextlib.suppress(Exception):
94
+ await self._close_runtime()
95
+ raise
96
+ if fresh:
97
+ await self._connect_runtime()
98
+ await _reject_finished_run(runtime, source.task_id)
99
+ source_request = to_source_request(source)
100
+ outcome = await runtime.sources.ingest(source_request, connector)
101
+ return IngestionResult(
102
+ task_id=outcome.task_id,
103
+ status=outcome.status.value,
104
+ discovered=outcome.discovered,
105
+ published=outcome.published,
106
+ unchanged=outcome.unchanged,
107
+ failed=outcome.failed,
108
+ skipped=outcome.skipped,
109
+ )
110
+
111
+ async def _import_connectors_once(self, runtime: IngestionRuntime) -> None:
112
+ """Migrate the control database, then import ``connectors.yaml`` if it never ran."""
113
+ stores = runtime.connection_stores
114
+ if stores is None or self._imported:
115
+ return
116
+ await asyncio.to_thread(migrate_control_plane, self._settings)
117
+ await import_connectors_once(
118
+ self._settings.connector_config_path,
119
+ tenant_id=self._settings.tenant_id,
120
+ projects=stores.projects,
121
+ connections=stores.connections,
122
+ settings=stores.settings,
123
+ )
124
+ self._imported = True
125
+
126
+ async def _rebuild_runtime(self) -> None:
127
+ await self._close_runtime()
128
+ self._runtime = build_ingestion_runtime(self._settings)
129
+
130
+ async def _connect_runtime(self) -> None:
131
+ """Start the built runtime, and close it again if startup fails."""
132
+ if self._runtime is None:
133
+ raise HarborInvariantError("self._runtime must not be None here")
134
+ try:
135
+ await self._runtime.start()
136
+ except BaseException as startup_error:
137
+ try:
138
+ await self._close_runtime()
139
+ except BaseException as cleanup_error:
140
+ raise BaseExceptionGroup(
141
+ "direct ingestion startup and cleanup failed",
142
+ [startup_error, cleanup_error],
143
+ ) from None
144
+ raise
145
+ self._runtime_started = True
146
+
147
+ async def aclose(self) -> None:
148
+ """Close the runtime. Safe to call more than once."""
149
+ async with self._lifecycle_lock:
150
+ await self._close_runtime()
151
+
152
+ async def _close_runtime(self) -> None:
153
+ self._runtime_started = False
154
+ if self._runtime is not None:
155
+ await self._runtime.close()
156
+ self._runtime = None
157
+
158
+
159
+ async def _reject_finished_run(runtime: IngestionRuntime, task_id: str) -> None:
160
+ """Refuse a run ID whose task already finished.
161
+
162
+ Without this check the reused ID would surface as an invalid state
163
+ transition from deep inside the run.
164
+ """
165
+ existing = await runtime.control.tasks.get(task_id)
166
+ if existing is not None and existing.status in _TERMINAL_TASK_STATES:
167
+ raise WorkflowRunAlreadyStartedError(
168
+ f"run id {task_id!r} already used ({existing.status.value})"
169
+ )
@@ -0,0 +1,97 @@
1
+ """Default gateway composition; applications may inject another implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Mapping
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, cast
8
+
9
+ from harborrag_core.ingestion.run_contracts import PreparedSourceSubmission, SourceSubmission
10
+ from harborrag_runtime.config.settings import RuntimeSettings
11
+ from harborrag_runtime.config.temporal import TemporalRuntimeConfig
12
+ from harborrag_runtime.ingestion_contracts import IngestionGateway
13
+ from harborrag_runtime.scheduling import ScheduleBackend
14
+ from harborrag_runtime.temporal.optional import load_temporal_attribute
15
+
16
+ from .source_submission import SourceSubmissionDefaults, prepare_source_submission
17
+
18
+ if TYPE_CHECKING:
19
+ from temporalio.client import Client
20
+
21
+ from harborrag_runtime.ingestion.connections import ResolvedConnection
22
+ from harborrag_runtime.temporal.client import IngestionTemporalClient
23
+ from harborrag_runtime.temporal.schedules import TemporalScheduleBackend
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class IngestionGatewayDescription:
28
+ """Provider and health settings of the ingestion gateway."""
29
+
30
+ provider: str
31
+ health_timeout_seconds: float
32
+ details: Mapping[str, object]
33
+
34
+
35
+ def describe_ingestion_gateway(settings: RuntimeSettings) -> IngestionGatewayDescription:
36
+ """Describe the ingestion gateway the settings select."""
37
+ config = TemporalRuntimeConfig.from_settings(settings)
38
+ return IngestionGatewayDescription(
39
+ provider="temporal",
40
+ health_timeout_seconds=config.health_timeout_seconds,
41
+ details={"target": config.connection.target, "namespace": config.connection.namespace},
42
+ )
43
+
44
+
45
+ def prepare_configured_source_submission(
46
+ settings: RuntimeSettings,
47
+ submission: SourceSubmission,
48
+ *,
49
+ connection: ResolvedConnection,
50
+ ) -> PreparedSourceSubmission:
51
+ """Translate the shared ingestion batch policy at composition only.
52
+
53
+ Reads only the ingestion section: this runs on the direct path too, which
54
+ never connects to Temporal and must not be failed by its deployment config.
55
+ """
56
+ defaults = TemporalRuntimeConfig.ingestion_from_settings(settings)
57
+ return prepare_source_submission(
58
+ settings,
59
+ submission,
60
+ connection=connection,
61
+ defaults=SourceSubmissionDefaults(
62
+ batch_size=defaults.batch_size,
63
+ document_concurrency=defaults.document_concurrency,
64
+ ),
65
+ )
66
+
67
+
68
+ async def connect_temporal_client(config: TemporalRuntimeConfig) -> IngestionTemporalClient:
69
+ """Legacy factory retained while optional SDK imports remain at the boundary."""
70
+ client_type = cast(
71
+ "type[IngestionTemporalClient]",
72
+ load_temporal_attribute("harborrag_runtime.temporal.client", "IngestionTemporalClient"),
73
+ )
74
+ return await client_type.connect(config)
75
+
76
+
77
+ async def connect_ingestion_gateway(settings: RuntimeSettings) -> IngestionGateway:
78
+ """Connect the ingestion gateway the settings select."""
79
+ from harborrag_runtime.temporal.gateway import TemporalIngestionGateway
80
+
81
+ return TemporalIngestionGateway(
82
+ await connect_temporal_client(TemporalRuntimeConfig.from_settings(settings))
83
+ )
84
+
85
+
86
+ async def connect_schedule_backend(settings: RuntimeSettings) -> ScheduleBackend:
87
+ """Connect the schedule backend the settings select."""
88
+ config = TemporalRuntimeConfig.from_settings(settings)
89
+ connect = cast(
90
+ "Callable[[TemporalRuntimeConfig], Awaitable[Client]]",
91
+ load_temporal_attribute("harborrag_runtime.temporal.connection", "connect_temporal_client"),
92
+ )
93
+ backend_type = cast(
94
+ "type[TemporalScheduleBackend]",
95
+ load_temporal_attribute("harborrag_runtime.temporal.schedules", "TemporalScheduleBackend"),
96
+ )
97
+ return backend_type(await connect(config), config)
@@ -0,0 +1,61 @@
1
+ """Convert neutral submission contracts into source ingestion requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import datetime
7
+
8
+ from harborrag_core.chunking import ConnectorType
9
+ from harborrag_core.ingestion import ProcessingProfile
10
+ from harborrag_core.ingestion.connector_contracts import ConnectorQuery
11
+ from harborrag_core.ingestion.run_contracts import PreparedSourceSubmission
12
+ from harborrag_core.ingestion.source_query import ProcessingProfileInput
13
+ from harborrag_engine.ingestion.source.models import SourceIngestionRequest
14
+
15
+
16
+ def to_source_request(source: PreparedSourceSubmission) -> SourceIngestionRequest:
17
+ """Convert a prepared submission to a source ingestion request."""
18
+ query = source.query
19
+ updated_after = (
20
+ datetime.fromisoformat(query.updated_after) if query.updated_after is not None else None
21
+ )
22
+ return SourceIngestionRequest(
23
+ tenant_id=source.tenant_id,
24
+ task_id=source.task_id,
25
+ connector_name=source.connector_name,
26
+ connector_type=ConnectorType(source.connector_type),
27
+ connection_id=source.connection_id,
28
+ source_scope_id=source.source_scope_id,
29
+ configuration_fingerprint=source.configuration_fingerprint,
30
+ processing=to_processing_profile(source.processing),
31
+ query=ConnectorQuery(
32
+ path=query.path,
33
+ pattern=query.pattern,
34
+ recursive=query.recursive,
35
+ updated_after=updated_after,
36
+ limit=query.limit,
37
+ include_attachments=query.include_attachments,
38
+ filters=json.loads(query.filters_json),
39
+ ),
40
+ force_reprocess=source.force_reprocess,
41
+ discovery_page_size=source.discovery_page_size,
42
+ discovery_concurrency=source.discovery_concurrency,
43
+ document_concurrency=source.document_concurrency,
44
+ missing_threshold=source.missing_threshold,
45
+ run_settings=source.run_settings,
46
+ )
47
+
48
+
49
+ def to_processing_profile(
50
+ processing: ProcessingProfileInput,
51
+ ) -> ProcessingProfile:
52
+ """Convert the submitted processing input to a processing profile."""
53
+ return ProcessingProfile(
54
+ parser_profile=processing.parser_profile,
55
+ normalizer_version=processing.normalizer_version,
56
+ chunk_strategy=processing.chunk_strategy,
57
+ dense_encoder_profile=processing.dense_encoder_profile,
58
+ sparse_encoder_profile=processing.sparse_encoder_profile,
59
+ graph_projection_version=processing.graph_projection_version,
60
+ vector_projection_schema=processing.vector_projection_schema,
61
+ )
@@ -0,0 +1,278 @@
1
+ """Preparation of one source ingestion run from a connection and a submission.
2
+
3
+ Provider-neutral: turns what a caller asked for and the connection snapshot into
4
+ the deterministic input every activity of the run receives. Connection config
5
+ filters are a ceiling a run can only narrow, with the function the source type
6
+ registers for that filter, and the source scope id comes from the run's own
7
+ query, so editing connection config keeps the scope.
8
+
9
+ Start from: prepare_source_submission.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from collections.abc import Mapping
16
+ from dataclasses import asdict, dataclass, replace
17
+ from hashlib import sha256
18
+
19
+ from harborrag_core.ingestion.run_contracts import PreparedSourceSubmission, SourceSubmission
20
+ from harborrag_core.ingestion.source_query import ProcessingProfileInput, SourceQuery
21
+ from harborrag_runtime.config.errors import ConnectorConfigurationError
22
+ from harborrag_runtime.config.settings import RuntimeSettings
23
+ from harborrag_runtime.ingestion.connections import ResolvedConnection
24
+ from harborrag_runtime.ingestion.profiles import build_processing_profile
25
+ from harborrag_runtime.serialization import to_json_value
26
+
27
+ _EXECUTION_FILTERS = ("include_comments", "build_graph")
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class SourceSubmissionDefaults:
32
+ """Execution policy supplied by the selected provider's composition.
33
+
34
+ Args:
35
+ batch_size: Documents per batch when neither the run nor the connection's
36
+ run settings set it.
37
+ document_concurrency: Documents processed at once when neither the run nor
38
+ the connection's run settings set it.
39
+ """
40
+
41
+ batch_size: int = 200
42
+ document_concurrency: int = 8
43
+
44
+
45
+ def prepare_source_submission(
46
+ settings: RuntimeSettings,
47
+ submission: SourceSubmission,
48
+ *,
49
+ connection: ResolvedConnection,
50
+ defaults: SourceSubmissionDefaults = SourceSubmissionDefaults(),
51
+ ) -> PreparedSourceSubmission:
52
+ """Turn a resolved connection and a submission into a provider-neutral run input.
53
+
54
+ A ``ConnectorConfigurationError`` passes through when a local query names a
55
+ filter the connector ignores, or when the run sets a filter the connection
56
+ configures and the run's value cannot narrow it.
57
+
58
+ Args:
59
+ settings: Runtime settings that pick the processing profile.
60
+ submission: What the caller asked to ingest.
61
+ connection: The connection snapshot the run will use.
62
+ defaults: Batch and concurrency policy of the execution provider.
63
+
64
+ Returns:
65
+ The deterministic input every activity of the run receives.
66
+ """
67
+ if connection.provider == "local":
68
+ _require_known_local_filters(submission.query)
69
+ source_key = connection.snapshot.source_key
70
+ query = _effective_query(connection, submission.query)
71
+ source_scope_id = submission.source_scope_id or _source_scope_id(
72
+ tenant_id=submission.tenant_id,
73
+ connector_name=source_key,
74
+ connector_type=connection.provider,
75
+ connection_id=source_key,
76
+ query=_without_empty_query_fields(submission.query, connection.spec.query_fields),
77
+ )
78
+ run_settings = connection.run_settings
79
+ processing = build_processing_profile(settings, run_settings=run_settings)
80
+ batch_size = (
81
+ submission.batch_size
82
+ if submission.batch_size is not None
83
+ else run_settings.batch_size
84
+ if run_settings is not None and run_settings.batch_size is not None
85
+ else defaults.batch_size
86
+ )
87
+ document_concurrency = (
88
+ submission.document_concurrency
89
+ if submission.document_concurrency is not None
90
+ else run_settings.document_concurrency
91
+ if run_settings is not None and run_settings.document_concurrency is not None
92
+ else defaults.document_concurrency
93
+ )
94
+ return PreparedSourceSubmission(
95
+ task_id=submission.task_id,
96
+ tenant_id=submission.tenant_id,
97
+ connector_name=source_key,
98
+ connector_type=connection.provider,
99
+ connection_id=source_key,
100
+ source_scope_id=source_scope_id,
101
+ configuration_fingerprint=connection.fingerprint,
102
+ processing=ProcessingProfileInput(
103
+ parser_profile=processing.parser_profile,
104
+ normalizer_version=processing.normalizer_version,
105
+ chunk_strategy=processing.chunk_strategy,
106
+ dense_encoder_profile=processing.dense_encoder_profile,
107
+ sparse_encoder_profile=processing.sparse_encoder_profile,
108
+ graph_projection_version=processing.graph_projection_version,
109
+ vector_projection_schema=processing.vector_projection_schema,
110
+ ),
111
+ query=query,
112
+ force_reprocess=submission.force_reprocess,
113
+ discovery_page_size=submission.discovery_page_size,
114
+ discovery_concurrency=submission.discovery_concurrency,
115
+ document_concurrency=document_concurrency,
116
+ missing_threshold=submission.missing_threshold,
117
+ batch_size=batch_size,
118
+ continue_after_batches=submission.continue_after_batches,
119
+ run_settings=run_settings,
120
+ )
121
+
122
+
123
+ def _require_known_local_filters(query: SourceQuery) -> None:
124
+ """Reject filter keys the local connector would silently ignore."""
125
+ from harborrag_adapters.connectors.local.filters import LOCAL_QUERY_FILTER_KEYS
126
+
127
+ filters = json.loads(query.filters_json)
128
+ if not isinstance(filters, dict):
129
+ return
130
+ unknown = sorted(str(key) for key in filters if key not in LOCAL_QUERY_FILTER_KEYS)
131
+ if unknown:
132
+ raise ConnectorConfigurationError(
133
+ f"Unknown filter keys for a local connector: {', '.join(unknown)}. "
134
+ f"Allowed keys: {', '.join(sorted(LOCAL_QUERY_FILTER_KEYS))}"
135
+ )
136
+
137
+
138
+ def _source_scope_id(
139
+ *,
140
+ tenant_id: str,
141
+ connector_name: str,
142
+ connector_type: str,
143
+ connection_id: str,
144
+ query: SourceQuery,
145
+ ) -> str:
146
+ """Return the stable scope id of one connection and the query the run submitted."""
147
+ payload = {
148
+ "tenant_id": tenant_id,
149
+ "connector_name": connector_name,
150
+ "connector_type": connector_type,
151
+ "connection_id": connection_id,
152
+ "query": _scope_query(query),
153
+ }
154
+ return f"scope-{_digest(payload)[:32]}"
155
+
156
+
157
+ def _effective_query(connection: ResolvedConnection, query: SourceQuery) -> SourceQuery:
158
+ """Apply the connection's feature ceilings and config filters to the run query.
159
+
160
+ A filter the connection configures is a ceiling the run can only narrow: a run
161
+ that leaves the key unset or empty gets the configured value, and a run value is
162
+ combined with it by ``_narrowed_filter``, whose ``ConnectorConfigurationError``
163
+ passes through when the two cannot be combined. ``_without_empty_query_fields``
164
+ keeps that unset-or-empty equivalence in the source scope id.
165
+
166
+ Args:
167
+ connection: The connection snapshot the run will use.
168
+ query: The query the run submitted.
169
+
170
+ Returns:
171
+ The query every activity of the run receives.
172
+ """
173
+ include_attachments = query.include_attachments and connection.include_attachments()
174
+ config_filters = connection.query_filters()
175
+ if not config_filters:
176
+ return replace(query, include_attachments=include_attachments)
177
+ filters = json.loads(query.filters_json)
178
+ for key, connection_value in config_filters.items():
179
+ run_value = filters.get(key)
180
+ filters[key] = (
181
+ _narrowed_filter(connection, key, connection_value, run_value)
182
+ if run_value
183
+ else connection_value
184
+ )
185
+ return replace(
186
+ query,
187
+ include_attachments=include_attachments,
188
+ filters_json=json.dumps(filters, ensure_ascii=False, separators=(",", ":"), sort_keys=True),
189
+ )
190
+
191
+
192
+ def _narrowed_filter(
193
+ connection: ResolvedConnection, key: str, connection_value: object, run_value: object
194
+ ) -> str:
195
+ """Combine a run's value for a configured filter with the connection's, narrowing it.
196
+
197
+ The source type's ``query_narrowers`` own how a filter narrows; Jira, for one,
198
+ ANDs a run ``jql`` onto the connection's so the run can only select fewer issues.
199
+
200
+ Args:
201
+ connection: The connection snapshot, whose source type names the narrowers.
202
+ key: Filter name both the connection and the run set.
203
+ connection_value: The connection's configured value.
204
+ run_value: The run's value.
205
+
206
+ Returns:
207
+ The combined filter value.
208
+
209
+ Raises:
210
+ ConnectorConfigurationError: The source type has no narrower for the filter,
211
+ either value is not text, or the narrower refuses to combine them.
212
+ """
213
+ narrow = connection.spec.query_narrowers.get(key)
214
+ if narrow is None or not isinstance(connection_value, str):
215
+ raise ConnectorConfigurationError(
216
+ f"A run cannot replace the connection's {key} filter; it can only narrow it"
217
+ )
218
+ if not isinstance(run_value, str):
219
+ raise ConnectorConfigurationError(f"A run {key} filter must be text")
220
+ try:
221
+ return narrow(connection_value, run_value)
222
+ except ValueError as error:
223
+ raise ConnectorConfigurationError(
224
+ f"Run {key} cannot narrow the connection {key}: {error}"
225
+ ) from error
226
+
227
+
228
+ def _without_empty_query_fields(query: SourceQuery, query_fields: frozenset[str]) -> SourceQuery:
229
+ """Drop the source type's query fields a run left empty from its filters.
230
+
231
+ An empty query field selects what leaving it out selects, so both runs must
232
+ get one source scope id.
233
+
234
+ Args:
235
+ query: The query the run submitted.
236
+ query_fields: The source type's query fields, such as Jira ``jql``.
237
+
238
+ Returns:
239
+ ``query`` itself when nothing was dropped, else a copy without the empty fields.
240
+ """
241
+ filters = json.loads(query.filters_json)
242
+ if not isinstance(filters, dict):
243
+ return query
244
+ kept = {key: value for key, value in filters.items() if value or key not in query_fields}
245
+ if len(kept) == len(filters):
246
+ return query
247
+ return replace(
248
+ query,
249
+ filters_json=json.dumps(kept, ensure_ascii=False, separators=(",", ":"), sort_keys=True),
250
+ )
251
+
252
+
253
+ def _scope_query(query: SourceQuery) -> dict[str, object]:
254
+ """Keep execution controls out of the stable source membership scope."""
255
+ values = asdict(query)
256
+ values.pop("include_attachments", None)
257
+ filters = json.loads(query.filters_json)
258
+ if isinstance(filters, dict):
259
+ for key in _EXECUTION_FILTERS:
260
+ filters.pop(key, None)
261
+ values["filters_json"] = json.dumps(
262
+ filters,
263
+ ensure_ascii=False,
264
+ separators=(",", ":"),
265
+ sort_keys=True,
266
+ )
267
+ return values
268
+
269
+
270
+ def _digest(payload: Mapping[str, object]) -> str:
271
+ """Return the SHA-256 hex digest of a payload's canonical JSON."""
272
+ encoded = json.dumps(
273
+ to_json_value(payload),
274
+ ensure_ascii=False,
275
+ separators=(",", ":"),
276
+ sort_keys=True,
277
+ ).encode("utf-8")
278
+ return sha256(encoded).hexdigest()
@@ -0,0 +1,64 @@
1
+ """Translate public SDK requests into durable ingestion contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from harborrag_core.ingestion.run_contracts import PreparedSourceSubmission, SourceSubmission
8
+ from harborrag_core.ingestion.source_query import SourceQuery
9
+ from harborrag_runtime.config.settings import RuntimeSettings
10
+ from harborrag_runtime.contracts import IngestionRequest
11
+ from harborrag_runtime.execution.gateway import prepare_configured_source_submission
12
+ from harborrag_runtime.ingestion.connections import ConnectionResolver, ResolvedConnection
13
+
14
+
15
+ def request_source_key(request: IngestionRequest) -> str:
16
+ """Return the ``source_key`` an SDK request names."""
17
+ return request.connection_id or request.connector_name
18
+
19
+
20
+ async def resolve_request_connection(
21
+ resolver: ConnectionResolver, request: IngestionRequest
22
+ ) -> ResolvedConnection:
23
+ """Load and snapshot the connection an SDK request names."""
24
+ return await resolver.resolve(
25
+ tenant_id=str(request.access.tenant_id), source_key=request_source_key(request)
26
+ )
27
+
28
+
29
+ def build_ingestion_input(
30
+ settings: RuntimeSettings,
31
+ request: IngestionRequest,
32
+ *,
33
+ connection: ResolvedConnection,
34
+ ) -> PreparedSourceSubmission:
35
+ """Build the single source input shared by direct and Temporal strategies."""
36
+ return prepare_configured_source_submission(
37
+ settings,
38
+ SourceSubmission(
39
+ task_id=request.task_id,
40
+ tenant_id=str(request.access.tenant_id),
41
+ connector_name=request.connector_name,
42
+ connection_id=request.connection_id,
43
+ source_scope_id=request.source_scope_id,
44
+ query=SourceQuery(
45
+ path=request.path,
46
+ pattern=request.pattern,
47
+ recursive=request.recursive,
48
+ updated_after=request.updated_after,
49
+ limit=request.limit,
50
+ include_attachments=request.include_attachments,
51
+ filters_json=json.dumps(
52
+ request.filters,
53
+ ensure_ascii=False,
54
+ separators=(",", ":"),
55
+ sort_keys=True,
56
+ ),
57
+ ),
58
+ force_reprocess=request.force_reprocess,
59
+ discovery_page_size=request.discovery_page_size,
60
+ discovery_concurrency=request.discovery_concurrency,
61
+ document_concurrency=request.document_concurrency,
62
+ ),
63
+ connection=connection,
64
+ )