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,5 @@
1
+ """The per-turn conversation context chat replays to the model."""
2
+
3
+ from .result import MemoryContext
4
+
5
+ __all__ = ["MemoryContext"]
@@ -0,0 +1,20 @@
1
+ """The immutable conversation context of one chat turn."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from harborrag_core.ports.conversation import ConversationMessage
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class MemoryContext:
12
+ """The history one chat turn replays and the query it searches for.
13
+
14
+ ``messages`` is the verbatim window to replay, oldest first, and excludes
15
+ the question being answered. ``standalone_query`` is what retrieval
16
+ searches for; chat passes the raw question through unchanged.
17
+ """
18
+
19
+ messages: tuple[ConversationMessage, ...]
20
+ standalone_query: str
@@ -0,0 +1,166 @@
1
+ """Listing, reading, renaming, and deleting the conversations one human owns.
2
+
3
+ Every operation here is keyed by the authenticated caller's own
4
+ ``MemoryAccess``: the transport builds it from verified claims, never from
5
+ request fields, so "my conversations" is enforced by the storage predicate
6
+ rather than by a route remembering to filter. ``user_id`` is what owns a
7
+ conversation, so one service credential fronting several people cannot pool
8
+ their histories into a single listing.
9
+
10
+ Deletion is deliberately not implemented here. Erasing a conversation must
11
+ also remove the memories and vector points that conversation produced, and
12
+ ``MemoryAdministrationService.erase_session`` already does exactly that, so
13
+ this service delegates to it instead of growing a second erasure path.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import TYPE_CHECKING
19
+
20
+ from harborrag_core.contracts.errors import HarborNotFoundError, HarborValidationError
21
+ from harborrag_core.ports.conversation import (
22
+ ConversationIdentity,
23
+ decode_conversation_cursor,
24
+ encode_conversation_cursor,
25
+ normalize_conversation_title,
26
+ )
27
+
28
+ from .presenters import conversation_message_data, conversation_summary_data
29
+
30
+ if TYPE_CHECKING:
31
+ from harborrag_core.ports.conversation import ConversationHistoryRepository
32
+ from harborrag_runtime.memory.access import MemoryAccess
33
+ from harborrag_runtime.memory.administration import MemoryAdministrationService
34
+
35
+ _NOT_FOUND = "Conversation session was not found"
36
+
37
+
38
+ class ConversationDirectoryService:
39
+ """The caller's own conversation directory: list, read, rename, delete.
40
+
41
+ Args:
42
+ repository: Conversation store the directory reads and renames through.
43
+ administration: Memory administration service that owns the erasure path.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ repository: ConversationHistoryRepository,
49
+ administration: MemoryAdministrationService,
50
+ ) -> None:
51
+ self._repository = repository
52
+ self._administration = administration
53
+
54
+ async def list_conversations(
55
+ self,
56
+ access: MemoryAccess,
57
+ *,
58
+ cursor: str | None = None,
59
+ limit: int = 20,
60
+ title_query: str | None = None,
61
+ ) -> dict[str, object]:
62
+ """Return one page of the caller's sessions, newest activity first.
63
+
64
+ Args:
65
+ access: The caller's own conversation key.
66
+ cursor: ``next_cursor`` of the previous page.
67
+ limit: Page size.
68
+ title_query: Keep titles that contain this text, ignoring case.
69
+
70
+ Returns:
71
+ ``items`` of sessions and ``next_cursor``, ``None`` on the last page.
72
+
73
+ Raises:
74
+ HarborValidationError: The cursor is malformed or not the caller's.
75
+ """
76
+ try:
77
+ page = await self._repository.list_conversations(
78
+ tenant_id=access.tenant_id,
79
+ user_id=access.user_id,
80
+ cursor=cursor,
81
+ limit=limit,
82
+ title_query=(title_query or "").strip() or None,
83
+ )
84
+ except ValueError as exc:
85
+ raise HarborValidationError(str(exc), {"field": "cursor"}) from exc
86
+ return {
87
+ "items": [conversation_summary_data(row) for row in page.conversations],
88
+ "next_cursor": page.next_cursor,
89
+ }
90
+
91
+ async def messages(
92
+ self,
93
+ access: MemoryAccess,
94
+ *,
95
+ cursor: str | None = None,
96
+ limit: int = 20,
97
+ ) -> dict[str, object]:
98
+ """Return one page of a session's history, newest first.
99
+
100
+ One extra message is read so the last page never advertises a cursor
101
+ that would only lead to an empty page.
102
+
103
+ Args:
104
+ access: The caller's own conversation key, with its session.
105
+ cursor: ``next_cursor`` of the previous page.
106
+ limit: Page size.
107
+
108
+ Returns:
109
+ ``items`` of messages and ``next_cursor``, ``None`` on the last page.
110
+
111
+ Raises:
112
+ HarborNotFoundError: The session does not exist or is not the caller's.
113
+ HarborValidationError: The cursor is malformed or not from this session.
114
+ """
115
+ identity = self._identity(access)
116
+ if not await self._repository.exists(identity):
117
+ raise HarborNotFoundError(_NOT_FOUND)
118
+ try:
119
+ before = None if cursor is None else decode_conversation_cursor(cursor)
120
+ found = await self._repository.history_page(
121
+ identity, before_message_id=before, limit=limit + 1
122
+ )
123
+ except ValueError as exc:
124
+ raise HarborValidationError(str(exc), {"field": "cursor"}) from exc
125
+ page = found[:limit]
126
+ has_more = len(found) > limit
127
+ return {
128
+ "items": [
129
+ conversation_message_data(message, session_id=identity.session_id)
130
+ for message in page
131
+ ],
132
+ "next_cursor": encode_conversation_cursor(page[-1].message_id) if has_more else None,
133
+ }
134
+
135
+ async def rename(self, access: MemoryAccess, *, title: str) -> dict[str, object]:
136
+ """Retitle the caller's conversation; blank clears the title."""
137
+ renamed = await self._repository.rename_conversation(
138
+ self._identity(access),
139
+ title=title,
140
+ )
141
+ if not renamed:
142
+ raise HarborNotFoundError(_NOT_FOUND)
143
+ return {
144
+ "session_id": access.session_id,
145
+ "title": normalize_conversation_title(title),
146
+ }
147
+
148
+ async def delete(self, access: MemoryAccess) -> dict[str, object]:
149
+ """Erase the conversation, its memories, and their vector points."""
150
+ report = await self._administration.erase_session(
151
+ access.owner(),
152
+ actor=access.principal_id,
153
+ )
154
+ return {"session_id": access.session_id, **report.as_dict()}
155
+
156
+ @staticmethod
157
+ def _identity(access: MemoryAccess) -> ConversationIdentity:
158
+ """Return the conversation isolation key; a missing session is a 404, not a 500."""
159
+ if access.session_id is None:
160
+ raise HarborNotFoundError(_NOT_FOUND)
161
+ return ConversationIdentity(
162
+ access.tenant_id,
163
+ access.principal_id,
164
+ access.session_id,
165
+ access.user_id,
166
+ )
@@ -0,0 +1,122 @@
1
+ """Durable deletion intents retain identifiers until every store is erased."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from collections.abc import Mapping
7
+ from dataclasses import asdict, fields
8
+ from typing import Any
9
+ from uuid import uuid4
10
+
11
+ from harborrag_core.contracts.errors import HarborUnavailableError
12
+ from harborrag_core.domain.pending_effect import PendingControlPlaneEffect
13
+ from harborrag_core.ports.control_plane import PendingEffectRepositoryPort
14
+ from harborrag_core.ports.memory import Memory, MemoryIndex, MemoryOwner, MemoryRepository
15
+
16
+ logger = logging.getLogger("harborrag.memory.erasure")
17
+ MEMORY_ERASURE = "erase_memory"
18
+ SESSION_ERASURE = "erase_memory_session"
19
+ _OWNER_FIELDS = frozenset(field.name for field in fields(MemoryOwner))
20
+
21
+
22
+ def stored_owner(payload: Mapping[str, Any]) -> MemoryOwner:
23
+ """Rebuild the owner an erasure intent recorded.
24
+
25
+ Args:
26
+ payload: The ``owner`` mapping of a pending effect.
27
+
28
+ Returns:
29
+ The owner, ignoring fields an earlier release wrote (``run_id``).
30
+ """
31
+ return MemoryOwner(**{key: value for key, value in payload.items() if key in _OWNER_FIELDS})
32
+
33
+
34
+ class MemoryErasureJournal:
35
+ """Record erasure intents durably so an interrupted deletion can be replayed.
36
+
37
+ Args:
38
+ memories: Canonical memory rows, or None when long-term memory is off.
39
+ index: Vector index for memories, or None when none is configured.
40
+ pending: Journal of pending effects, or None to erase without recovery.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ memories: MemoryRepository | None,
46
+ index: MemoryIndex | None,
47
+ pending: PendingEffectRepositoryPort | None,
48
+ ) -> None:
49
+ self.memories = memories
50
+ self.index = index
51
+ self.pending = pending
52
+
53
+ async def begin(self, kind: str, owner: MemoryOwner, **fields: object) -> str | None:
54
+ """Enqueue an erasure intent and return its id, or None when no journal exists.
55
+
56
+ The enqueue failure propagates before any deletion loses the recovery identifiers.
57
+ """
58
+ if self.pending is None:
59
+ return None
60
+ effect = PendingControlPlaneEffect(
61
+ id=f"eff_{uuid4().hex}", kind=kind, payload={"owner": asdict(owner), **fields}
62
+ )
63
+ await self.pending.enqueue(effect)
64
+ return effect.id
65
+
66
+ async def complete(self, effect_id: str | None) -> None:
67
+ """Mark an erasure intent done; a missing id or journal is a no-op."""
68
+ if effect_id is not None and self.pending is not None:
69
+ await self.pending.complete(effect_id)
70
+
71
+ async def erase_memory(self, memory: Memory) -> int:
72
+ """Delete one memory row and its index point, returning the points removed.
73
+
74
+ Without a journal the index is cleared first, so the canonical row survives an
75
+ unavailable index; with one, an index failure queues the point for retry and returns 0.
76
+ """
77
+ effect_id = await self.begin(
78
+ MEMORY_ERASURE,
79
+ memory.owner,
80
+ memory_id=memory.memory_id,
81
+ index_required=self.index is not None,
82
+ )
83
+ if self.pending is None:
84
+ count = await self._unindex(memory.owner, memory.memory_id)
85
+ if self.memories is not None:
86
+ await self.memories.delete(memory.owner, memory.memory_id)
87
+ return count
88
+ if self.memories is not None:
89
+ await self.memories.delete(memory.owner, memory.memory_id)
90
+ try:
91
+ count = await self._unindex(memory.owner, memory.memory_id)
92
+ except Exception:
93
+ logger.warning(
94
+ "Memory index delete failed for tenant=%s memory_id=%s; queued for retry",
95
+ memory.owner.tenant_id,
96
+ memory.memory_id,
97
+ )
98
+ return 0
99
+ await self.complete(effect_id)
100
+ return count
101
+
102
+ async def replay(self, effect: PendingControlPlaneEffect) -> bool:
103
+ """Re-run a recorded memory erasure; return False for any other effect kind.
104
+
105
+ Raises:
106
+ HarborUnavailableError: The stores the intent needs are not configured.
107
+ """
108
+ if effect.kind != MEMORY_ERASURE:
109
+ return False
110
+ owner = stored_owner(effect.payload["owner"])
111
+ memory_id = effect.payload["memory_id"]
112
+ if self.memories is None or (effect.payload.get("index_required") and self.index is None):
113
+ raise HarborUnavailableError("memory erasure stores are not configured")
114
+ await self.memories.delete(owner, memory_id)
115
+ await self._unindex(owner, memory_id)
116
+ return True
117
+
118
+ async def _unindex(self, owner: MemoryOwner, memory_id: str) -> int:
119
+ if self.index is None:
120
+ return 0
121
+ await self.index.delete_memory(owner, memory_id)
122
+ return 1
@@ -0,0 +1,170 @@
1
+ """Per-session serialization for completions that read then write memory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import math
7
+ from collections import Counter
8
+ from collections.abc import AsyncIterator
9
+ from contextlib import asynccontextmanager, suppress
10
+ from uuid import uuid4
11
+
12
+ from harborrag_core.contracts.errors import HarborConflictError
13
+ from harborrag_core.ports.conversation import ConversationIdentity, ConversationTurnLeases
14
+
15
+
16
+ class ConversationTurnBusyError(HarborConflictError):
17
+ """The session remained busy beyond the configured acquisition deadline."""
18
+
19
+ error_code = "session_busy"
20
+
21
+
22
+ class ConversationTurnLeaseLostError(HarborConflictError):
23
+ """A running completion could no longer prove exclusive session ownership."""
24
+
25
+ error_code = "session_busy"
26
+
27
+
28
+ class SessionLocks:
29
+ """Serialize turns locally and, when supplied, through a shared lease store.
30
+
31
+ A completion recalls the latest turns, calls the model, then appends the
32
+ new turn. Two concurrent completions on one session (a client retry, a
33
+ double-submit) would otherwise interleave ``recent -> append`` and both
34
+ miss each other's turn. Holding the session lock for the whole completion
35
+ serializes them. Locks are dropped once nobody holds or awaits them, so
36
+ the map does not grow with the number of sessions ever seen.
37
+
38
+ Production callers supply the conversation repository. Omitting it is an
39
+ explicit process-local fallback for small test doubles. Shared leases are
40
+ renewed during inference, expire after worker crashes, and cancel their
41
+ owner if renewal fails. Idempotent response replay is a separate concern.
42
+
43
+ Args:
44
+ repository: Shared lease store; ``None`` keeps locks process-local.
45
+ lease_seconds: Lifetime of a shared lease before it must be renewed.
46
+ acquire_timeout: Longest a turn waits for a busy session, in seconds.
47
+ poll_interval: Pause between attempts to take a shared lease, in seconds.
48
+
49
+ Raises:
50
+ ValueError: A duration is not positive and finite.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ repository: ConversationTurnLeases | None = None,
56
+ *,
57
+ lease_seconds: float = 120,
58
+ acquire_timeout: float = 30,
59
+ poll_interval: float = 0.1,
60
+ ) -> None:
61
+ if any(
62
+ not math.isfinite(value) or value <= 0
63
+ for value in (lease_seconds, acquire_timeout, poll_interval)
64
+ ):
65
+ raise ValueError("conversation lock durations must be positive and finite")
66
+ self._repository = repository
67
+ self._lease_seconds = lease_seconds
68
+ self._acquire_timeout = acquire_timeout
69
+ self._poll_interval = poll_interval
70
+ self._locks: dict[ConversationIdentity, asyncio.Lock] = {}
71
+ self._holders: Counter[ConversationIdentity] = Counter()
72
+
73
+ @asynccontextmanager
74
+ async def hold(
75
+ self, identity: ConversationIdentity, *, wait: bool = True
76
+ ) -> AsyncIterator[None]:
77
+ """Hold the session's turn for the body of the ``async with``.
78
+
79
+ Args:
80
+ identity: The session.
81
+ wait: Wait up to the acquire timeout for a busy session; ``False`` refuses
82
+ at once.
83
+
84
+ Raises:
85
+ ConversationTurnBusyError: Another turn holds the session.
86
+ """
87
+ lock = self._locks.setdefault(identity, asyncio.Lock())
88
+ self._holders[identity] += 1
89
+ deadline = asyncio.get_running_loop().time() + self._acquire_timeout
90
+ try:
91
+ try:
92
+ if not wait and lock.locked():
93
+ raise ConversationTurnBusyError("conversation has an active completion")
94
+ async with asyncio.timeout_at(deadline):
95
+ await lock.acquire()
96
+ except TimeoutError as exc:
97
+ raise ConversationTurnBusyError("conversation has an active completion") from exc
98
+ try:
99
+ async with self._hold_shared(identity, deadline=deadline, wait=wait):
100
+ yield
101
+ finally:
102
+ lock.release()
103
+ finally:
104
+ self._holders[identity] -= 1
105
+ if self._holders[identity] <= 0:
106
+ del self._holders[identity]
107
+ self._locks.pop(identity, None)
108
+
109
+ @asynccontextmanager
110
+ async def _hold_shared(
111
+ self, identity: ConversationIdentity, *, deadline: float, wait: bool
112
+ ) -> AsyncIterator[None]:
113
+ """Hold the shared lease, renewing it while the body runs.
114
+
115
+ A heartbeat renews the lease every third of its lifetime and cancels the owning task
116
+ when renewal fails. On exit the lease is released, and when it was lost only the
117
+ cancellation sent by this heartbeat is consumed before the loss is raised.
118
+ """
119
+ repository = self._repository
120
+ if repository is None:
121
+ yield
122
+ return
123
+ token = uuid4().hex
124
+ try:
125
+ async with asyncio.timeout_at(deadline):
126
+ while not await repository.acquire_turn_lease(
127
+ identity, token=token, lease_seconds=self._lease_seconds
128
+ ):
129
+ if not wait:
130
+ raise ConversationTurnBusyError("conversation has an active completion")
131
+ await asyncio.sleep(self._poll_interval)
132
+ except TimeoutError as exc:
133
+ raise ConversationTurnBusyError("conversation has an active completion") from exc
134
+
135
+ owner = asyncio.current_task()
136
+ assert owner is not None
137
+ lost = asyncio.Event()
138
+
139
+ async def heartbeat() -> None:
140
+ interval = self._lease_seconds / 3
141
+ try:
142
+ while True:
143
+ await asyncio.sleep(interval)
144
+ async with asyncio.timeout(interval):
145
+ renewed = await repository.renew_turn_lease(
146
+ identity, token=token, lease_seconds=self._lease_seconds
147
+ )
148
+ if not renewed:
149
+ raise ConversationTurnLeaseLostError("conversation lease expired")
150
+ except Exception:
151
+ lost.set()
152
+ owner.cancel()
153
+
154
+ renewal = asyncio.create_task(heartbeat(), name="conversation-turn-lease")
155
+ try:
156
+ yield
157
+ finally:
158
+ renewal.cancel()
159
+ with suppress(asyncio.CancelledError):
160
+ await renewal
161
+ try:
162
+ await repository.release_turn_lease(identity, token=token)
163
+ finally:
164
+ if lost.is_set():
165
+ owner.uncancel()
166
+ raise ConversationTurnLeaseLostError("conversation turn lease was lost")
167
+
168
+ def active(self, identity: ConversationIdentity) -> bool:
169
+ """Report whether a completion currently holds or awaits this session's lock."""
170
+ return self._holders[identity] > 0
@@ -0,0 +1,202 @@
1
+ """Build and persist per-message history records for one conversation turn.
2
+
3
+ The question and the answer are written separately, because they become
4
+ durable at different moments: the question is committed to as soon as the
5
+ turn starts, while the answer only exists once the provider has delivered
6
+ text. A streamed turn that dies mid-flight therefore still leaves both the
7
+ question and whatever answer reached the caller, the latter marked
8
+ ``partial``.
9
+
10
+ ``record_exchange`` writes a completed exchange in one write instead, with the
11
+ answer's mode, trace and numbered citations, so the assistant message id can
12
+ serve as the completion's ``completion_id``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import logging
19
+ from collections.abc import Sequence
20
+ from dataclasses import asdict, dataclass, field
21
+ from typing import Literal, get_args
22
+
23
+ from harborrag_core.base import utc_now
24
+ from harborrag_core.ports.conversation import (
25
+ ConversationIdentity,
26
+ ConversationMessage,
27
+ ConversationMessageStore,
28
+ new_message_id,
29
+ )
30
+
31
+ logger = logging.getLogger("harborrag.memory.messages")
32
+
33
+ ChatMode = Literal["instant", "classic"]
34
+ """The answer modes chat runs in this release."""
35
+ CHAT_MODES: tuple[ChatMode, ...] = get_args(ChatMode)
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class CitationRecord:
40
+ """One numbered source of an assistant answer, stored as history returns it.
41
+
42
+ Raises:
43
+ ValueError: ``n`` is below 1.
44
+ """
45
+
46
+ n: int
47
+ chunk_id: str
48
+ document_id: str
49
+ title: str
50
+ snippet: str
51
+ url: str | None = None
52
+ page: int | None = None
53
+
54
+ def __post_init__(self) -> None:
55
+ """Reject a citation number below 1."""
56
+ if self.n < 1:
57
+ raise ValueError("citation n starts at 1")
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class ExchangeRecord:
62
+ """One completed question and its answer, with what the answer was built from.
63
+
64
+ ``answer_id`` is the assistant message id; a caller that must hand it out
65
+ before the write (a completion's ``completion_id``) generates it with
66
+ ``new_message_id`` and passes it here.
67
+
68
+ Raises:
69
+ ValueError: ``mode`` is not one of ``CHAT_MODES``.
70
+ """
71
+
72
+ question: str
73
+ answer: str
74
+ mode: ChatMode
75
+ trace_id: str
76
+ citations: tuple[CitationRecord, ...] = ()
77
+ completion_tokens: int | None = None
78
+ question_id: str = field(default_factory=new_message_id)
79
+ answer_id: str = field(default_factory=new_message_id)
80
+
81
+ def __post_init__(self) -> None:
82
+ """Reject a mode outside ``CHAT_MODES``."""
83
+ if self.mode not in CHAT_MODES:
84
+ raise ValueError(f"exchange mode must be one of {', '.join(CHAT_MODES)}")
85
+
86
+
87
+ async def record_exchange(
88
+ store: ConversationMessageStore,
89
+ identity: ConversationIdentity,
90
+ exchange: ExchangeRecord,
91
+ ) -> tuple[ConversationMessage, ConversationMessage]:
92
+ """Persist a user message and its assistant answer in one write.
93
+
94
+ Args:
95
+ store: The conversation message store.
96
+ identity: The owner and session the exchange belongs to.
97
+ exchange: The question, the answer and the answer's metadata.
98
+
99
+ Returns:
100
+ The stored user message and assistant message, in that order.
101
+
102
+ Raises:
103
+ ValueError: The session does not exist.
104
+ HarborConflictError: Another completion holds the session's turn lease, or the
105
+ caller's lease expired; a plain conflict, answered as ``invalid_state``.
106
+ """
107
+ created_at = utc_now()
108
+ question = ConversationMessage(
109
+ message_id=exchange.question_id,
110
+ role="user",
111
+ content=exchange.question,
112
+ created_at=created_at,
113
+ )
114
+ answer = ConversationMessage(
115
+ message_id=exchange.answer_id,
116
+ role="assistant",
117
+ content=exchange.answer,
118
+ created_at=created_at,
119
+ token_count=exchange.completion_tokens,
120
+ citations_json=json.dumps([asdict(citation) for citation in exchange.citations]),
121
+ mode=exchange.mode,
122
+ trace_id=exchange.trace_id,
123
+ )
124
+ await store.append_messages(identity, (question, answer))
125
+ return question, answer
126
+
127
+
128
+ def question_message(content: str) -> ConversationMessage:
129
+ """The user's question, persisted before the model is called.
130
+
131
+ Prompt tokens are not attributable to one message, so this record carries
132
+ no ``token_count``; the answer carries the completion count instead.
133
+ """
134
+ return ConversationMessage(
135
+ message_id=new_message_id(),
136
+ role="user",
137
+ content=content,
138
+ created_at=utc_now(),
139
+ )
140
+
141
+
142
+ def answer_message(
143
+ content: str,
144
+ *,
145
+ citations: Sequence[object] = (),
146
+ completion_tokens: int | None = None,
147
+ partial: bool = False,
148
+ ) -> ConversationMessage:
149
+ """The assistant answer, with the citations already returned to the caller.
150
+
151
+ Both the streaming and the non-streaming path build their answer here, so
152
+ an incomplete stream is marked exactly the same way whichever path wrote
153
+ it. ``partial`` defaults to False: a turn is complete unless a caller says
154
+ otherwise, and it is a field on the canonical record so the flag survives
155
+ a database round trip rather than only living in this process.
156
+ """
157
+ return ConversationMessage(
158
+ message_id=new_message_id(),
159
+ role="assistant",
160
+ content=content,
161
+ created_at=utc_now(),
162
+ token_count=completion_tokens,
163
+ citations_json=json.dumps(list(citations)) if citations else None,
164
+ partial=partial,
165
+ )
166
+
167
+
168
+ async def append_exchange(
169
+ store: ConversationMessageStore,
170
+ identity: ConversationIdentity,
171
+ messages: Sequence[ConversationMessage],
172
+ ) -> tuple[ConversationMessage, ...] | None:
173
+ """Append ``messages`` and return them; ``None`` (never raise) on failure.
174
+
175
+ The model call has already been paid for by the time this runs, so a
176
+ memory failure must not turn a good answer into a 503. It is logged with
177
+ identifiers only -- never prompt or answer text. The persisted records are
178
+ returned so long-term extraction can cite them as provenance without
179
+ re-deriving their identifiers.
180
+ """
181
+ persisted = tuple(messages)
182
+ try:
183
+ await store.append_messages(identity, persisted)
184
+ except Exception: # noqa: BLE001 - non-fatal by design
185
+ logger.exception(
186
+ "Conversation memory append failed for tenant=%s session=%s; "
187
+ "answer returned without persisting the turn",
188
+ identity.tenant_id,
189
+ identity.session_id,
190
+ )
191
+ return None
192
+ return persisted
193
+
194
+
195
+ async def append_message(
196
+ store: ConversationMessageStore,
197
+ identity: ConversationIdentity,
198
+ message: ConversationMessage,
199
+ ) -> ConversationMessage | None:
200
+ """Append one message and return it; ``None`` (never raise) on failure."""
201
+ persisted = await append_exchange(store, identity, (message,))
202
+ return None if persisted is None else persisted[0]