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,470 @@
1
+ """Facade for source discovery, dispatch, retry, and finalization.
2
+
3
+ Every terminal summary stored here replaces the task's summary, so each one
4
+ keeps the discovery skip counts that status views read after the run ends and
5
+ the progress bridge's state.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ from collections.abc import Mapping
13
+
14
+ from harborrag_adapters.connectors.base import BaseConnector
15
+ from harborrag_adapters.connectors.harbor_connector import HarborConnector
16
+ from harborrag_adapters.repositories.database import (
17
+ IngestionControlPlaneDatabase,
18
+ )
19
+ from harborrag_adapters.repositories.errors import HarborStorageValidationError
20
+ from harborrag_core.ingestion import IngestionTaskState
21
+ from harborrag_engine.ingestion.release.service import DocumentReleaseService
22
+ from harborrag_engine.ingestion.source.models import (
23
+ DISCOVERY_SKIPS_KEY,
24
+ PlannedDocuments,
25
+ RelationRepairProgress,
26
+ SourceDiscoveryPage,
27
+ SourceDiscoveryRun,
28
+ SourceDispatchSummary,
29
+ SourceIngestionOutcome,
30
+ SourceIngestionRequest,
31
+ )
32
+ from harborrag_engine.ingestion.source.tasks import pending_source_task, source_scan_id
33
+
34
+ from ...errors import VectorIndexSchemaError
35
+ from ..maintenance.relation_repair import GraphRelationRepairService
36
+ from .discovery import SourceDiscoveryPlanner
37
+ from .documents import SourceDocumentService
38
+ from .finalization import SourceFinalizationService
39
+ from .operations import SourceDocumentOperations
40
+ from .retry import SourceRetryService
41
+ from .skips import carried_discovery_skips, carried_progress_state, run_skip_summary
42
+
43
+ logger = logging.getLogger("harborrag.runtime.ingestion.source")
44
+
45
+
46
+ class SourceIngestionService(SourceDocumentOperations):
47
+ """Coordinate authoritative discovery and bounded document dispatch.
48
+
49
+ Args:
50
+ control: Control-plane database that holds tasks, scans and results.
51
+ documents: Release service that ingests one document.
52
+ relations: Graph relation repair. Without it, finalization skips repair.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ *,
58
+ control: IngestionControlPlaneDatabase,
59
+ documents: DocumentReleaseService,
60
+ relations: GraphRelationRepairService | None = None,
61
+ ) -> None:
62
+ self._control = control
63
+ self._documents = documents
64
+ self._discovery = SourceDiscoveryPlanner(control)
65
+ self._document_results = SourceDocumentService(
66
+ control=control,
67
+ documents=documents,
68
+ )
69
+ self._retries = SourceRetryService(
70
+ control=control,
71
+ documents=documents,
72
+ document_results=self._document_results,
73
+ )
74
+ self._finalization = SourceFinalizationService(
75
+ control=control,
76
+ relations=relations,
77
+ )
78
+
79
+ async def ingest(
80
+ self,
81
+ request: SourceIngestionRequest,
82
+ connector: BaseConnector | HarborConnector,
83
+ ) -> SourceIngestionOutcome:
84
+ """Discover, dispatch and finalize one source run in this process.
85
+
86
+ A cancellation, such as Ctrl-C on a direct run, cancels the task before it
87
+ propagates. Left RUNNING, the run's scan would block every later scan of
88
+ the scope, and a PENDING task would look like an unsubmitted durable run.
89
+ Any other error marks the task failed. A failure to record either outcome
90
+ is logged and never hides the run's own error.
91
+ """
92
+ logger.info(
93
+ "Source ingestion started task_id=%s connector_type=%s concurrency=%d",
94
+ request.task_id,
95
+ request.connector_type.value,
96
+ request.document_concurrency,
97
+ )
98
+ stage = "discovery"
99
+ try:
100
+ discovery = await self.discover(request, connector)
101
+ logger.info(
102
+ "Source discovery completed task_id=%s scan_id=%s documents=%d",
103
+ request.task_id,
104
+ discovery.scan_id,
105
+ len(discovery.planned),
106
+ )
107
+ stage = "dispatch"
108
+ results = await self._dispatch(
109
+ request,
110
+ connector,
111
+ discovery.planned,
112
+ )
113
+ stage = "finalization"
114
+ outcome = await self.finish(
115
+ request,
116
+ scan_id=discovery.scan_id,
117
+ planned=PlannedDocuments.of(discovery.planned),
118
+ summary=SourceDispatchSummary.from_results(results),
119
+ )
120
+ except asyncio.CancelledError:
121
+ logger.warning(
122
+ "Source ingestion interrupted task_id=%s stage=%s", request.task_id, stage
123
+ )
124
+ try:
125
+ await self.cancel(request.task_id)
126
+ except Exception: # noqa: BLE001 - never mask the cancellation itself
127
+ logger.exception(
128
+ "Source cancellation could not be persisted task_id=%s", request.task_id
129
+ )
130
+ raise
131
+ except Exception as error:
132
+ stage = _failure_stage(error, stage)
133
+ logger.error(
134
+ "Source %s failed task_id=%s connector_type=%s error_type=%s",
135
+ stage,
136
+ request.task_id,
137
+ request.connector_type.value,
138
+ type(error).__name__,
139
+ )
140
+ try:
141
+ await self.fail(
142
+ request.task_id,
143
+ error_code=f"{stage}_{type(error).__name__.lower()}",
144
+ stage=stage,
145
+ )
146
+ except Exception: # noqa: BLE001 - never mask the run's own error
147
+ logger.exception(
148
+ "Source failure could not be persisted task_id=%s", request.task_id
149
+ )
150
+ raise error
151
+ logger.info(
152
+ "Source ingestion completed task_id=%s scan_id=%s status=%s "
153
+ "discovered=%d published=%d unchanged=%d failed=%d removals=%d",
154
+ outcome.task_id,
155
+ outcome.scan_id,
156
+ outcome.status.value,
157
+ outcome.discovered,
158
+ outcome.published,
159
+ outcome.unchanged,
160
+ outcome.failed,
161
+ len(outcome.removal_candidates),
162
+ )
163
+ return outcome
164
+
165
+ async def cancel(self, task_id: str) -> None:
166
+ """Converge a graceful workflow cancellation on durable task state.
167
+
168
+ The open scan is cancelled first, so a cancel during discovery cannot
169
+ block later scans of the scope. The task keeps its summary, with the
170
+ skips counted so far at discovery and per document.
171
+ """
172
+ if await self._control.source_scans.cancel_if_started(source_scan_id(task_id)):
173
+ logger.info("Open source scan cancelled task_id=%s", task_id)
174
+ task = await self._control.tasks.get(task_id)
175
+ if task is None or task.status == IngestionTaskState.CANCELLED:
176
+ logger.debug(
177
+ "Source cancellation skipped task_id=%s reason=missing_or_cancelled", task_id
178
+ )
179
+ return
180
+ if task.status in {
181
+ IngestionTaskState.COMPLETED,
182
+ IngestionTaskState.PARTIAL,
183
+ IngestionTaskState.FAILED,
184
+ }:
185
+ logger.debug(
186
+ "Source cancellation skipped task_id=%s reason=terminal status=%s",
187
+ task_id,
188
+ task.status.value,
189
+ )
190
+ return
191
+ await self._control.tasks.transition(
192
+ task_id,
193
+ IngestionTaskState.CANCELLED,
194
+ summary={
195
+ **task.summary,
196
+ **await run_skip_summary(self._control, task_id),
197
+ "cancelled_at_safe_boundary": True,
198
+ },
199
+ )
200
+ logger.info("Source ingestion cancelled task_id=%s", task_id)
201
+
202
+ async def is_cancelled(self, task_id: str) -> bool:
203
+ """Whether the run is recorded as cancelled, as a Temporal cancel records it."""
204
+ task = await self._control.tasks.get(task_id)
205
+ return task is not None and task.status is IngestionTaskState.CANCELLED
206
+
207
+ async def pause(self, task_id: str) -> None:
208
+ """Pause a running ingestion task; a missing or paused task is left as is."""
209
+ task = await self._control.tasks.get(task_id)
210
+ if task is None or task.status == IngestionTaskState.PAUSED:
211
+ return
212
+ if task.status == IngestionTaskState.RUNNING:
213
+ await self._control.tasks.transition(task_id, IngestionTaskState.PAUSED)
214
+
215
+ async def resume(self, task_id: str) -> None:
216
+ """Resume a paused ingestion task; a missing or running task is left as is."""
217
+ task = await self._control.tasks.get(task_id)
218
+ if task is None or task.status == IngestionTaskState.RUNNING:
219
+ return
220
+ if task.status == IngestionTaskState.PAUSED:
221
+ await self._control.tasks.transition(task_id, IngestionTaskState.RUNNING)
222
+
223
+ async def fail(self, task_id: str, *, error_code: str, stage: str = "discovery") -> None:
224
+ """Persist one terminal source-workflow failure without runtime details.
225
+
226
+ The failed task keeps the counts of what discovery skipped, so status
227
+ views still show them, and the progress bridge's state. When finalization
228
+ recorded the stage it failed in, the task keeps that summary instead and
229
+ ``stage`` is ignored. A task that already ended is left as it is.
230
+ """
231
+ await self._control.source_scans.fail_if_started(
232
+ source_scan_id(task_id),
233
+ safe_reason=error_code,
234
+ )
235
+ task = await self._control.tasks.get(task_id)
236
+ if task is None or task.status in {
237
+ IngestionTaskState.COMPLETED,
238
+ IngestionTaskState.PARTIAL,
239
+ IngestionTaskState.FAILED,
240
+ IngestionTaskState.CANCELLED,
241
+ }:
242
+ logger.debug(
243
+ "Source failure persistence skipped task_id=%s error_code=%s reason=terminal",
244
+ task_id,
245
+ error_code,
246
+ )
247
+ return
248
+ await self._control.tasks.transition(
249
+ task_id,
250
+ IngestionTaskState.FAILED,
251
+ summary=(
252
+ {**task.summary, "error_code": error_code}
253
+ if _finalization_failed(task.summary)
254
+ else {
255
+ "failed_stage": stage,
256
+ "error_code": error_code,
257
+ **carried_discovery_skips(task.summary),
258
+ **carried_progress_state(task.summary),
259
+ }
260
+ ),
261
+ )
262
+ logger.warning(
263
+ "Source ingestion marked failed task_id=%s error_code=%s",
264
+ task_id,
265
+ error_code,
266
+ )
267
+
268
+ async def discover(
269
+ self,
270
+ request: SourceIngestionRequest,
271
+ connector: BaseConnector | HarborConnector,
272
+ ) -> SourceDiscoveryRun:
273
+ """Run and persist an authoritative descriptor-only source scan."""
274
+ discovery = await self.prepare_discovery(request, connector)
275
+ await self.complete_discovery(discovery.scan_id)
276
+ return discovery
277
+
278
+ async def prepare_discovery(
279
+ self,
280
+ request: SourceIngestionRequest,
281
+ connector: BaseConnector | HarborConnector,
282
+ ) -> SourceDiscoveryRun:
283
+ """Discover descriptors while leaving the scan open for plan persistence."""
284
+ scan_id = await self.begin_discovery(request)
285
+ planned = await self._discovery.discover(
286
+ request,
287
+ connector,
288
+ scan_id=scan_id,
289
+ )
290
+ logger.debug(
291
+ "Source discovery plan persisted task_id=%s scan_id=%s documents=%d",
292
+ request.task_id,
293
+ scan_id,
294
+ len(planned),
295
+ )
296
+ return SourceDiscoveryRun(scan_id=scan_id, planned=planned)
297
+
298
+ async def begin_discovery(self, request: SourceIngestionRequest) -> str:
299
+ """Create or resume the deterministic authoritative scan."""
300
+ await self._initialize(request)
301
+ return await self._control.source_scans.start(
302
+ request.source_scope_id,
303
+ scan_id=source_scan_id(request.task_id),
304
+ )
305
+
306
+ async def discover_page(
307
+ self,
308
+ request: SourceIngestionRequest,
309
+ connector: BaseConnector | HarborConnector,
310
+ *,
311
+ scan_id: str,
312
+ cursor: str | None,
313
+ page_size: int | None = None,
314
+ ) -> SourceDiscoveryPage:
315
+ """Persist one native provider page without completing the scan."""
316
+ return await self._discovery.discover_page(
317
+ request,
318
+ connector,
319
+ scan_id=scan_id,
320
+ cursor=cursor,
321
+ page_size=page_size,
322
+ )
323
+
324
+ async def record_discovery_progress(
325
+ self,
326
+ task_id: str,
327
+ *,
328
+ root_count: int,
329
+ document_count: int,
330
+ page_count: int,
331
+ ) -> None:
332
+ """Record discovery counts on the task summary."""
333
+ await self._control.tasks.update_summary(
334
+ task_id,
335
+ {
336
+ "stage": "DISCOVERING",
337
+ "discovery_pages": page_count,
338
+ "discovery_roots": root_count,
339
+ "discovered": document_count,
340
+ "admitted": document_count,
341
+ },
342
+ )
343
+
344
+ async def complete_discovery(self, scan_id: str) -> None:
345
+ """Make a scan authoritative after its dispatch plan is durable."""
346
+ await self._control.source_scans.complete(scan_id)
347
+ logger.debug("Source discovery scan completed scan_id=%s", scan_id)
348
+
349
+ async def discovery_skip_counts(self, task_id: str) -> dict[str, int]:
350
+ """Return the discovery-time skip counts recorded on the task so far."""
351
+ task = await self._control.tasks.get(task_id)
352
+ if task is None:
353
+ return {}
354
+ reasons = task.summary.get(DISCOVERY_SKIPS_KEY)
355
+ if not isinstance(reasons, Mapping):
356
+ return {}
357
+ return {
358
+ str(reason): int(count)
359
+ for reason, count in reasons.items()
360
+ if isinstance(count, int) and not isinstance(count, bool)
361
+ }
362
+
363
+ async def record_discovery_planned(self, task_id: str, document_count: int) -> None:
364
+ """Expose durable coarse progress without leaking workflow activities."""
365
+ await self._control.tasks.update_summary(
366
+ task_id,
367
+ {
368
+ "stage": "PROCESSING_DOCUMENTS",
369
+ "discovered": document_count,
370
+ "admitted": document_count,
371
+ },
372
+ )
373
+
374
+ async def finish(
375
+ self,
376
+ request: SourceIngestionRequest,
377
+ *,
378
+ scan_id: str,
379
+ planned: PlannedDocuments,
380
+ summary: SourceDispatchSummary,
381
+ repair_progress: RelationRepairProgress | None = None,
382
+ ) -> SourceIngestionOutcome:
383
+ """Close the source ingestion once every planned document has an outcome."""
384
+ return await self._finalization.finish(
385
+ request,
386
+ scan_id=scan_id,
387
+ planned=planned,
388
+ summary=summary,
389
+ repair_progress=repair_progress,
390
+ )
391
+
392
+ async def _initialize(self, request: SourceIngestionRequest) -> None:
393
+ """Register the task and scan scope before discovery starts.
394
+
395
+ The task executes in this process, so it is never awaiting submission: the marker keeps the
396
+ API outbox from re-submitting it if it stops while PENDING. A row a durable start registered
397
+ already exists and keeps its summary. The marker is set after the task exists and runs, so a
398
+ provisioning failure can be recorded.
399
+ """
400
+ await self._control.source_scans.register_scope(
401
+ tenant_id=request.tenant_id,
402
+ source_scope_id=request.source_scope_id,
403
+ connector_type=request.connector_type.value,
404
+ connection_id=request.connection_id,
405
+ configuration_fingerprint=request.configuration_fingerprint,
406
+ )
407
+ await self._control.tasks.create(
408
+ pending_source_task(request).model_copy(
409
+ update={"summary": {"submission_state": "executor"}}
410
+ )
411
+ )
412
+ await self._control.tasks.transition(
413
+ request.task_id,
414
+ IngestionTaskState.RUNNING,
415
+ )
416
+ try:
417
+ await self._documents.provision(tenant_id=request.tenant_id)
418
+ except HarborStorageValidationError as error:
419
+ dimensions = _schema_mismatch_dimensions(error)
420
+ if dimensions is None:
421
+ raise
422
+ raise VectorIndexSchemaError(_schema_mismatch_message(error, *dimensions)) from error
423
+
424
+
425
+ def _finalization_failed(summary: Mapping[str, object]) -> bool:
426
+ """Whether a finalization attempt recorded its failed stage and counts on the task."""
427
+ failed_stage = summary.get("failed_stage")
428
+ return isinstance(failed_stage, str) and bool(failed_stage)
429
+
430
+
431
+ def _failure_stage(error: Exception, stage: str) -> str:
432
+ """Return the stage to record for a run that failed while in ``stage``.
433
+
434
+ Provisioning runs inside discovery's first step, but a vector index schema
435
+ mismatch is a configuration fault, not a discovery one.
436
+ """
437
+ return "provision" if isinstance(error, VectorIndexSchemaError) else stage
438
+
439
+
440
+ def _schema_mismatch_dimensions(error: HarborStorageValidationError) -> tuple[int, int] | None:
441
+ """Both dimensions when ``error`` is the existing-index schema mismatch, else None.
442
+
443
+ Only that mismatch is a configuration verdict the operator can act on; other
444
+ validation failures (an invalid tenant or index name, say) keep their type.
445
+ """
446
+ if error.context.operation != "ensure_index":
447
+ return None
448
+ existing = error.context.metadata.get("existing_dimension")
449
+ configured = error.context.metadata.get("configured_dimension")
450
+ if isinstance(existing, int) and isinstance(configured, int):
451
+ return existing, configured
452
+ return None
453
+
454
+
455
+ def _schema_mismatch_message(
456
+ error: HarborStorageValidationError, existing: int, configured: int
457
+ ) -> str:
458
+ """Authored text plus the safe values the adapter attached, never its message."""
459
+ index = error.context.resource_name
460
+ subject = f"Vector index {index!r}" if isinstance(index, str) and index else "The vector index"
461
+ detail = (
462
+ f"existing dimension {existing}, configured dimension {configured}"
463
+ if existing != configured
464
+ else f"dimension {existing}; the distance or vector names differ"
465
+ )
466
+ return (
467
+ f"{subject} already exists with a different vector schema ({detail}). "
468
+ "Configure the embedding model and dimension to match it, or use a new "
469
+ "collection and re-ingest."
470
+ )
@@ -0,0 +1,172 @@
1
+ """Per-run skip accounting for source ingestion tasks, and the summary state a run keeps.
2
+
3
+ Discovery skips come from the connector's ``skipped`` report and stay on the
4
+ task under ``DISCOVERY_SKIPS_KEY``, which status views read even after the run
5
+ ends. Per-document skips are read back from the task's document results.
6
+ A summary that replaces the task's summary keeps both these counts and the
7
+ progress bridge's state. Connector and database types are imported for
8
+ annotations only, so importing this module stays light.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections import Counter
14
+ from collections.abc import Mapping
15
+ from typing import TYPE_CHECKING, TypedDict
16
+
17
+ from harborrag_engine.ingestion.source.models import DISCOVERY_SKIPS_KEY
18
+
19
+ if TYPE_CHECKING:
20
+ from harborrag_adapters.connectors.base import BaseConnector
21
+ from harborrag_adapters.connectors.harbor_connector import HarborConnector
22
+ from harborrag_adapters.repositories.database import IngestionControlPlaneDatabase
23
+
24
+ EXTRACTION_FAILED = "EXTRACTION_FAILED"
25
+ _EXTRACTION_STAGE = "ParseAndNormalize"
26
+ _EXTRACTION_FAILURE_CODES = frozenset({"parser_rejected_document", "document_unsupported"})
27
+ """Codes of a parser rejecting the document; other failures while parsing are not extraction skips."""
28
+ _DOCUMENT_FAILURE_PREFIX = "document_release_"
29
+ _RESULT_PAGE_SIZE = 200
30
+ PROGRESS_SNAPSHOT_KEY = "_last_progress_snapshot"
31
+ """Summary key of the progress bridge's last status and counters snapshot."""
32
+ FAILURE_CURSOR_KEY = "_last_failure_cursor"
33
+ """Summary key of the last failed document the progress bridge has reported."""
34
+
35
+
36
+ class SkipSummary(TypedDict):
37
+ """Skip counts that finalization stores on a finished task.
38
+
39
+ Attributes:
40
+ skipped: Items the run skipped, at discovery or per document.
41
+ skipped_by_reason: ``skipped`` broken down by reason code.
42
+ discovery_skipped_by_reason: The discovery part of ``skipped_by_reason``.
43
+ Its name is ``DISCOVERY_SKIPS_KEY``, the key status views read.
44
+ """
45
+
46
+ skipped: int
47
+ skipped_by_reason: dict[str, int]
48
+ discovery_skipped_by_reason: dict[str, int]
49
+
50
+
51
+ def bind_connector_run(connector: BaseConnector | HarborConnector, run_id: str) -> None:
52
+ """Tag a connector's structured logs with the task's run ID, when it supports it."""
53
+ bind = getattr(connector, "bind_run_id", None)
54
+ if callable(bind):
55
+ bind(run_id)
56
+
57
+
58
+ def discovery_skip_summary(
59
+ connector: BaseConnector | HarborConnector,
60
+ ) -> dict[str, object] | None:
61
+ """Return skip counts from the connector's latest traversal.
62
+
63
+ ``None`` means the connector cannot report skips. A connector that reports
64
+ an empty collection yields zero counts, so a retried traversal clears the
65
+ counts an earlier one left on the task.
66
+ """
67
+ reported = getattr(connector, "skipped", None)
68
+ if reported is None:
69
+ return None
70
+ skipped = tuple(reported)
71
+ counts = dict(sorted(Counter(str(skip.reason) for skip in skipped).items()))
72
+ return {
73
+ "skipped": len(skipped),
74
+ "skipped_by_reason": counts,
75
+ DISCOVERY_SKIPS_KEY: counts,
76
+ }
77
+
78
+
79
+ def carried_discovery_skips(summary: Mapping[str, object]) -> dict[str, object]:
80
+ """Return the discovery skip counts that a replacement task summary must keep.
81
+
82
+ Moving a task to a terminal state stores a new summary in place of the old
83
+ one, and status views read these counts after the run ends. The result is
84
+ empty when the summary holds no discovery counts.
85
+ """
86
+ stored = summary.get(DISCOVERY_SKIPS_KEY)
87
+ return {DISCOVERY_SKIPS_KEY: dict(stored)} if isinstance(stored, Mapping) else {}
88
+
89
+
90
+ def carried_progress_state(summary: Mapping[str, object]) -> dict[str, object]:
91
+ """Return the progress bridge state that a replacement task summary must keep.
92
+
93
+ The bridge's snapshot and failure cursor let it emit each event once. A terminal
94
+ summary without it made the bridge emit every ``document.failed`` again when
95
+ the run ended. The result is empty when the bridge has not seen the run.
96
+ """
97
+ return {
98
+ key: summary[key] for key in (PROGRESS_SNAPSHOT_KEY, FAILURE_CURSOR_KEY) if key in summary
99
+ }
100
+
101
+
102
+ async def run_skip_summary(
103
+ control: IngestionControlPlaneDatabase,
104
+ task_id: str,
105
+ ) -> SkipSummary:
106
+ """Combine discovery skips already on the task with per-document skips.
107
+
108
+ Per-document skips are recounted from the document results on every call.
109
+ Finalization replaces the stored summary, so the discovery counts come back
110
+ too, for it to keep on the task. A retried finalization reads them back
111
+ unchanged and never counts a skip twice.
112
+
113
+ Args:
114
+ control: Control-plane database that holds the task and its results.
115
+ task_id: Run whose skips to count.
116
+
117
+ Returns:
118
+ The run's skip total, its breakdown by reason, and the discovery part.
119
+ """
120
+ task = await control.tasks.get(task_id)
121
+ stored = task.summary.get(DISCOVERY_SKIPS_KEY) if task is not None else None
122
+ discovered = (
123
+ {str(reason): int(count) for reason, count in stored.items()}
124
+ if isinstance(stored, Mapping)
125
+ else {}
126
+ )
127
+ counts: Counter[str] = Counter(discovered)
128
+ counts.update(await _document_skips(control, task_id))
129
+ return SkipSummary(
130
+ skipped=sum(counts.values()),
131
+ skipped_by_reason=dict(sorted(counts.items())),
132
+ discovery_skipped_by_reason=dict(sorted(discovered.items())),
133
+ )
134
+
135
+
136
+ async def _document_skips(control: IngestionControlPlaneDatabase, task_id: str) -> Counter[str]:
137
+ """Count failed documents that are skips: item-load skips and parser rejections."""
138
+ counts: Counter[str] = Counter()
139
+ after_updated_at = None
140
+ after_document_id = None
141
+ while True:
142
+ page = await control.tasks.document_results_page(
143
+ task_id,
144
+ statuses=("failed",),
145
+ after_updated_at=after_updated_at,
146
+ after_document_id=after_document_id,
147
+ limit=_RESULT_PAGE_SIZE,
148
+ )
149
+ for item in page.items:
150
+ skip_reason = item.result.get("skip_reason")
151
+ if isinstance(skip_reason, str) and skip_reason:
152
+ counts[skip_reason] += 1
153
+ elif _is_extraction_failure(item.result):
154
+ counts[EXTRACTION_FAILED] += 1
155
+ if not page.has_more or not page.items:
156
+ return counts
157
+ last = page.items[-1]
158
+ after_updated_at, after_document_id = last.updated_at, last.document_id
159
+
160
+
161
+ def _is_extraction_failure(result: Mapping[str, object]) -> bool:
162
+ """Whether a parser rejected the document while parsing it.
163
+
164
+ Infrastructure errors, a missing parser and cancellations at the same stage
165
+ are failures to retry, not skips.
166
+ """
167
+ code = result.get("safe_error_code")
168
+ return (
169
+ result.get("failure_stage") == _EXTRACTION_STAGE
170
+ and isinstance(code, str)
171
+ and code.strip().lower().removeprefix(_DOCUMENT_FAILURE_PREFIX) in _EXTRACTION_FAILURE_CODES
172
+ )