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.
- harborrag_runtime/__init__.py +22 -0
- harborrag_runtime/application/README.md +39 -0
- harborrag_runtime/application/__init__.py +39 -0
- harborrag_runtime/application/chat/__init__.py +7 -0
- harborrag_runtime/application/chat/citations.py +149 -0
- harborrag_runtime/application/chat/client.py +201 -0
- harborrag_runtime/application/chat/completion.py +92 -0
- harborrag_runtime/application/chat/completion_request.py +130 -0
- harborrag_runtime/application/chat/evidence.py +202 -0
- harborrag_runtime/application/chat/options.py +43 -0
- harborrag_runtime/application/chat/preparation.py +135 -0
- harborrag_runtime/application/chat/presenters.py +130 -0
- harborrag_runtime/application/chat/prompting.py +127 -0
- harborrag_runtime/application/chat/query_scope.py +146 -0
- harborrag_runtime/application/chat/replay.py +141 -0
- harborrag_runtime/application/chat/request_filters.py +134 -0
- harborrag_runtime/application/chat/retrieval.py +127 -0
- harborrag_runtime/application/chat/service.py +371 -0
- harborrag_runtime/application/composition/__init__.py +1 -0
- harborrag_runtime/application/composition/factories.py +106 -0
- harborrag_runtime/application/composition/resources.py +141 -0
- harborrag_runtime/application/composition/selection.py +65 -0
- harborrag_runtime/application/composition/service.py +550 -0
- harborrag_runtime/application/composition/tenant_models.py +45 -0
- harborrag_runtime/application/control_plane/__init__.py +1 -0
- harborrag_runtime/application/control_plane/active_runs.py +38 -0
- harborrag_runtime/application/control_plane/connection_models.py +109 -0
- harborrag_runtime/application/control_plane/connection_testing.py +91 -0
- harborrag_runtime/application/control_plane/connection_writes.py +227 -0
- harborrag_runtime/application/control_plane/connections.py +749 -0
- harborrag_runtime/application/control_plane/effect_recovery.py +235 -0
- harborrag_runtime/application/control_plane/projects.py +313 -0
- harborrag_runtime/application/control_plane/settings_import.py +239 -0
- harborrag_runtime/application/control_plane/settings_service.py +233 -0
- harborrag_runtime/application/control_plane/tenants.py +55 -0
- harborrag_runtime/application/errors.py +110 -0
- harborrag_runtime/application/ingestion/__init__.py +1 -0
- harborrag_runtime/application/ingestion/client.py +65 -0
- harborrag_runtime/application/ingestion/connection_sources.py +96 -0
- harborrag_runtime/application/ingestion/direct.py +120 -0
- harborrag_runtime/application/ingestion/follower.py +83 -0
- harborrag_runtime/application/ingestion/ports.py +174 -0
- harborrag_runtime/application/ingestion/progress_bridge.py +221 -0
- harborrag_runtime/application/ingestion/retry_selection.py +71 -0
- harborrag_runtime/application/ingestion/service.py +564 -0
- harborrag_runtime/application/ingestion/starter.py +78 -0
- harborrag_runtime/application/memory/__init__.py +21 -0
- harborrag_runtime/application/memory/client.py +114 -0
- harborrag_runtime/application/memory/composition.py +90 -0
- harborrag_runtime/application/memory/context.py +45 -0
- harborrag_runtime/application/memory/sessions.py +117 -0
- harborrag_runtime/application/ports.py +133 -0
- harborrag_runtime/application/retrieval/__init__.py +1 -0
- harborrag_runtime/application/retrieval/access.py +26 -0
- harborrag_runtime/application/scheduling/service.py +58 -0
- harborrag_runtime/application/schemas.py +15 -0
- harborrag_runtime/chat/README.md +40 -0
- harborrag_runtime/chat/__init__.py +18 -0
- harborrag_runtime/chat/composition.py +53 -0
- harborrag_runtime/chat/facade.py +46 -0
- harborrag_runtime/chat/service.py +183 -0
- harborrag_runtime/chat/tenant_clients.py +341 -0
- harborrag_runtime/chat/tenant_config.py +235 -0
- harborrag_runtime/chat/tenant_models.py +22 -0
- harborrag_runtime/composition/__init__.py +5 -0
- harborrag_runtime/composition/config_store.py +53 -0
- harborrag_runtime/composition/connection_removal.py +120 -0
- harborrag_runtime/composition/connection_stores.py +107 -0
- harborrag_runtime/composition/control_plane.py +401 -0
- harborrag_runtime/composition/mcp_auth.py +39 -0
- harborrag_runtime/composition/readers.py +113 -0
- harborrag_runtime/composition/resources.py +336 -0
- harborrag_runtime/composition/storage_providers.py +113 -0
- harborrag_runtime/config/__init__.py +84 -0
- harborrag_runtime/config/checkout.py +212 -0
- harborrag_runtime/config/chunking.py +167 -0
- harborrag_runtime/config/connectors/__init__.py +19 -0
- harborrag_runtime/config/connectors/fingerprints.py +54 -0
- harborrag_runtime/config/connectors/importing.py +611 -0
- harborrag_runtime/config/connectors/loader.py +95 -0
- harborrag_runtime/config/connectors/models/__init__.py +30 -0
- harborrag_runtime/config/connectors/models/atlassian.py +199 -0
- harborrag_runtime/config/connectors/models/builder.py +208 -0
- harborrag_runtime/config/connectors/models/common.py +45 -0
- harborrag_runtime/config/connectors/models/fields.py +134 -0
- harborrag_runtime/config/connectors/models/github.py +143 -0
- harborrag_runtime/config/connectors/models/local_file.py +119 -0
- harborrag_runtime/config/connectors/models/registry.py +149 -0
- harborrag_runtime/config/connectors/models/sharepoint.py +186 -0
- harborrag_runtime/config/connectors/models/spec.py +563 -0
- harborrag_runtime/config/connectors/parsing.py +275 -0
- harborrag_runtime/config/connectors/providers.py +177 -0
- harborrag_runtime/config/connectors/schemas.py +215 -0
- harborrag_runtime/config/errors.py +26 -0
- harborrag_runtime/config/graph_build.py +335 -0
- harborrag_runtime/config/graph_build_loading.py +38 -0
- harborrag_runtime/config/loading.py +245 -0
- harborrag_runtime/config/models.py +95 -0
- harborrag_runtime/config/ontology_loading.py +76 -0
- harborrag_runtime/config/parsers/__init__.py +19 -0
- harborrag_runtime/config/parsers/loader.py +85 -0
- harborrag_runtime/config/parsers/parsing.py +285 -0
- harborrag_runtime/config/parsers/providers.py +305 -0
- harborrag_runtime/config/parsers/schemas.py +614 -0
- harborrag_runtime/config/settings.py +378 -0
- harborrag_runtime/config/settings_document.py +133 -0
- harborrag_runtime/config/temporal.py +331 -0
- harborrag_runtime/config/temporal_loading.py +310 -0
- harborrag_runtime/config_store/__init__.py +5 -0
- harborrag_runtime/config_store/defaults.py +47 -0
- harborrag_runtime/config_store/provider.py +153 -0
- harborrag_runtime/config_store/run_settings.py +72 -0
- harborrag_runtime/connections/__init__.py +27 -0
- harborrag_runtime/connections/secrets.py +348 -0
- harborrag_runtime/contracts.py +237 -0
- harborrag_runtime/document_stage_catalog.py +82 -0
- harborrag_runtime/errors.py +64 -0
- harborrag_runtime/events/__init__.py +3 -0
- harborrag_runtime/events/in_process.py +100 -0
- harborrag_runtime/execution/__init__.py +26 -0
- harborrag_runtime/execution/contracts.py +32 -0
- harborrag_runtime/execution/direct.py +169 -0
- harborrag_runtime/execution/gateway.py +97 -0
- harborrag_runtime/execution/source_conversion.py +61 -0
- harborrag_runtime/execution/source_submission.py +278 -0
- harborrag_runtime/execution/submission.py +64 -0
- harborrag_runtime/execution/task_registry.py +387 -0
- harborrag_runtime/execution/temporal.py +165 -0
- harborrag_runtime/ingestion/README.md +79 -0
- harborrag_runtime/ingestion/__init__.py +59 -0
- harborrag_runtime/ingestion/chunking_profile.py +97 -0
- harborrag_runtime/ingestion/composition.py +279 -0
- harborrag_runtime/ingestion/connection_checks.py +239 -0
- harborrag_runtime/ingestion/connections.py +507 -0
- harborrag_runtime/ingestion/document/__init__.py +1 -0
- harborrag_runtime/ingestion/document/normalization.py +14 -0
- harborrag_runtime/ingestion/document/normalizers/__init__.py +9 -0
- harborrag_runtime/ingestion/document/normalizers/builtins.py +39 -0
- harborrag_runtime/ingestion/document/normalizers/transform.py +30 -0
- harborrag_runtime/ingestion/document/run_tools.py +152 -0
- harborrag_runtime/ingestion/failure_classification.py +82 -0
- harborrag_runtime/ingestion/field_indexes.py +56 -0
- harborrag_runtime/ingestion/maintenance/__init__.py +1 -0
- harborrag_runtime/ingestion/maintenance/connection_removal.py +115 -0
- harborrag_runtime/ingestion/maintenance/projection_admin.py +180 -0
- harborrag_runtime/ingestion/maintenance/relation_repair.py +555 -0
- harborrag_runtime/ingestion/maintenance/retention.py +353 -0
- harborrag_runtime/ingestion/observability.py +3 -0
- harborrag_runtime/ingestion/profiles.py +127 -0
- harborrag_runtime/ingestion/runtime_builder.py +339 -0
- harborrag_runtime/ingestion/source/__init__.py +1 -0
- harborrag_runtime/ingestion/source/descriptor_mapping.py +144 -0
- harborrag_runtime/ingestion/source/discovery.py +290 -0
- harborrag_runtime/ingestion/source/documents.py +184 -0
- harborrag_runtime/ingestion/source/finalization.py +288 -0
- harborrag_runtime/ingestion/source/operations.py +175 -0
- harborrag_runtime/ingestion/source/plan.py +413 -0
- harborrag_runtime/ingestion/source/retry.py +150 -0
- harborrag_runtime/ingestion/source/service.py +470 -0
- harborrag_runtime/ingestion/source/skips.py +172 -0
- harborrag_runtime/ingestion_contracts.py +107 -0
- harborrag_runtime/memory/__init__.py +81 -0
- harborrag_runtime/memory/access.py +47 -0
- harborrag_runtime/memory/administration.py +460 -0
- harborrag_runtime/memory/context/__init__.py +5 -0
- harborrag_runtime/memory/context/result.py +20 -0
- harborrag_runtime/memory/directory.py +166 -0
- harborrag_runtime/memory/erasure.py +122 -0
- harborrag_runtime/memory/locks.py +170 -0
- harborrag_runtime/memory/messages.py +202 -0
- harborrag_runtime/memory/presenters.py +117 -0
- harborrag_runtime/memory/projects.py +38 -0
- harborrag_runtime/memory/tiers/__init__.py +1 -0
- harborrag_runtime/memory/tiers/in_memory.py +491 -0
- harborrag_runtime/memory/titles.py +32 -0
- harborrag_runtime/memory/usage.py +131 -0
- harborrag_runtime/observability/__init__.py +1 -0
- harborrag_runtime/observability/connector_metrics.py +14 -0
- harborrag_runtime/observability/discovery_metrics.py +46 -0
- harborrag_runtime/observability/model.py +410 -0
- harborrag_runtime/observability/observability_types.py +47 -0
- harborrag_runtime/observability/stage_observation.py +96 -0
- harborrag_runtime/observability/tool_audit.py +17 -0
- harborrag_runtime/plugins.py +56 -0
- harborrag_runtime/rate_limiting.py +39 -0
- harborrag_runtime/reader_contracts.py +149 -0
- harborrag_runtime/retrieval/__init__.py +1 -0
- harborrag_runtime/retrieval/composition.py +174 -0
- harborrag_runtime/retrieval/facades.py +224 -0
- harborrag_runtime/scheduling/__init__.py +48 -0
- harborrag_runtime/scheduling/config.py +185 -0
- harborrag_runtime/scheduling/errors.py +37 -0
- harborrag_runtime/scheduling/models.py +146 -0
- harborrag_runtime/scheduling/service.py +297 -0
- harborrag_runtime/scheduling/validation.py +213 -0
- harborrag_runtime/sdk/__init__.py +86 -0
- harborrag_runtime/sdk/configuration.py +44 -0
- harborrag_runtime/sdk/facades.py +47 -0
- harborrag_runtime/sdk/runtime.py +242 -0
- harborrag_runtime/security/__init__.py +1 -0
- harborrag_runtime/security/api_key_operations.py +236 -0
- harborrag_runtime/serialization.py +35 -0
- harborrag_runtime/temporal/__init__.py +19 -0
- harborrag_runtime/temporal/activity_observability.py +313 -0
- harborrag_runtime/temporal/client.py +580 -0
- harborrag_runtime/temporal/connection.py +39 -0
- harborrag_runtime/temporal/conversion.py +147 -0
- harborrag_runtime/temporal/dispatch.py +38 -0
- harborrag_runtime/temporal/document_workflow.py +154 -0
- harborrag_runtime/temporal/failure_handling.py +68 -0
- harborrag_runtime/temporal/gateway.py +121 -0
- harborrag_runtime/temporal/heartbeats.py +67 -0
- harborrag_runtime/temporal/identity.py +14 -0
- harborrag_runtime/temporal/ingestion_activities.py +435 -0
- harborrag_runtime/temporal/maintenance_activities.py +251 -0
- harborrag_runtime/temporal/maintenance_schemas.py +88 -0
- harborrag_runtime/temporal/optional.py +19 -0
- harborrag_runtime/temporal/plan_resolver.py +149 -0
- harborrag_runtime/temporal/policies.py +18 -0
- harborrag_runtime/temporal/reindex_workflow.py +71 -0
- harborrag_runtime/temporal/retry_activities.py +147 -0
- harborrag_runtime/temporal/retry_workflow.py +222 -0
- harborrag_runtime/temporal/sandbox.py +51 -0
- harborrag_runtime/temporal/schedules.py +341 -0
- harborrag_runtime/temporal/schemas.py +482 -0
- harborrag_runtime/temporal/source_activities.py +590 -0
- harborrag_runtime/temporal/source_batch_workflow.py +226 -0
- harborrag_runtime/temporal/source_workflow.py +908 -0
- harborrag_runtime/temporal/submission.py +23 -0
- harborrag_runtime/temporal/worker.py +478 -0
- harborrag_runtime/temporal/worker_registry.py +141 -0
- harborrag_runtime/temporal_models.py +227 -0
- harborrag_runtime/testing/chat_fakes.py +309 -0
- harborrag_runtime/testing/chat_service_double.py +126 -0
- harborrag_runtime/testing/connection_fakes.py +278 -0
- harborrag_runtime/testing/memory_fakes.py +128 -0
- harborrag_runtime/topology/__init__.py +1 -0
- harborrag_runtime/topology/budgeted_extractor.py +110 -0
- harborrag_runtime/topology/chunk_runner.py +41 -0
- harborrag_runtime/topology/composition.py +168 -0
- harborrag_runtime/topology/configuration.py +126 -0
- harborrag_runtime/topology/contextual.py +140 -0
- harborrag_runtime/topology/derived.py +238 -0
- harborrag_runtime/topology/derived_coverage.py +5 -0
- harborrag_runtime/topology/derived_dispatch.py +63 -0
- harborrag_runtime/topology/derived_factory.py +175 -0
- harborrag_runtime/topology/derived_models.py +251 -0
- harborrag_runtime/topology/derived_projection.py +127 -0
- harborrag_runtime/topology/description_factory.py +81 -0
- harborrag_runtime/topology/embedding_profile.py +85 -0
- harborrag_runtime/topology/entity_summary_index.py +304 -0
- harborrag_runtime/topology/maintenance.py +126 -0
- harborrag_runtime/topology/operations.py +277 -0
- harborrag_runtime/topology/parent_materializer.py +167 -0
- harborrag_runtime/topology/run_cost.py +43 -0
- harborrag_runtime/topology/security_operations.py +46 -0
- harborrag_runtime/topology/service.py +349 -0
- harborrag_runtime/topology/summary_factory.py +164 -0
- harborrag_runtime/topology/summary_inputs.py +129 -0
- harborrag_runtime/topology/summary_operations.py +128 -0
- harborrag_runtime/topology/summary_policy.py +39 -0
- harborrag_runtime/topology/summary_products.py +43 -0
- harborrag_runtime/topology/summary_service.py +625 -0
- harborrag_runtime/topology/summary_worker.py +129 -0
- harborrag_runtime/topology/summary_workflow.py +32 -0
- harborrag_runtime/topology/worker.py +101 -0
- harborrag_runtime/topology/workflow.py +32 -0
- harborrag_runtime-2.0.0.dist-info/METADATA +267 -0
- harborrag_runtime-2.0.0.dist-info/RECORD +271 -0
- harborrag_runtime-2.0.0.dist-info/WHEEL +4 -0
- harborrag_runtime-2.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Fail-closed request-scope admission, before answer generation or SSE headers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, ValidationError
|
|
11
|
+
|
|
12
|
+
from harborrag_core.contracts.errors import HarborUnavailableError
|
|
13
|
+
from harborrag_core.models.chat import (
|
|
14
|
+
HarborChatMessage,
|
|
15
|
+
HarborChatMetadata,
|
|
16
|
+
HarborChatRequest,
|
|
17
|
+
HarborChatResponse,
|
|
18
|
+
)
|
|
19
|
+
from harborrag_core.ports.conversation import ConversationIdentity
|
|
20
|
+
from harborrag_core.ports.usage import ModelUsageRecord
|
|
21
|
+
from harborrag_runtime.chat import ChatPrompt
|
|
22
|
+
from harborrag_runtime.memory.access import MemoryAccess
|
|
23
|
+
|
|
24
|
+
from .preparation import ChatTurnResources
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("harborrag.runtime.application.chat.query_scope")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ScopeDecision(BaseModel):
|
|
30
|
+
"""The model's one-field verdict on whether a request is in scope."""
|
|
31
|
+
|
|
32
|
+
model_config = ConfigDict(extra="forbid")
|
|
33
|
+
scope: Literal["knowledge", "conversation", "unsupported"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
OUT_OF_SCOPE = (
|
|
37
|
+
"This assistant answers questions about indexed knowledge and this conversation. "
|
|
38
|
+
"It cannot create unrelated content; ask about a source or provide relevant material."
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
type ScopeHistory = list[dict[str, str]]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class ScopeCheck:
|
|
47
|
+
"""The scope check's model call, and the refusal to answer with when out of scope."""
|
|
48
|
+
|
|
49
|
+
response: HarborChatResponse
|
|
50
|
+
refusal: str | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def scope_history(resources: ChatTurnResources, access: MemoryAccess) -> ScopeHistory:
|
|
54
|
+
"""Return the session's last three exchanges for the scope check; none for a one-off."""
|
|
55
|
+
if access.session_id is None:
|
|
56
|
+
return []
|
|
57
|
+
turns = await resources.memory.recent(
|
|
58
|
+
ConversationIdentity(
|
|
59
|
+
tenant_id=access.tenant_id,
|
|
60
|
+
principal_id=access.principal_id,
|
|
61
|
+
session_id=access.session_id,
|
|
62
|
+
user_id=access.user_id,
|
|
63
|
+
),
|
|
64
|
+
limit=3,
|
|
65
|
+
)
|
|
66
|
+
return [
|
|
67
|
+
{"user": turn.user_content[:4000], "assistant": turn.assistant_content[:4000]}
|
|
68
|
+
for turn in turns
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def check_query_scope( # noqa: PLR0913 - the check's inputs, then the call's options
|
|
73
|
+
resources: ChatTurnResources,
|
|
74
|
+
query: str,
|
|
75
|
+
access: MemoryAccess,
|
|
76
|
+
*,
|
|
77
|
+
history: ScopeHistory,
|
|
78
|
+
model: str | None,
|
|
79
|
+
trace_id: str | None = None,
|
|
80
|
+
) -> ScopeCheck:
|
|
81
|
+
"""Ask the model whether a request is about indexed knowledge or the conversation.
|
|
82
|
+
|
|
83
|
+
Makes the model call and nothing else that can fail before it, so a caller can treat
|
|
84
|
+
the call as started once this is awaited. The call asks for at most 512 tokens, because
|
|
85
|
+
reasoning models can consume a smaller output budget before producing even a one-field
|
|
86
|
+
decision. Admission is a real model call even when rejected, so its usage is recorded
|
|
87
|
+
separately; the completion's cost scope remains answer generation, not admission.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
resources: The turn's ports.
|
|
91
|
+
query: The question.
|
|
92
|
+
access: The caller, for the call's metadata and the usage record.
|
|
93
|
+
history: The session's last exchanges, from ``scope_history``.
|
|
94
|
+
model: The logical model; ``None`` is the default.
|
|
95
|
+
trace_id: The request's trace id, put on the model call.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
The model call, with the refusal text when the request is out of scope.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
HarborUnavailableError: The model's decision could not be read.
|
|
102
|
+
"""
|
|
103
|
+
response = await resources.runtime().chat.complete(
|
|
104
|
+
HarborChatRequest(
|
|
105
|
+
messages=(
|
|
106
|
+
HarborChatMessage.user(json.dumps({"query": query, "recent_history": history})),
|
|
107
|
+
),
|
|
108
|
+
logical_model=model,
|
|
109
|
+
max_tokens=512,
|
|
110
|
+
sensitive=True,
|
|
111
|
+
metadata=HarborChatMetadata(
|
|
112
|
+
trace_id=trace_id,
|
|
113
|
+
tenant_id=access.tenant_id,
|
|
114
|
+
user_id=access.user_id,
|
|
115
|
+
conversation_id=access.session_id,
|
|
116
|
+
),
|
|
117
|
+
),
|
|
118
|
+
prompt=ChatPrompt.QUERY_GATE,
|
|
119
|
+
)
|
|
120
|
+
if resources.usage is not None:
|
|
121
|
+
try:
|
|
122
|
+
await resources.usage.record(
|
|
123
|
+
ModelUsageRecord(
|
|
124
|
+
tenant_id=access.tenant_id,
|
|
125
|
+
user_id=access.user_id,
|
|
126
|
+
principal_id=access.principal_id,
|
|
127
|
+
session_id=access.session_id,
|
|
128
|
+
logical_model=response.logical_model,
|
|
129
|
+
provider=response.provider,
|
|
130
|
+
provider_model=response.provider_model,
|
|
131
|
+
prompt_tokens=response.usage.prompt_tokens,
|
|
132
|
+
completion_tokens=response.usage.completion_tokens,
|
|
133
|
+
total_tokens=response.usage.total_tokens,
|
|
134
|
+
estimated_cost_usd=response.estimated_cost_usd,
|
|
135
|
+
finish_reason="query_scope_gate",
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
except Exception: # noqa: BLE001 - accounting cannot override admission
|
|
139
|
+
logger.warning("Could not record query-scope usage for tenant=%s", access.tenant_id)
|
|
140
|
+
try:
|
|
141
|
+
decision = ScopeDecision.model_validate_json(response.text)
|
|
142
|
+
except ValidationError:
|
|
143
|
+
raise HarborUnavailableError(
|
|
144
|
+
"Request scope could not be determined; please retry"
|
|
145
|
+
) from None
|
|
146
|
+
return ScopeCheck(response, OUT_OF_SCOPE if decision.scope == "unsupported" else None)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Durable duplicate suppression for paid completion requests.
|
|
2
|
+
|
|
3
|
+
A retry with the same ``Idempotency-Key`` and the same body within 24 hours gets the
|
|
4
|
+
stored completion back without a second model call. The key is scoped to the caller's
|
|
5
|
+
tenant and end user.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import logging
|
|
12
|
+
from collections.abc import AsyncGenerator
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from harborrag_core.contracts.errors import (
|
|
16
|
+
CompletionInProgressError,
|
|
17
|
+
HarborConflictError,
|
|
18
|
+
HarborConnectionError,
|
|
19
|
+
HarborValidationError,
|
|
20
|
+
)
|
|
21
|
+
from harborrag_core.ports.completion_requests import CompletionRequestStore
|
|
22
|
+
|
|
23
|
+
from .completion import Completion, RetrievalFound, TurnCompleted, TurnEvent
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("harborrag.runtime.application.chat.replay")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(slots=True)
|
|
29
|
+
class CompletionAttempt:
|
|
30
|
+
"""One request's claim on its idempotency key, from claim to finish or release."""
|
|
31
|
+
|
|
32
|
+
store: CompletionRequestStore
|
|
33
|
+
tenant_id: str
|
|
34
|
+
user_id: str
|
|
35
|
+
key: str | None
|
|
36
|
+
request_hash: str
|
|
37
|
+
claimed: bool = False
|
|
38
|
+
|
|
39
|
+
async def claim(self) -> str | None:
|
|
40
|
+
"""Claim the key; return the stored completion body when it already answered.
|
|
41
|
+
|
|
42
|
+
Raises:
|
|
43
|
+
HarborValidationError: The key was used with a different body (field
|
|
44
|
+
``Idempotency-Key``).
|
|
45
|
+
CompletionInProgressError: The first request with the key is still running.
|
|
46
|
+
HarborConflictError: The first request failed; a new key is needed.
|
|
47
|
+
"""
|
|
48
|
+
if self.key is None:
|
|
49
|
+
return None
|
|
50
|
+
claim = await self.store.claim_completion(
|
|
51
|
+
tenant_id=self.tenant_id,
|
|
52
|
+
user_id=self.user_id,
|
|
53
|
+
key=self.key,
|
|
54
|
+
request_hash=self.request_hash,
|
|
55
|
+
)
|
|
56
|
+
if claim.status == "completed" and claim.result_json is not None:
|
|
57
|
+
return claim.result_json
|
|
58
|
+
if claim.status == "conflict":
|
|
59
|
+
raise HarborValidationError(
|
|
60
|
+
"Idempotency-Key was already used with a different request",
|
|
61
|
+
{"field": "Idempotency-Key"},
|
|
62
|
+
)
|
|
63
|
+
if claim.status == "in_progress":
|
|
64
|
+
raise CompletionInProgressError(
|
|
65
|
+
"The first request with this Idempotency-Key is still being answered"
|
|
66
|
+
)
|
|
67
|
+
if claim.status != "claimed":
|
|
68
|
+
raise HarborConflictError(
|
|
69
|
+
"The request with this Idempotency-Key failed; use a new key to retry"
|
|
70
|
+
)
|
|
71
|
+
self.claimed = True
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
async def settle(self, events: AsyncGenerator[TurnEvent, None]) -> Completion:
|
|
75
|
+
"""Run the turn, giving the key back on a failure before any model call and spending it after.
|
|
76
|
+
|
|
77
|
+
The turn yields ``RetrievalFound`` after every read and check it makes before its
|
|
78
|
+
first model call, so a failure until then (a store or retrieval outage, a busy
|
|
79
|
+
session, a refused request, a caller that went away) leaves the key reusable. From
|
|
80
|
+
then on a model may have been paid for, and a failure records the key as failed.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
events: The turn's events, closed when this returns.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
The turn's completion.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
HarborConnectionError: The turn ended without its answer.
|
|
90
|
+
"""
|
|
91
|
+
spent = False
|
|
92
|
+
try:
|
|
93
|
+
async with contextlib.aclosing(events):
|
|
94
|
+
async for event in events:
|
|
95
|
+
if isinstance(event, RetrievalFound):
|
|
96
|
+
spent = True
|
|
97
|
+
elif isinstance(event, TurnCompleted):
|
|
98
|
+
return event.completion
|
|
99
|
+
except BaseException:
|
|
100
|
+
await (self.finish() if spent else self.release())
|
|
101
|
+
raise
|
|
102
|
+
await self.finish()
|
|
103
|
+
raise HarborConnectionError("The chat turn ended without its answer")
|
|
104
|
+
|
|
105
|
+
async def release(self) -> None:
|
|
106
|
+
"""Give the key back after a refusal that came before any model call.
|
|
107
|
+
|
|
108
|
+
Marking such a claim failed would spend the key on work that produced
|
|
109
|
+
nothing, and the only way past a failed claim is a new key.
|
|
110
|
+
"""
|
|
111
|
+
if not self.claimed or self.key is None:
|
|
112
|
+
return
|
|
113
|
+
try:
|
|
114
|
+
await self.store.release_completion(
|
|
115
|
+
tenant_id=self.tenant_id,
|
|
116
|
+
user_id=self.user_id,
|
|
117
|
+
key=self.key,
|
|
118
|
+
request_hash=self.request_hash,
|
|
119
|
+
)
|
|
120
|
+
except Exception: # noqa: BLE001 - a stranded claim must not mask the real error
|
|
121
|
+
logger.exception("Completion claim could not be released")
|
|
122
|
+
finally:
|
|
123
|
+
self.claimed = False
|
|
124
|
+
|
|
125
|
+
async def finish(self, body: str | None = None, *, session_id: str | None = None) -> None:
|
|
126
|
+
"""Store the completion body, or record a failure when ``body`` is ``None``."""
|
|
127
|
+
if not self.claimed or self.key is None:
|
|
128
|
+
return
|
|
129
|
+
try:
|
|
130
|
+
await self.store.finish_completion(
|
|
131
|
+
tenant_id=self.tenant_id,
|
|
132
|
+
user_id=self.user_id,
|
|
133
|
+
key=self.key,
|
|
134
|
+
request_hash=self.request_hash,
|
|
135
|
+
response_json=body,
|
|
136
|
+
session_id=session_id,
|
|
137
|
+
)
|
|
138
|
+
except Exception: # noqa: BLE001 - never discard an already paid-for result
|
|
139
|
+
logger.exception("Completion replay state could not be saved")
|
|
140
|
+
finally:
|
|
141
|
+
self.claimed = False
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Turn a completion request's explorer filter into what chat retrieval applies.
|
|
2
|
+
|
|
3
|
+
Retrieval combines conditions with AND only, so a flat ``and`` of conditions is
|
|
4
|
+
supported: ``eq`` and ``in`` on any indexed evidence field, ``gt``/``gte``/``lt``/``lte``
|
|
5
|
+
on number fields (``fields.<key>``, never on the exactly matched evidence keys), and
|
|
6
|
+
``connection`` (``eq`` or ``in``) to narrow to connections.
|
|
7
|
+
Anything else is refused on field ``filters`` rather than ignored.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Literal, TypeGuard
|
|
15
|
+
|
|
16
|
+
from harborrag_core.contracts.errors import HarborValidationError
|
|
17
|
+
from harborrag_engine.retrieval.evidence_filters import (
|
|
18
|
+
EVIDENCE_FILTER_KEYS,
|
|
19
|
+
validate_evidence_filter_keys,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
CONNECTION_FIELD = "connection"
|
|
23
|
+
SOURCE_SCOPE_FIELD = "source_scope_id"
|
|
24
|
+
_RANGE_OPS = frozenset({"gt", "gte", "lt", "lte"})
|
|
25
|
+
_CONNECTION_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*/[a-z0-9][a-z0-9_-]{0,62}$")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class FilterCondition:
|
|
30
|
+
"""One condition on a filterable field."""
|
|
31
|
+
|
|
32
|
+
field: str
|
|
33
|
+
op: str
|
|
34
|
+
value: object
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True, slots=True)
|
|
38
|
+
class FilterGroup:
|
|
39
|
+
"""Conditions or nested groups that all hold (``and``) or any of which holds (``or``)."""
|
|
40
|
+
|
|
41
|
+
combinator: Literal["and", "or"]
|
|
42
|
+
items: tuple[FilterCondition | FilterGroup, ...]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True, slots=True)
|
|
46
|
+
class RetrievalFilters:
|
|
47
|
+
"""Evidence filters, and the connections a ``connection`` condition names (``None``: none)."""
|
|
48
|
+
|
|
49
|
+
evidence: dict[str, object]
|
|
50
|
+
connections: tuple[str, ...] | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def retrieval_filters(filters: FilterGroup | None) -> RetrievalFilters:
|
|
54
|
+
"""Translate a request's ``filters``.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
filters: The request's filter, if any.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
The evidence filters and the connections to narrow to.
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
HarborValidationError: The filter uses ``or``, nesting, an unsupported operator or
|
|
64
|
+
value, repeats a field, or names a field that is not indexed (field ``filters``).
|
|
65
|
+
"""
|
|
66
|
+
if filters is None:
|
|
67
|
+
return RetrievalFilters({})
|
|
68
|
+
if filters.combinator != "and":
|
|
69
|
+
raise _refused("or filters are not supported yet; combine conditions with and")
|
|
70
|
+
evidence: dict[str, object] = {}
|
|
71
|
+
connections: tuple[str, ...] | None = None
|
|
72
|
+
for item in filters.items:
|
|
73
|
+
if not isinstance(item, FilterCondition):
|
|
74
|
+
raise _refused("nested filters are not supported yet")
|
|
75
|
+
if item.field == CONNECTION_FIELD:
|
|
76
|
+
if connections is not None:
|
|
77
|
+
raise _refused("one connection condition per filter")
|
|
78
|
+
connections = _connection_refs(item)
|
|
79
|
+
else:
|
|
80
|
+
_add(evidence, item)
|
|
81
|
+
try:
|
|
82
|
+
validate_evidence_filter_keys(evidence)
|
|
83
|
+
except HarborValidationError as error:
|
|
84
|
+
raise _refused(str(error)) from error
|
|
85
|
+
return RetrievalFilters(evidence, connections)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _add(evidence: dict[str, object], condition: FilterCondition) -> None:
|
|
89
|
+
if condition.op in _RANGE_OPS:
|
|
90
|
+
if condition.field in EVIDENCE_FILTER_KEYS:
|
|
91
|
+
raise _refused(f"{condition.field} is matched exactly; ranges apply to number fields")
|
|
92
|
+
bounds = evidence.setdefault(condition.field, {})
|
|
93
|
+
number = condition.value
|
|
94
|
+
if (
|
|
95
|
+
not isinstance(bounds, dict)
|
|
96
|
+
or condition.op in bounds
|
|
97
|
+
or isinstance(number, bool)
|
|
98
|
+
or not isinstance(number, int | float)
|
|
99
|
+
):
|
|
100
|
+
raise _refused(f"{condition.op} on {condition.field} needs one number")
|
|
101
|
+
bounds[condition.op] = number
|
|
102
|
+
return
|
|
103
|
+
if condition.field in evidence:
|
|
104
|
+
raise _refused(f"one eq or in condition per field: {condition.field}")
|
|
105
|
+
if condition.field == SOURCE_SCOPE_FIELD and not (
|
|
106
|
+
isinstance(condition.value, str) or _strings(condition.value)
|
|
107
|
+
):
|
|
108
|
+
raise _refused(f"{SOURCE_SCOPE_FIELD} takes source scope ids")
|
|
109
|
+
if condition.op == "eq" and isinstance(condition.value, str | int | float | bool):
|
|
110
|
+
evidence[condition.field] = condition.value
|
|
111
|
+
elif condition.op == "in" and _strings(condition.value):
|
|
112
|
+
evidence[condition.field] = list(condition.value)
|
|
113
|
+
else:
|
|
114
|
+
raise _refused(f"{condition.op} on {condition.field} is not supported")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _connection_refs(condition: FilterCondition) -> tuple[str, ...]:
|
|
118
|
+
if condition.op == "eq" and isinstance(condition.value, str):
|
|
119
|
+
refs: tuple[str, ...] = (condition.value,)
|
|
120
|
+
elif condition.op == "in" and _strings(condition.value):
|
|
121
|
+
refs = tuple(condition.value)
|
|
122
|
+
else:
|
|
123
|
+
raise _refused("connection takes eq or in with connection refs")
|
|
124
|
+
if not all(_CONNECTION_REF.fullmatch(ref) for ref in refs):
|
|
125
|
+
raise _refused("a connection ref is <project_id>/<connection_id>")
|
|
126
|
+
return refs
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _strings(value: object) -> TypeGuard[list[str]]:
|
|
130
|
+
return isinstance(value, list) and bool(value) and all(isinstance(item, str) for item in value)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _refused(message: str) -> HarborValidationError:
|
|
134
|
+
return HarborValidationError(message, {"field": "filters"})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Tenant-scoped document retrieval and evidence relevance filtering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from harborrag_core.config_store import SettingsLevel
|
|
9
|
+
from harborrag_core.domain.retrieval import RetrievalResult
|
|
10
|
+
from harborrag_core.schemas.ids import TenantId
|
|
11
|
+
from harborrag_core.security import AccessContext
|
|
12
|
+
from harborrag_runtime.sdk import RetrievalLane, RetrievalMode, RetrievalRequest
|
|
13
|
+
|
|
14
|
+
from ..retrieval.access import corpus_mode_for
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from harborrag_core.domain.identity import MemoryIdentity
|
|
18
|
+
from harborrag_core.ports.config_store import ConfigProvider
|
|
19
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
20
|
+
from harborrag_runtime.contracts import RetrievalResponse
|
|
21
|
+
from harborrag_runtime.memory import MemoryContext
|
|
22
|
+
from harborrag_runtime.sdk import HarborRAG
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def relevant_results(
|
|
26
|
+
results: Sequence[RetrievalResult],
|
|
27
|
+
*,
|
|
28
|
+
minimum: float,
|
|
29
|
+
) -> tuple[RetrievalResult, ...]:
|
|
30
|
+
"""Drop results the lane did not judge similar enough to be worth showing.
|
|
31
|
+
|
|
32
|
+
Filtering here rather than in the prompt builder is deliberate: the same
|
|
33
|
+
tuple becomes the model's evidence *and* the caller's citations, so one
|
|
34
|
+
gate keeps an answer from being reported as grounded in a document it
|
|
35
|
+
never used.
|
|
36
|
+
|
|
37
|
+
A result whose lane reported no relevance is kept. ``None`` means "this
|
|
38
|
+
lane cannot say", not "this is a poor match", and discarding on absence
|
|
39
|
+
would silently empty the context for any backend that does not score.
|
|
40
|
+
"""
|
|
41
|
+
if minimum <= 0.0:
|
|
42
|
+
return tuple(results)
|
|
43
|
+
return tuple(
|
|
44
|
+
result for result in results if result.relevance is None or result.relevance >= minimum
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def chat_top_k(
|
|
49
|
+
config: ConfigProvider | None, identity: MemoryIdentity, settings: RuntimeSettings
|
|
50
|
+
) -> int:
|
|
51
|
+
"""Return the ``retrieval.top_k`` override for the session's level, else the environment value.
|
|
52
|
+
|
|
53
|
+
A provider that cannot load a never-cached tenant raises ``HarborUnavailableError``.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
config: Runtime settings provider; ``None`` uses the environment value.
|
|
57
|
+
identity: Session whose project, else tenant, is the settings level.
|
|
58
|
+
settings: Process settings holding ``chat_retrieval_top_k``.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
Passages chat retrieval returns.
|
|
62
|
+
"""
|
|
63
|
+
if config is None:
|
|
64
|
+
return settings.chat_retrieval_top_k
|
|
65
|
+
effective = await config.effective(identity.tenant_id, _settings_level(identity))
|
|
66
|
+
override = effective.override("retrieval.top_k")
|
|
67
|
+
return override if isinstance(override, int) else settings.chat_retrieval_top_k
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def chat_rerank(config: ConfigProvider | None, identity: MemoryIdentity) -> bool:
|
|
71
|
+
"""Return whether ``retrieval.rerank`` is on for the session's level.
|
|
72
|
+
|
|
73
|
+
A provider that cannot load a never-cached tenant raises ``HarborUnavailableError``.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
config: Runtime settings provider; ``None`` never reranks.
|
|
77
|
+
identity: Session whose project, else tenant, is the settings level.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Whether chat retrieval reranks its passages.
|
|
81
|
+
"""
|
|
82
|
+
if config is None:
|
|
83
|
+
return False
|
|
84
|
+
effective = await config.effective(identity.tenant_id, _settings_level(identity))
|
|
85
|
+
return effective.override("retrieval.rerank") is True
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _settings_level(identity: MemoryIdentity) -> SettingsLevel:
|
|
89
|
+
"""Return the project level when the session has a project, else the tenant level."""
|
|
90
|
+
if identity.project_id:
|
|
91
|
+
return SettingsLevel("project", project_id=identity.project_id)
|
|
92
|
+
return SettingsLevel("tenant")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def search_documents( # noqa: PLR0913 - one keyword-only input per retrieval parameter
|
|
96
|
+
runtime: HarborRAG,
|
|
97
|
+
context: MemoryContext,
|
|
98
|
+
*,
|
|
99
|
+
identity: MemoryIdentity,
|
|
100
|
+
acl_subject: str,
|
|
101
|
+
settings: RuntimeSettings,
|
|
102
|
+
observe_graph: bool,
|
|
103
|
+
top_k: int,
|
|
104
|
+
filters: Mapping[str, object],
|
|
105
|
+
rerank: bool,
|
|
106
|
+
) -> RetrievalResponse:
|
|
107
|
+
"""Search the current question within ``filters``, observing the graph or reranking as asked.
|
|
108
|
+
|
|
109
|
+
The document ACL checks ``acl_subject``, which can differ from the session owner
|
|
110
|
+
``identity.principal_id``.
|
|
111
|
+
"""
|
|
112
|
+
return await runtime.retrieval.search(
|
|
113
|
+
RetrievalRequest(
|
|
114
|
+
access=AccessContext(
|
|
115
|
+
principal_id=acl_subject,
|
|
116
|
+
tenant_id=TenantId(identity.tenant_id),
|
|
117
|
+
corpus_mode=corpus_mode_for(settings, identity.tenant_id),
|
|
118
|
+
),
|
|
119
|
+
query=context.standalone_query,
|
|
120
|
+
top_k=top_k,
|
|
121
|
+
filters=dict(filters),
|
|
122
|
+
lane=RetrievalLane.HYBRID,
|
|
123
|
+
observe_graph=observe_graph,
|
|
124
|
+
mode=RetrievalMode.LOCAL_SEMANTIC if observe_graph else RetrievalMode.FLAT,
|
|
125
|
+
rerank=rerank,
|
|
126
|
+
)
|
|
127
|
+
)
|