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,625 @@
|
|
|
1
|
+
"""Published-content summaries independent of extraction and vector availability."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Awaitable, Callable
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from decimal import Decimal
|
|
11
|
+
from uuid import uuid4
|
|
12
|
+
|
|
13
|
+
from harborrag_adapters.topology.descriptions import (
|
|
14
|
+
DESCRIPTION_MAX_REPAIR_ATTEMPTS,
|
|
15
|
+
description_max_chars,
|
|
16
|
+
description_output_tokens,
|
|
17
|
+
)
|
|
18
|
+
from harborrag_core.base import utc_now
|
|
19
|
+
from harborrag_core.chunking import ChunkRecord
|
|
20
|
+
from harborrag_core.chunking.tokenization import ApproximateTokenCounter
|
|
21
|
+
from harborrag_core.contracts import HarborConflictError
|
|
22
|
+
from harborrag_core.ingestion import (
|
|
23
|
+
DocumentIdentityBuilder,
|
|
24
|
+
GraphEntityType,
|
|
25
|
+
GraphNodeRecord,
|
|
26
|
+
GraphOwnershipScope,
|
|
27
|
+
KnowledgeNodeKind,
|
|
28
|
+
)
|
|
29
|
+
from harborrag_core.ports.description_generation import UsageAwareDescriptionPort
|
|
30
|
+
from harborrag_core.ports.summary_projection import SummaryExecutionRepositoryPort
|
|
31
|
+
from harborrag_core.ports.topology import TopologyBudgetRepositoryPort
|
|
32
|
+
from harborrag_core.schemas.ids import TenantId
|
|
33
|
+
from harborrag_core.summaries import (
|
|
34
|
+
LEAF_SUMMARY_KINDS,
|
|
35
|
+
MissingSourceDocument,
|
|
36
|
+
SummaryAttribute,
|
|
37
|
+
SummaryBinding,
|
|
38
|
+
SummaryCard,
|
|
39
|
+
SummaryCoverage,
|
|
40
|
+
SummaryLease,
|
|
41
|
+
SummaryManifest,
|
|
42
|
+
SummaryPolicy,
|
|
43
|
+
SummarySnapshot,
|
|
44
|
+
generation_key,
|
|
45
|
+
)
|
|
46
|
+
from harborrag_core.topology.budget import BudgetRequest, UsageSettlement
|
|
47
|
+
from harborrag_core.topology.derived import (
|
|
48
|
+
DescriptionOutput,
|
|
49
|
+
DescriptionPacket,
|
|
50
|
+
description_prompt_json,
|
|
51
|
+
)
|
|
52
|
+
from harborrag_core.topology.extraction import digest
|
|
53
|
+
from harborrag_core.topology.text_policy import PARENT_DESCRIPTION_MAX_WORDS
|
|
54
|
+
from harborrag_engine.topology.reservation_deadline import reservation_seconds
|
|
55
|
+
from harborrag_engine.topology.summary_planner import SummaryPlanNode
|
|
56
|
+
from harborrag_engine.topology.summary_reducer import (
|
|
57
|
+
SummaryBudgetDeferred,
|
|
58
|
+
SummaryReducer,
|
|
59
|
+
input_digest,
|
|
60
|
+
)
|
|
61
|
+
from harborrag_runtime.config.settings import RuntimeSettings
|
|
62
|
+
|
|
63
|
+
from .budgeted_extractor import EnrichmentDeferredError
|
|
64
|
+
from .entity_summary_index import EntitySummaryIndex
|
|
65
|
+
|
|
66
|
+
logger = logging.getLogger("harborrag.runtime.topology")
|
|
67
|
+
type SummaryPlanLoader = Callable[
|
|
68
|
+
[SummaryLease, SummarySnapshot], Awaitable[tuple[SummaryPlanNode, ...]]
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class BudgetedSummaryGenerator:
|
|
74
|
+
"""Description generator that checks each call against the topology budget."""
|
|
75
|
+
|
|
76
|
+
delegate: UsageAwareDescriptionPort
|
|
77
|
+
repository: SummaryExecutionRepositoryPort
|
|
78
|
+
budget: TopologyBudgetRepositoryPort
|
|
79
|
+
lease: SummaryLease
|
|
80
|
+
settings: RuntimeSettings
|
|
81
|
+
spent_usd: Decimal = Decimal(0)
|
|
82
|
+
|
|
83
|
+
async def generate(
|
|
84
|
+
self,
|
|
85
|
+
packets: tuple[DescriptionPacket, ...],
|
|
86
|
+
*,
|
|
87
|
+
max_words: int = PARENT_DESCRIPTION_MAX_WORDS,
|
|
88
|
+
) -> DescriptionOutput:
|
|
89
|
+
"""Generate a description for the packets within the budget.
|
|
90
|
+
|
|
91
|
+
A dossier is allowed more words than a navigation card, so the reservation has to cover them
|
|
92
|
+
or a wide budget would be admitted against a narrow one's estimate.
|
|
93
|
+
"""
|
|
94
|
+
ceiling = self.settings.topology_llm_operation_cost_usd
|
|
95
|
+
if ceiling is None:
|
|
96
|
+
raise SummaryBudgetDeferred("provider_cost_ceiling_unconfigured")
|
|
97
|
+
run_ceiling = self.settings.topology_parent_run_budget_usd
|
|
98
|
+
if run_ceiling is not None and self.spent_usd + ceiling > run_ceiling:
|
|
99
|
+
raise SummaryBudgetDeferred("summary_run_budget")
|
|
100
|
+
calls = DESCRIPTION_MAX_REPAIR_ATTEMPTS + 1
|
|
101
|
+
request = BudgetRequest(
|
|
102
|
+
reservation_id=uuid4().hex,
|
|
103
|
+
purpose="parent_description",
|
|
104
|
+
input_tokens=calls
|
|
105
|
+
* (ApproximateTokenCounter().count(description_prompt_json(packets)) + 2048),
|
|
106
|
+
output_tokens=calls * self._output_tokens(max_words),
|
|
107
|
+
cost_usd=ceiling,
|
|
108
|
+
operation_key=digest(
|
|
109
|
+
[
|
|
110
|
+
self.lease.policy.fingerprint,
|
|
111
|
+
description_prompt_json(packets),
|
|
112
|
+
max_words,
|
|
113
|
+
]
|
|
114
|
+
),
|
|
115
|
+
provider_calls=calls,
|
|
116
|
+
)
|
|
117
|
+
admission = await self.repository.reserve(self.lease, request)
|
|
118
|
+
if not admission.admitted:
|
|
119
|
+
raise SummaryBudgetDeferred(admission.reason or "budget_unavailable")
|
|
120
|
+
usage = UsageSettlement()
|
|
121
|
+
try:
|
|
122
|
+
async with asyncio.timeout(reservation_seconds(admission)):
|
|
123
|
+
result = await self.delegate.generate_usage(packets, max_words=max_words)
|
|
124
|
+
self.spent_usd += result.cost_usd if result.cost_usd is not None else ceiling
|
|
125
|
+
usage = UsageSettlement(
|
|
126
|
+
input_tokens=result.usage.prompt_tokens or None,
|
|
127
|
+
output_tokens=result.usage.completion_tokens or None,
|
|
128
|
+
cost_usd=result.cost_usd,
|
|
129
|
+
)
|
|
130
|
+
return result.output
|
|
131
|
+
finally:
|
|
132
|
+
await asyncio.shield(
|
|
133
|
+
self.budget.settle_budget(self.lease.tenant_id, request.reservation_id, usage)
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
def _output_tokens(self, max_words: int) -> int:
|
|
137
|
+
"""Reserve exactly what the request will be allowed to spend."""
|
|
138
|
+
return description_output_tokens(max_words, self.settings.topology_parent_max_output_tokens)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass(frozen=True)
|
|
142
|
+
class SummaryProjectionService:
|
|
143
|
+
"""Generate and store summaries for one tenant's pending topology nodes."""
|
|
144
|
+
|
|
145
|
+
repository: SummaryExecutionRepositoryPort
|
|
146
|
+
budget: TopologyBudgetRepositoryPort
|
|
147
|
+
settings: RuntimeSettings
|
|
148
|
+
generator_factory: Callable[[SummaryLease], UsageAwareDescriptionPort]
|
|
149
|
+
load_inputs: SummaryPlanLoader
|
|
150
|
+
entity_index: EntitySummaryIndex | None = None
|
|
151
|
+
"""Absent when the deployment has no vector backend wired into the summary worker; cards are
|
|
152
|
+
still written and still readable, only not searchable.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
async def run_once(
|
|
156
|
+
self,
|
|
157
|
+
tenant_id: str,
|
|
158
|
+
*,
|
|
159
|
+
source_scope_id: str | None = None,
|
|
160
|
+
heartbeat: Callable[[], None] | None = None,
|
|
161
|
+
) -> str:
|
|
162
|
+
"""Run one summary pass and return its status.
|
|
163
|
+
|
|
164
|
+
Lease expiry allows another worker to reuse completed reductions.
|
|
165
|
+
"""
|
|
166
|
+
lease = await self.repository.claim(
|
|
167
|
+
tenant_id,
|
|
168
|
+
lease_seconds=self.settings.topology_lease_seconds,
|
|
169
|
+
source_scope_id=source_scope_id,
|
|
170
|
+
)
|
|
171
|
+
if lease is None:
|
|
172
|
+
return "idle"
|
|
173
|
+
try:
|
|
174
|
+
async with asyncio.timeout(self.settings.topology_job_seconds):
|
|
175
|
+
async with asyncio.TaskGroup() as tasks:
|
|
176
|
+
renewal = tasks.create_task(self._renew(lease, heartbeat))
|
|
177
|
+
try:
|
|
178
|
+
await self._complete(lease)
|
|
179
|
+
finally:
|
|
180
|
+
renewal.cancel()
|
|
181
|
+
current = await self.repository.finish(lease)
|
|
182
|
+
return "current" if current else "superseded"
|
|
183
|
+
except asyncio.CancelledError:
|
|
184
|
+
raise
|
|
185
|
+
except Exception as error:
|
|
186
|
+
blocked, code = _summary_failure(error)
|
|
187
|
+
details = {
|
|
188
|
+
"tenant_id": lease.tenant_id,
|
|
189
|
+
"source_scope_id": lease.source_scope_id,
|
|
190
|
+
"error_code": code,
|
|
191
|
+
"blocked": blocked,
|
|
192
|
+
}
|
|
193
|
+
if blocked:
|
|
194
|
+
logger.info("Summary projection blocked", extra=details)
|
|
195
|
+
else:
|
|
196
|
+
logger.warning("Summary projection attempt failed", exc_info=True, extra=details)
|
|
197
|
+
await self.repository.finish(lease, error_code=code[:128], blocked=blocked)
|
|
198
|
+
return "blocked" if blocked else "failed"
|
|
199
|
+
|
|
200
|
+
async def _renew(self, lease: SummaryLease, heartbeat: Callable[[], None] | None) -> None:
|
|
201
|
+
while True:
|
|
202
|
+
if heartbeat:
|
|
203
|
+
heartbeat()
|
|
204
|
+
await asyncio.sleep(min(20, self.settings.topology_lease_seconds / 3))
|
|
205
|
+
await self.repository.renew(lease, lease_seconds=self.settings.topology_lease_seconds)
|
|
206
|
+
|
|
207
|
+
async def _complete(self, lease: SummaryLease) -> None:
|
|
208
|
+
"""``max_calls`` is configured per document; a scope run covers them all.
|
|
209
|
+
|
|
210
|
+
Spend is still bounded by the tenant's daily token/cost caps. Cards are generated in
|
|
211
|
+
dependency waves: every section, then every document, then the entities. Within a wave
|
|
212
|
+
nothing depends on anything else, so the tenant's card concurrency applies -- the old
|
|
213
|
+
one-at-a-time walk spent hours on a scope that needs minutes. Entity cards compose every
|
|
214
|
+
document under the entity. While the scope is still being ingested each one would be
|
|
215
|
+
superseded by the next publish, so leaves are built now and entities wait.
|
|
216
|
+
"""
|
|
217
|
+
if lease.source_scope_id == "@tenant":
|
|
218
|
+
await self._complete_tenant(lease)
|
|
219
|
+
return
|
|
220
|
+
repository = self.repository
|
|
221
|
+
snapshot = await repository.snapshot(lease)
|
|
222
|
+
plan = await self.load_inputs(lease, snapshot)
|
|
223
|
+
coverage = _CoverageLedger.of(
|
|
224
|
+
await repository.missing_documents(lease.tenant_id, lease.source_scope_id)
|
|
225
|
+
)
|
|
226
|
+
run = _Run(
|
|
227
|
+
lease=lease,
|
|
228
|
+
snapshot=snapshot,
|
|
229
|
+
coverage=coverage,
|
|
230
|
+
plans={item.node.node_key: item for item in plan},
|
|
231
|
+
reducer=SummaryReducer(
|
|
232
|
+
lease.tenant_id,
|
|
233
|
+
lease.policy,
|
|
234
|
+
repository,
|
|
235
|
+
BudgetedSummaryGenerator(
|
|
236
|
+
self.generator_factory(lease), repository, self.budget, lease, self.settings
|
|
237
|
+
),
|
|
238
|
+
max_calls=lease.policy.max_calls * max(1, len(snapshot.document_versions)),
|
|
239
|
+
),
|
|
240
|
+
semaphore=asyncio.Semaphore(lease.policy.max_concurrency),
|
|
241
|
+
)
|
|
242
|
+
for wave in _waves(plan):
|
|
243
|
+
if any(item.kind not in LEAF_SUMMARY_KINDS for item in wave):
|
|
244
|
+
if await repository.ingestion_active(lease.tenant_id, lease.source_scope_id):
|
|
245
|
+
raise HarborConflictError("SUMMARY_INGESTION_ACTIVE")
|
|
246
|
+
if not await repository.scope_current(lease):
|
|
247
|
+
run.complete = False
|
|
248
|
+
break
|
|
249
|
+
async with asyncio.TaskGroup() as tasks:
|
|
250
|
+
for item in wave:
|
|
251
|
+
tasks.create_task(self._bounded_card(run, item))
|
|
252
|
+
if run.complete:
|
|
253
|
+
await self._publish_entities(lease, tuple(run.entities))
|
|
254
|
+
|
|
255
|
+
async def _bounded_card(self, run: _Run, item: SummaryPlanNode) -> None:
|
|
256
|
+
"""One card at a time per semaphore slot -- the model call *and* the accept.
|
|
257
|
+
|
|
258
|
+
Bounding only the model call let a wave of a few hundred shortcut cards open
|
|
259
|
+
a database session each for ``accept`` at once and exhaust the control-plane
|
|
260
|
+
pool. The limit is on cards in flight, which is also what the budget means.
|
|
261
|
+
"""
|
|
262
|
+
async with run.semaphore:
|
|
263
|
+
await self._card(run, item)
|
|
264
|
+
|
|
265
|
+
async def _card(self, run: _Run, item: SummaryPlanNode) -> None:
|
|
266
|
+
"""Produce and accept one node's card.
|
|
267
|
+
|
|
268
|
+
The entity's own document is the one its direct chunks belong to; attachments hang beneath
|
|
269
|
+
it as their own entities.
|
|
270
|
+
"""
|
|
271
|
+
lease, policy = run.lease, run.lease.policy
|
|
272
|
+
direct = tuple(chunk for chunk in item.direct_chunks if chunk.content.strip())
|
|
273
|
+
metadata: dict[str, object] = {
|
|
274
|
+
"name": item.node.title or item.node.entity_type.value,
|
|
275
|
+
"type": item.node.entity_type.value,
|
|
276
|
+
"path": item.node.section_path,
|
|
277
|
+
}
|
|
278
|
+
inputs = (
|
|
279
|
+
*tuple(chunk.content for chunk in direct),
|
|
280
|
+
*(
|
|
281
|
+
json.dumps(
|
|
282
|
+
{
|
|
283
|
+
"name": run.plans[key].node.title,
|
|
284
|
+
"type": run.plans[key].node.entity_type.value,
|
|
285
|
+
"path": run.plans[key].node.section_path,
|
|
286
|
+
"card": run.cards[key].model_dump(mode="json"),
|
|
287
|
+
},
|
|
288
|
+
sort_keys=True,
|
|
289
|
+
ensure_ascii=False,
|
|
290
|
+
separators=(",", ":"),
|
|
291
|
+
)
|
|
292
|
+
for key in item.children
|
|
293
|
+
),
|
|
294
|
+
)
|
|
295
|
+
shortcut = _shortcut(lease.tenant_id, policy, item, direct, run.cards)
|
|
296
|
+
if shortcut is not None:
|
|
297
|
+
card, key = shortcut
|
|
298
|
+
else:
|
|
299
|
+
card, key = await run.reducer.reduce(item.kind, metadata, inputs)
|
|
300
|
+
if item.kind == "SourceEntity":
|
|
301
|
+
own = tuple(dict.fromkeys(str(chunk.document_id) for chunk in direct))
|
|
302
|
+
card = _with_facets(card, item.node, policy, own or item.document_ids)
|
|
303
|
+
versions = {
|
|
304
|
+
key: run.snapshot.document_versions[key]
|
|
305
|
+
for key in item.document_ids
|
|
306
|
+
if key in run.snapshot.document_versions
|
|
307
|
+
}
|
|
308
|
+
dependencies = tuple(
|
|
309
|
+
dep
|
|
310
|
+
for dep in run.snapshot.permission_dependencies
|
|
311
|
+
if dep.resource_kind == "source" or dep.resource_id in versions
|
|
312
|
+
)
|
|
313
|
+
missing = run.coverage.missing_for(item.kind, item.document_ids)
|
|
314
|
+
binding = SummaryBinding(
|
|
315
|
+
manifest=SummaryManifest(
|
|
316
|
+
node_key=item.node.node_key,
|
|
317
|
+
kind=item.kind,
|
|
318
|
+
source_scope_id=lease.source_scope_id,
|
|
319
|
+
input_document_versions=versions,
|
|
320
|
+
permission_dependencies=dependencies,
|
|
321
|
+
child_keys=item.children,
|
|
322
|
+
child_artifact_hashes={key: run.cards[key].artifact_hash for key in item.children},
|
|
323
|
+
input_chunk_ids=item.input_chunk_ids,
|
|
324
|
+
missing_document_ids=missing,
|
|
325
|
+
policy_fingerprint=policy.fingerprint,
|
|
326
|
+
membership_digest=run.snapshot.membership_digest,
|
|
327
|
+
input_digest=input_digest(metadata, inputs),
|
|
328
|
+
),
|
|
329
|
+
card=card,
|
|
330
|
+
generation_key=key,
|
|
331
|
+
artifact_hash=card.artifact_hash,
|
|
332
|
+
revision=lease.revision,
|
|
333
|
+
updated_at=utc_now(),
|
|
334
|
+
coverage_mode=_coverage_mode(item.input_chunk_ids, missing),
|
|
335
|
+
)
|
|
336
|
+
await self.repository.accept(lease, run.snapshot, binding, item.node)
|
|
337
|
+
run.cards[item.node.node_key] = card
|
|
338
|
+
if item.kind == "SourceEntity":
|
|
339
|
+
run.entities.append(binding)
|
|
340
|
+
|
|
341
|
+
async def _publish_entities(
|
|
342
|
+
self, lease: SummaryLease, bindings: tuple[SummaryBinding, ...]
|
|
343
|
+
) -> None:
|
|
344
|
+
"""Make this scope's entity cards searchable, and only this scope's.
|
|
345
|
+
|
|
346
|
+
A failure here must not fail the run: the cards are already accepted and
|
|
347
|
+
readable, and the index is rebuilt from them on the next pass. Losing a
|
|
348
|
+
search entry point is a degraded result; losing the binding is not. It is
|
|
349
|
+
logged as an error all the same: until it succeeds, ``find_entities`` and
|
|
350
|
+
``facet.*`` filters answer nothing for the scope, and a failure that repeats
|
|
351
|
+
every run must be alertable rather than a warning nobody reads.
|
|
352
|
+
"""
|
|
353
|
+
if self.entity_index is None or not await self.repository.scope_current(lease):
|
|
354
|
+
return
|
|
355
|
+
try:
|
|
356
|
+
await self.entity_index.publish(
|
|
357
|
+
lease.tenant_id, lease.source_scope_id, bindings, lease.policy.facets
|
|
358
|
+
)
|
|
359
|
+
except Exception:
|
|
360
|
+
logger.exception(
|
|
361
|
+
"Entity summary index publication failed",
|
|
362
|
+
extra={
|
|
363
|
+
"tenant_id": lease.tenant_id,
|
|
364
|
+
"source_scope_id": lease.source_scope_id,
|
|
365
|
+
"entities": len(bindings),
|
|
366
|
+
},
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
async def _complete_tenant(self, lease: SummaryLease) -> None:
|
|
370
|
+
repository = self.repository
|
|
371
|
+
snapshot = await repository.snapshot(lease)
|
|
372
|
+
children = await repository.tenant_inputs(lease)
|
|
373
|
+
node = GraphNodeRecord(
|
|
374
|
+
node_key=DocumentIdentityBuilder().tenant_node_key(tenant_id=lease.tenant_id),
|
|
375
|
+
node_kind=KnowledgeNodeKind.TENANT,
|
|
376
|
+
entity_type=GraphEntityType.TENANT,
|
|
377
|
+
logical_id=lease.tenant_id,
|
|
378
|
+
ownership_scope=GraphOwnershipScope.TENANT,
|
|
379
|
+
owner_id=TenantId(lease.tenant_id),
|
|
380
|
+
title=lease.tenant_id,
|
|
381
|
+
)
|
|
382
|
+
reducer = SummaryReducer(
|
|
383
|
+
lease.tenant_id,
|
|
384
|
+
lease.policy,
|
|
385
|
+
repository,
|
|
386
|
+
BudgetedSummaryGenerator(
|
|
387
|
+
self.generator_factory(lease), repository, self.budget, lease, self.settings
|
|
388
|
+
),
|
|
389
|
+
)
|
|
390
|
+
inputs = tuple(child.card.model_dump_json() for child in children)
|
|
391
|
+
metadata: dict[str, object] = {"name": lease.tenant_id, "type": "tenant"}
|
|
392
|
+
card, key = await reducer.reduce("Tenant", metadata, inputs)
|
|
393
|
+
chunk_ids = tuple(
|
|
394
|
+
sorted({key for child in children for key in child.manifest.input_chunk_ids})
|
|
395
|
+
)
|
|
396
|
+
missing = tuple(
|
|
397
|
+
sorted({key for child in children for key in child.manifest.missing_document_ids})
|
|
398
|
+
)
|
|
399
|
+
binding = SummaryBinding(
|
|
400
|
+
manifest=SummaryManifest(
|
|
401
|
+
node_key=node.node_key,
|
|
402
|
+
kind="Tenant",
|
|
403
|
+
source_scope_id="@tenant",
|
|
404
|
+
input_document_versions=snapshot.document_versions,
|
|
405
|
+
permission_dependencies=snapshot.permission_dependencies,
|
|
406
|
+
child_keys=tuple(child.manifest.node_key for child in children),
|
|
407
|
+
child_artifact_hashes={
|
|
408
|
+
child.manifest.node_key: child.artifact_hash for child in children
|
|
409
|
+
},
|
|
410
|
+
input_chunk_ids=chunk_ids,
|
|
411
|
+
missing_document_ids=missing,
|
|
412
|
+
policy_fingerprint=lease.policy.fingerprint,
|
|
413
|
+
membership_digest=snapshot.membership_digest,
|
|
414
|
+
input_digest=input_digest(metadata, inputs),
|
|
415
|
+
),
|
|
416
|
+
card=card,
|
|
417
|
+
generation_key=key,
|
|
418
|
+
artifact_hash=card.artifact_hash,
|
|
419
|
+
revision=lease.revision,
|
|
420
|
+
updated_at=utc_now(),
|
|
421
|
+
coverage_mode=_coverage_mode(chunk_ids, missing),
|
|
422
|
+
)
|
|
423
|
+
await repository.accept(lease, snapshot, binding, node)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@dataclass
|
|
427
|
+
class _Run:
|
|
428
|
+
"""Everything one scope run shares across its concurrently generated cards."""
|
|
429
|
+
|
|
430
|
+
lease: SummaryLease
|
|
431
|
+
snapshot: SummarySnapshot
|
|
432
|
+
coverage: _CoverageLedger
|
|
433
|
+
plans: dict[str, SummaryPlanNode]
|
|
434
|
+
reducer: SummaryReducer
|
|
435
|
+
semaphore: asyncio.Semaphore
|
|
436
|
+
cards: dict[str, SummaryCard] = field(default_factory=dict)
|
|
437
|
+
entities: list[SummaryBinding] = field(default_factory=list)
|
|
438
|
+
complete: bool = True
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _waves(plan: tuple[SummaryPlanNode, ...]) -> tuple[tuple[SummaryPlanNode, ...], ...]:
|
|
442
|
+
"""Group the plan by dependency depth; every node's children are in an earlier wave.
|
|
443
|
+
|
|
444
|
+
The planner emits children before parents.
|
|
445
|
+
"""
|
|
446
|
+
depth: dict[str, int] = {}
|
|
447
|
+
for item in plan:
|
|
448
|
+
depth[item.node.node_key] = 1 + max(
|
|
449
|
+
(depth[child] for child in item.children if child in depth), default=-1
|
|
450
|
+
)
|
|
451
|
+
waves: dict[int, list[SummaryPlanNode]] = {}
|
|
452
|
+
for item in plan:
|
|
453
|
+
waves.setdefault(depth[item.node.node_key], []).append(item)
|
|
454
|
+
return tuple(tuple(waves[level]) for level in sorted(waves))
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _shortcut(
|
|
458
|
+
tenant_id: str,
|
|
459
|
+
policy: SummaryPolicy,
|
|
460
|
+
item: SummaryPlanNode,
|
|
461
|
+
direct: tuple[ChunkRecord, ...],
|
|
462
|
+
cards: dict[str, SummaryCard],
|
|
463
|
+
) -> tuple[SummaryCard, str] | None:
|
|
464
|
+
"""A card that needs no model: the content already fits, or there is one child.
|
|
465
|
+
|
|
466
|
+
A section holding one 250-token comment does not need a model to say what it
|
|
467
|
+
says; neither does an attachment entity whose only child is the document card
|
|
468
|
+
written a moment earlier. Both were a model call each -- together well over
|
|
469
|
+
half of every run -- and the model's answer was a paraphrase of the input.
|
|
470
|
+
|
|
471
|
+
A verbatim card of children that carry facets keeps their union; leaves have none today, but the
|
|
472
|
+
rule is what makes the shortcut safe to widen later.
|
|
473
|
+
"""
|
|
474
|
+
words = policy.card_words.for_kind(item.kind)
|
|
475
|
+
if not direct and len(item.children) == 1:
|
|
476
|
+
child = cards[item.children[0]]
|
|
477
|
+
return child, generation_key(
|
|
478
|
+
tenant_id, policy, ["inherit", item.node.node_key, child.artifact_hash, words]
|
|
479
|
+
)
|
|
480
|
+
if item.kind not in LEAF_SUMMARY_KINDS:
|
|
481
|
+
return None
|
|
482
|
+
texts = [
|
|
483
|
+
*(chunk.content.strip() for chunk in direct),
|
|
484
|
+
*(cards[key].description.strip() for key in item.children),
|
|
485
|
+
]
|
|
486
|
+
joined = "\n\n".join(text for text in texts if text)
|
|
487
|
+
if not joined or len(joined.split()) > words or len(joined) > description_max_chars(words):
|
|
488
|
+
return None
|
|
489
|
+
return SummaryCard(description=joined), generation_key(
|
|
490
|
+
tenant_id, policy, ["verbatim", texts, words], fingerprint=policy.leaf_fingerprint
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _with_facets(
|
|
495
|
+
card: SummaryCard,
|
|
496
|
+
node: GraphNodeRecord,
|
|
497
|
+
policy: SummaryPolicy,
|
|
498
|
+
document_ids: tuple[str, ...] = (),
|
|
499
|
+
) -> SummaryCard:
|
|
500
|
+
"""Copy the connector's structured fields onto the card as its facets.
|
|
501
|
+
|
|
502
|
+
A Jira *Stage* field is the editor's own statement, so it is copied as-is
|
|
503
|
+
rather than read back out of the content by a model. ``document_ids`` is the
|
|
504
|
+
provenance to record: a source entity node carries no document id of its own,
|
|
505
|
+
so the caller names the document(s) the fields came from.
|
|
506
|
+
|
|
507
|
+
One value per member, so ``skill_set == java`` matches a card whose Skill Set is Java and Python
|
|
508
|
+
-- as ``fields.skill_set`` does on evidence.
|
|
509
|
+
"""
|
|
510
|
+
if not policy.facets:
|
|
511
|
+
return card
|
|
512
|
+
fields = _node_fields(node)
|
|
513
|
+
copied: dict[str, SummaryAttribute] = {}
|
|
514
|
+
for facet in policy.facets:
|
|
515
|
+
values = tuple(
|
|
516
|
+
dict.fromkeys(
|
|
517
|
+
value[:200]
|
|
518
|
+
for member in fields.get(facet.field.strip().casefold(), ())
|
|
519
|
+
if (value := member.strip())
|
|
520
|
+
)
|
|
521
|
+
)[:24]
|
|
522
|
+
if not values:
|
|
523
|
+
continue
|
|
524
|
+
copied[facet.name] = SummaryAttribute(
|
|
525
|
+
name=facet.name,
|
|
526
|
+
values=values,
|
|
527
|
+
from_document_ids=tuple(sorted(document_ids))[:64],
|
|
528
|
+
)
|
|
529
|
+
if not copied:
|
|
530
|
+
return card
|
|
531
|
+
return card.model_copy(update={"attributes": tuple(copied.values())})
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _node_fields(node: GraphNodeRecord) -> dict[str, tuple[str, ...]]:
|
|
535
|
+
"""Every field a facet may name on this node, keyed case-insensitively.
|
|
536
|
+
|
|
537
|
+
Standard issue attributes come first (``status``, ``priority``, ``labels``, ...):
|
|
538
|
+
the pipeline stage of a candidate is the issue status, not a custom field. A
|
|
539
|
+
custom field answers to its field id and to its display name alike.
|
|
540
|
+
|
|
541
|
+
Each field keeps its members: a list attribute (``labels``) as its items, and
|
|
542
|
+
a typed custom field as the lines of its text. Prose fields never reach the
|
|
543
|
+
node, so a line break in a typed field's text is where the connector joined
|
|
544
|
+
one option, user or value to the next.
|
|
545
|
+
"""
|
|
546
|
+
fields: dict[str, tuple[str, ...]] = {}
|
|
547
|
+
for key, value in node.attributes.items():
|
|
548
|
+
if key == "custom_fields" or value in (None, "", [], {}):
|
|
549
|
+
continue
|
|
550
|
+
members = tuple(str(v) for v in value) if isinstance(value, list) else (str(value),)
|
|
551
|
+
fields[str(key).strip().casefold()] = members
|
|
552
|
+
rows = node.attributes.get("custom_fields")
|
|
553
|
+
for row in rows if isinstance(rows, list) else ():
|
|
554
|
+
if not isinstance(row, dict) or not row.get("value"):
|
|
555
|
+
continue
|
|
556
|
+
for key in ("field_id", "name"):
|
|
557
|
+
if row.get(key):
|
|
558
|
+
fields[str(row[key]).strip().casefold()] = tuple(str(row["value"]).splitlines())
|
|
559
|
+
return fields
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _coverage_mode(chunks: tuple[str, ...], missing: tuple[str, ...]) -> SummaryCoverage:
|
|
563
|
+
"""Say whether a card covers everything, part of it, or nothing."""
|
|
564
|
+
if missing:
|
|
565
|
+
return "partial"
|
|
566
|
+
return "complete" if chunks else "empty"
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
@dataclass(frozen=True)
|
|
570
|
+
class _CoverageLedger:
|
|
571
|
+
"""Attribute each undelivered source item to the nodes that should contain it.
|
|
572
|
+
|
|
573
|
+
An attachment still in OCR, or one whose file type nothing can parse, is
|
|
574
|
+
discovered long before it is parsed. Reading the gap from discovery rather
|
|
575
|
+
than from what published is what lets a card say it is partial instead of
|
|
576
|
+
silently describing an issue without its attached design document.
|
|
577
|
+
"""
|
|
578
|
+
|
|
579
|
+
by_parent: dict[str, tuple[str, ...]]
|
|
580
|
+
orphans: tuple[str, ...]
|
|
581
|
+
|
|
582
|
+
@classmethod
|
|
583
|
+
def of(cls, missing: tuple[MissingSourceDocument, ...]) -> _CoverageLedger:
|
|
584
|
+
"""Group the missing source documents by the node that should contain them.
|
|
585
|
+
|
|
586
|
+
A child of an absent parent has no node to belong to either, so it rises to the source level
|
|
587
|
+
rather than disappearing from the count.
|
|
588
|
+
"""
|
|
589
|
+
identifiers = {item.document_id for item in missing}
|
|
590
|
+
by_parent: dict[str, tuple[str, ...]] = {}
|
|
591
|
+
orphans: tuple[str, ...] = ()
|
|
592
|
+
for item in missing:
|
|
593
|
+
parent = item.parent_document_id
|
|
594
|
+
if parent is None or parent in identifiers:
|
|
595
|
+
orphans += (item.document_id,)
|
|
596
|
+
continue
|
|
597
|
+
by_parent[parent] = by_parent.get(parent, ()) + (item.document_id,)
|
|
598
|
+
return cls(by_parent, orphans)
|
|
599
|
+
|
|
600
|
+
def missing_for(self, kind: str, documents: tuple[str, ...]) -> tuple[str, ...]:
|
|
601
|
+
found = {item for parent in documents for item in self.by_parent.get(parent, ())}
|
|
602
|
+
if kind in {"DataSource", "Tenant"}:
|
|
603
|
+
found.update(self.orphans)
|
|
604
|
+
return tuple(sorted(found))
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def _summary_failure(error: BaseException) -> tuple[bool, str]:
|
|
608
|
+
"""Classify every concurrent failure; infrastructure errors take precedence."""
|
|
609
|
+
leaves = _exception_leaves(error)
|
|
610
|
+
blocked_types = (SummaryBudgetDeferred, EnrichmentDeferredError, HarborConflictError)
|
|
611
|
+
failures = tuple(cause for cause in leaves if not isinstance(cause, blocked_types))
|
|
612
|
+
cause = failures[0] if failures else leaves[0]
|
|
613
|
+
blocked = not failures
|
|
614
|
+
code = (
|
|
615
|
+
str(cause)
|
|
616
|
+
if isinstance(cause, (SummaryBudgetDeferred, HarborConflictError))
|
|
617
|
+
else type(cause).__name__
|
|
618
|
+
)
|
|
619
|
+
return blocked, code
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _exception_leaves(error: BaseException) -> tuple[BaseException, ...]:
|
|
623
|
+
if isinstance(error, BaseExceptionGroup):
|
|
624
|
+
return tuple(leaf for child in error.exceptions for leaf in _exception_leaves(child))
|
|
625
|
+
return (error,)
|