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,277 @@
1
+ """Operator entry points for opt-in, backfill, status and projection recovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from dataclasses import asdict
7
+ from hashlib import sha256
8
+ from pathlib import Path
9
+
10
+ from harborrag_adapters.models.chat import HarborChatClientConfig
11
+ from harborrag_adapters.topology import default_extraction_profile, pinned_configuration
12
+ from harborrag_core.schemas.ids import TenantId
13
+ from harborrag_core.security.context import AccessContext
14
+ from harborrag_core.storage import StorageOperationContext
15
+ from harborrag_core.topology import ExtractionProfile, TopologyPolicy, digest
16
+ from harborrag_core.topology.records import TopologyBuildContent
17
+ from harborrag_core.topology.resolution import ResolutionRequest
18
+ from harborrag_engine.topology.assembly import build_identity
19
+ from harborrag_engine.topology.inspection import TopologyInspectionBuilder
20
+ from harborrag_runtime.config.graph_build import GraphBuildConfig, graph_build_runtime_view
21
+ from harborrag_runtime.config.settings import RuntimeSettings
22
+
23
+ from .composition import connect_topology_authority, connect_topology_runtime
24
+ from .configuration import GraphBuildConfigSynchronizer, GraphBuildProfileFactory
25
+ from .derived_dispatch import DerivedDispatcher
26
+
27
+
28
+ async def configure(
29
+ settings: RuntimeSettings,
30
+ policy: TopologyPolicy,
31
+ ) -> dict[str, object]:
32
+ """Store a source's topology policy and enqueue jobs for it, never new document versions."""
33
+ if policy.enabled:
34
+ pinned_configuration(
35
+ HarborChatClientConfig.from_file(settings.model_config_path), policy.profile
36
+ )
37
+ async with connect_topology_authority(settings) as control:
38
+ revision = await control.topology.configure_policy(policy)
39
+ count = await control.topology.reconcile(policy.tenant_id)
40
+ stored = await control.topology.get_policy(policy.tenant_id, policy.source_scope_id)
41
+ return {
42
+ "policy_revision": revision,
43
+ "enqueued": count,
44
+ "enabled": policy.enabled,
45
+ "fingerprint": stored.fingerprint if stored else policy.fingerprint,
46
+ }
47
+
48
+
49
+ def make_profile(settings: RuntimeSettings, model: str | None = None) -> ExtractionProfile:
50
+ """Build the default extraction profile from the model catalog."""
51
+ return default_extraction_profile(
52
+ HarborChatClientConfig.from_file(settings.model_config_path), model
53
+ )
54
+
55
+
56
+ async def disable(settings: RuntimeSettings, tenant_id: str, scope: str) -> dict[str, object]:
57
+ """Turn off topology enrichment for one source scope."""
58
+ async with connect_topology_authority(settings) as control:
59
+ policy = await control.topology.get_policy(tenant_id, scope)
60
+ if policy is None:
61
+ raise ValueError("source has no topology policy")
62
+ revision = await control.topology.configure_policy(
63
+ policy.model_copy(update={"enabled": False})
64
+ )
65
+ return {"enabled": False, "policy_revision": revision}
66
+
67
+
68
+ async def status(settings: RuntimeSettings, tenant_id: str) -> list[dict[str, object]]:
69
+ """List the tenant's topology jobs with their state and accepted build."""
70
+ async with connect_topology_authority(settings) as control:
71
+ jobs = await control.topology.list_jobs(tenant_id)
72
+ return [
73
+ {
74
+ "job_id": job.job_id,
75
+ "document_id": job.document_id,
76
+ "document_version_id": job.document_version_id,
77
+ "state": job.state,
78
+ "attempts": job.attempts,
79
+ "error_code": job.error_code,
80
+ "available_at": job.available_at,
81
+ "policy_revision": job.policy_revision,
82
+ "build_id": build_identity(job) if job.state == "accepted" else None,
83
+ }
84
+ for job in jobs
85
+ ]
86
+
87
+
88
+ async def run(
89
+ settings: RuntimeSettings, tenant_id: str, *, limit: int = 100, watch: bool = False
90
+ ) -> list[dict[str, object]]:
91
+ """DIRECT durable worker; process limits count attempts, including failed work."""
92
+ reports: list[dict[str, object]] = []
93
+ async with connect_topology_runtime(settings) as runtime:
94
+ settings = runtime.settings
95
+ derived = DerivedDispatcher(runtime.control.topology, runtime.derive, settings)
96
+ while True:
97
+ await runtime.control.topology.reconcile(tenant_id)
98
+ for _ in range(limit):
99
+ result = await runtime.service.run_once(tenant_id)
100
+ if result.state == "idle":
101
+ break
102
+ if not watch:
103
+ reports.append(asdict(result))
104
+ if not watch:
105
+ return reports
106
+ await derived.run_page(tenant_id)
107
+ await asyncio.sleep(settings.topology_poll_seconds)
108
+
109
+
110
+ async def apply_graph_build_config(settings: RuntimeSettings) -> dict[str, object]:
111
+ """Validate and synchronize the desired graph-build policy explicitly."""
112
+ config = GraphBuildConfig.from_settings(settings)
113
+ effective = config.effective_settings(settings)
114
+ async with connect_topology_authority(effective) as control:
115
+ report = await GraphBuildConfigSynchronizer(
116
+ config,
117
+ control.topology,
118
+ GraphBuildProfileFactory(effective.model_config_path, config.resolved_ontologies),
119
+ ).apply()
120
+ return {
121
+ "config_path": str(Path(settings.graph_build_config_path).expanduser().resolve()),
122
+ "runtime": graph_build_runtime_view(effective),
123
+ "synchronization": report.as_dict(),
124
+ }
125
+
126
+
127
+ async def rebuild(settings: RuntimeSettings, tenant_id: str, build_id: str) -> dict[str, object]:
128
+ """Restore only an eligible generation from frozen data, with no model calls."""
129
+ async with connect_topology_runtime(settings) as runtime:
130
+ repo = runtime.control.topology
131
+ if await repo.get_build_lineage(tenant_id, build_id) is None:
132
+ raise ValueError("topology build is not currently eligible")
133
+ build = await repo.get_build(tenant_id, build_id)
134
+ if build is None:
135
+ raise ValueError("topology build is missing")
136
+ context = StorageOperationContext.system(tenant_id)
137
+ payload = await runtime.artifact_reader.get(build.artifact, context=context)
138
+ if sha256(payload).hexdigest() != build.artifact.sha256:
139
+ raise ValueError("topology build artifact checksum mismatch")
140
+ frozen = TopologyBuildContent.model_validate_json(payload)
141
+ canonical = TopologyBuildContent.model_validate(build.model_dump(exclude={"artifact"}))
142
+ if _topology_content_digest(frozen) != _topology_content_digest(canonical):
143
+ raise ValueError("canonical topology records do not match frozen artifact")
144
+ await runtime.projection.write(build, context=context)
145
+ valid = await runtime.projection.verify(build, context=context)
146
+ eligible = await repo.get_build_lineage(tenant_id, build_id) is not None
147
+ return {"build_id": build_id, "verified": valid, "eligible": eligible}
148
+
149
+
150
+ def _topology_content_digest(content: TopologyBuildContent) -> str:
151
+ """Compare set-like records independently of canonical database read order."""
152
+ payload = content.model_dump(mode="json")
153
+ payload["mentions"] = sorted(payload["mentions"], key=lambda item: item["mention_id"])
154
+ payload["assertions"] = sorted(payload["assertions"], key=lambda item: item["assertion_id"])
155
+ return digest(payload)
156
+
157
+
158
+ async def entities(
159
+ settings: RuntimeSettings,
160
+ tenant_id: str,
161
+ label: str | None = None,
162
+ *,
163
+ principal_id: str | None = None,
164
+ ) -> list[dict[str, object]]:
165
+ """List up to 100 active entity mentions, filtered by label and the principal's access."""
166
+ async with connect_topology_authority(settings) as control:
167
+ mentions = await control.topology.active_mentions(
168
+ tenant_id,
169
+ labels=(label,) if label else (),
170
+ limit=100,
171
+ access=AccessContext(principal_id=principal_id, tenant_id=TenantId(tenant_id))
172
+ if principal_id
173
+ else None,
174
+ )
175
+ return [
176
+ {
177
+ "entity_id": item.entity_id,
178
+ "label": item.observation.name,
179
+ "type": item.observation.entity_type,
180
+ "document_id": item.document_id,
181
+ "chunk_id": item.chunk_id,
182
+ "build_id": item.build_id,
183
+ }
184
+ for item in mentions
185
+ ]
186
+
187
+
188
+ async def inspect_build(
189
+ settings: RuntimeSettings,
190
+ tenant_id: str,
191
+ build_id: str,
192
+ *,
193
+ principal_id: str,
194
+ limit: int = 20,
195
+ ) -> dict[str, object]:
196
+ """Return generated topology and exact evidence only after canonical ACL checks.
197
+
198
+ One error covers missing, retired, stale-ACL and forbidden builds.
199
+ """
200
+ access = AccessContext(principal_id=principal_id, tenant_id=TenantId(tenant_id))
201
+ async with connect_topology_authority(settings) as control:
202
+ repo = control.topology
203
+ eligible = await repo.eligible_build_ids(tenant_id, (build_id,), access=access)
204
+ if build_id not in eligible:
205
+ raise ValueError("topology build is unavailable")
206
+ topology = await repo.get_build(tenant_id, build_id)
207
+ if topology is None:
208
+ raise ValueError("topology build is unavailable")
209
+ job = await repo.get_job(tenant_id, topology.job_id)
210
+ if job is None:
211
+ raise ValueError("topology build is unavailable")
212
+ checkpoints = await repo.checkpoints(job)
213
+ deployment = _resolved_deployment(settings, job.policy.profile)
214
+ result = TopologyInspectionBuilder(topology, job, checkpoints, deployment).build(
215
+ limit=limit
216
+ )
217
+ if build_id not in await repo.eligible_build_ids(tenant_id, (build_id,), access=access):
218
+ raise ValueError("topology build is unavailable")
219
+ return result
220
+
221
+
222
+ def _resolved_deployment(
223
+ settings: RuntimeSettings, profile: ExtractionProfile
224
+ ) -> dict[str, object]:
225
+ """Name a deployment only when current config matches the immutable revision."""
226
+ model_config_path = getattr(settings, "model_config_path", None)
227
+ if model_config_path is None:
228
+ return {"configuration_match": False}
229
+ try:
230
+ config = pinned_configuration(HarborChatClientConfig.from_file(model_config_path), profile)
231
+ _, logical = config.model_for(profile.model)
232
+ deployment = logical.deployments[0]
233
+ except (KeyError, OSError, ValueError):
234
+ return {"configuration_match": False}
235
+ return {
236
+ "configuration_match": True,
237
+ "deployment_name": deployment.name,
238
+ "provider": deployment.provider.value,
239
+ "provider_model": deployment.model,
240
+ }
241
+
242
+
243
+ async def derive(settings: RuntimeSettings, tenant_id: str, build_id: str) -> object:
244
+ """Generate independent contextual/parent artifacts for an accepted build."""
245
+ async with connect_topology_runtime(settings) as runtime:
246
+ return await runtime.derive(tenant_id, build_id)
247
+
248
+
249
+ async def resolve(settings: RuntimeSettings, request: ResolutionRequest) -> dict[str, object]:
250
+ """Record an entity resolution decision and enqueue the jobs it affects."""
251
+ async with connect_topology_authority(settings) as control:
252
+ decision = await control.topology.record_resolution(request)
253
+ count = await control.topology.reconcile(request.tenant_id)
254
+ return {"decision": decision.model_dump(mode="json"), "enqueued": count}
255
+
256
+
257
+ async def resolutions(settings: RuntimeSettings, tenant_id: str) -> list[dict[str, object]]:
258
+ """List the tenant's recorded entity resolution decisions."""
259
+ async with connect_topology_authority(settings) as control:
260
+ return [
261
+ item.model_dump(mode="json")
262
+ for item in await control.topology.list_resolutions(tenant_id)
263
+ ]
264
+
265
+
266
+ async def evaluate(payload: str) -> dict[str, object]:
267
+ """Offline, bounded, exact extraction evaluation; never contacts a model."""
268
+ from harborrag_core.topology.evaluation import TopologyEvaluationUnit
269
+ from harborrag_engine.topology.evaluation import evaluate_extractions
270
+
271
+ if len(payload) > 20_000_000:
272
+ raise ValueError("evaluation input exceeds 20 million characters")
273
+ rows = [line for line in payload.splitlines() if line.strip()]
274
+ if not rows or len(rows) > 10000:
275
+ raise ValueError("evaluation requires between 1 and 10000 units")
276
+ units = tuple(TopologyEvaluationUnit.model_validate_json(line) for line in rows)
277
+ return evaluate_extractions(units).model_dump(mode="json")
@@ -0,0 +1,167 @@
1
+ """Frozen parent vector views with all-input lineage and narrower citation maps."""
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from hashlib import sha256
6
+ from uuid import NAMESPACE_URL, uuid5
7
+
8
+ from harborrag_adapters.repositories.object_store import ARTIFACT_BUCKET, ImmutableArtifact
9
+ from harborrag_core.indexing import VectorIndexRecord
10
+ from harborrag_core.ingestion import ArtifactReference
11
+ from harborrag_core.models.embed import EmbeddingPurpose, HarborEmbedMetadata, HarborEmbedRequest
12
+ from harborrag_core.schemas.ids import TenantId
13
+ from harborrag_core.storage import StorageOperationContext
14
+ from harborrag_core.topology import DocumentTopologyBuild, TopologyJob
15
+ from harborrag_core.topology.derived import (
16
+ ContextualIndexProfile,
17
+ ContextualManifest,
18
+ ParentDescription,
19
+ )
20
+ from harborrag_core.topology.extraction import digest
21
+ from harborrag_engine.topology.vector_values import canonical_dense_vector
22
+
23
+ from .contextual import ContextualResources, read_contextual_records
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ParentMaterializer:
28
+ resources: ContextualResources
29
+ profile: ContextualIndexProfile
30
+
31
+ async def freeze_summaries(
32
+ self,
33
+ job: TopologyJob,
34
+ build: DocumentTopologyBuild,
35
+ parents: tuple[ParentDescription, ...],
36
+ ) -> ArtifactReference:
37
+ """Persist the generated summary product before either projection is attempted."""
38
+
39
+ context = StorageOperationContext.system(job.tenant_id)
40
+ payload = json.dumps(
41
+ [parent.model_dump(mode="json") for parent in parents],
42
+ sort_keys=True,
43
+ separators=(",", ":"),
44
+ ).encode()
45
+ content_digest = sha256(payload).hexdigest()
46
+ key = (
47
+ f"topology/parent-summaries/{build.build_id}/"
48
+ f"{self.profile.parent_fingerprint}/{content_digest}.json"
49
+ )
50
+ reference = await self.resources.reader.find(
51
+ bucket=ARTIFACT_BUCKET,
52
+ key=key,
53
+ media_type="application/json",
54
+ context=context,
55
+ )
56
+ if reference is not None:
57
+ existing = await self.resources.reader.get(reference, context=context)
58
+ if sha256(existing).hexdigest() != content_digest:
59
+ raise ValueError("parent summary artifact integrity failure")
60
+ return reference
61
+ return await self.resources.writer.put(
62
+ ImmutableArtifact(
63
+ bucket=ARTIFACT_BUCKET,
64
+ key=key,
65
+ payload=payload,
66
+ media_type="application/json",
67
+ artifact_kind="parent-descriptions",
68
+ ),
69
+ context=context,
70
+ )
71
+
72
+ async def materialize(
73
+ self,
74
+ job: TopologyJob,
75
+ build: DocumentTopologyBuild,
76
+ parents: tuple[ParentDescription, ...],
77
+ ) -> ContextualManifest:
78
+ context = StorageOperationContext.system(job.tenant_id)
79
+ content_digest = digest([parent.model_dump(mode="json") for parent in parents])
80
+ key = f"topology/parent-vectors/{build.build_id}/{self.profile.parent_fingerprint}/{content_digest}.json"
81
+ reference = await self.resources.reader.find(
82
+ bucket=ARTIFACT_BUCKET,
83
+ key=key,
84
+ media_type="application/json",
85
+ context=context,
86
+ )
87
+ if reference is None:
88
+ records = [await self._record(job, build, parent) for parent in parents]
89
+ reference = await self.resources.writer.put(
90
+ ImmutableArtifact(
91
+ bucket=ARTIFACT_BUCKET,
92
+ key=key,
93
+ payload=json.dumps(
94
+ [row.model_dump(mode="json") for row in records], sort_keys=True
95
+ ).encode(),
96
+ media_type="application/json",
97
+ artifact_kind="parent-description-vectors",
98
+ ),
99
+ context=context,
100
+ )
101
+ else:
102
+ records = await read_contextual_records(self.resources.reader, reference, context)
103
+ return ContextualManifest(
104
+ artifact=reference,
105
+ embedding_profile=self.profile.parent_fingerprint,
106
+ dimension=self.profile.dimension,
107
+ point_ids=tuple(row.id for row in records),
108
+ index_name=self.profile.parent_index_name,
109
+ )
110
+
111
+ async def _record(
112
+ self,
113
+ job: TopologyJob,
114
+ build: DocumentTopologyBuild,
115
+ parent: ParentDescription,
116
+ ) -> VectorIndexRecord:
117
+ if len(parent.description.encode()) > self.profile.max_input_bytes:
118
+ raise ValueError("parent description exceeds embedding input budget")
119
+ response = await self.resources.embed.aembed(
120
+ HarborEmbedRequest(
121
+ inputs=(parent.description,),
122
+ logical_model=self.profile.model,
123
+ dimensions=self.profile.dimension,
124
+ purpose=EmbeddingPurpose.DOCUMENT,
125
+ cacheable=False,
126
+ normalize=True,
127
+ sensitive=True,
128
+ metadata=HarborEmbedMetadata(
129
+ tenant_id=job.tenant_id, document_ids=(job.document_id,)
130
+ ),
131
+ )
132
+ )
133
+ if len(response.embeddings) != 1 or not isinstance(response.embeddings[0].value, tuple):
134
+ raise ValueError("parent embedding is not a single dense vector")
135
+ vector = canonical_dense_vector(response.embeddings[0].value)
136
+ if len(vector) != self.profile.dimension:
137
+ raise ValueError("parent embedding dimension mismatch")
138
+ identity = str(
139
+ uuid5(
140
+ NAMESPACE_URL,
141
+ f"{job.tenant_id}:{build.build_id}:parent:{parent.parent_key}:{self.profile.parent_fingerprint}",
142
+ )
143
+ )
144
+ return VectorIndexRecord(
145
+ id=identity,
146
+ tenant_id=TenantId(job.tenant_id),
147
+ vector=list(vector),
148
+ payload={
149
+ "record_kind": "parent_description",
150
+ "build_id": build.build_id,
151
+ "document_id": job.document_id,
152
+ "document_version_id": job.document_version_id,
153
+ "source_scope_id": job.source_scope_id,
154
+ "config_epoch": job.config_epoch,
155
+ "embedding_profile": self.profile.parent_fingerprint,
156
+ "projection_point_id": identity,
157
+ "parent_key": parent.parent_key,
158
+ "level": parent.level,
159
+ "section_path": list(parent.section_path),
160
+ "structure_id": parent.structure_id,
161
+ "chunk_ids": list(parent.input_chunk_ids),
162
+ "cited_chunk_ids": list(parent.cited_chunk_ids),
163
+ "description": parent.description,
164
+ "input_coverage": parent.input_coverage,
165
+ "semantic_coverage": parent.semantic_coverage,
166
+ },
167
+ )
@@ -0,0 +1,43 @@
1
+ """Run-scoped spend ceiling for the parent rollup.
2
+
3
+ The tenant ledger is per-day and the parent call budget is per-document, so neither
4
+ bounds a single operator-initiated run. This does, and it stops the run by *deferring*:
5
+ work already frozen stays frozen and is reused, and the rest is picked up by the next
6
+ sweep rather than being recorded as a failure.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from decimal import Decimal
13
+
14
+ from .budgeted_extractor import EnrichmentDeferredError
15
+
16
+
17
+ @dataclass
18
+ class RunCostLedger:
19
+ """Accumulate measured spend for one run and refuse to start work past the ceiling."""
20
+
21
+ ceiling_usd: Decimal | None
22
+ spent_usd: Decimal = Decimal(0)
23
+ # Calls whose deployment declares no pricing. Counted, never priced as zero: doing so
24
+ # would let an unpriced model run past the ceiling indefinitely.
25
+ unpriced_calls: int = field(default=0)
26
+
27
+ def record(self, cost_usd: Decimal | None) -> None:
28
+ """Account for one completed call."""
29
+
30
+ if cost_usd is None:
31
+ self.unpriced_calls += 1
32
+ return
33
+ if cost_usd < 0:
34
+ raise ValueError("a recorded call cost cannot be negative")
35
+ self.spent_usd += cost_usd
36
+
37
+ def ensure_capacity(self) -> None:
38
+ """Defer the run when the next call would spend beyond the ceiling."""
39
+
40
+ if self.ceiling_usd is None:
41
+ return
42
+ if self.spent_usd >= self.ceiling_usd:
43
+ raise EnrichmentDeferredError("run_budget_exhausted")
@@ -0,0 +1,46 @@
1
+ """Explicit trusted-operator mode and resolved ACL administration; no model I/O."""
2
+
3
+ from harborrag_core.topology.config import TenantIndexingConfig
4
+ from harborrag_core.topology.permissions import ResolvedPermissionSnapshot
5
+ from harborrag_runtime.config.settings import RuntimeSettings
6
+
7
+ from .composition import connect_topology_authority
8
+
9
+
10
+ async def configure_indexing(
11
+ settings: RuntimeSettings, config: TenantIndexingConfig
12
+ ) -> dict[str, object]:
13
+ """Store a tenant's indexing configuration and enqueue the jobs it affects."""
14
+ async with connect_topology_authority(settings) as control:
15
+ state = await control.topology.configure_indexing(config)
16
+ count = await control.topology.reconcile(config.tenant_id)
17
+ return {"state": state.model_dump(mode="json"), "enqueued": count}
18
+
19
+
20
+ async def indexing_status(settings: RuntimeSettings, tenant_id: str) -> dict[str, object]:
21
+ """Return a tenant's stored indexing configuration state."""
22
+ async with connect_topology_authority(settings) as control:
23
+ state = await control.topology.get_indexing(tenant_id)
24
+ return state.model_dump(mode="json")
25
+
26
+
27
+ async def permission_coverage(settings: RuntimeSettings, tenant_id: str) -> dict[str, object]:
28
+ """Return aggregate active-corpus ACL coverage without source or principal identifiers."""
29
+ async with connect_topology_authority(settings) as control:
30
+ report = await control.topology.permission_coverage(tenant_id)
31
+ return report.model_dump(mode="json")
32
+
33
+
34
+ async def import_permissions(
35
+ settings: RuntimeSettings, snapshot: ResolvedPermissionSnapshot
36
+ ) -> dict[str, object]:
37
+ """Store one resolved permission snapshot and enqueue the jobs it affects."""
38
+ async with connect_topology_authority(settings) as control:
39
+ await control.topology.set_permissions(snapshot)
40
+ count = await control.topology.reconcile(snapshot.tenant_id)
41
+ return {
42
+ "resource_kind": snapshot.resource_kind,
43
+ "resource_id": snapshot.resource_id,
44
+ "revision": snapshot.revision,
45
+ "enqueued": count,
46
+ }