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,107 @@
1
+ """Execution-provider-neutral ingestion outcomes and gateway."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Protocol
7
+
8
+ from harborrag_core.ingestion.run_contracts import (
9
+ IngestionRetryRequest,
10
+ PreparedSourceSubmission,
11
+ RunKind,
12
+ )
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class IngestionExecutionReference:
17
+ """Handle of a started ingestion execution."""
18
+
19
+ run_id: str
20
+ workflow_id: str
21
+ first_execution_run_id: str | None = None
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class IngestionExecutionStatus:
26
+ """Control-plane view of one execution's state."""
27
+
28
+ task_id: str
29
+ status: str
30
+ paused: bool
31
+ cancel_requested: bool
32
+ pause_applied: bool = False
33
+ native_pause_pending: bool = False
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class IngestionExecutionResult:
38
+ """Counts a finished source execution reports.
39
+
40
+ Args:
41
+ task_id: Run the counts belong to.
42
+ scan_id: Discovery scan of the run.
43
+ discovered: Documents discovered.
44
+ published: Documents published.
45
+ unchanged: Documents left as they were.
46
+ failed: Documents that failed.
47
+ removal_candidates: A bounded sample of the removed documents.
48
+ unresolved_relations: Relations left unresolved.
49
+ status: Final task state name.
50
+ removal_count: Every removed document; defaults to the sample size.
51
+ """
52
+
53
+ task_id: str
54
+ scan_id: str
55
+ discovered: int
56
+ published: int
57
+ unchanged: int
58
+ failed: int
59
+ removal_candidates: tuple[str, ...]
60
+ unresolved_relations: int
61
+ status: str = "COMPLETED"
62
+ removal_count: int | None = None
63
+ skipped: int = 0
64
+ skipped_by_reason: dict[str, int] = field(default_factory=dict)
65
+
66
+ def __post_init__(self) -> None:
67
+ """Default ``removal_count`` to the sample size."""
68
+ if self.removal_count is None:
69
+ object.__setattr__(self, "removal_count", len(self.removal_candidates))
70
+
71
+
72
+ class IngestionGateway(Protocol):
73
+ """Durable ingestion capability consumed by application services."""
74
+
75
+ async def start_ingestion(
76
+ self, source: PreparedSourceSubmission
77
+ ) -> IngestionExecutionReference:
78
+ """Start the source ingestion run for ``source``."""
79
+
80
+ async def start_retry_failures(
81
+ self, request: IngestionRetryRequest
82
+ ) -> IngestionExecutionReference:
83
+ """Start a retry run for the failed documents named in ``request``."""
84
+
85
+ async def get_status(self, task_id: str) -> IngestionExecutionStatus:
86
+ """Return the execution status of run ``task_id``."""
87
+
88
+ async def get_progress(self, task_id: str) -> dict[str, int]:
89
+ """Return the document counts of run ``task_id``."""
90
+
91
+ async def execution_status(self, task_id: str, kind: RunKind = RunKind.SOURCE) -> str:
92
+ """Return the provider's status string for run ``task_id`` of ``kind``."""
93
+
94
+ async def result(self, task_id: str) -> IngestionExecutionResult:
95
+ """Return the final result of run ``task_id``."""
96
+
97
+ async def pause(self, task_id: str) -> None:
98
+ """Pause run ``task_id``."""
99
+
100
+ async def resume(self, task_id: str) -> None:
101
+ """Resume run ``task_id``."""
102
+
103
+ async def cancel(self, task_id: str, kind: RunKind = RunKind.SOURCE) -> None:
104
+ """Cancel run ``task_id`` of ``kind``."""
105
+
106
+ async def health(self) -> bool:
107
+ """Return whether the execution provider is reachable."""
@@ -0,0 +1,81 @@
1
+ """Conversation history for HarborRAG chat.
2
+
3
+ This package re-exports the conversation contracts from ``harborrag_core`` and
4
+ ``MemoryContext``, the per-turn replay window that chat sends to the model.
5
+ Messages, titles, turn locks, usage records, the conversation directory, memory
6
+ administration and erasure live in its submodules.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from harborrag_core.ports.conversation import (
12
+ MAX_CONVERSATION_PAGE_LIMIT,
13
+ MAX_CONVERSATION_TITLE_LENGTH,
14
+ ConversationDirectory,
15
+ ConversationHistoryRepository,
16
+ ConversationIdentity,
17
+ ConversationMemory,
18
+ ConversationMessage,
19
+ ConversationMessageStore,
20
+ ConversationPage,
21
+ ConversationRepository,
22
+ ConversationRole,
23
+ ConversationSessions,
24
+ ConversationSummaryRow,
25
+ ConversationTurn,
26
+ decode_conversation_cursor,
27
+ encode_conversation_cursor,
28
+ new_message_id,
29
+ new_session_id,
30
+ normalize_conversation_title,
31
+ turns_from_messages,
32
+ )
33
+ from harborrag_core.ports.memory import (
34
+ Memory,
35
+ MemoryOwner,
36
+ MemoryQuery,
37
+ MemoryRepository,
38
+ MemoryScope,
39
+ MemoryType,
40
+ )
41
+ from harborrag_core.ports.usage import (
42
+ ModelUsageRecord,
43
+ ModelUsageRepository,
44
+ ModelUsageTotals,
45
+ new_usage_id,
46
+ )
47
+ from harborrag_runtime.memory.context import MemoryContext
48
+
49
+ __all__ = [
50
+ "MAX_CONVERSATION_PAGE_LIMIT",
51
+ "MAX_CONVERSATION_TITLE_LENGTH",
52
+ "ConversationDirectory",
53
+ "ConversationHistoryRepository",
54
+ "ConversationIdentity",
55
+ "ConversationMemory",
56
+ "ConversationMessage",
57
+ "ConversationMessageStore",
58
+ "ConversationPage",
59
+ "ConversationRepository",
60
+ "ConversationRole",
61
+ "ConversationSessions",
62
+ "ConversationSummaryRow",
63
+ "ConversationTurn",
64
+ "Memory",
65
+ "MemoryContext",
66
+ "MemoryOwner",
67
+ "MemoryQuery",
68
+ "MemoryRepository",
69
+ "MemoryScope",
70
+ "MemoryType",
71
+ "ModelUsageRecord",
72
+ "ModelUsageRepository",
73
+ "ModelUsageTotals",
74
+ "decode_conversation_cursor",
75
+ "encode_conversation_cursor",
76
+ "new_message_id",
77
+ "new_session_id",
78
+ "new_usage_id",
79
+ "normalize_conversation_title",
80
+ "turns_from_messages",
81
+ ]
@@ -0,0 +1,47 @@
1
+ """The authenticated caller's own memory isolation key.
2
+
3
+ ``MemoryIdentity`` covers a *turn* (in a session, or a one-off question). Administration
4
+ is broader: listing and user erasure have no session, so this is the same
5
+ identity with ``session_id`` optional. Both are built from the authenticated
6
+ principal, never from request fields, which is what makes "the caller's own
7
+ memories" enforceable at the storage layer rather than in a route.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+
14
+ from harborrag_core.ports.memory import MemoryOwner
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class MemoryAccess:
19
+ """Who is asking, and which slice of their memory they are asking about."""
20
+
21
+ tenant_id: str
22
+ principal_id: str
23
+ user_id: str
24
+ project_id: str | None = None
25
+ session_id: str | None = None
26
+
27
+ def owner(self) -> MemoryOwner:
28
+ """The long-term memory isolation key for this caller."""
29
+ return MemoryOwner(
30
+ tenant_id=self.tenant_id,
31
+ project_id=self.project_id,
32
+ principal_id=self.principal_id,
33
+ user_id=self.user_id,
34
+ session_id=self.session_id,
35
+ )
36
+
37
+ def target(self, user_id: str) -> MemoryOwner:
38
+ """The isolation key of another end user in the caller's tenant.
39
+
40
+ Used only by the administrative erasure path, where the actor and the
41
+ subject of the erasure are different people.
42
+ """
43
+ return MemoryOwner(
44
+ tenant_id=self.tenant_id,
45
+ principal_id=self.principal_id,
46
+ user_id=user_id,
47
+ )
@@ -0,0 +1,460 @@
1
+ """Introspection and right-to-erasure over one caller's remembered data.
2
+
3
+ Erasure spans conversation history, stored completion requests, canonical
4
+ memories and the memory vector index, which are keyed differently. A user's
5
+ sessions are found through the conversation listing, so a session that produced
6
+ no memory is erased too. No caller deletes a GLOBAL memory here.
7
+
8
+ Typical usage example:
9
+
10
+ service = MemoryAdministrationService(conversations=history, memories=store)
11
+ report = await service.erase_user(owner, actor=admin_id)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import dataclasses
17
+ import logging
18
+ from dataclasses import dataclass
19
+ from typing import TYPE_CHECKING
20
+
21
+ from harborrag_core.contracts.errors import (
22
+ HarborAuthError,
23
+ HarborNotFoundError,
24
+ HarborUnavailableError,
25
+ )
26
+ from harborrag_core.domain.pending_effect import PendingControlPlaneEffect
27
+ from harborrag_core.ports.control_plane import PendingEffectRepositoryPort
28
+ from harborrag_core.ports.conversation import MAX_CONVERSATION_PAGE_LIMIT, ConversationIdentity
29
+ from harborrag_core.ports.memory import MemoryOwner, MemoryQuery, MemoryScope
30
+
31
+ from .erasure import SESSION_ERASURE, MemoryErasureJournal, stored_owner
32
+
33
+ if TYPE_CHECKING:
34
+ from harborrag_core.ports.conversation import ConversationHistoryRepository
35
+ from harborrag_core.ports.memory import Memory, MemoryIndex, MemoryRepository
36
+
37
+ logger = logging.getLogger("harborrag.memory.administration")
38
+
39
+ _PAGE = 1_000
40
+ _MAX_PASSES = 50
41
+ """Most pages one purge or session erasure reads: 50k memories or 5k sessions of one user.
42
+
43
+ Bounds an erasure of a store that keeps growing while it is erased.
44
+ """
45
+ _USER_SCOPES = (MemoryScope.USER,)
46
+ _SESSION_SCOPES = (MemoryScope.SESSION,)
47
+ _AUTHORED_SCOPES = (MemoryScope.PROJECT, MemoryScope.TENANT)
48
+ """Scopes of rows a user authored that a visibility query cannot single out.
49
+
50
+ PROJECT and TENANT key on fields other than the user, so these rows are matched
51
+ on the row's stored user instead.
52
+ """
53
+ _SHARED_SCOPES = frozenset({MemoryScope.PROJECT, MemoryScope.TENANT})
54
+ """Scopes whose rows are shared beyond their author.
55
+
56
+ They are visible to anyone in the tenant (and project) by design, but only the
57
+ author -- or a caller granted the scope through ``shared_scopes`` -- may delete
58
+ one, and only the author sees its provenance.
59
+ """
60
+ _NO_STORE = "long-term memory is not configured for this deployment"
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class _Purged:
65
+ """Totals of one purge, plus the conversations its rows came from.
66
+
67
+ Attributes:
68
+ memories: Canonical memory rows deleted.
69
+ index_points: Vector index points deleted.
70
+ conversations: ``(principal_id, session_id)`` pairs the deleted rows came from.
71
+ """
72
+
73
+ memories: int = 0
74
+ index_points: int = 0
75
+ conversations: frozenset[tuple[str, str]] = frozenset()
76
+
77
+
78
+ @dataclass(frozen=True, slots=True)
79
+ class ErasureReport:
80
+ """What one erasure actually removed, per category.
81
+
82
+ Attributes:
83
+ memories: Canonical memory rows deleted.
84
+ index_points: Memory vector index points deleted.
85
+ sessions: Conversation sessions deleted.
86
+ conversation_messages_cleared: Sessions whose messages were deleted, not a
87
+ message count.
88
+ completion_requests: Stored completion requests deleted, with their answers.
89
+ """
90
+
91
+ memories: int = 0
92
+ index_points: int = 0
93
+ sessions: int = 0
94
+ conversation_messages_cleared: int = 0
95
+ completion_requests: int = 0
96
+
97
+ def as_dict(self) -> dict[str, int]:
98
+ """Return the counts keyed by category, as the erasure endpoints report them."""
99
+ return {
100
+ "memories": self.memories,
101
+ "index_points": self.index_points,
102
+ "sessions": self.sessions,
103
+ "conversation_messages_cleared": self.conversation_messages_cleared,
104
+ "completion_requests": self.completion_requests,
105
+ }
106
+
107
+
108
+ class MemoryAdministrationService:
109
+ """Read and erase the memory of one authenticated caller.
110
+
111
+ Args:
112
+ conversations: Conversation history store whose sessions and messages are erased.
113
+ memories: Canonical long-term memory store, or None when the deployment has none.
114
+ index: Vector index over memories, or None when the deployment has none.
115
+ pending_effects: Durable journal of erasure intents, replayed after a
116
+ partial failure. None erases without a journal.
117
+ """
118
+
119
+ def __init__(
120
+ self,
121
+ *,
122
+ conversations: ConversationHistoryRepository,
123
+ memories: MemoryRepository | None = None,
124
+ index: MemoryIndex | None = None,
125
+ pending_effects: PendingEffectRepositoryPort | None = None,
126
+ ) -> None:
127
+ self._conversations = conversations
128
+ self._memories = memories
129
+ self._index = index
130
+ self._erasure = MemoryErasureJournal(memories, index, pending_effects)
131
+
132
+ def _store(self) -> MemoryRepository:
133
+ if self._memories is None:
134
+ raise HarborUnavailableError(_NO_STORE)
135
+ return self._memories
136
+
137
+ async def list_memories(
138
+ self,
139
+ owner: MemoryOwner,
140
+ *,
141
+ scopes: tuple[MemoryScope, ...] = (),
142
+ limit: int = 20,
143
+ ) -> tuple[Memory, ...]:
144
+ """Return the memories visible to ``owner``, newest and most important first.
145
+
146
+ Besides the caller's own rows, this includes PROJECT and TENANT rows other
147
+ users authored, which come back without provenance. Facts outside their
148
+ validity window are included, but not expired rows. A deployment without
149
+ a long-term store raises ``HarborUnavailableError``.
150
+
151
+ Args:
152
+ owner: The authenticated caller. Its ``project_id`` is the project it
153
+ chose to read.
154
+ scopes: Scopes to return, or empty for every scope.
155
+ limit: Maximum memories to return.
156
+
157
+ Returns:
158
+ At most ``limit`` visible memories.
159
+ """
160
+ rows = await self._store().search(
161
+ MemoryQuery(owner=owner, scopes=scopes, limit=limit, include_invalid=True)
162
+ )
163
+ return tuple(
164
+ row
165
+ if _authored_by(row, owner)
166
+ else dataclasses.replace(row, source_session_id=None, source_message_ids=())
167
+ for row in rows
168
+ )
169
+
170
+ async def delete_memory(
171
+ self,
172
+ owner: MemoryOwner,
173
+ memory_id: str,
174
+ *,
175
+ shared_scopes: frozenset[MemoryScope] = frozenset(),
176
+ ) -> None:
177
+ """Delete one memory the caller can see, with its vector index point.
178
+
179
+ Refusals come before anything is erased or journaled. A deployment without
180
+ a long-term store raises ``HarborUnavailableError``.
181
+
182
+ Args:
183
+ owner: The authenticated caller. Visibility and authorship are judged
184
+ against it.
185
+ memory_id: The memory to delete.
186
+ shared_scopes: Shared scopes the caller's role moderates. In them it
187
+ may delete rows other users authored.
188
+
189
+ Raises:
190
+ HarborNotFoundError: The memory does not exist or ``owner`` cannot see it.
191
+ HarborAuthError: The memory is GLOBAL, or is a PROJECT or TENANT row
192
+ ``owner`` neither authored nor moderates. The error is ``forbidden``.
193
+ """
194
+ store = self._store()
195
+ memory = await store.get(owner, memory_id)
196
+ if memory is None:
197
+ raise HarborNotFoundError("Memory was not found")
198
+ if memory.scope is MemoryScope.GLOBAL:
199
+ raise HarborAuthError(
200
+ "global memory deletes require an administrative capability", forbidden=True
201
+ )
202
+ if (
203
+ memory.scope in _SHARED_SCOPES
204
+ and memory.scope not in shared_scopes
205
+ and not _authored_by(memory, owner)
206
+ ):
207
+ raise HarborAuthError(
208
+ f"only the author may delete this {memory.scope.value} memory", forbidden=True
209
+ )
210
+ await self._erasure.erase_memory(memory)
211
+ logger.info(
212
+ "Memory deleted tenant=%s actor=%s memory_id=%s scope=%s",
213
+ owner.tenant_id,
214
+ owner.principal_id,
215
+ memory_id,
216
+ memory.scope.value,
217
+ )
218
+
219
+ async def erase_session(self, owner: MemoryOwner, *, actor: str) -> ErasureReport:
220
+ """Erase one session with its messages, session memories and their vectors.
221
+
222
+ The session itself is deleted, so it leaves the caller's conversation list.
223
+ When a journal is configured, the intent is recorded first, so recovery
224
+ finishes an erasure that fails partway.
225
+
226
+ Args:
227
+ owner: The caller, naming the principal and session to erase.
228
+ actor: Who asked for the erasure, recorded in the log.
229
+
230
+ Returns:
231
+ What the erasure removed.
232
+
233
+ Raises:
234
+ HarborNotFoundError: ``owner`` names no session, or the session does not
235
+ exist.
236
+ """
237
+ if owner.session_id is None or owner.principal_id is None:
238
+ raise HarborNotFoundError("Conversation session was not found")
239
+ identity = ConversationIdentity(
240
+ owner.tenant_id,
241
+ owner.principal_id,
242
+ owner.session_id,
243
+ owner.user_id or owner.principal_id,
244
+ )
245
+ if not await self._conversations.exists(identity):
246
+ raise HarborNotFoundError("Conversation session was not found")
247
+ effect_id = await self._erasure.begin(
248
+ SESSION_ERASURE,
249
+ owner,
250
+ memories_required=self._memories is not None,
251
+ index_required=self._index is not None,
252
+ )
253
+ purged = await self._purge(owner, _SESSION_SCOPES)
254
+ await self._conversations.delete(identity)
255
+ await self._erasure.complete(effect_id)
256
+ report = ErasureReport(
257
+ memories=purged.memories,
258
+ index_points=purged.index_points,
259
+ sessions=1,
260
+ conversation_messages_cleared=1,
261
+ )
262
+ _log_erasure("session", owner.tenant_id, actor, owner.session_id, report)
263
+ return report
264
+
265
+ async def recover_erasure(self, effect: PendingControlPlaneEffect) -> bool:
266
+ """Replay an erasure intent that a partial failure left pending.
267
+
268
+ The intent's stored owner was authorized when it was queued, so the replay
269
+ works even after the session or canonical row is gone.
270
+
271
+ Args:
272
+ effect: A pending control-plane effect of any kind.
273
+
274
+ Returns:
275
+ True when the effect was an erasure intent and was replayed, False when
276
+ it is another kind of effect.
277
+
278
+ Raises:
279
+ HarborUnavailableError: A store the intent requires is not configured.
280
+ """
281
+ if await self._erasure.replay(effect):
282
+ return True
283
+ if effect.kind != SESSION_ERASURE:
284
+ return False
285
+ owner = stored_owner(effect.payload["owner"])
286
+ if effect.payload.get("memories_required") and self._memories is None:
287
+ raise HarborUnavailableError("session erasure memory store is not configured")
288
+ if effect.payload.get("index_required") and self._index is None:
289
+ raise HarborUnavailableError("session erasure index is not configured")
290
+ if owner.principal_id is None or owner.session_id is None:
291
+ raise ValueError("session erasure intent lacks its ownership key")
292
+ await self._purge(owner, _SESSION_SCOPES)
293
+ await self._conversations.delete(
294
+ ConversationIdentity(
295
+ owner.tenant_id,
296
+ owner.principal_id,
297
+ owner.session_id,
298
+ owner.user_id or owner.principal_id,
299
+ )
300
+ )
301
+ return True
302
+
303
+ async def erase_user(self, owner: MemoryOwner, *, actor: str) -> ErasureReport:
304
+ """Erase everything kept for one end user within the tenant.
305
+
306
+ User-scoped memories are purged first. Every conversation session of the
307
+ user is then deleted with its messages and session memories, whether or not
308
+ it produced a memory, and session memories of sessions already gone are
309
+ purged too. A last pass erases PROJECT and TENANT rows the user authored,
310
+ which no visibility query reaches, then every stored completion request of
311
+ the user, with or without a session. Erasing again finishes an erasure that
312
+ failed partway.
313
+
314
+ Args:
315
+ owner: The caller, naming the tenant and the end user to erase.
316
+ actor: Who asked for the erasure, recorded in the log.
317
+
318
+ Returns:
319
+ What the erasure removed.
320
+
321
+ Raises:
322
+ HarborNotFoundError: ``owner`` names no end user.
323
+ HarborConflictError: A session of the user is answering a turn; erase
324
+ again once it ends.
325
+ """
326
+ target = owner.user_id
327
+ if target is None:
328
+ raise HarborNotFoundError("User was not found")
329
+ user_owner = MemoryOwner(tenant_id=owner.tenant_id, user_id=target)
330
+ user_memories = await self._purge(user_owner, _USER_SCOPES)
331
+ session_memories, sessions = await self._erase_sessions(owner.tenant_id, target)
332
+ purged = [user_memories, session_memories]
333
+ remembered = {session_id for _, session_id in user_memories.conversations}
334
+ for session_id in sorted(remembered.difference(sessions)):
335
+ session_owner = dataclasses.replace(user_owner, session_id=session_id)
336
+ purged.append(await self._purge(session_owner, _SESSION_SCOPES))
337
+ purged.append(await self._purge(user_owner, _AUTHORED_SCOPES, stored_by_owner=True))
338
+ requests = await self._conversations.erase_completions(
339
+ tenant_id=owner.tenant_id, user_id=target
340
+ )
341
+ report = ErasureReport(
342
+ memories=sum(item.memories for item in purged),
343
+ index_points=sum(item.index_points for item in purged),
344
+ sessions=len(sessions),
345
+ conversation_messages_cleared=len(sessions),
346
+ completion_requests=requests,
347
+ )
348
+ _log_erasure("user", owner.tenant_id, actor, target, report)
349
+ return report
350
+
351
+ async def _erase_sessions(
352
+ self, tenant_id: str, user_id: str
353
+ ) -> tuple[_Purged, tuple[str, ...]]:
354
+ """Delete every session of one end user, each after its session memories.
355
+
356
+ A session whose memories could not be purged is still listed for the next
357
+ erasure. Deleted sessions leave the listing, so each pass reads its first
358
+ page again until a pass deletes nothing.
359
+
360
+ Returns:
361
+ The session memories purged, and the ids of the sessions deleted.
362
+ """
363
+ memories = points = 0
364
+ deleted: list[str] = []
365
+ for _ in range(_MAX_PASSES):
366
+ page = await self._conversations.list_conversations(
367
+ tenant_id=tenant_id, user_id=user_id, limit=MAX_CONVERSATION_PAGE_LIMIT
368
+ )
369
+ before = len(deleted)
370
+ for row in page.conversations:
371
+ session_owner = MemoryOwner(
372
+ tenant_id=tenant_id, user_id=user_id, session_id=row.session_id
373
+ )
374
+ session_purge = await self._purge(session_owner, _SESSION_SCOPES)
375
+ memories += session_purge.memories
376
+ points += session_purge.index_points
377
+ identity = ConversationIdentity(tenant_id, user_id, row.session_id, user_id)
378
+ if await self._conversations.delete(identity):
379
+ deleted.append(row.session_id)
380
+ if len(deleted) == before:
381
+ return _Purged(memories, points), tuple(deleted)
382
+ logger.warning(
383
+ "Session erasure stopped after %d passes for tenant=%s; sessions may remain",
384
+ _MAX_PASSES,
385
+ tenant_id,
386
+ )
387
+ return _Purged(memories, points), tuple(deleted)
388
+
389
+ async def _purge(
390
+ self,
391
+ owner: MemoryOwner,
392
+ scopes: tuple[MemoryScope, ...],
393
+ *,
394
+ stored_by_owner: bool = False,
395
+ ) -> _Purged:
396
+ """Delete the memories of ``owner`` at ``scopes``, with their vectors.
397
+
398
+ Rows are matched by visibility to ``owner``, or by stored user when
399
+ ``stored_by_owner`` is set. Each row is erased under its own stored owner,
400
+ which always passes the repository's visibility check. The conversations
401
+ the rows came from are collected across every page.
402
+ """
403
+ if self._memories is None:
404
+ return _Purged()
405
+ deleted = 0
406
+ unindexed = 0
407
+ conversations: set[tuple[str, str]] = set()
408
+ for _ in range(_MAX_PASSES):
409
+ rows = await self._memories.search(
410
+ MemoryQuery(
411
+ owner=owner,
412
+ scopes=scopes,
413
+ limit=_PAGE,
414
+ include_invalid=True,
415
+ stored_by_owner=stored_by_owner,
416
+ )
417
+ )
418
+ if not rows:
419
+ return _Purged(deleted, unindexed, frozenset(conversations))
420
+ for row in rows:
421
+ unindexed += await self._erasure.erase_memory(row)
422
+ deleted += 1
423
+ principal_id = row.owner.principal_id
424
+ session_id = row.source_session_id or row.owner.session_id
425
+ if principal_id is not None and session_id is not None:
426
+ conversations.add((principal_id, session_id))
427
+ logger.warning(
428
+ "Memory purge stopped after %d passes for tenant=%s scopes=%s; rows may remain",
429
+ _MAX_PASSES,
430
+ owner.tenant_id,
431
+ ",".join(scope.value for scope in scopes),
432
+ )
433
+ return _Purged(deleted, unindexed, frozenset(conversations))
434
+
435
+
436
+ def _authored_by(memory: Memory, caller: MemoryOwner) -> bool:
437
+ """Return whether ``caller`` is the end user ``memory`` was stored under."""
438
+ return (
439
+ memory.owner.tenant_id == caller.tenant_id
440
+ and memory.owner.user_id is not None
441
+ and memory.owner.user_id == caller.user_id
442
+ )
443
+
444
+
445
+ def _log_erasure(
446
+ kind: str,
447
+ tenant_id: str,
448
+ actor: str,
449
+ target: str,
450
+ report: ErasureReport,
451
+ ) -> None:
452
+ """Log one erasure with identifiers and counts only, never content."""
453
+ logger.info(
454
+ "Memory erasure kind=%s tenant=%s actor=%s target=%s %s",
455
+ kind,
456
+ tenant_id,
457
+ actor,
458
+ target,
459
+ " ".join(f"{name}={value}" for name, value in report.as_dict().items()),
460
+ )