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,353 @@
1
+ """Retention TTL for RETIRED document versions.
2
+
3
+ Projection cleanup removes a retired version's vectors and graph data but keeps
4
+ its object-store artifacts and projection manifest. Once the version has been
5
+ retired for longer than the configured TTL, this service deletes the objects
6
+ the version owns and marks it PURGED. The row itself stays: task results keep
7
+ referencing it, and re-ingesting identical content rebuilds the same
8
+ deterministic version id from PENDING.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import time
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass
17
+ from datetime import datetime, timedelta
18
+
19
+ from harborrag_adapters.repositories.database import IngestionControlPlaneDatabase
20
+ from harborrag_adapters.repositories.database.ingestion_control.retention import PurgeClaim
21
+ from harborrag_adapters.repositories.object_store import (
22
+ ARTIFACT_BUCKET,
23
+ IngestionArtifactLayout,
24
+ )
25
+ from harborrag_core.base import utc_now
26
+ from harborrag_core.contracts.errors import StorageNotFoundError
27
+ from harborrag_core.ingestion import PurgeableDocumentVersion
28
+ from harborrag_core.ports.storage import ObjectStorePort
29
+ from harborrag_core.storage import StorageOperationContext
30
+
31
+ logger = logging.getLogger("harborrag.runtime.ingestion.retention")
32
+
33
+ _VERSION_FAMILIES = (
34
+ "canonical",
35
+ "chunks",
36
+ "comments",
37
+ "relations",
38
+ "projections",
39
+ "tables",
40
+ "representations",
41
+ )
42
+ """Object families whose keys are addressed by (document_id, document_version_id). ``parsed/`` is a
43
+ content-addressed cache shared across versions and ``source-plans/`` belongs to tasks, so neither
44
+ is ever touched here.
45
+ """
46
+ _SHARED_PREFIXES = ("parsed/", "source-plans/")
47
+ _LIST_PAGE = 1_000
48
+ _MAX_LIST_PASSES = 100
49
+ _SWEEP_BATCH = 1_000
50
+ SWEEP_TIME_BUDGET_SECONDS = 600.0
51
+ """One periodic sweep keeps claiming batches while they come back full, for at most this long, so a
52
+ backlog drains in one sweep rather than 1000 a day.
53
+ """
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class RetiredVersionPurgeBatch:
58
+ """Counts from one purge batch of retired versions."""
59
+
60
+ eligible: int = 0
61
+ purged: int = 0
62
+ skipped: int = 0
63
+ failed: int = 0
64
+ deleted_objects: int = 0
65
+ backlog: int = 0
66
+ """Versions still eligible when a sweep stopped; only ``run_all`` counts them."""
67
+
68
+ def __add__(self, other: RetiredVersionPurgeBatch) -> RetiredVersionPurgeBatch:
69
+ return RetiredVersionPurgeBatch(
70
+ eligible=self.eligible + other.eligible,
71
+ purged=self.purged + other.purged,
72
+ skipped=self.skipped + other.skipped,
73
+ failed=self.failed + other.failed,
74
+ deleted_objects=self.deleted_objects + other.deleted_objects,
75
+ backlog=other.backlog,
76
+ )
77
+
78
+
79
+ class RetiredVersionPurgeService:
80
+ """Delete the artifacts of retired versions whose retention TTL elapsed."""
81
+
82
+ def __init__(
83
+ self,
84
+ *,
85
+ control: IngestionControlPlaneDatabase,
86
+ object_store: ObjectStorePort,
87
+ retention_days: int | None,
88
+ clock: Callable[[], datetime] = utc_now,
89
+ ) -> None:
90
+ if retention_days is not None and retention_days < 0:
91
+ raise ValueError("retired version retention days must not be negative")
92
+ self._control = control
93
+ self._store = object_store
94
+ self._retention_days = retention_days
95
+ self._clock = clock
96
+
97
+ async def run_scope(
98
+ self,
99
+ *,
100
+ tenant_id: str,
101
+ source_scope_id: str,
102
+ limit: int = 100,
103
+ ) -> RetiredVersionPurgeBatch:
104
+ """Purge eligible retired versions of one source scope, up to ``limit``."""
105
+ versions = await self._control.retention.purgeable_versions(
106
+ tenant_id=tenant_id,
107
+ source_scope_id=source_scope_id,
108
+ retired_before=self._retired_before(),
109
+ limit=limit,
110
+ )
111
+ return await self._purge_all(versions, label=source_scope_id)
112
+
113
+ async def run_all(
114
+ self,
115
+ *,
116
+ limit: int = _SWEEP_BATCH,
117
+ time_budget_seconds: float = SWEEP_TIME_BUDGET_SECONDS,
118
+ ) -> RetiredVersionPurgeBatch:
119
+ """Purge eligible versions of every tenant and scope.
120
+
121
+ The periodic sweep: a scope that is never re-ingested never runs the
122
+ post-cleanup purge, so its retired versions would otherwise outlive the TTL.
123
+ Batches repeat while they come back full and still purge something, within
124
+ ``time_budget_seconds``. Safe beside other workers -- each version is
125
+ claimed (RETIRED -> PURGING) under a row lock and a lease before anything
126
+ is deleted. With retention off only interrupted purges are resumed.
127
+ """
128
+ deadline = time.monotonic() + time_budget_seconds
129
+ total = RetiredVersionPurgeBatch()
130
+ while True:
131
+ versions = await self._control.retention.purgeable_versions(
132
+ retired_before=self._retired_before(),
133
+ limit=limit,
134
+ )
135
+ batch = await self._purge_all(versions, label="*")
136
+ total += batch
137
+ if batch.eligible < limit or batch.purged == 0 or time.monotonic() >= deadline:
138
+ break
139
+ backlog = 0
140
+ if total.eligible:
141
+ backlog = await self._control.retention.count_purgeable(
142
+ retired_before=self._retired_before()
143
+ )
144
+ return total + RetiredVersionPurgeBatch(backlog=backlog)
145
+
146
+ def _retired_before(self) -> datetime | None:
147
+ """The TTL cutoff; None (retention off) still resumes interrupted purges."""
148
+ if self._retention_days is None:
149
+ return None
150
+ return self._clock() - timedelta(days=self._retention_days)
151
+
152
+ async def _purge_all(
153
+ self,
154
+ versions: tuple[PurgeableDocumentVersion, ...],
155
+ *,
156
+ label: str,
157
+ ) -> RetiredVersionPurgeBatch:
158
+ purged = skipped = failed = deleted = 0
159
+ for version in versions:
160
+ outcome, removed = await self._purge(version)
161
+ deleted += removed
162
+ purged += outcome == "purged"
163
+ skipped += outcome == "skipped"
164
+ failed += outcome == "failed"
165
+ batch = RetiredVersionPurgeBatch(
166
+ eligible=len(versions),
167
+ purged=purged,
168
+ skipped=skipped,
169
+ failed=failed,
170
+ deleted_objects=deleted,
171
+ )
172
+ if versions:
173
+ logger.info(
174
+ "Retired version purge completed source_scope_id=%s retention_days=%s "
175
+ "eligible=%d purged=%d skipped=%d failed=%d deleted_objects=%d",
176
+ label,
177
+ self._retention_days if self._retention_days is not None else "off",
178
+ batch.eligible,
179
+ batch.purged,
180
+ batch.skipped,
181
+ batch.failed,
182
+ batch.deleted_objects,
183
+ )
184
+ return batch
185
+
186
+ async def _purge(self, version: PurgeableDocumentVersion) -> tuple[str, int]:
187
+ """Purge one retired version and return its outcome with the objects removed.
188
+
189
+ Artifacts are deleted with the tenant context they were written with, because keys are
190
+ tenant-relative and the store adds the tenant prefix itself. The version stays PURGING under
191
+ its lease, which is the retry backoff: a failed delete cannot prove the object survived, so
192
+ replay must not restore the version until a purge completes.
193
+ """
194
+ snapshot = version.snapshot
195
+ document_id = str(snapshot.document_id)
196
+ version_id = str(snapshot.document_version_id)
197
+ run: _PurgeRun | None = None
198
+ try:
199
+ claim = await self._control.retention.claim_purge(version_id)
200
+ if claim is None:
201
+ _log_skip(document_id, version_id, "no_longer_retired_or_held")
202
+ return "skipped", 0
203
+ run = _PurgeRun(claim, StorageOperationContext.system(version.tenant_id))
204
+ await self._delete_owned(version, run)
205
+ if not await self._control.retention.mark_version_purged(
206
+ version_id, claimed_at=run.claim.claimed_at
207
+ ):
208
+ _log_skip(document_id, version_id, "finished_elsewhere")
209
+ return "skipped", run.removed
210
+ except _ClaimLost:
211
+ _log_skip(document_id, version_id, "claim_lost")
212
+ return "skipped", run.removed if run is not None else 0
213
+ except Exception as error:
214
+ removed = run.removed if run is not None else 0
215
+ logger.error(
216
+ "Retired version purge failed document_id=%s document_version_id=%s "
217
+ "error_type=%s deleted_objects=%d",
218
+ document_id,
219
+ version_id,
220
+ type(error).__name__,
221
+ removed,
222
+ exc_info=True,
223
+ )
224
+ return "failed", removed
225
+ logger.info(
226
+ "Retired version purged document_id=%s document_version_id=%s deleted_objects=%d",
227
+ document_id,
228
+ version_id,
229
+ run.removed,
230
+ )
231
+ return "purged", run.removed
232
+
233
+ async def _delete_owned(self, version: PurgeableDocumentVersion, run: _PurgeRun) -> None:
234
+ """Delete the objects a version owns, then its unshared raw objects.
235
+
236
+ Shared raw objects go last, right after checking who still references them, so a version
237
+ recording the same raw key meanwhile keeps it.
238
+ """
239
+ snapshot = version.snapshot
240
+ document_id = str(snapshot.document_id)
241
+ version_id = str(snapshot.document_version_id)
242
+ for bucket, key in sorted(self._recorded_objects(version)):
243
+ await self._delete(bucket, key, run)
244
+ for family in _VERSION_FAMILIES:
245
+ await self._delete_stem(f"{family}/{document_id}/{version_id}", run)
246
+ await self._renew(run)
247
+ for bucket, key in sorted(await self._unshared_raw_objects(version)):
248
+ await self._delete(bucket, key, run)
249
+
250
+ async def _renew(self, run: _PurgeRun) -> None:
251
+ renewed = await self._control.retention.renew_purge(run.claim)
252
+ if renewed is None:
253
+ raise _ClaimLost
254
+ run.claim = renewed
255
+
256
+ @staticmethod
257
+ def _recorded_objects(version: PurgeableDocumentVersion) -> set[tuple[str, str]]:
258
+ """Artifacts the version row records plus its deterministic keys.
259
+
260
+ Deterministic keys a crash may have written without recording them on the version row;
261
+ deleting a missing key is a no-op.
262
+ """
263
+ snapshot = version.snapshot
264
+ document_id = str(snapshot.document_id)
265
+ version_id = str(snapshot.document_version_id)
266
+ targets = {
267
+ (reference.bucket, reference.key)
268
+ for reference in (
269
+ snapshot.canonical_artifact,
270
+ snapshot.chunk_artifact,
271
+ snapshot.chunk_index_artifact,
272
+ snapshot.representation_artifact,
273
+ )
274
+ if reference is not None and not reference.key.startswith(_SHARED_PREFIXES)
275
+ }
276
+ layout = IngestionArtifactLayout
277
+ targets |= {
278
+ (ARTIFACT_BUCKET, layout.canonical(document_id, version_id)),
279
+ (ARTIFACT_BUCKET, layout.chunks(document_id, version_id)),
280
+ (ARTIFACT_BUCKET, layout.chunk_index(document_id, version_id)),
281
+ (ARTIFACT_BUCKET, layout.comments(document_id, version_id)),
282
+ (ARTIFACT_BUCKET, layout.relations(document_id, version_id)),
283
+ }
284
+ return targets
285
+
286
+ async def _unshared_raw_objects(
287
+ self,
288
+ version: PurgeableDocumentVersion,
289
+ ) -> set[tuple[str, str]]:
290
+ snapshot = version.snapshot
291
+ raw = {
292
+ (reference.bucket, reference.key)
293
+ for reference in (snapshot.raw_artifact, snapshot.raw_metadata_artifact)
294
+ if reference is not None
295
+ }
296
+ if not raw:
297
+ return set()
298
+ in_use = await self._control.retention.raw_keys_in_use(
299
+ document_id=str(snapshot.document_id),
300
+ excluding_version_id=str(snapshot.document_version_id),
301
+ )
302
+ return raw - in_use
303
+
304
+ async def _delete_stem(self, stem: str, run: _PurgeRun) -> None:
305
+ """Delete every ``{stem}.ext`` and ``{stem}/...`` object in the artifact bucket.
306
+
307
+ ``comments/{doc}/{version}`` is a stem, not a directory, so only keys
308
+ continuing with ``.`` or ``/`` match: a version id that happens to be a
309
+ prefix of another can never select the other version's objects.
310
+ Listing has no cursor, so full pages are deleted and listed again.
311
+ """
312
+ for _ in range(_MAX_LIST_PASSES):
313
+ await self._renew(run)
314
+ page = await self._store.list(
315
+ ARTIFACT_BUCKET, stem, limit=_LIST_PAGE, context=run.context
316
+ )
317
+ matching = [
318
+ item.reference.key
319
+ for item in page
320
+ if item.reference.key[len(stem) :].startswith((".", "/"))
321
+ ]
322
+ for key in matching:
323
+ await self._delete(ARTIFACT_BUCKET, key, run)
324
+ if len(page) < _LIST_PAGE or not matching:
325
+ return
326
+
327
+ async def _delete(self, bucket: str, key: str, run: _PurgeRun) -> None:
328
+ """Already deleted by an earlier, interrupted purge."""
329
+ try:
330
+ existed = await self._store.delete(bucket, key, context=run.context)
331
+ except StorageNotFoundError:
332
+ return
333
+ run.removed += int(existed)
334
+
335
+
336
+ class _ClaimLost(Exception):
337
+ """Another worker took the purge over after this one's lease lapsed."""
338
+
339
+
340
+ @dataclass(slots=True)
341
+ class _PurgeRun:
342
+ claim: PurgeClaim
343
+ context: StorageOperationContext
344
+ removed: int = 0
345
+
346
+
347
+ def _log_skip(document_id: str, version_id: str, reason: str) -> None:
348
+ logger.info(
349
+ "Retired version purge skipped document_id=%s document_version_id=%s reason=%s",
350
+ document_id,
351
+ version_id,
352
+ reason,
353
+ )
@@ -0,0 +1,3 @@
1
+ """Compatibility exports for runtime telemetry."""
2
+
3
+ from harborrag_runtime.observability.model import * # noqa: F403
@@ -0,0 +1,127 @@
1
+ """Processing identity: digests of the configuration an ingestion ran with.
2
+
3
+ A run's identity must change exactly when its parsing or chunking output can change,
4
+ so a run setting enters it the same way the run's parser and chunker apply it.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from hashlib import sha256
10
+ from pathlib import Path
11
+
12
+ from harborrag_core.ingestion import ProcessingProfile
13
+ from harborrag_core.ingestion.run_contracts import RunSettings
14
+ from harborrag_engine.ingestion.chunking import ChunkingConfig, ChunkStrategy
15
+ from harborrag_engine.ingestion.chunking.config import cap_chunking_config, pin_chunking_overlap
16
+ from harborrag_runtime.config.chunking import chunking_settings_from
17
+ from harborrag_runtime.config.errors import ParserConfigurationError
18
+ from harborrag_runtime.config.parsers import load_parser_catalog
19
+ from harborrag_runtime.config.settings import RuntimeSettings
20
+
21
+ from .chunking_profile import chunk_strategy_fingerprint
22
+ from .document.normalization import CANONICAL_NORMALIZER_VERSION
23
+
24
+ GRAPH_PROJECTION_VERSION = "graph-v5-unique-visible-edges"
25
+ """Source assertions and metadata observations have independent document supports. Legacy
26
+ scope-owned assertions are rejected on reads until rebuilt and retired.
27
+ """
28
+ VECTOR_PROJECTION_SCHEMA = "vector-v2"
29
+
30
+
31
+ def build_processing_profile(
32
+ settings: RuntimeSettings,
33
+ *,
34
+ chunking_config: ChunkingConfig | None = None,
35
+ chunking_strategies: tuple[ChunkStrategy, ...] = (),
36
+ run_settings: RunSettings | None = None,
37
+ ) -> ProcessingProfile:
38
+ """Build the deterministic processing identity shared by clients and workers.
39
+
40
+ Args:
41
+ settings: Runtime settings naming the parser and chunking files.
42
+ chunking_config: Profiles that replace those of ``chunking.yaml``. The
43
+ refiner choice always comes from the file or its defaults.
44
+ chunking_strategies: Extra chunking strategies of this deployment.
45
+ run_settings: Per-run overrides. They change the identity only when
46
+ they change the effective parser, its OCR or the chunking limits and
47
+ overlap, the same way the run's parser and chunker apply them.
48
+
49
+ Returns:
50
+ The identity every stage of the run compares against stored work.
51
+
52
+ Raises:
53
+ ParserConfigurationError: The parser catalog file is missing or
54
+ unreadable, or is invalid when a run overrides the PDF parser or OCR.
55
+ """
56
+ chunking = chunking_settings_from(settings)
57
+ chunk_config = chunking_config or chunking.config
58
+ parser_profile = _parser_catalog_digest(settings.parser_config_path)
59
+ if run_settings is not None:
60
+ if run_settings.chunk_max_tokens is not None:
61
+ chunk_config = cap_chunking_config(chunk_config, run_settings.chunk_max_tokens)
62
+ if run_settings.chunk_overlap_tokens is not None:
63
+ chunk_config = pin_chunking_overlap(chunk_config, run_settings.chunk_overlap_tokens)
64
+ parser_profile = _run_parser_profile(parser_profile, settings, run_settings)
65
+ return ProcessingProfile(
66
+ parser_profile=parser_profile,
67
+ normalizer_version=CANONICAL_NORMALIZER_VERSION,
68
+ chunk_strategy=chunk_strategy_fingerprint(
69
+ chunk_config,
70
+ chunking_strategies,
71
+ refiner=chunking.refiner,
72
+ ),
73
+ dense_encoder_profile=settings.dense_encoder_profile,
74
+ sparse_encoder_profile=settings.sparse_encoder_profile,
75
+ graph_projection_version=GRAPH_PROJECTION_VERSION,
76
+ vector_projection_schema=VECTOR_PROJECTION_SCHEMA,
77
+ )
78
+
79
+
80
+ def _run_parser_profile(base: str, settings: RuntimeSettings, run_settings: RunSettings) -> str:
81
+ """Append the run's PDF engine and OCR choice to ``base`` when they change parsing."""
82
+ has_ocr_override = (
83
+ run_settings.ocr_enabled is not None or run_settings.ocr_languages is not None
84
+ )
85
+ if run_settings.pdf_parser is None and not has_ocr_override:
86
+ return base
87
+ catalog = load_parser_catalog(settings.parser_config_path)
88
+ profile = base
89
+ pdf_definition: str | None = None
90
+ pdf_parser = run_settings.pdf_parser
91
+ if pdf_parser is not None and pdf_parser != catalog.enabled_pdf_backend():
92
+ profile = f"{profile}+pdf-{pdf_parser}"
93
+ pdf_definition = catalog.pdf_definition_for(pdf_parser)
94
+ if has_ocr_override and catalog.ocr_overrides_change_parsing(
95
+ ocr_enabled=run_settings.ocr_enabled,
96
+ ocr_languages=run_settings.ocr_languages,
97
+ pdf_definition=pdf_definition,
98
+ ):
99
+ profile = f"{profile}+ocr-{_ocr_label(run_settings)}"
100
+ return profile
101
+
102
+
103
+ def _ocr_label(run_settings: RunSettings) -> str:
104
+ """Return ``on`` or ``off`` and the languages, such as ``off`` or ``on-en.vi``."""
105
+ parts: list[str] = []
106
+ if run_settings.ocr_enabled is not None:
107
+ parts.append("on" if run_settings.ocr_enabled else "off")
108
+ if run_settings.ocr_languages:
109
+ parts.append(".".join(run_settings.ocr_languages))
110
+ return "-".join(parts)
111
+
112
+
113
+ def configuration_file_digest(prefix: str, path: Path) -> str:
114
+ """Return ``prefix`` plus a short digest of the file's bytes."""
115
+ digest = sha256(path.read_bytes()).hexdigest()[:16]
116
+ return f"{prefix}-{digest}"
117
+
118
+
119
+ def _parser_catalog_digest(path: Path) -> str:
120
+ """Digest the parser catalog, reporting a missing file as a configuration error."""
121
+ try:
122
+ return configuration_file_digest("parser", path)
123
+ except OSError as error:
124
+ reason = error.strerror or type(error).__name__
125
+ raise ParserConfigurationError(
126
+ f"Parser configuration file cannot be read: {path} ({reason})"
127
+ ) from error