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,97 @@
1
+ """Fingerprint the effective chunking inputs used by runtime and submission."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict
7
+ from hashlib import sha256
8
+
9
+ from harborrag_adapters.chunking import (
10
+ GrammarSetMismatch,
11
+ RecursiveTextRefiner,
12
+ build_text_refiner,
13
+ text_refiner_fingerprint,
14
+ )
15
+ from harborrag_adapters.chunking.factory import grammar_set_problems
16
+ from harborrag_core.chunking.tokenization import ApproximateTokenCounter
17
+ from harborrag_core.contracts.chunking import TextRefiner, TokenCounter
18
+ from harborrag_engine.ingestion.chunking import ChunkingConfig, ChunkStrategy, ChunkStrategyRegistry
19
+ from harborrag_engine.ingestion.chunking.pipeline.composition import builtin_chunking_strategies
20
+ from harborrag_engine.ingestion.chunking.table.rendering import TableRenderer
21
+ from harborrag_runtime.config.chunking import RefinerConfig, default_chunking_settings
22
+ from harborrag_runtime.config.errors import ChunkingConfigurationError
23
+
24
+
25
+ def default_chunking_config() -> ChunkingConfig:
26
+ """Return the chunking configuration from the default settings."""
27
+ return default_chunking_settings().config
28
+
29
+
30
+ def build_refiner(token_counter: TokenCounter, refiner: RefinerConfig | None = None) -> TextRefiner:
31
+ """Build the oversized-unit refiner selected in ``chunking.yaml``."""
32
+ refiner = refiner or RefinerConfig()
33
+ if refiner.strategy == "recursive":
34
+ return RecursiveTextRefiner(token_counter)
35
+ try:
36
+ return build_text_refiner(token_counter, require_grammars=refiner.require_code_grammars)
37
+ except GrammarSetMismatch as error:
38
+ raise ChunkingConfigurationError(
39
+ "Code chunking needs the tree-sitter grammars of the declared grammar set "
40
+ f"({'; '.join(grammar_set_problems())}). Install "
41
+ "harborrag-adapters[chunking-code] on every process that ingests, or set "
42
+ "refiner.require_code_grammars: false in chunking.yaml to split code at "
43
+ "separators (the same processing identity then no longer guarantees the "
44
+ "same code splits on every worker)."
45
+ ) from error
46
+
47
+
48
+ def code_grammar_problems(refiner: RefinerConfig | None = None) -> list[str]:
49
+ """Missing or mismatched tree-sitter packages the selected refiner would use.
50
+
51
+ Empty when grammars match the declared set or the refiner does not parse code.
52
+ """
53
+ if (refiner or RefinerConfig()).strategy != "structure":
54
+ return []
55
+ return grammar_set_problems()
56
+
57
+
58
+ def refiner_fingerprint(refiner: RefinerConfig | None = None) -> str:
59
+ """Identify the refiner's split behaviour without building it.
60
+
61
+ Independent of installed extras (``require_code_grammars`` only decides
62
+ whether missing grammars fail startup), so API and worker processes agree.
63
+ """
64
+ if (refiner or RefinerConfig()).strategy == "recursive":
65
+ return f"{RecursiveTextRefiner.name}:{RecursiveTextRefiner.version}"
66
+ return text_refiner_fingerprint()
67
+
68
+
69
+ def chunk_strategy_fingerprint(
70
+ config: ChunkingConfig,
71
+ additional_strategies: tuple[ChunkStrategy, ...] = (),
72
+ *,
73
+ refiner: RefinerConfig | None = None,
74
+ ) -> str:
75
+ """Hash normalized policies and explicit versions, independent of mapping order."""
76
+ counter = ApproximateTokenCounter()
77
+ strategies = (*builtin_chunking_strategies(counter), *additional_strategies)
78
+ registry = ChunkStrategyRegistry(strategies)
79
+ for profile in config.profiles.values():
80
+ registry.get(profile.strategy)
81
+ versions = {strategy.name.strip(): strategy.version.strip() for strategy in strategies}
82
+ if any(not version for version in versions.values()):
83
+ raise ValueError("processing identity requires a version for every chunk strategy")
84
+ value = {
85
+ "configuration_version": config.configuration_version,
86
+ "default_profile": config.default_profile,
87
+ "create_route_chunks": config.create_route_chunks,
88
+ "profiles": {key: asdict(profile) for key, profile in config.profiles.items()},
89
+ "source_profiles": dict(config.source_profiles),
90
+ "strategies": versions,
91
+ "tokenizer": {"name": counter.name, "version": counter.version},
92
+ "refiner": refiner_fingerprint(refiner),
93
+ "table_renderer": TableRenderer.version,
94
+ "pipeline_version": "canonical-route-evidence-v5-scoped-code-embeddings",
95
+ }
96
+ serialized = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
97
+ return "chunking-v3-" + sha256(serialized.encode()).hexdigest()
@@ -0,0 +1,279 @@
1
+ """Runtime resource ownership and public composition entry point.
2
+
3
+ ``_START_HINTS`` is the fallback fix hint per resource for runtimes built without
4
+ ``resource_hints`` (tests, embedders).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import logging
11
+ from collections.abc import Awaitable, Callable, Mapping
12
+ from dataclasses import dataclass, field
13
+ from typing import TYPE_CHECKING
14
+
15
+ from harborrag_adapters.connectors.harbor_connector import HarborConnector
16
+ from harborrag_adapters.connectors.rate_limiting import ConnectorRateLimiter
17
+ from harborrag_adapters.models.embed import HarborEmbedClient
18
+ from harborrag_adapters.repositories.database import IngestionControlPlaneDatabase
19
+ from harborrag_adapters.repositories.object_store import ARTIFACT_BUCKET, RAW_BUCKET
20
+ from harborrag_core.ingestion import ProcessingProfile
21
+ from harborrag_core.ingestion.run_contracts import RunSettings
22
+ from harborrag_core.ports import KnowledgeGraphRepositoryPort
23
+ from harborrag_core.ports.storage import ObjectStorePort, VectorRepositoryPort
24
+ from harborrag_engine.ingestion.maintenance.cleanup import ProjectionCleanupService
25
+ from harborrag_engine.ingestion.maintenance.reindex import DocumentReindexService
26
+ from harborrag_engine.ingestion.release.pipeline import DocumentStagePipeline
27
+ from harborrag_engine.ingestion.release.service import DocumentReleaseService
28
+ from harborrag_runtime.composition.connection_stores import ConnectionStores
29
+ from harborrag_runtime.config.settings import RuntimeSettings
30
+ from harborrag_runtime.errors import RuntimeConnectionError
31
+
32
+ from .connections import ConnectionHealth, ConnectionResolver, ConnectorPool
33
+ from .maintenance.relation_repair import GraphRelationRepairService
34
+ from .maintenance.retention import RetiredVersionPurgeService
35
+ from .observability import IngestionTelemetry
36
+ from .source.plan import SourcePlanRepository
37
+ from .source.service import SourceIngestionService
38
+
39
+ if TYPE_CHECKING:
40
+ from harborrag_engine.ingestion import ChunkingConfig, ChunkStrategy
41
+ from harborrag_engine.ingestion.normalizers.builder import SourceDocumentNormalizerBuilder
42
+ from harborrag_runtime.config_store import CachedConfigProvider
43
+
44
+ logger = logging.getLogger("harborrag.runtime.ingestion.composition")
45
+
46
+ _FALLBACK_TARGETS = {
47
+ "control": "the control database",
48
+ "object_store": "the object store",
49
+ "vector": "the vector store",
50
+ "graph": "the graph store",
51
+ }
52
+ _START_HINTS = {
53
+ "control": "check HARBORRAG_CONTROL_DB_URL",
54
+ "object_store": "check HARBORRAG_OBJECT_STORE_* credentials and that MinIO is running",
55
+ "vector": (
56
+ "start Qdrant, check HARBORRAG_QDRANT_GRPC_PORT, or set "
57
+ "HARBORRAG_QDRANT_PREFER_GRPC=false to use HTTP"
58
+ ),
59
+ "graph": "start FalkorDB",
60
+ }
61
+
62
+
63
+ @dataclass(slots=True)
64
+ class IngestionRuntime:
65
+ """Own connected providers and production ingestion application services.
66
+
67
+ Args:
68
+ connector_pool: Per-run connectors built on first use.
69
+ processing: Processing profile new versions are built with.
70
+ control: Ingestion control-plane database.
71
+ documents: Document release service.
72
+ stages: Ordered document stage pipeline.
73
+ sources: Source ingestion service.
74
+ relations: Graph relation repair service.
75
+ cleanup: Projection cleanup service.
76
+ reindex: Connector-free reindex service.
77
+ source_plans: Repository of source ingestion plans.
78
+ object_store: Object store holding artifacts.
79
+ vector_repository: Vector store repository.
80
+ graph_repository: Knowledge graph repository.
81
+ embed_client: Embedding client.
82
+ connector_rate_limiter: Limiter shared by the connectors.
83
+ telemetry: Ingestion metrics.
84
+ connection_health: Health of the configured connections.
85
+ connection_resolver: Resolves connection snapshots for a run.
86
+ connection_stores: Stores behind connection records.
87
+ retention: Retired-version purge; ``None`` keeps hand-built runtimes (tests,
88
+ embedders) free of the purge.
89
+ resource_targets: Safe display string per resource label; read only on the failure
90
+ path.
91
+ resource_hints: What to check per resource label for the configured providers; read
92
+ only on the failure path.
93
+ config: Cached runtime configuration provider.
94
+ """
95
+
96
+ connector_pool: ConnectorPool
97
+ processing: ProcessingProfile
98
+ control: IngestionControlPlaneDatabase
99
+ documents: DocumentReleaseService
100
+ stages: DocumentStagePipeline
101
+ sources: SourceIngestionService
102
+ relations: GraphRelationRepairService
103
+ cleanup: ProjectionCleanupService
104
+ reindex: DocumentReindexService
105
+ source_plans: SourcePlanRepository
106
+ object_store: ObjectStorePort
107
+ vector_repository: VectorRepositoryPort
108
+ graph_repository: KnowledgeGraphRepositoryPort
109
+ embed_client: HarborEmbedClient
110
+ connector_rate_limiter: ConnectorRateLimiter
111
+ telemetry: IngestionTelemetry
112
+ connection_health: ConnectionHealth = field(default_factory=lambda: ConnectionHealth(None))
113
+ connection_resolver: ConnectionResolver | None = None
114
+ connection_stores: ConnectionStores | None = None
115
+ retention: RetiredVersionPurgeService | None = None
116
+ resource_targets: Mapping[str, str] = field(default_factory=dict)
117
+ resource_hints: Mapping[str, str] = field(default_factory=dict)
118
+ config: CachedConfigProvider | None = None
119
+ _started: bool = field(default=False, init=False)
120
+
121
+ async def start(self) -> None:
122
+ """Connect shared infrastructure only; connectors are built per run on first use."""
123
+ if self._started:
124
+ logger.debug("Ingestion runtime start skipped reason=already_started")
125
+ return
126
+ connected: list[Callable[[], Awaitable[None]]] = []
127
+ try:
128
+ await self.telemetry.start()
129
+ connected.append(self.telemetry.close)
130
+ for label, resource in (
131
+ ("control", self.control),
132
+ ("object_store", self.object_store),
133
+ ("vector", self.vector_repository),
134
+ ("graph", self.graph_repository),
135
+ ):
136
+ try:
137
+ await resource.connect()
138
+ except Exception as error:
139
+ raise self._unreachable(label, error) from error
140
+ connected.append(resource.close)
141
+ try:
142
+ await self.object_store.ensure_buckets((RAW_BUCKET, ARTIFACT_BUCKET))
143
+ except Exception as error:
144
+ raise self._unreachable("object_store", error) from error
145
+ config = getattr(self, "config", None)
146
+ if config is not None:
147
+ await config.start()
148
+ connected.append(config.aclose)
149
+ except BaseException as error:
150
+ logger.error(
151
+ "Ingestion runtime startup failed error_type=%s connected_resources=%d",
152
+ type(error).__name__,
153
+ len(connected),
154
+ )
155
+ await asyncio.gather(
156
+ *(close() for close in reversed(connected)),
157
+ asyncio.to_thread(self.connector_rate_limiter.close),
158
+ self.embed_client.aclose(),
159
+ return_exceptions=True,
160
+ )
161
+ raise
162
+ self._started = True
163
+ logger.info("Ingestion runtime started resources=%d", len(connected))
164
+
165
+ def _unreachable(self, label: str, error: Exception) -> RuntimeConnectionError:
166
+ """Build a connection error from authored text only, as the driver's text may carry credentials."""
167
+ targets = getattr(self, "resource_targets", None) or {}
168
+ target = targets.get(label) or _FALLBACK_TARGETS[label]
169
+ hints = getattr(self, "resource_hints", None) or {}
170
+ hint = hints.get(label) or _START_HINTS[label]
171
+ logger.error(
172
+ "Ingestion runtime resource unreachable resource=%s error_type=%s",
173
+ label,
174
+ type(error).__name__,
175
+ )
176
+ return RuntimeConnectionError(f"Could not connect to or initialise {target}; {hint}")
177
+
178
+ async def _close_config(self) -> None:
179
+ config = getattr(self, "config", None)
180
+ if config is not None:
181
+ await config.aclose()
182
+
183
+ async def close(self) -> None:
184
+ """Close every owned resource, then mark the runtime not started.
185
+
186
+ On failure the runtime stays started and retryable: repository and connector close
187
+ contracts are idempotent, so a later close attempt can converge the resources whose
188
+ first close failed.
189
+
190
+ Raises:
191
+ BaseExceptionGroup: One or more resources failed to close.
192
+ """
193
+ if not self._started:
194
+ await asyncio.gather(
195
+ self._close_config(),
196
+ asyncio.to_thread(self.connector_rate_limiter.close),
197
+ self.embed_client.aclose(),
198
+ self.telemetry.close(),
199
+ self._close_connection_stores(),
200
+ )
201
+ logger.debug("Ingestion runtime closed from unstarted state")
202
+ return
203
+ outcomes = await asyncio.gather(
204
+ self._close_config(),
205
+ self.connector_pool.aclose(),
206
+ self._close_connection_stores(),
207
+ self.graph_repository.close(),
208
+ self.vector_repository.close(),
209
+ self.object_store.close(),
210
+ self.control.close(),
211
+ asyncio.to_thread(self.connector_rate_limiter.close),
212
+ self.embed_client.aclose(),
213
+ self.telemetry.close(),
214
+ return_exceptions=True,
215
+ )
216
+ failures = [outcome for outcome in outcomes if isinstance(outcome, BaseException)]
217
+ if failures:
218
+ logger.error(
219
+ "Ingestion runtime shutdown failed failures=%d error_types=%s",
220
+ len(failures),
221
+ ",".join(sorted({type(error).__name__ for error in failures})),
222
+ )
223
+ raise BaseExceptionGroup("ingestion runtime shutdown failed", failures)
224
+ self._started = False
225
+ logger.info("Ingestion runtime closed")
226
+
227
+ async def connector(
228
+ self,
229
+ *,
230
+ tenant_id: str,
231
+ task_id: str,
232
+ configuration_fingerprint: str,
233
+ run_settings: RunSettings | None = None,
234
+ ) -> HarborConnector:
235
+ """Return the run's connector, built from the snapshot the run started with.
236
+
237
+ Args:
238
+ tenant_id: Tenant of the run.
239
+ task_id: The run; every activity of one run shares its connector.
240
+ configuration_fingerprint: Fingerprint of the run's connection snapshot.
241
+ run_settings: The run's pinned settings; its ``capture.*`` overrides
242
+ narrow the connection's own size/extension ceiling.
243
+
244
+ Returns:
245
+ The connector facade.
246
+
247
+ Raises:
248
+ ConnectorConfigurationError: The snapshot is unknown or rejected.
249
+ SecretUnavailableError: A referenced secret cannot be read on this worker.
250
+ """
251
+ return await self.connector_pool.connector(
252
+ tenant_id=tenant_id,
253
+ task_id=task_id,
254
+ configuration_fingerprint=configuration_fingerprint,
255
+ run_settings=run_settings,
256
+ )
257
+
258
+ async def _close_connection_stores(self) -> None:
259
+ """Dispose the control-plane engine the connection stores use."""
260
+ if self.connection_stores is not None:
261
+ await self.connection_stores.aclose()
262
+
263
+
264
+ def build_ingestion_runtime(
265
+ settings: RuntimeSettings | None = None,
266
+ *,
267
+ normalizer_builder: SourceDocumentNormalizerBuilder | None = None,
268
+ chunking_config: ChunkingConfig | None = None,
269
+ chunking_strategies: tuple[ChunkStrategy, ...] = (),
270
+ ) -> IngestionRuntime:
271
+ """Build an ingestion runtime through the production object-graph builder."""
272
+ from .runtime_builder import build_ingestion_runtime as build
273
+
274
+ return build(
275
+ settings,
276
+ normalizer_builder=normalizer_builder,
277
+ chunking_config=chunking_config,
278
+ chunking_strategies=chunking_strategies,
279
+ )
@@ -0,0 +1,239 @@
1
+ """Check a connection against its source: reachability, credentials, permissions, preview.
2
+
3
+ Connector errors map to the spec's ``error_category`` without leaking source text.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import time
10
+ from abc import ABC, abstractmethod
11
+ from collections.abc import Iterator
12
+ from dataclasses import dataclass, field
13
+ from itertools import islice
14
+ from typing import Any, Literal
15
+
16
+ from harborrag_adapters.connectors.exceptions import RateLimitError
17
+ from harborrag_adapters.connectors.harbor_connector import HarborConnector
18
+ from harborrag_adapters.connectors.policies.network import BlockedDestinationError
19
+ from harborrag_core.domain.source import SourceRecord
20
+ from harborrag_core.ingestion.connector_contracts import ConnectorQuery
21
+ from harborrag_core.ingestion.errors import (
22
+ SourceAuthenticationError,
23
+ SourceAuthorizationError,
24
+ )
25
+ from harborrag_runtime.connections.secrets import (
26
+ EnvSecretUnavailableError,
27
+ SecretUnavailableError,
28
+ )
29
+
30
+ CheckName = Literal["schema", "auth", "reachable", "permissions", "preview"]
31
+ ErrorCategory = Literal[
32
+ "auth_invalid",
33
+ "auth_expired",
34
+ "forbidden",
35
+ "unreachable",
36
+ "rate_limited",
37
+ "secret_unavailable",
38
+ ]
39
+
40
+ _SOURCE_CHECKS: tuple[CheckName, ...] = ("reachable", "auth", "permissions", "preview")
41
+ _NOT_PERMITTED = frozenset({403, 404})
42
+ _CLIENT_ERROR_STATUSES = range(400, 500)
43
+ _NOT_REFUSED_STATUSES = frozenset({401, 403, 404, 408, 429})
44
+
45
+ PREVIEW_SIZE = 5
46
+ ENV_SECRET_MESSAGE = "the secret is read from the worker's environment; the API cannot check it"
47
+
48
+
49
+ @dataclass(frozen=True, slots=True)
50
+ class CheckResult:
51
+ """One named check and why it failed, if it did."""
52
+
53
+ name: CheckName
54
+ ok: bool
55
+ message: str | None = None
56
+
57
+
58
+ @dataclass(slots=True)
59
+ class ConnectionTestReport:
60
+ """The spec's ``ConnectionTest`` result, built up by the chain."""
61
+
62
+ checks: list[CheckResult] = field(default_factory=list)
63
+ error_category: ErrorCategory | None = None
64
+ sample: list[dict[str, str]] = field(default_factory=list)
65
+ latency_ms: int = 0
66
+
67
+ @property
68
+ def ok(self) -> bool:
69
+ """True when every recorded check passed."""
70
+ return all(check.ok for check in self.checks)
71
+
72
+ def passed(self, *names: CheckName) -> None:
73
+ """Record checks that succeeded."""
74
+ self.checks.extend(CheckResult(name, True) for name in names)
75
+
76
+ def failed(self, name: CheckName, category: ErrorCategory, message: str) -> None:
77
+ """Record the check that failed and the category clients branch on."""
78
+ self.checks.append(CheckResult(name, False, message))
79
+ self.error_category = category
80
+
81
+ def secret_unavailable(self, error: SecretUnavailableError) -> None:
82
+ """Record an unreadable secret; an ``env:`` one lives in the worker, not the API."""
83
+ message = ENV_SECRET_MESSAGE if isinstance(error, EnvSecretUnavailableError) else str(error)
84
+ self.failed("auth", "secret_unavailable", message)
85
+
86
+ def as_dict(self) -> dict[str, Any]:
87
+ """Return the response body."""
88
+ return {
89
+ "ok": self.ok,
90
+ "checks": [
91
+ {"name": check.name, "ok": check.ok, "message": check.message}
92
+ for check in self.checks
93
+ ],
94
+ "error_category": self.error_category,
95
+ "preview": {"estimated_items": None, "sample": list(self.sample)},
96
+ "latency_ms": self.latency_ms,
97
+ }
98
+
99
+
100
+ class CheckStep(ABC):
101
+ """One link of the chain; it records its checks and says whether to go on."""
102
+
103
+ def __init__(self, successor: CheckStep | None = None) -> None:
104
+ self._successor = successor
105
+
106
+ def handle(self, connector: HarborConnector, report: ConnectionTestReport) -> None:
107
+ """Run this step, then the next one unless this step failed."""
108
+ try:
109
+ self.run(connector, report)
110
+ except Exception as error:
111
+ check, category, message = classify(error, default=self.default_check)
112
+ recorded = {result.name for result in report.checks}
113
+ if check in recorded:
114
+ check = self.default_check
115
+ report.passed(
116
+ *(
117
+ name
118
+ for name in _SOURCE_CHECKS[: _SOURCE_CHECKS.index(check)]
119
+ if name in self.implied and name not in recorded
120
+ )
121
+ )
122
+ report.failed(check, category, message)
123
+ return
124
+ if self._successor is not None:
125
+ self._successor.handle(connector, report)
126
+
127
+ implied: tuple[CheckName, ...] = ()
128
+ """Checks a failure in this step proves passed when it fails a later check."""
129
+
130
+ @property
131
+ @abstractmethod
132
+ def default_check(self) -> CheckName:
133
+ """Check blamed for an error that names no better one."""
134
+
135
+ @abstractmethod
136
+ def run(self, connector: HarborConnector, report: ConnectionTestReport) -> None:
137
+ """Do the step's work and record its passed checks."""
138
+
139
+
140
+ class ConnectStep(CheckStep):
141
+ """Open the connector: each connector's ``connect`` calls the source with the credentials."""
142
+
143
+ default_check: CheckName = "reachable"
144
+ implied: tuple[CheckName, ...] = ("reachable",)
145
+
146
+ def run(self, connector: HarborConnector, report: ConnectionTestReport) -> None:
147
+ """Connect and record ``reachable`` and ``auth``."""
148
+ connector.connect()
149
+ report.passed("reachable", "auth")
150
+
151
+
152
+ class PreviewStep(CheckStep):
153
+ """List the first items: proves read permission and shows a sample."""
154
+
155
+ default_check: CheckName = "permissions"
156
+ implied: tuple[CheckName, ...] = ("reachable", "auth", "permissions")
157
+
158
+ def __init__(self, successor: CheckStep | None = None, *, size: int = PREVIEW_SIZE) -> None:
159
+ super().__init__(successor)
160
+ self._size = size
161
+
162
+ def run(self, connector: HarborConnector, report: ConnectionTestReport) -> None:
163
+ """Read up to ``size`` items and record ``permissions`` and ``preview``."""
164
+ records: Iterator[SourceRecord] = connector.discover(ConnectorQuery(limit=self._size))
165
+ report.sample = [_sample(record) for record in islice(records, self._size)]
166
+ report.passed("permissions", "preview")
167
+
168
+
169
+ def run_connection_checks(connector: HarborConnector) -> ConnectionTestReport:
170
+ """Run the chain against a built connector, after the schema check passed.
171
+
172
+ Args:
173
+ connector: The connector built from the values under test.
174
+
175
+ Returns:
176
+ The report; ``ok`` is False when any check failed.
177
+ """
178
+ report = ConnectionTestReport()
179
+ report.passed("schema")
180
+ started = time.monotonic()
181
+ try:
182
+ ConnectStep(PreviewStep()).handle(connector, report)
183
+ finally:
184
+ report.latency_ms = int((time.monotonic() - started) * 1000)
185
+ with contextlib.suppress(Exception):
186
+ connector.close()
187
+ return report
188
+
189
+
190
+ def classify(error: BaseException, *, default: CheckName) -> tuple[CheckName, ErrorCategory, str]:
191
+ """Map a connector error to the failing check, its category and a safe message.
192
+
193
+ An error with no HTTP status means the source never answered, so it fails
194
+ ``reachable`` whichever step raised it, as does a blocked private address,
195
+ whose message is HarborRAG's own. A rate limit is reported as one whatever
196
+ its status, since GitHub answers a secondary limit with 403. Any other 403
197
+ or 404 fails ``permissions``, as does another 4xx the error marks as not
198
+ retryable, such as a 400 or 422: the source answered and refused the request.
199
+ """
200
+ status = getattr(error, "status_code", None)
201
+ prefix = f"{status} from the source: " if status else ""
202
+ if isinstance(error, BlockedDestinationError):
203
+ return "reachable", "unreachable", str(error)
204
+ if isinstance(error, SourceAuthenticationError):
205
+ return "auth", "auth_invalid", f"{prefix}the credentials were rejected"
206
+ if isinstance(error, RateLimitError):
207
+ return "reachable", "rate_limited", f"{prefix}the source is rate limiting requests"
208
+ if isinstance(error, SourceAuthorizationError) or status in _NOT_PERMITTED:
209
+ return "permissions", "forbidden", f"{prefix}the credentials cannot read this content"
210
+ if _refused_request(error, status):
211
+ return "permissions", "forbidden", f"{prefix}the source refused the request"
212
+ if isinstance(error, TimeoutError):
213
+ return "reachable", "unreachable", "the source did not answer in time"
214
+ check = default if status else "reachable"
215
+ return check, "unreachable", f"{prefix}the source could not be read ({type(error).__name__})"
216
+
217
+
218
+ def _refused_request(error: BaseException, status: object) -> bool:
219
+ """Return whether the source answered a 4xx the error marks as not retryable."""
220
+ return (
221
+ getattr(error, "retryable", None) is False
222
+ and isinstance(status, int)
223
+ and status in _CLIENT_ERROR_STATUSES
224
+ and status not in _NOT_REFUSED_STATUSES
225
+ )
226
+
227
+
228
+ def timed_out_report() -> ConnectionTestReport:
229
+ """Report for a test that ran past its deadline."""
230
+ report = ConnectionTestReport()
231
+ report.passed("schema")
232
+ report.failed("reachable", "unreachable", "the source did not answer within 15 s")
233
+ return report
234
+
235
+
236
+ def _sample(record: SourceRecord) -> dict[str, str]:
237
+ """Reduce a discovered record to the preview's ``{ref, title}``."""
238
+ title = record.metadata.get("title") or record.metadata.get("name") or record.locator
239
+ return {"item_ref": record.id, "title": str(title)}