nvs-runtime 1.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.
- nvs_runtime/__init__.py +29 -0
- nvs_runtime/__version__.py +3 -0
- nvs_runtime/config/__init__.py +3 -0
- nvs_runtime/config/settings.py +26 -0
- nvs_runtime/core/__init__.py +6 -0
- nvs_runtime/core/clock.py +32 -0
- nvs_runtime/core/composition.py +92 -0
- nvs_runtime/core/errors.py +69 -0
- nvs_runtime/core/hext.py +43 -0
- nvs_runtime/core/models.py +151 -0
- nvs_runtime/core/protocols.py +77 -0
- nvs_runtime/core/runtime.py +373 -0
- nvs_runtime/events/__init__.py +4 -0
- nvs_runtime/events/bus.py +50 -0
- nvs_runtime/events/types.py +35 -0
- nvs_runtime/executors/__init__.py +2 -0
- nvs_runtime/governance/__init__.py +4 -0
- nvs_runtime/governance/engine.py +58 -0
- nvs_runtime/governance/quota.py +48 -0
- nvs_runtime/graph/__init__.py +3 -0
- nvs_runtime/graph/capability_graph.py +100 -0
- nvs_runtime/hidden_trajectory/__init__.py +62 -0
- nvs_runtime/hidden_trajectory/_gate_child.py +375 -0
- nvs_runtime/hidden_trajectory/adapter_loader.py +70 -0
- nvs_runtime/hidden_trajectory/canonical.py +22 -0
- nvs_runtime/hidden_trajectory/capture_archive.py +204 -0
- nvs_runtime/hidden_trajectory/capture_chain.py +319 -0
- nvs_runtime/hidden_trajectory/cli.py +765 -0
- nvs_runtime/hidden_trajectory/envelope.py +303 -0
- nvs_runtime/hidden_trajectory/formal_save.py +499 -0
- nvs_runtime/hidden_trajectory/formal_writer.py +590 -0
- nvs_runtime/hidden_trajectory/gate_client.py +460 -0
- nvs_runtime/hidden_trajectory/item_set.py +317 -0
- nvs_runtime/hidden_trajectory/k_measure.py +145 -0
- nvs_runtime/hidden_trajectory/model_catalog.py +56 -0
- nvs_runtime/hidden_trajectory/payload.py +382 -0
- nvs_runtime/hidden_trajectory/phase2/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase2/evaluate.py +319 -0
- nvs_runtime/hidden_trajectory/phase2/geometry.py +80 -0
- nvs_runtime/hidden_trajectory/phase2/labels.py +72 -0
- nvs_runtime/hidden_trajectory/phase4/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase4/normalize.py +171 -0
- nvs_runtime/hidden_trajectory/phase4/summary.py +270 -0
- nvs_runtime/hidden_trajectory/phase4b/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase4b/load.py +46 -0
- nvs_runtime/hidden_trajectory/phase4b/metrics.py +96 -0
- nvs_runtime/hidden_trajectory/phase4b/scan.py +33 -0
- nvs_runtime/hidden_trajectory/record.py +334 -0
- nvs_runtime/hidden_trajectory/record_schema.py +781 -0
- nvs_runtime/hidden_trajectory/replay/__init__.py +6 -0
- nvs_runtime/hidden_trajectory/replay/risk_control.py +196 -0
- nvs_runtime/hidden_trajectory/rerun.py +302 -0
- nvs_runtime/hidden_trajectory/rsa/__init__.py +6 -0
- nvs_runtime/hidden_trajectory/rsa/analysis.py +248 -0
- nvs_runtime/hidden_trajectory/rsa/calibration.py +659 -0
- nvs_runtime/hidden_trajectory/rsa/compare.py +714 -0
- nvs_runtime/hidden_trajectory/rsa/readout.py +192 -0
- nvs_runtime/hidden_trajectory/run.py +362 -0
- nvs_runtime/hidden_trajectory/token_temporal.py +368 -0
- nvs_runtime/hidden_trajectory/window.py +344 -0
- nvs_runtime/integrations/__init__.py +4 -0
- nvs_runtime/integrations/hekb_formal.py +169 -0
- nvs_runtime/integrations/hekb_vnext.py +302 -0
- nvs_runtime/metrics/__init__.py +3 -0
- nvs_runtime/metrics/collector.py +63 -0
- nvs_runtime/observability/__init__.py +3 -0
- nvs_runtime/observability/store.py +44 -0
- nvs_runtime/planner/__init__.py +3 -0
- nvs_runtime/planner/planner.py +158 -0
- nvs_runtime/providers/__init__.py +19 -0
- nvs_runtime/providers/base.py +43 -0
- nvs_runtime/providers/edge.py +165 -0
- nvs_runtime/providers/grpc.py +58 -0
- nvs_runtime/providers/hekb.py +77 -0
- nvs_runtime/providers/http.py +59 -0
- nvs_runtime/providers/kernel.py +67 -0
- nvs_runtime/providers/local.py +88 -0
- nvs_runtime/providers/mcp.py +84 -0
- nvs_runtime/providers/registry.py +56 -0
- nvs_runtime/providers/replay.py +138 -0
- nvs_runtime/py.typed +0 -0
- nvs_runtime/security/__init__.py +4 -0
- nvs_runtime/security/cbac.py +106 -0
- nvs_runtime/security/signer.py +20 -0
- nvs_runtime/session/__init__.py +4 -0
- nvs_runtime/session/checkpoint.py +108 -0
- nvs_runtime/session/manager.py +149 -0
- nvs_runtime/transport/__init__.py +3 -0
- nvs_runtime/transport/memory.py +36 -0
- nvs_runtime-1.0.0.dist-info/METADATA +234 -0
- nvs_runtime-1.0.0.dist-info/RECORD +94 -0
- nvs_runtime-1.0.0.dist-info/WHEEL +4 -0
- nvs_runtime-1.0.0.dist-info/entry_points.txt +2 -0
- nvs_runtime-1.0.0.dist-info/licenses/LICENSE +190 -0
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""NVSRuntime — stable, provider-agnostic public API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from nvs_runtime.core.clock import elapsed_ms
|
|
10
|
+
from nvs_runtime.core.errors import (
|
|
11
|
+
AuthorizationError,
|
|
12
|
+
CapabilityNotFoundError,
|
|
13
|
+
GovernanceError,
|
|
14
|
+
ProviderError,
|
|
15
|
+
ProviderNotFoundError,
|
|
16
|
+
RuntimeError,
|
|
17
|
+
ShutdownError,
|
|
18
|
+
)
|
|
19
|
+
from nvs_runtime.core.models import (
|
|
20
|
+
CheckpointRequest,
|
|
21
|
+
DiscoverQuery,
|
|
22
|
+
DiscoverResult,
|
|
23
|
+
ExecutionPlan,
|
|
24
|
+
InvokeRequest,
|
|
25
|
+
InvokeResult,
|
|
26
|
+
ObserveQuery,
|
|
27
|
+
ObserveResult,
|
|
28
|
+
PlanRequest,
|
|
29
|
+
SessionAction,
|
|
30
|
+
SessionRequest,
|
|
31
|
+
)
|
|
32
|
+
from nvs_runtime.events.bus import EventBus
|
|
33
|
+
from nvs_runtime.events.types import EventType
|
|
34
|
+
from nvs_runtime.governance.engine import GovernanceEngine
|
|
35
|
+
from nvs_runtime.graph.capability_graph import CapabilityGraph
|
|
36
|
+
from nvs_runtime.metrics.collector import MetricsCollector
|
|
37
|
+
from nvs_runtime.observability.store import ObservabilityStore
|
|
38
|
+
from nvs_runtime.planner.planner import Planner
|
|
39
|
+
from nvs_runtime.providers.registry import ProviderRegistry
|
|
40
|
+
from nvs_runtime.security.cbac import CBACEngine
|
|
41
|
+
from nvs_runtime.session.checkpoint import CheckpointManager
|
|
42
|
+
from nvs_runtime.session.manager import SessionManager
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class NVSRuntime:
|
|
47
|
+
"""Reference NVS Runtime — applications never talk to providers directly."""
|
|
48
|
+
|
|
49
|
+
providers: ProviderRegistry
|
|
50
|
+
graph: CapabilityGraph
|
|
51
|
+
planner: Planner
|
|
52
|
+
sessions: SessionManager
|
|
53
|
+
checkpoints: CheckpointManager
|
|
54
|
+
governance: GovernanceEngine
|
|
55
|
+
metrics_collector: MetricsCollector
|
|
56
|
+
observability: ObservabilityStore
|
|
57
|
+
events: EventBus
|
|
58
|
+
cbac: CBACEngine
|
|
59
|
+
clock: Callable[[], int]
|
|
60
|
+
_shut_down: bool = field(default=False, init=False, repr=False)
|
|
61
|
+
|
|
62
|
+
def discover(
|
|
63
|
+
self,
|
|
64
|
+
query: DiscoverQuery | dict[str, Any] | None = None,
|
|
65
|
+
) -> DiscoverResult:
|
|
66
|
+
self._ensure_alive()
|
|
67
|
+
self._refresh_graph()
|
|
68
|
+
q = (
|
|
69
|
+
DiscoverQuery()
|
|
70
|
+
if query is None
|
|
71
|
+
else query
|
|
72
|
+
if isinstance(query, DiscoverQuery)
|
|
73
|
+
else DiscoverQuery.model_validate(query)
|
|
74
|
+
)
|
|
75
|
+
caps = self.graph.all()
|
|
76
|
+
if q.provider_id:
|
|
77
|
+
caps = [c for c in caps if c.provider_id == q.provider_id]
|
|
78
|
+
if q.tag:
|
|
79
|
+
caps = [c for c in caps if q.tag in c.tags]
|
|
80
|
+
if q.input_type:
|
|
81
|
+
caps = [c for c in caps if c.input_type in {q.input_type, "any", "*"}]
|
|
82
|
+
if q.output_type:
|
|
83
|
+
caps = [c for c in caps if c.output_type in {q.output_type, "any", "*"}]
|
|
84
|
+
result = DiscoverResult(
|
|
85
|
+
capabilities=caps,
|
|
86
|
+
providers=self.providers.list_providers(),
|
|
87
|
+
)
|
|
88
|
+
self.events.publish(
|
|
89
|
+
EventType.CAPABILITY_DISCOVERED,
|
|
90
|
+
{"count": len(caps)},
|
|
91
|
+
)
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
def plan(self, request: PlanRequest | dict[str, Any]) -> ExecutionPlan:
|
|
95
|
+
self._ensure_alive()
|
|
96
|
+
self._refresh_graph()
|
|
97
|
+
req = request if isinstance(request, PlanRequest) else PlanRequest.model_validate(request)
|
|
98
|
+
plan = self.planner.plan(req)
|
|
99
|
+
self.metrics_collector.record_plan(executable=plan.executable)
|
|
100
|
+
self.observability.record_plan(plan.to_dict())
|
|
101
|
+
self.events.publish(
|
|
102
|
+
EventType.PLAN_CREATED,
|
|
103
|
+
{"plan_id": plan.plan_id, "executable": plan.executable},
|
|
104
|
+
)
|
|
105
|
+
topo = self.graph.build()
|
|
106
|
+
self.observability.record_topology(
|
|
107
|
+
{"node_count": topo["node_count"], "edge_count": topo["edge_count"]}
|
|
108
|
+
)
|
|
109
|
+
return plan
|
|
110
|
+
|
|
111
|
+
async def invoke(self, request: InvokeRequest | dict[str, Any]) -> InvokeResult:
|
|
112
|
+
self._ensure_alive()
|
|
113
|
+
self._refresh_graph()
|
|
114
|
+
req = (
|
|
115
|
+
request if isinstance(request, InvokeRequest) else InvokeRequest.model_validate(request)
|
|
116
|
+
)
|
|
117
|
+
t0 = self.clock()
|
|
118
|
+
tenant_id = "anonymous"
|
|
119
|
+
try:
|
|
120
|
+
if req.token:
|
|
121
|
+
payload = self.cbac.require_scopes(req.token, {"scope:invoke"})
|
|
122
|
+
if payload:
|
|
123
|
+
tenant_id = payload.tenant_id
|
|
124
|
+
|
|
125
|
+
if req.plan_id:
|
|
126
|
+
return await self._invoke_plan(req, tenant_id=tenant_id, t0=t0)
|
|
127
|
+
|
|
128
|
+
if not req.capability_id:
|
|
129
|
+
raise CapabilityNotFoundError("<missing>")
|
|
130
|
+
|
|
131
|
+
provider, cap = self.providers.find_capability(req.capability_id)
|
|
132
|
+
if req.provider_id and req.provider_id != provider.provider_id:
|
|
133
|
+
raise ProviderNotFoundError(req.provider_id)
|
|
134
|
+
|
|
135
|
+
if req.token:
|
|
136
|
+
self.cbac.check_budget(req.token, cap.cost_units)
|
|
137
|
+
|
|
138
|
+
self.governance.quota.admit(tenant_id, cost=cap.cost_units)
|
|
139
|
+
try:
|
|
140
|
+
self.events.publish(
|
|
141
|
+
EventType.INVOKE_STARTED,
|
|
142
|
+
{"capability_id": cap.id, "provider_id": provider.provider_id},
|
|
143
|
+
)
|
|
144
|
+
if req.session_id:
|
|
145
|
+
self.sessions.start(req.session_id)
|
|
146
|
+
output = await provider.invoke(cap.id, dict(req.payload))
|
|
147
|
+
latency = elapsed_ms(t0, self.clock)
|
|
148
|
+
result = InvokeResult(
|
|
149
|
+
ok=True,
|
|
150
|
+
capability_id=cap.id,
|
|
151
|
+
provider_id=provider.provider_id,
|
|
152
|
+
session_id=req.session_id,
|
|
153
|
+
output=output,
|
|
154
|
+
latency_ms=latency,
|
|
155
|
+
)
|
|
156
|
+
self.metrics_collector.record_invoke(ok=True, latency_ms=latency)
|
|
157
|
+
self.events.publish(EventType.INVOKE_COMPLETED, result.to_dict())
|
|
158
|
+
self.observability.record_timeline(
|
|
159
|
+
{"kind": "invoke", **result.to_dict()}
|
|
160
|
+
)
|
|
161
|
+
if req.session_id:
|
|
162
|
+
self.sessions.advance(req.session_id)
|
|
163
|
+
return result
|
|
164
|
+
finally:
|
|
165
|
+
self.governance.release(tenant_id)
|
|
166
|
+
except (
|
|
167
|
+
AuthorizationError,
|
|
168
|
+
CapabilityNotFoundError,
|
|
169
|
+
ProviderError,
|
|
170
|
+
ProviderNotFoundError,
|
|
171
|
+
GovernanceError,
|
|
172
|
+
RuntimeError,
|
|
173
|
+
KeyError,
|
|
174
|
+
) as exc:
|
|
175
|
+
latency = elapsed_ms(t0, self.clock)
|
|
176
|
+
code = getattr(exc, "code", "INVOKE_ERROR")
|
|
177
|
+
message = getattr(exc, "message", str(exc))
|
|
178
|
+
result = InvokeResult(
|
|
179
|
+
ok=False,
|
|
180
|
+
capability_id=req.capability_id,
|
|
181
|
+
provider_id=req.provider_id,
|
|
182
|
+
session_id=req.session_id,
|
|
183
|
+
plan_id=req.plan_id,
|
|
184
|
+
error_code=code,
|
|
185
|
+
detail=message,
|
|
186
|
+
latency_ms=latency,
|
|
187
|
+
)
|
|
188
|
+
self.metrics_collector.record_invoke(ok=False, latency_ms=latency)
|
|
189
|
+
self.events.publish(EventType.INVOKE_FAILED, result.to_dict())
|
|
190
|
+
self.observability.record_timeline({"kind": "invoke_failed", **result.to_dict()})
|
|
191
|
+
return result
|
|
192
|
+
|
|
193
|
+
def observe(self, query: ObserveQuery | dict[str, Any] | None = None) -> ObserveResult:
|
|
194
|
+
self._ensure_alive()
|
|
195
|
+
q = (
|
|
196
|
+
ObserveQuery()
|
|
197
|
+
if query is None
|
|
198
|
+
else query
|
|
199
|
+
if isinstance(query, ObserveQuery)
|
|
200
|
+
else ObserveQuery.model_validate(query)
|
|
201
|
+
)
|
|
202
|
+
if q.kind == "sessions":
|
|
203
|
+
items = self.sessions.list_sessions()
|
|
204
|
+
if q.session_id:
|
|
205
|
+
items = [s for s in items if s.get("session_id") == q.session_id]
|
|
206
|
+
return ObserveResult(kind="sessions", items=items)
|
|
207
|
+
|
|
208
|
+
if q.kind == "topology":
|
|
209
|
+
self._refresh_graph()
|
|
210
|
+
topo = self.graph.build()
|
|
211
|
+
return ObserveResult(kind="topology", items=[topo])
|
|
212
|
+
|
|
213
|
+
if q.kind == "statistics":
|
|
214
|
+
return ObserveResult(
|
|
215
|
+
kind="statistics",
|
|
216
|
+
statistics={
|
|
217
|
+
**self.metrics_collector.snapshot(),
|
|
218
|
+
"events": len(self.events.history(limit=10_000)),
|
|
219
|
+
},
|
|
220
|
+
items=self.observability.query("statistics", limit=q.limit),
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
items = self.observability.query("timeline", limit=q.limit)
|
|
224
|
+
if q.session_id:
|
|
225
|
+
items = [i for i in items if i.get("session_id") == q.session_id]
|
|
226
|
+
if q.plan_id:
|
|
227
|
+
items = [i for i in items if i.get("plan_id") == q.plan_id]
|
|
228
|
+
# Merge event bus history for richer observe()
|
|
229
|
+
events = self.events.history(limit=q.limit)
|
|
230
|
+
return ObserveResult(
|
|
231
|
+
kind=q.kind,
|
|
232
|
+
items=items or events,
|
|
233
|
+
statistics=self.metrics_collector.snapshot(),
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
def session(self, request: SessionRequest | dict[str, Any] | None = None) -> dict[str, Any]:
|
|
237
|
+
self._ensure_alive()
|
|
238
|
+
req = (
|
|
239
|
+
SessionRequest()
|
|
240
|
+
if request is None
|
|
241
|
+
else request
|
|
242
|
+
if isinstance(request, SessionRequest)
|
|
243
|
+
else SessionRequest.model_validate(request)
|
|
244
|
+
)
|
|
245
|
+
result = self.sessions.handle(req)
|
|
246
|
+
if req.action == SessionAction.CREATE:
|
|
247
|
+
self.metrics_collector.record_session_created()
|
|
248
|
+
self.events.publish(EventType.SESSION_CREATED, result)
|
|
249
|
+
else:
|
|
250
|
+
self.events.publish(EventType.SESSION_UPDATED, result)
|
|
251
|
+
return result
|
|
252
|
+
|
|
253
|
+
def checkpoint(
|
|
254
|
+
self,
|
|
255
|
+
request: CheckpointRequest | dict[str, Any] | None = None,
|
|
256
|
+
) -> dict[str, Any]:
|
|
257
|
+
self._ensure_alive()
|
|
258
|
+
req = (
|
|
259
|
+
CheckpointRequest()
|
|
260
|
+
if request is None
|
|
261
|
+
else request
|
|
262
|
+
if isinstance(request, CheckpointRequest)
|
|
263
|
+
else CheckpointRequest.model_validate(request)
|
|
264
|
+
)
|
|
265
|
+
result = self.checkpoints.handle(req)
|
|
266
|
+
if req.action.value == "save":
|
|
267
|
+
self.metrics_collector.record_checkpoint()
|
|
268
|
+
self.events.publish(EventType.CHECKPOINT_SAVED, result)
|
|
269
|
+
elif req.action.value == "restore":
|
|
270
|
+
self.events.publish(EventType.CHECKPOINT_RESTORED, result)
|
|
271
|
+
return result
|
|
272
|
+
|
|
273
|
+
def metrics(self) -> dict[str, Any]:
|
|
274
|
+
self._ensure_alive()
|
|
275
|
+
snap = self.metrics_collector.snapshot()
|
|
276
|
+
snap["providers"] = self.providers.list_providers()
|
|
277
|
+
snap["plans"] = len(self.governance.list_plans())
|
|
278
|
+
return snap
|
|
279
|
+
|
|
280
|
+
async def shutdown(self) -> None:
|
|
281
|
+
if self._shut_down:
|
|
282
|
+
return
|
|
283
|
+
for provider in self.providers.providers():
|
|
284
|
+
await provider.shutdown()
|
|
285
|
+
self.events.publish(EventType.RUNTIME_SHUTDOWN, {})
|
|
286
|
+
self._shut_down = True
|
|
287
|
+
|
|
288
|
+
def register_provider(self, provider: Any) -> None:
|
|
289
|
+
self._ensure_alive()
|
|
290
|
+
self.providers.register(provider)
|
|
291
|
+
self._refresh_graph()
|
|
292
|
+
self.events.publish(
|
|
293
|
+
EventType.PROVIDER_REGISTERED,
|
|
294
|
+
{"provider_id": provider.provider_id, "kind": provider.kind},
|
|
295
|
+
)
|
|
296
|
+
self.events.publish(EventType.TOPOLOGY_CHANGED, self.graph.build())
|
|
297
|
+
|
|
298
|
+
# --- internals ---
|
|
299
|
+
|
|
300
|
+
async def _invoke_plan(
|
|
301
|
+
self,
|
|
302
|
+
req: InvokeRequest,
|
|
303
|
+
*,
|
|
304
|
+
tenant_id: str,
|
|
305
|
+
t0: int,
|
|
306
|
+
) -> InvokeResult:
|
|
307
|
+
assert req.plan_id is not None
|
|
308
|
+
plan = self.governance.get_plan(req.plan_id)
|
|
309
|
+
self.governance.admit(tenant_id=tenant_id, plan=plan)
|
|
310
|
+
session_id = req.session_id
|
|
311
|
+
# A caller-supplied session_id means the caller owns that session's lifecycle
|
|
312
|
+
# (it created it, and will complete/cancel it itself -- e.g. one long-lived
|
|
313
|
+
# session invoked by plan_id once per token). Only a session this call creates
|
|
314
|
+
# for itself (session_id was None) is also this call's to complete -- the
|
|
315
|
+
# single-shot pattern (README "Quick Start": invoke({"plan_id":...}) with no
|
|
316
|
+
# session_id) is unchanged.
|
|
317
|
+
session_owned_by_this_call = session_id is None
|
|
318
|
+
try:
|
|
319
|
+
if session_id is None:
|
|
320
|
+
session = self.sessions.create(
|
|
321
|
+
plan_id=plan.plan_id,
|
|
322
|
+
total_steps=len(plan.steps),
|
|
323
|
+
)
|
|
324
|
+
session_id = session.session_id
|
|
325
|
+
self.metrics_collector.record_session_created()
|
|
326
|
+
self.sessions.start(session_id)
|
|
327
|
+
|
|
328
|
+
output: dict[str, Any] = dict(req.payload)
|
|
329
|
+
last_cap = None
|
|
330
|
+
last_provider = None
|
|
331
|
+
for idx, step in enumerate(plan.steps):
|
|
332
|
+
if self.governance.is_cancelled(plan.plan_id):
|
|
333
|
+
raise GovernanceError("plan cancelled during invoke", code="PLAN_CANCELLED")
|
|
334
|
+
provider, cap = self.providers.find_capability(step.capability_id)
|
|
335
|
+
last_cap = cap.id
|
|
336
|
+
last_provider = provider.provider_id
|
|
337
|
+
self.events.publish(
|
|
338
|
+
EventType.INVOKE_STARTED,
|
|
339
|
+
{
|
|
340
|
+
"capability_id": cap.id,
|
|
341
|
+
"provider_id": provider.provider_id,
|
|
342
|
+
"plan_id": plan.plan_id,
|
|
343
|
+
"step": idx,
|
|
344
|
+
},
|
|
345
|
+
)
|
|
346
|
+
output = await provider.invoke(cap.id, output)
|
|
347
|
+
self.sessions.advance(session_id, step=idx + 1)
|
|
348
|
+
|
|
349
|
+
if session_owned_by_this_call:
|
|
350
|
+
self.sessions.complete(session_id)
|
|
351
|
+
latency = elapsed_ms(t0, self.clock)
|
|
352
|
+
result = InvokeResult(
|
|
353
|
+
ok=True,
|
|
354
|
+
capability_id=last_cap,
|
|
355
|
+
provider_id=last_provider,
|
|
356
|
+
session_id=session_id,
|
|
357
|
+
plan_id=plan.plan_id,
|
|
358
|
+
output=output,
|
|
359
|
+
latency_ms=latency,
|
|
360
|
+
)
|
|
361
|
+
self.metrics_collector.record_invoke(ok=True, latency_ms=latency)
|
|
362
|
+
self.events.publish(EventType.INVOKE_COMPLETED, result.to_dict())
|
|
363
|
+
self.observability.record_timeline({"kind": "invoke_plan", **result.to_dict()})
|
|
364
|
+
return result
|
|
365
|
+
finally:
|
|
366
|
+
self.governance.release(tenant_id)
|
|
367
|
+
|
|
368
|
+
def _refresh_graph(self) -> None:
|
|
369
|
+
self.graph.replace(self.providers.all_capabilities())
|
|
370
|
+
|
|
371
|
+
def _ensure_alive(self) -> None:
|
|
372
|
+
if self._shut_down:
|
|
373
|
+
raise ShutdownError()
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""In-process event bus with optional transport fan-out."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from nvs_runtime.events.types import EventType, RuntimeEvent
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EventBus:
|
|
12
|
+
"""Pub/sub bus. Transports attach as subscribers — never embedded."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, *, clock: Callable[[], int]) -> None:
|
|
15
|
+
self._clock = clock
|
|
16
|
+
self._subscribers: list[Callable[[RuntimeEvent], None]] = []
|
|
17
|
+
self._history: list[RuntimeEvent] = []
|
|
18
|
+
self._max_history = 1_000
|
|
19
|
+
|
|
20
|
+
def subscribe(self, handler: Callable[[RuntimeEvent], None]) -> None:
|
|
21
|
+
self._subscribers.append(handler)
|
|
22
|
+
|
|
23
|
+
def publish(
|
|
24
|
+
self,
|
|
25
|
+
event_type: EventType | str,
|
|
26
|
+
payload: dict[str, Any] | None = None,
|
|
27
|
+
) -> RuntimeEvent:
|
|
28
|
+
et = event_type if isinstance(event_type, EventType) else EventType(event_type)
|
|
29
|
+
event = RuntimeEvent(
|
|
30
|
+
type=et,
|
|
31
|
+
timestamp_ns=self._clock(),
|
|
32
|
+
payload=dict(payload or {}),
|
|
33
|
+
)
|
|
34
|
+
self._history.append(event)
|
|
35
|
+
if len(self._history) > self._max_history:
|
|
36
|
+
self._history = self._history[-self._max_history :]
|
|
37
|
+
for handler in list(self._subscribers):
|
|
38
|
+
handler(event)
|
|
39
|
+
return event
|
|
40
|
+
|
|
41
|
+
def history(
|
|
42
|
+
self,
|
|
43
|
+
*,
|
|
44
|
+
limit: int = 50,
|
|
45
|
+
event_type: EventType | None = None,
|
|
46
|
+
) -> list[dict[str, Any]]:
|
|
47
|
+
items = self._history
|
|
48
|
+
if event_type is not None:
|
|
49
|
+
items = [e for e in items if e.type == event_type]
|
|
50
|
+
return [e.to_dict() for e in items[-limit:]]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Runtime event types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, Field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EventType(StrEnum):
|
|
13
|
+
PROVIDER_REGISTERED = "provider.registered"
|
|
14
|
+
PROVIDER_REMOVED = "provider.removed"
|
|
15
|
+
CAPABILITY_DISCOVERED = "capability.discovered"
|
|
16
|
+
PLAN_CREATED = "plan.created"
|
|
17
|
+
INVOKE_STARTED = "invoke.started"
|
|
18
|
+
INVOKE_COMPLETED = "invoke.completed"
|
|
19
|
+
INVOKE_FAILED = "invoke.failed"
|
|
20
|
+
SESSION_CREATED = "session.created"
|
|
21
|
+
SESSION_UPDATED = "session.updated"
|
|
22
|
+
CHECKPOINT_SAVED = "checkpoint.saved"
|
|
23
|
+
CHECKPOINT_RESTORED = "checkpoint.restored"
|
|
24
|
+
TOPOLOGY_CHANGED = "topology.changed"
|
|
25
|
+
RUNTIME_SHUTDOWN = "runtime.shutdown"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RuntimeEvent(BaseModel):
|
|
29
|
+
event_id: str = Field(default_factory=lambda: f"evt_{uuid4().hex[:12]}")
|
|
30
|
+
type: EventType
|
|
31
|
+
timestamp_ns: int = 0
|
|
32
|
+
payload: dict[str, Any] = Field(default_factory=dict)
|
|
33
|
+
|
|
34
|
+
def to_dict(self) -> dict[str, Any]:
|
|
35
|
+
return self.model_dump(mode="json")
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Governance — plan admission, cancel, and durable plan store."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from nvs_runtime.core.errors import GovernanceError
|
|
8
|
+
from nvs_runtime.core.models import ExecutionPlan
|
|
9
|
+
from nvs_runtime.core.protocols import ObjectStore
|
|
10
|
+
from nvs_runtime.governance.quota import QuotaEngine
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GovernanceEngine:
|
|
14
|
+
"""Owns execution plans and admission decisions."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, *, store: ObjectStore, quota: QuotaEngine | None = None) -> None:
|
|
17
|
+
self._store = store
|
|
18
|
+
self._quota = quota or QuotaEngine()
|
|
19
|
+
self._plans: dict[str, ExecutionPlan] = {}
|
|
20
|
+
self._cancelled: set[str] = set()
|
|
21
|
+
|
|
22
|
+
def store_plan(self, plan: ExecutionPlan) -> str:
|
|
23
|
+
self._plans[plan.plan_id] = plan
|
|
24
|
+
return self._store.put_object(
|
|
25
|
+
plan.to_dict(),
|
|
26
|
+
labels={"kind": "execution_plan", "plan_id": plan.plan_id},
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def get_plan(self, plan_id: str) -> ExecutionPlan:
|
|
30
|
+
try:
|
|
31
|
+
return self._plans[plan_id]
|
|
32
|
+
except KeyError as exc:
|
|
33
|
+
raise GovernanceError(f"unknown plan: {plan_id}", code="PLAN_NOT_FOUND") from exc
|
|
34
|
+
|
|
35
|
+
def admit(self, *, tenant_id: str, plan: ExecutionPlan) -> None:
|
|
36
|
+
if not plan.executable:
|
|
37
|
+
raise GovernanceError("plan is not executable", code="PLAN_NOT_EXECUTABLE")
|
|
38
|
+
if plan.plan_id in self._cancelled:
|
|
39
|
+
raise GovernanceError("plan was cancelled", code="PLAN_CANCELLED")
|
|
40
|
+
self._quota.admit(tenant_id, cost=plan.estimated_cost_units)
|
|
41
|
+
|
|
42
|
+
def release(self, tenant_id: str) -> None:
|
|
43
|
+
self._quota.release(tenant_id)
|
|
44
|
+
|
|
45
|
+
def cancel_plan(self, plan_id: str, *, reason: str = "cancelled") -> dict[str, Any]:
|
|
46
|
+
plan = self.get_plan(plan_id)
|
|
47
|
+
self._cancelled.add(plan_id)
|
|
48
|
+
return {"plan_id": plan.plan_id, "cancelled": True, "reason": reason}
|
|
49
|
+
|
|
50
|
+
def is_cancelled(self, plan_id: str) -> bool:
|
|
51
|
+
return plan_id in self._cancelled
|
|
52
|
+
|
|
53
|
+
def list_plans(self) -> list[dict[str, Any]]:
|
|
54
|
+
return [p.to_dict() for p in self._plans.values()]
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def quota(self) -> QuotaEngine:
|
|
58
|
+
return self._quota
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Tenant quota enforcement."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from nvs_runtime.core.errors import GovernanceError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class QuotaEngine:
|
|
9
|
+
"""Simple in-process concurrency / cost quotas."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
*,
|
|
14
|
+
max_concurrent: int = 32,
|
|
15
|
+
max_cost_per_tenant: int = 10_000,
|
|
16
|
+
) -> None:
|
|
17
|
+
self._max_concurrent = max_concurrent
|
|
18
|
+
self._max_cost = max_cost_per_tenant
|
|
19
|
+
self._active: dict[str, int] = {}
|
|
20
|
+
self._spent: dict[str, int] = {}
|
|
21
|
+
|
|
22
|
+
def admit(self, tenant_id: str, *, cost: int = 1) -> None:
|
|
23
|
+
active = self._active.get(tenant_id, 0)
|
|
24
|
+
if active >= self._max_concurrent:
|
|
25
|
+
raise GovernanceError(
|
|
26
|
+
f"tenant {tenant_id} concurrent limit reached",
|
|
27
|
+
code="QUOTA_CONCURRENT",
|
|
28
|
+
)
|
|
29
|
+
spent = self._spent.get(tenant_id, 0)
|
|
30
|
+
if spent + cost > self._max_cost:
|
|
31
|
+
raise GovernanceError(
|
|
32
|
+
f"tenant {tenant_id} cost quota exceeded",
|
|
33
|
+
code="QUOTA_COST",
|
|
34
|
+
)
|
|
35
|
+
self._active[tenant_id] = active + 1
|
|
36
|
+
self._spent[tenant_id] = spent + cost
|
|
37
|
+
|
|
38
|
+
def release(self, tenant_id: str) -> None:
|
|
39
|
+
active = self._active.get(tenant_id, 0)
|
|
40
|
+
if active > 0:
|
|
41
|
+
self._active[tenant_id] = active - 1
|
|
42
|
+
|
|
43
|
+
def snapshot(self) -> dict[str, dict[str, int]]:
|
|
44
|
+
tenants = set(self._active) | set(self._spent)
|
|
45
|
+
return {
|
|
46
|
+
t: {"active": self._active.get(t, 0), "spent": self._spent.get(t, 0)}
|
|
47
|
+
for t in sorted(tenants)
|
|
48
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Capability Graph — DAG of capabilities, never hardcoded pipelines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
from nvs_runtime.core.models import Capability
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GraphNode(BaseModel):
|
|
13
|
+
capability_id: str
|
|
14
|
+
provider_id: str
|
|
15
|
+
input_type: str
|
|
16
|
+
output_type: str
|
|
17
|
+
tags: list[str] = Field(default_factory=list)
|
|
18
|
+
cost_units: int = 1
|
|
19
|
+
latency_ms: int = 1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class GraphEdge(BaseModel):
|
|
23
|
+
source: str
|
|
24
|
+
target: str
|
|
25
|
+
data_format: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class CapabilityGraph:
|
|
29
|
+
"""Rebuildable capability DAG sourced from the provider registry."""
|
|
30
|
+
|
|
31
|
+
def __init__(self) -> None:
|
|
32
|
+
self._capabilities: dict[str, Capability] = {}
|
|
33
|
+
|
|
34
|
+
def replace(self, capabilities: list[Capability]) -> None:
|
|
35
|
+
self._capabilities = {c.id: c for c in capabilities}
|
|
36
|
+
|
|
37
|
+
def upsert(self, capability: Capability) -> None:
|
|
38
|
+
self._capabilities[capability.id] = capability
|
|
39
|
+
|
|
40
|
+
def remove_provider(self, provider_id: str) -> None:
|
|
41
|
+
self._capabilities = {
|
|
42
|
+
cid: cap for cid, cap in self._capabilities.items() if cap.provider_id != provider_id
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
def get(self, capability_id: str) -> Capability:
|
|
46
|
+
try:
|
|
47
|
+
return self._capabilities[capability_id]
|
|
48
|
+
except KeyError as exc:
|
|
49
|
+
raise KeyError(f"unknown capability: {capability_id}") from exc
|
|
50
|
+
|
|
51
|
+
def all(self) -> list[Capability]:
|
|
52
|
+
return list(self._capabilities.values())
|
|
53
|
+
|
|
54
|
+
def build(self) -> dict[str, Any]:
|
|
55
|
+
caps = self.all()
|
|
56
|
+
nodes = [
|
|
57
|
+
GraphNode(
|
|
58
|
+
capability_id=c.id,
|
|
59
|
+
provider_id=c.provider_id,
|
|
60
|
+
input_type=c.input_type,
|
|
61
|
+
output_type=c.output_type,
|
|
62
|
+
tags=list(c.tags),
|
|
63
|
+
cost_units=c.cost_units,
|
|
64
|
+
latency_ms=c.latency_ms,
|
|
65
|
+
)
|
|
66
|
+
for c in caps
|
|
67
|
+
]
|
|
68
|
+
edges: list[GraphEdge] = []
|
|
69
|
+
for src in caps:
|
|
70
|
+
for dst in caps:
|
|
71
|
+
if src.id == dst.id:
|
|
72
|
+
continue
|
|
73
|
+
if _types_compatible(src.output_type, dst.input_type):
|
|
74
|
+
edges.append(
|
|
75
|
+
GraphEdge(
|
|
76
|
+
source=src.id,
|
|
77
|
+
target=dst.id,
|
|
78
|
+
data_format=src.output_type,
|
|
79
|
+
)
|
|
80
|
+
)
|
|
81
|
+
return {
|
|
82
|
+
"nodes": [n.model_dump(mode="json") for n in nodes],
|
|
83
|
+
"edges": [e.model_dump(mode="json") for e in edges],
|
|
84
|
+
"node_count": len(nodes),
|
|
85
|
+
"edge_count": len(edges),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
def neighbors(self, capability_id: str) -> list[Capability]:
|
|
89
|
+
src = self.get(capability_id)
|
|
90
|
+
return [
|
|
91
|
+
dst
|
|
92
|
+
for dst in self.all()
|
|
93
|
+
if dst.id != src.id and _types_compatible(src.output_type, dst.input_type)
|
|
94
|
+
]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _types_compatible(output_type: str, input_type: str) -> bool:
|
|
98
|
+
if input_type in {"any", "*"} or output_type in {"any", "*"}:
|
|
99
|
+
return True
|
|
100
|
+
return output_type == input_type
|