cap-sdk-python 2.17.0__py3-none-any.whl → 2.19.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.
- cap/__init__.py +68 -0
- cap/cancel.py +102 -0
- cap/client.py +34 -3
- cap/dispatch_fence.py +121 -0
- cap/job_events.py +101 -0
- cap/outcome.py +160 -0
- cap/production_resource.py +15 -6
- cap/resource_nats_kv.py +196 -0
- cap/resource_registry.py +360 -0
- cap/runtime.py +662 -120
- cap/telemetry.py +366 -0
- cap/testing.py +36 -2
- cap_sdk_python-2.19.0.dist-info/METADATA +700 -0
- {cap_sdk_python-2.17.0.dist-info → cap_sdk_python-2.19.0.dist-info}/RECORD +17 -10
- cap_sdk_python-2.17.0.dist-info/METADATA +0 -414
- {cap_sdk_python-2.17.0.dist-info → cap_sdk_python-2.19.0.dist-info}/WHEEL +0 -0
- {cap_sdk_python-2.17.0.dist-info → cap_sdk_python-2.19.0.dist-info}/licenses/LICENSE +0 -0
- {cap_sdk_python-2.17.0.dist-info → cap_sdk_python-2.19.0.dist-info}/top_level.txt +0 -0
cap/runtime.py
CHANGED
|
@@ -2,13 +2,15 @@ import asyncio
|
|
|
2
2
|
import hashlib
|
|
3
3
|
import json
|
|
4
4
|
import logging
|
|
5
|
+
import math
|
|
5
6
|
import os
|
|
6
7
|
import secrets
|
|
8
|
+
import threading
|
|
7
9
|
import time
|
|
8
|
-
from dataclasses import dataclass, replace
|
|
9
|
-
from datetime import timezone
|
|
10
|
+
from dataclasses import dataclass, field, replace
|
|
11
|
+
from datetime import datetime, timedelta, timezone
|
|
10
12
|
from types import MappingProxyType
|
|
11
|
-
from typing import Any, Awaitable, Callable, Coroutine, Dict, Optional, Protocol, Type, TypeVar, Union
|
|
13
|
+
from typing import Any, Awaitable, Callable, Coroutine, Dict, Optional, Protocol, Tuple, Type, TypeVar, Union
|
|
12
14
|
|
|
13
15
|
from google.protobuf import timestamp_pb2
|
|
14
16
|
from cap.pb.cordum.agent.v1 import buspacket_pb2, handshake_pb2, job_pb2
|
|
@@ -26,10 +28,44 @@ except Exception: # pragma: no cover - optional until runtime used
|
|
|
26
28
|
ValidationError = Exception
|
|
27
29
|
|
|
28
30
|
|
|
29
|
-
from cap.
|
|
31
|
+
from cap.telemetry import (
|
|
32
|
+
ErrorType,
|
|
33
|
+
MessagingSpan,
|
|
34
|
+
Process,
|
|
35
|
+
Publish,
|
|
36
|
+
TelemetryConfig,
|
|
37
|
+
extract,
|
|
38
|
+
inject_headers,
|
|
39
|
+
start_process,
|
|
40
|
+
start_publish,
|
|
41
|
+
)
|
|
42
|
+
from cap.subjects import SUBJECT_CANCEL, SUBJECT_HANDSHAKE, SUBJECT_PROGRESS, SUBJECT_RESULT
|
|
43
|
+
from cap.job_events import ARTIFACT_PURPOSE_PREFIX, _JobEvents, check_artifact, check_marker
|
|
44
|
+
from cap.cancel import (
|
|
45
|
+
CancelRegistry, _JOB_CANCELLED, _JOB_TIMEOUT, handler_deadline,
|
|
46
|
+
peek_cancel_job_id, validate_max_deadline,
|
|
47
|
+
)
|
|
30
48
|
from cap.errors import InvalidInputError
|
|
49
|
+
from cap.dispatch_fence import Dispatch, DispatchFence, FenceDecision, RecordedResult
|
|
31
50
|
from cap.metrics import MetricsHook, NoopMetrics, safe_metrics_call
|
|
32
51
|
from cap.heartbeat import heartbeat_loop, heartbeat_payload
|
|
52
|
+
from cap.outcome import (
|
|
53
|
+
JobFailure,
|
|
54
|
+
_CONTEXT_DECODE_FAILED,
|
|
55
|
+
_CONTEXT_FETCH_FAILED,
|
|
56
|
+
_CONTEXT_NOT_FOUND,
|
|
57
|
+
_CONTEXT_POINTER_INVALID,
|
|
58
|
+
_CONTEXT_REF_REFUSED,
|
|
59
|
+
_CONTEXT_REF_REQUIRED,
|
|
60
|
+
_CONTEXT_TOO_LARGE,
|
|
61
|
+
_HANDLER_FAILED,
|
|
62
|
+
_INPUT_INVALID,
|
|
63
|
+
_Outcome,
|
|
64
|
+
_RESULT_ENCODE_FAILED,
|
|
65
|
+
_RESULT_TOO_LARGE,
|
|
66
|
+
_RESULT_WRITE_FAILED,
|
|
67
|
+
_failure_outcome,
|
|
68
|
+
)
|
|
33
69
|
from cap.packet_boundary import decode_packet, finalize_packet, parse_packet
|
|
34
70
|
from cap.production_signing import (
|
|
35
71
|
ProductionSignatureError,
|
|
@@ -46,7 +82,15 @@ from cap.production_events import (
|
|
|
46
82
|
seal_production_event,
|
|
47
83
|
)
|
|
48
84
|
from cap.production_validation import IdentityMismatchError, validate_identity_binding
|
|
49
|
-
from cap.
|
|
85
|
+
from cap.production_resource import validate_resource_ref_compatibility
|
|
86
|
+
from cap.resource_registry import (
|
|
87
|
+
ResourceBackendUnavailableError,
|
|
88
|
+
ResourceRegistry,
|
|
89
|
+
ResourceRegistryError,
|
|
90
|
+
ResourceTooLargeError,
|
|
91
|
+
TrustedResourceContext,
|
|
92
|
+
)
|
|
93
|
+
from cap.validate import MAX_REPEATED_FIELD_SIZE, validate_bus_packet
|
|
50
94
|
from cap.worker_trust import WorkerTrustConfig, WorkerTrustMode
|
|
51
95
|
from cap.worker_trust_runtime import (
|
|
52
96
|
DEFAULT_RENEW_MIN_INTERVAL,
|
|
@@ -59,6 +103,8 @@ from cap.constants import DEFAULT_PROTOCOL_VERSION # noqa: E402 — must be aft
|
|
|
59
103
|
|
|
60
104
|
|
|
61
105
|
_HANDLER_FAILED_MESSAGE = "handler failed"
|
|
106
|
+
_JSON_MEDIA_TYPE = "application/json"
|
|
107
|
+
_RESULT_PURPOSE = "job-result"
|
|
62
108
|
_LOG_FIELD_LIMIT = 256
|
|
63
109
|
|
|
64
110
|
|
|
@@ -101,7 +147,7 @@ def _log_handler_failure(
|
|
|
101
147
|
) -> None:
|
|
102
148
|
try:
|
|
103
149
|
logger.warning(
|
|
104
|
-
|
|
150
|
+
_HANDLER_FAILED_MESSAGE,
|
|
105
151
|
extra={
|
|
106
152
|
"job_id": _bounded_log_field(request.job_id),
|
|
107
153
|
"trace_id": _bounded_log_field(packet.trace_id),
|
|
@@ -116,6 +162,16 @@ def _log_handler_failure(
|
|
|
116
162
|
pass
|
|
117
163
|
|
|
118
164
|
|
|
165
|
+
def _empty_otel_context() -> Any:
|
|
166
|
+
"""Return a new, empty OpenTelemetry context.
|
|
167
|
+
|
|
168
|
+
Called only when telemetry is configured, so OpenTelemetry is installed.
|
|
169
|
+
"""
|
|
170
|
+
from opentelemetry.context import Context as OtelContext
|
|
171
|
+
|
|
172
|
+
return OtelContext()
|
|
173
|
+
|
|
174
|
+
|
|
119
175
|
class BlobStore(Protocol):
|
|
120
176
|
"""Abstraction over payload storage (Redis, in-memory, etc.)."""
|
|
121
177
|
|
|
@@ -299,11 +355,53 @@ def _default_logger() -> logging.Logger:
|
|
|
299
355
|
|
|
300
356
|
@dataclass
|
|
301
357
|
class Context:
|
|
302
|
-
"""Per-request context
|
|
358
|
+
"""Per-request context. deadline is a monotonic instant, or None.
|
|
359
|
+
|
|
360
|
+
cancelled is read-only and thread-safe: True after an accepted cancel or
|
|
361
|
+
deadline stops the handler. Constructing with job/packet/logger still works.
|
|
362
|
+
"""
|
|
303
363
|
|
|
304
364
|
job: job_pb2.JobRequest
|
|
305
365
|
packet: buspacket_pb2.BusPacket
|
|
306
366
|
logger: logging.LoggerAdapter
|
|
367
|
+
deadline: Optional[float] = None
|
|
368
|
+
_stop_signal: threading.Event = field(default_factory=threading.Event, repr=False)
|
|
369
|
+
_events: Optional[_JobEvents] = field(default=None, repr=False, compare=False)
|
|
370
|
+
_dispatch_claim: Optional[Tuple[str, Dispatch]] = field(default=None, init=False, repr=False, compare=False)
|
|
371
|
+
# The OpenTelemetry context holding the job's process span when the Agent
|
|
372
|
+
# has telemetry configured, else None. It is never made current: pass it
|
|
373
|
+
# as ``context=`` to start child spans.
|
|
374
|
+
otel_context: Optional[Any] = None
|
|
375
|
+
|
|
376
|
+
async def report_progress(self, marker: str) -> None:
|
|
377
|
+
"""Await a RUNNING JobProgress with message=marker (1-256 printable UTF-8 bytes).
|
|
378
|
+
|
|
379
|
+
Calls publish in order, sealed for sys.job.progress in production; I/O
|
|
380
|
+
errors propagate. Async handlers on the event-loop thread only. A call
|
|
381
|
+
that runs after the handler's final attempt ended is dropped. Closed or
|
|
382
|
+
unbound contexts validate but do no I/O; run_worker is unchanged.
|
|
383
|
+
"""
|
|
384
|
+
check_marker(marker)
|
|
385
|
+
if self._events is not None:
|
|
386
|
+
await self._events.progress(marker)
|
|
387
|
+
|
|
388
|
+
async def attach_artifact(self, name: str, media_type: str, content: bytes) -> None:
|
|
389
|
+
"""Externalize bytes through the registry as job-artifact:<name>.
|
|
390
|
+
|
|
391
|
+
Name matches [a-z0-9][a-z0-9._-]{0,63}; media type is canonical (127-byte
|
|
392
|
+
max), content nonempty bytes. Per-attempt count/byte bounds and write
|
|
393
|
+
failures latch RESOURCE_EXHAUSTED and raise JobFailure even if caught.
|
|
394
|
+
Only SUCCEEDED carries refs, in call order; retries reset refs. Await
|
|
395
|
+
on the event-loop thread, not from a sync handler. Closed/unbound hooks
|
|
396
|
+
validate but do nothing; a call after the final attempt ended is dropped.
|
|
397
|
+
"""
|
|
398
|
+
check_artifact(name, media_type, content)
|
|
399
|
+
if self._events is not None:
|
|
400
|
+
await self._events.artifact(name, media_type, content)
|
|
401
|
+
|
|
402
|
+
@property
|
|
403
|
+
def cancelled(self) -> bool:
|
|
404
|
+
return self._stop_signal.is_set()
|
|
307
405
|
|
|
308
406
|
@property
|
|
309
407
|
def job_id(self) -> str:
|
|
@@ -339,6 +437,32 @@ class Agent:
|
|
|
339
437
|
"""High-level runtime that manages typed job handlers, blob storage, and NATS subscriptions.
|
|
340
438
|
|
|
341
439
|
Register handlers with :meth:`job`, then call :meth:`run` to start processing.
|
|
440
|
+
|
|
441
|
+
``resource_registry`` (an operator-built :class:`cap.ResourceRegistry`) switches
|
|
442
|
+
job input and output to ResourceRefs: input comes only from
|
|
443
|
+
``JobRequest.context_ref`` and a SUCCEEDED result carries ``result_ref``,
|
|
444
|
+
externalized to ``result_backend_id`` for ``result_ref_ttl`` seconds. Both are
|
|
445
|
+
scoped to the worker-trust tenant and the admitted job id, so :meth:`start`
|
|
446
|
+
fails closed without a worker-trust configuration (mode warn or enforce).
|
|
447
|
+
Without a registry, ``context_ptr`` and ``result_ptr`` work as before.
|
|
448
|
+
``max_artifacts`` (default 8, 0..1000) and ``max_artifact_bytes`` (default
|
|
449
|
+
2 MiB, positive) bound each attempt's artifacts. Only SUCCEEDED carries
|
|
450
|
+
their refs. Bounds and writes fail closed with RESOURCE_EXHAUSTED.
|
|
451
|
+
|
|
452
|
+
``max_deadline`` is a positive finite bound in seconds, or None (unbounded).
|
|
453
|
+
The smaller of it and a positive budget.deadline_ms applies from handler
|
|
454
|
+
start, including middleware/retries. A zero budget uses max_deadline.
|
|
455
|
+
Admitted, dispatch-fenced sys.job.cancel stops the handler without a slot.
|
|
456
|
+
Synchronous handlers block the loop and cannot be pre-empted; their result
|
|
457
|
+
wins. Work in a thread finishes independently after the bounded result.
|
|
458
|
+
Suppressing CancelledError keeps the slot until return; that outcome is
|
|
459
|
+
discarded. close() drains cancel subscriptions. run_worker is unchanged.
|
|
460
|
+
|
|
461
|
+
Admitted requests with DispatchIdentity are fenced by worker and attempt.
|
|
462
|
+
Exact completed redeliveries replay the result, including production duplicates.
|
|
463
|
+
dispatch_fence_max_jobs (1024, 1..1000000) and dispatch_fence_max_age
|
|
464
|
+
(3600 seconds, positive finite) bound this per-process, in-memory store.
|
|
465
|
+
Eviction or restart forgets a job; requests without a dispatch are unchanged.
|
|
342
466
|
"""
|
|
343
467
|
|
|
344
468
|
def __init__(
|
|
@@ -352,6 +476,7 @@ class Agent:
|
|
|
352
476
|
worker_id: Optional[str] = None,
|
|
353
477
|
pool: str = "",
|
|
354
478
|
max_parallel: int = 1,
|
|
479
|
+
max_deadline: Optional[float] = None,
|
|
355
480
|
heartbeat_interval: float = 5.0,
|
|
356
481
|
heartbeat_payload_fn: Optional[Callable[[], bytes]] = None,
|
|
357
482
|
retries: int = 0,
|
|
@@ -368,7 +493,16 @@ class Agent:
|
|
|
368
493
|
worker_trust_renew_min_interval: float = DEFAULT_RENEW_MIN_INTERVAL,
|
|
369
494
|
production_trust: Optional[ProductionTrust] = None,
|
|
370
495
|
replay_store: Optional[ReplayStore] = None,
|
|
496
|
+
telemetry: Optional[TelemetryConfig] = None,
|
|
497
|
+
resource_registry: Optional[ResourceRegistry] = None,
|
|
498
|
+
result_backend_id: Optional[str] = None,
|
|
499
|
+
result_ref_ttl: float = 3600.0,
|
|
500
|
+
max_artifacts: int = 8,
|
|
501
|
+
max_artifact_bytes: int = 2 * 1024 * 1024,
|
|
502
|
+
dispatch_fence_max_jobs: int = 1024,
|
|
503
|
+
dispatch_fence_max_age: float = 3600.0,
|
|
371
504
|
) -> None:
|
|
505
|
+
self._dispatch_fence = DispatchFence(dispatch_fence_max_jobs, dispatch_fence_max_age)
|
|
372
506
|
self._nats_url = nats_url or os.getenv("NATS_URL", "nats://127.0.0.1:4222")
|
|
373
507
|
self._redis_url = redis_url or os.getenv("REDIS_URL", "redis://127.0.0.1:6379/0")
|
|
374
508
|
self._store = store
|
|
@@ -377,6 +511,7 @@ class Agent:
|
|
|
377
511
|
self._sender_id = worker_id or sender_id
|
|
378
512
|
self._pool = pool
|
|
379
513
|
self._max_parallel = _normalize_max_parallel(max_parallel)
|
|
514
|
+
self._max_deadline = validate_max_deadline(max_deadline)
|
|
380
515
|
self._heartbeat_interval = heartbeat_interval if heartbeat_interval > 0 else 5.0
|
|
381
516
|
self._heartbeat_payload_fn = heartbeat_payload_fn
|
|
382
517
|
self._default_retries = max(0, retries)
|
|
@@ -401,6 +536,14 @@ class Agent:
|
|
|
401
536
|
)
|
|
402
537
|
self._production_trust = _snapshot_production_trust(production_trust)
|
|
403
538
|
self._replay_store = replay_store
|
|
539
|
+
# W3C trace context (cap.telemetry); None sends no headers and starts no spans.
|
|
540
|
+
self._telemetry = telemetry
|
|
541
|
+
self._configure_resources(resource_registry, result_backend_id, result_ref_ttl)
|
|
542
|
+
if type(max_artifacts) is not int or not 0 <= max_artifacts <= MAX_REPEATED_FIELD_SIZE:
|
|
543
|
+
raise ValueError("max_artifacts must be an int from 0 to 1000")
|
|
544
|
+
if type(max_artifact_bytes) is not int or max_artifact_bytes <= 0:
|
|
545
|
+
raise ValueError("max_artifact_bytes must be a positive int")
|
|
546
|
+
self._max_artifacts, self._max_artifact_bytes = max_artifacts, max_artifact_bytes
|
|
404
547
|
Agent._initialize_lifecycle(self)
|
|
405
548
|
|
|
406
549
|
def _configure_worker_trust(
|
|
@@ -417,11 +560,37 @@ class Agent:
|
|
|
417
560
|
self._worker_trust_retries = retries
|
|
418
561
|
self._worker_trust_renew_min_interval = renew_min_interval
|
|
419
562
|
|
|
563
|
+
def _configure_resources(
|
|
564
|
+
self,
|
|
565
|
+
registry: Optional[ResourceRegistry],
|
|
566
|
+
backend_id: Optional[str],
|
|
567
|
+
ttl: float,
|
|
568
|
+
) -> None:
|
|
569
|
+
if registry is not None and not isinstance(registry, ResourceRegistry):
|
|
570
|
+
raise ValueError("resource_registry must be a ResourceRegistry")
|
|
571
|
+
if (registry is None) != (backend_id is None):
|
|
572
|
+
raise ValueError(
|
|
573
|
+
"resource_registry and result_backend_id must be configured together"
|
|
574
|
+
)
|
|
575
|
+
if registry is not None and backend_id not in registry.backend_ids:
|
|
576
|
+
raise ValueError("result_backend_id is not an installed backend")
|
|
577
|
+
if (
|
|
578
|
+
isinstance(ttl, bool)
|
|
579
|
+
or not isinstance(ttl, (int, float))
|
|
580
|
+
or not math.isfinite(ttl)
|
|
581
|
+
or ttl <= 0
|
|
582
|
+
):
|
|
583
|
+
raise ValueError("result_ref_ttl must be a positive number of seconds")
|
|
584
|
+
self._resource_registry = registry
|
|
585
|
+
self._result_backend_id = backend_id
|
|
586
|
+
self._result_ref_ttl = float(ttl)
|
|
587
|
+
|
|
420
588
|
def _initialize_lifecycle(self) -> None:
|
|
421
589
|
self._handlers: Dict[str, HandlerSpec] = {}
|
|
422
590
|
self._middlewares: list = []
|
|
423
591
|
self._nc = None
|
|
424
592
|
self._active_jobs: set[str] = set()
|
|
593
|
+
self._cancel_registry = CancelRegistry()
|
|
425
594
|
self._heartbeat_cancel_event: Optional[asyncio.Event] = None
|
|
426
595
|
self._heartbeat_task: Optional[asyncio.Task[Any]] = None
|
|
427
596
|
self._subscriptions: list[Any] = []
|
|
@@ -498,6 +667,7 @@ class Agent:
|
|
|
498
667
|
renew_min_interval=self._worker_trust_renew_min_interval,
|
|
499
668
|
)
|
|
500
669
|
self._validate_production_startup()
|
|
670
|
+
self._validate_resource_startup()
|
|
501
671
|
self._capability = self._build_capability_handshake()
|
|
502
672
|
self._lifecycle_state = "starting"
|
|
503
673
|
try:
|
|
@@ -549,7 +719,7 @@ class Agent:
|
|
|
549
719
|
connect_fn(**connect_options),
|
|
550
720
|
"nats connect",
|
|
551
721
|
)
|
|
552
|
-
if self._store is None:
|
|
722
|
+
if self._store is None and self._resource_registry is None:
|
|
553
723
|
self._store = RedisBlobStore(self._redis_url)
|
|
554
724
|
await self._establish_worker_trust()
|
|
555
725
|
self._require_trust_startup_continuity()
|
|
@@ -632,6 +802,23 @@ class Agent:
|
|
|
632
802
|
|
|
633
803
|
handle = await self._nc.subscribe(subject, cb=on_direct)
|
|
634
804
|
self._remember_subscription(handle)
|
|
805
|
+
handle = await self._nc.subscribe(SUBJECT_CANCEL, cb=self._on_cancel)
|
|
806
|
+
self._remember_subscription(handle)
|
|
807
|
+
|
|
808
|
+
async def _on_cancel(self, msg: object) -> None:
|
|
809
|
+
payload = getattr(msg, "data", b"")
|
|
810
|
+
if not self._cancel_registry.is_running(peek_cancel_job_id(payload)):
|
|
811
|
+
return
|
|
812
|
+
packet = self._decode_admitted_packet(payload, SUBJECT_CANCEL)
|
|
813
|
+
if packet is None or not packet.HasField("job_cancel"):
|
|
814
|
+
return
|
|
815
|
+
cancel = packet.job_cancel
|
|
816
|
+
if (self._production_enabled() and cancel.HasField("identity")
|
|
817
|
+
and cancel.identity != packet.identity):
|
|
818
|
+
return
|
|
819
|
+
if self._cancel_registry.apply(cancel):
|
|
820
|
+
self._logger.info("job cancel accepted", extra={
|
|
821
|
+
"job_id": _bounded_log_field(cancel.job_id)})
|
|
635
822
|
|
|
636
823
|
def _remember_subscription(self, handle: Any) -> None:
|
|
637
824
|
if handle is not None and callable(getattr(handle, "drain", None)):
|
|
@@ -992,6 +1179,12 @@ class Agent:
|
|
|
992
1179
|
audience: Optional[str] = None,
|
|
993
1180
|
bind_session: bool = False,
|
|
994
1181
|
) -> Optional[buspacket_pb2.BusPacket]:
|
|
1182
|
+
packet, duplicate = self._admit_production_packet(payload, audience, bind_session)
|
|
1183
|
+
return None if duplicate else packet
|
|
1184
|
+
|
|
1185
|
+
def _admit_production_packet(
|
|
1186
|
+
self, payload: bytes, audience: Optional[str] = None, bind_session: bool = False,
|
|
1187
|
+
) -> Tuple[Optional[buspacket_pb2.BusPacket], bool]:
|
|
995
1188
|
"""Raw-wire CAP-PRODUCTION admission: verify the exact received
|
|
996
1189
|
bytes (never a re-serialized object), then authoritative identity,
|
|
997
1190
|
then atomic replay admission — all BEFORE any handler runs. Any
|
|
@@ -999,7 +1192,7 @@ class Agent:
|
|
|
999
1192
|
base_trust = self._production_trust
|
|
1000
1193
|
replay_store = self._replay_store
|
|
1001
1194
|
if base_trust is None or replay_store is None:
|
|
1002
|
-
return None
|
|
1195
|
+
return None, False
|
|
1003
1196
|
try:
|
|
1004
1197
|
trust = replace(
|
|
1005
1198
|
base_trust, audience=audience or base_trust.audience
|
|
@@ -1010,21 +1203,20 @@ class Agent:
|
|
|
1010
1203
|
packet = verify_production_packet(payload, trust)
|
|
1011
1204
|
except ProductionSignatureError as exc:
|
|
1012
1205
|
self._logger.warning("production admission rejected packet: %s", exc)
|
|
1013
|
-
return None
|
|
1206
|
+
return None, False
|
|
1014
1207
|
if validate_bus_packet(packet):
|
|
1015
1208
|
self._logger.warning("production admission rejected packet: invalid envelope")
|
|
1016
|
-
return None
|
|
1209
|
+
return None, False
|
|
1017
1210
|
if packet.HasField("job_request") and packet.HasField("identity"):
|
|
1018
1211
|
try:
|
|
1019
1212
|
validate_identity_binding(packet.job_request, packet.identity)
|
|
1020
1213
|
except IdentityMismatchError as exc:
|
|
1021
1214
|
self._logger.warning("production admission rejected packet: %s", exc)
|
|
1022
|
-
return None
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
return packet
|
|
1215
|
+
return None, False
|
|
1216
|
+
outcome = self._admit_production_replay(packet, unsigned, trust, replay_store)
|
|
1217
|
+
if outcome is None:
|
|
1218
|
+
return None, False
|
|
1219
|
+
return packet, outcome == ReplayOutcome.DUPLICATE
|
|
1028
1220
|
|
|
1029
1221
|
def _admit_production_replay(
|
|
1030
1222
|
self,
|
|
@@ -1032,7 +1224,7 @@ class Agent:
|
|
|
1032
1224
|
unsigned: bytes,
|
|
1033
1225
|
trust: ProductionTrust,
|
|
1034
1226
|
replay_store: ReplayStore,
|
|
1035
|
-
) ->
|
|
1227
|
+
) -> Optional[ReplayOutcome]:
|
|
1036
1228
|
metadata = packet.signature_metadata
|
|
1037
1229
|
digest = hashlib.sha256(unsigned).digest()
|
|
1038
1230
|
expiry = metadata.expires_at.ToDatetime(tzinfo=timezone.utc)
|
|
@@ -1050,15 +1242,22 @@ class Agent:
|
|
|
1050
1242
|
"production admission rejected packet: %s",
|
|
1051
1243
|
_replay_error_category(exc),
|
|
1052
1244
|
)
|
|
1053
|
-
return
|
|
1054
|
-
if outcome
|
|
1055
|
-
return False
|
|
1056
|
-
if outcome != ReplayOutcome.FIRST:
|
|
1245
|
+
return None
|
|
1246
|
+
if outcome not in (ReplayOutcome.FIRST, ReplayOutcome.DUPLICATE):
|
|
1057
1247
|
self._logger.warning(
|
|
1058
1248
|
"production admission rejected packet: invalid outcome"
|
|
1059
1249
|
)
|
|
1060
|
-
return
|
|
1061
|
-
return
|
|
1250
|
+
return None
|
|
1251
|
+
return outcome
|
|
1252
|
+
|
|
1253
|
+
def _admit_request_packet(
|
|
1254
|
+
self, payload: bytes, audience: Optional[str],
|
|
1255
|
+
) -> Tuple[Optional[buspacket_pb2.BusPacket], bool]:
|
|
1256
|
+
if self._production_enabled():
|
|
1257
|
+
if not audience or not self._production_session_active():
|
|
1258
|
+
return None, False
|
|
1259
|
+
return self._admit_production_packet(payload, audience, bind_session=True)
|
|
1260
|
+
return self._decode_admitted_packet(payload, audience), False
|
|
1062
1261
|
|
|
1063
1262
|
def _decode_admitted_packet(
|
|
1064
1263
|
self, payload: bytes, audience: Optional[str] = None
|
|
@@ -1105,6 +1304,26 @@ class Agent:
|
|
|
1105
1304
|
raise RuntimeError("CAP-PRODUCTION trust is unavailable")
|
|
1106
1305
|
self._session_bound_production_trust(trust)
|
|
1107
1306
|
|
|
1307
|
+
def _validate_resource_startup(self) -> None:
|
|
1308
|
+
if self._resource_registry is None:
|
|
1309
|
+
return
|
|
1310
|
+
settings = self._trust_settings
|
|
1311
|
+
if settings is None or settings.config is None:
|
|
1312
|
+
raise RuntimeError("resource registry requires worker trust configuration")
|
|
1313
|
+
|
|
1314
|
+
def _trusted_resource_context(
|
|
1315
|
+
self,
|
|
1316
|
+
req: job_pb2.JobRequest,
|
|
1317
|
+
authority: Optional[ProductionEventAuthority],
|
|
1318
|
+
) -> TrustedResourceContext:
|
|
1319
|
+
"""The worker-trust tenant and the admitted job id; nothing comes from the ref."""
|
|
1320
|
+
settings = self._trust_settings
|
|
1321
|
+
config = settings.config if settings is not None else None
|
|
1322
|
+
if config is None:
|
|
1323
|
+
raise RuntimeError("resource registry requires worker trust configuration")
|
|
1324
|
+
job_id = authority.job_id if authority is not None else req.job_id
|
|
1325
|
+
return TrustedResourceContext(tenant_id=config.tenant_id, job_id=job_id)
|
|
1326
|
+
|
|
1108
1327
|
def _session_bound_production_trust(self, trust: ProductionTrust) -> ProductionTrust:
|
|
1109
1328
|
settings = self._trust_settings
|
|
1110
1329
|
config = settings.config if settings is not None else None
|
|
@@ -1130,7 +1349,7 @@ class Agent:
|
|
|
1130
1349
|
|
|
1131
1350
|
async def _on_direct_msg(self, msg: Any) -> None:
|
|
1132
1351
|
"""Route a direct worker message to the correct handler by topic."""
|
|
1133
|
-
packet = self.
|
|
1352
|
+
packet, duplicate = self._admit_request_packet(
|
|
1134
1353
|
msg.data, getattr(msg, "subject", None)
|
|
1135
1354
|
)
|
|
1136
1355
|
if packet is None:
|
|
@@ -1140,16 +1359,19 @@ class Agent:
|
|
|
1140
1359
|
if spec is None:
|
|
1141
1360
|
self._logger.warning("no handler for topic %s on direct subject", topic)
|
|
1142
1361
|
return
|
|
1143
|
-
await self._on_msg(msg, spec, packet)
|
|
1362
|
+
await self._on_msg(msg, spec, packet, duplicate)
|
|
1144
1363
|
|
|
1145
1364
|
async def _on_msg(
|
|
1146
1365
|
self,
|
|
1147
1366
|
msg: Any,
|
|
1148
1367
|
spec: HandlerSpec,
|
|
1149
1368
|
packet: Optional[buspacket_pb2.BusPacket] = None,
|
|
1369
|
+
duplicate: bool = False,
|
|
1150
1370
|
) -> None:
|
|
1371
|
+
# Only _on_direct_msg passes a decoded packet.
|
|
1372
|
+
direct = packet is not None
|
|
1151
1373
|
if packet is None:
|
|
1152
|
-
packet = self.
|
|
1374
|
+
packet, duplicate = self._admit_request_packet(
|
|
1153
1375
|
msg.data, getattr(msg, "subject", None)
|
|
1154
1376
|
)
|
|
1155
1377
|
if packet is None:
|
|
@@ -1161,6 +1383,35 @@ class Agent:
|
|
|
1161
1383
|
authority = (
|
|
1162
1384
|
freeze_production_authority(req) if self._production_enabled() else None
|
|
1163
1385
|
)
|
|
1386
|
+
job_id, dispatch_snapshot = req.job_id, None
|
|
1387
|
+
if req.HasField("dispatch"):
|
|
1388
|
+
dispatch = authority.dispatch if authority is not None else req.dispatch
|
|
1389
|
+
dispatch_snapshot = (dispatch.dispatch_id, dispatch.attempt, dispatch.assigned_worker_id)
|
|
1390
|
+
decision, reason, recorded = self._dispatch_fence.admit(
|
|
1391
|
+
job_id, dispatch_snapshot, hashlib.sha256(req.SerializeToString(deterministic=True)).digest(),
|
|
1392
|
+
self._sender_id, replay_only=duplicate,
|
|
1393
|
+
)
|
|
1394
|
+
if decision == FenceDecision.REPLAY and recorded is not None:
|
|
1395
|
+
await self._replay_result(packet, authority, recorded)
|
|
1396
|
+
return
|
|
1397
|
+
if decision != FenceDecision.RUN and not duplicate:
|
|
1398
|
+
self._logger.warning("dispatch dropped: %s job_id=%s", reason, _bounded_log_field(job_id))
|
|
1399
|
+
return
|
|
1400
|
+
if duplicate:
|
|
1401
|
+
return
|
|
1402
|
+
events = _JobEvents(
|
|
1403
|
+
lambda marker: self._publish_progress(packet, marker, authority),
|
|
1404
|
+
(lambda name, media, content: self._externalize_artifact(req, authority, name, media, content))
|
|
1405
|
+
if self._resource_registry is not None else None,
|
|
1406
|
+
self._max_artifacts, self._max_artifact_bytes,
|
|
1407
|
+
)
|
|
1408
|
+
running = self._cancel_registry.register(
|
|
1409
|
+
req.job_id, authority.dispatch if authority is not None else req.dispatch
|
|
1410
|
+
)
|
|
1411
|
+
# Trace headers are untrusted correlation hints. They are read only
|
|
1412
|
+
# here, after admission or validation, and never used for identity
|
|
1413
|
+
# or policy. Nothing between this call and the try below may raise.
|
|
1414
|
+
otel_context, span = self._start_process_span(msg, spec, packet, direct)
|
|
1164
1415
|
|
|
1165
1416
|
self._active_jobs.add(req.job_id)
|
|
1166
1417
|
try:
|
|
@@ -1178,73 +1429,146 @@ class Agent:
|
|
|
1178
1429
|
"sender_id": _bounded_log_field(packet.sender_id),
|
|
1179
1430
|
},
|
|
1180
1431
|
)
|
|
1181
|
-
ctx = Context(job=req, packet=packet, logger=ctx_logger
|
|
1432
|
+
ctx = Context(job=req, packet=packet, logger=ctx_logger, otel_context=otel_context,
|
|
1433
|
+
_stop_signal=running.stopped, _events=events)
|
|
1434
|
+
ctx._dispatch_claim = (job_id, dispatch_snapshot) if dispatch_snapshot is not None else None
|
|
1182
1435
|
|
|
1436
|
+
registry = self._resource_registry
|
|
1183
1437
|
store = self._store
|
|
1184
|
-
if
|
|
1438
|
+
if registry is not None:
|
|
1439
|
+
trusted = self._trusted_resource_context(req, authority)
|
|
1440
|
+
input_failure, input_data = await self._resolve_input(
|
|
1441
|
+
registry, trusted, spec, req
|
|
1442
|
+
)
|
|
1443
|
+
elif store is None:
|
|
1185
1444
|
ctx_logger.error("blob store not initialized")
|
|
1186
1445
|
return
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
if payload is None:
|
|
1192
|
-
raise ValueError("context not found")
|
|
1193
|
-
if self._max_context_bytes is not None and len(payload) > self._max_context_bytes:
|
|
1194
|
-
raise ValueError("context exceeds max size")
|
|
1195
|
-
except Exception as exc:
|
|
1446
|
+
else:
|
|
1447
|
+
input_failure, input_data = await self._read_input(store, spec, req)
|
|
1448
|
+
if input_failure is not None:
|
|
1449
|
+
span.fail(ErrorType.OTHER)
|
|
1196
1450
|
await self._publish_failure(
|
|
1197
|
-
ctx, req,
|
|
1451
|
+
ctx, req, input_failure, execution_ms=0, authority=authority
|
|
1198
1452
|
)
|
|
1199
1453
|
return
|
|
1200
1454
|
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
await self._publish_failure(
|
|
1205
|
-
ctx,
|
|
1206
|
-
req,
|
|
1207
|
-
f"context decode failed: {exc}",
|
|
1208
|
-
execution_ms=0,
|
|
1209
|
-
authority=authority,
|
|
1210
|
-
)
|
|
1455
|
+
if running.requested.is_set():
|
|
1456
|
+
running.stopped.set()
|
|
1457
|
+
await self._publish_cancelled(ctx, 0, authority)
|
|
1211
1458
|
return
|
|
1212
|
-
|
|
1459
|
+
start_time = time.monotonic()
|
|
1460
|
+
ctx.deadline = handler_deadline(start_time, req.budget.deadline_ms, self._max_deadline)
|
|
1461
|
+
task = asyncio.create_task(self._invoke_handler(ctx, spec, input_data))
|
|
1462
|
+
cancel_task = asyncio.create_task(running.requested.wait())
|
|
1213
1463
|
try:
|
|
1214
|
-
|
|
1215
|
-
|
|
1464
|
+
deadline = ctx.deadline
|
|
1465
|
+
while True:
|
|
1466
|
+
timeout = max(0, deadline - time.monotonic()) if deadline is not None else None
|
|
1467
|
+
await asyncio.wait({task, cancel_task}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
|
|
1468
|
+
# asyncio runs a timer up to one clock-resolution tick early (15.625 ms on
|
|
1469
|
+
# Windows before CPython 3.13); time out only once the deadline has passed.
|
|
1470
|
+
if task.done() or cancel_task.done() or deadline is None or time.monotonic() >= deadline:
|
|
1471
|
+
break
|
|
1472
|
+
# Observe completion before cancel before deadline, even on the same tick.
|
|
1473
|
+
if task.done():
|
|
1474
|
+
failure, output = task.result()
|
|
1475
|
+
else:
|
|
1476
|
+
running.stopped.set()
|
|
1477
|
+
task.cancel()
|
|
1478
|
+
elapsed_ms = int((time.monotonic() - start_time) * 1000)
|
|
1479
|
+
if running.requested.is_set():
|
|
1480
|
+
await self._publish_cancelled(ctx, elapsed_ms, authority)
|
|
1481
|
+
else:
|
|
1482
|
+
span.fail(ErrorType.OTHER)
|
|
1483
|
+
await self._publish_failure(ctx, req, _JOB_TIMEOUT, elapsed_ms, authority)
|
|
1484
|
+
await asyncio.gather(task, return_exceptions=True)
|
|
1485
|
+
return
|
|
1486
|
+
finally:
|
|
1487
|
+
task.cancel()
|
|
1488
|
+
task.add_done_callback(self._consume_detached)
|
|
1489
|
+
cancel_task.cancel()
|
|
1490
|
+
await asyncio.gather(cancel_task, return_exceptions=True)
|
|
1491
|
+
refs = events.refs()
|
|
1492
|
+
if events.failure is not None:
|
|
1493
|
+
failure = events.failure
|
|
1494
|
+
elapsed_ms = int((time.monotonic() - start_time) * 1000)
|
|
1495
|
+
result = job_pb2.JobResult(
|
|
1496
|
+
job_id=req.job_id,
|
|
1497
|
+
status=job_pb2.JOB_STATUS_SUCCEEDED,
|
|
1498
|
+
artifact_refs=refs,
|
|
1499
|
+
worker_id=self._sender_id,
|
|
1500
|
+
execution_ms=elapsed_ms,
|
|
1501
|
+
)
|
|
1502
|
+
# A failure set so far is the handler's; one set below is the result store's.
|
|
1503
|
+
error_type = ErrorType.HANDLER_FAILED if failure is not None else ErrorType.OTHER
|
|
1504
|
+
if failure is None and registry is not None:
|
|
1505
|
+
failure, result_ref = await self._externalize_result(
|
|
1506
|
+
registry, trusted, output
|
|
1507
|
+
)
|
|
1508
|
+
if result_ref is not None:
|
|
1509
|
+
result.result_ref.CopyFrom(result_ref)
|
|
1510
|
+
elif failure is None:
|
|
1511
|
+
failure, result_ptr = await self._write_result(store, req, output)
|
|
1512
|
+
result.result_ptr = result_ptr
|
|
1513
|
+
if failure is not None:
|
|
1514
|
+
span.fail(error_type)
|
|
1216
1515
|
await self._publish_failure(
|
|
1217
|
-
ctx,
|
|
1218
|
-
req,
|
|
1219
|
-
f"input validation failed: {exc}",
|
|
1220
|
-
execution_ms=0,
|
|
1221
|
-
authority=authority,
|
|
1516
|
+
ctx, req, failure, execution_ms=elapsed_ms, authority=authority
|
|
1222
1517
|
)
|
|
1223
1518
|
return
|
|
1224
1519
|
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1520
|
+
await self._publish_result(ctx, result, authority)
|
|
1521
|
+
safe_metrics_call(
|
|
1522
|
+
self._logger,
|
|
1523
|
+
lambda: self._metrics.on_job_completed(
|
|
1524
|
+
req.job_id, elapsed_ms, "SUCCEEDED"
|
|
1525
|
+
),
|
|
1526
|
+
)
|
|
1527
|
+
finally:
|
|
1528
|
+
span.end()
|
|
1529
|
+
events.close()
|
|
1530
|
+
self._cancel_registry.unregister(running)
|
|
1531
|
+
self._active_jobs.discard(job_id)
|
|
1532
|
+
if dispatch_snapshot is not None:
|
|
1533
|
+
self._dispatch_fence.finish(job_id, dispatch_snapshot)
|
|
1534
|
+
|
|
1535
|
+
async def _invoke_handler(
|
|
1536
|
+
self, ctx: Context, spec: HandlerSpec, input_data: object
|
|
1537
|
+
) -> Tuple[Optional[_Outcome], object]:
|
|
1538
|
+
# Build middleware chain: outermost first, terminal calls handler.
|
|
1539
|
+
async def _terminal(c: Context, d: object) -> object:
|
|
1540
|
+
result = spec.func(c, d)
|
|
1541
|
+
if asyncio.iscoroutine(result):
|
|
1542
|
+
result = await result
|
|
1543
|
+
return result
|
|
1544
|
+
|
|
1545
|
+
chain = _terminal
|
|
1546
|
+
for mw in reversed(self._middlewares):
|
|
1547
|
+
_next = chain
|
|
1548
|
+
chain = (lambda m, n: (lambda c, d: m(c, d, n)))(mw, _next)
|
|
1549
|
+
|
|
1550
|
+
packet, req = ctx.packet, ctx.job
|
|
1551
|
+
failure: Optional[_Outcome] = None
|
|
1552
|
+
output: object = None
|
|
1553
|
+
events = ctx._events
|
|
1554
|
+
try:
|
|
1240
1555
|
for attempt in range(spec.retries + 1):
|
|
1556
|
+
if events is not None:
|
|
1557
|
+
events.begin_attempt()
|
|
1241
1558
|
try:
|
|
1242
1559
|
output = await chain(ctx, input_data)
|
|
1243
1560
|
output = self._validate_output(spec, output)
|
|
1244
|
-
|
|
1561
|
+
failure = None
|
|
1562
|
+
break
|
|
1563
|
+
except JobFailure as reported:
|
|
1564
|
+
# The operator chose the outcome: publish it, never retry.
|
|
1565
|
+
failure = _failure_outcome(reported)
|
|
1566
|
+
_log_handler_failure(
|
|
1567
|
+
self._logger, packet, req, reported, attempt + 1, spec.retries + 1
|
|
1568
|
+
)
|
|
1245
1569
|
break
|
|
1246
1570
|
except Exception as exc:
|
|
1247
|
-
|
|
1571
|
+
failure = _HANDLER_FAILED
|
|
1248
1572
|
_log_handler_failure(
|
|
1249
1573
|
self._logger,
|
|
1250
1574
|
packet,
|
|
@@ -1255,47 +1579,180 @@ class Agent:
|
|
|
1255
1579
|
)
|
|
1256
1580
|
if attempt >= spec.retries:
|
|
1257
1581
|
break
|
|
1582
|
+
finally:
|
|
1583
|
+
if events is not None:
|
|
1584
|
+
events.close() # invocation exit: before this coroutine yields completion
|
|
1585
|
+
return failure, output
|
|
1258
1586
|
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1587
|
+
async def _publish_cancelled(
|
|
1588
|
+
self, ctx: Context, elapsed_ms: int, authority: Optional[ProductionEventAuthority]
|
|
1589
|
+
) -> None:
|
|
1590
|
+
result = job_pb2.JobResult(
|
|
1591
|
+
job_id=ctx.job_id, status=_JOB_CANCELLED.status,
|
|
1592
|
+
error_code_enum=_JOB_CANCELLED.error_code_enum, error_code=_JOB_CANCELLED.error_code,
|
|
1593
|
+
error_message=_JOB_CANCELLED.error_message,
|
|
1594
|
+
worker_id=self._sender_id, execution_ms=elapsed_ms,
|
|
1595
|
+
)
|
|
1596
|
+
await self._publish_result(ctx, result, authority)
|
|
1597
|
+
safe_metrics_call(self._logger, lambda: self._metrics.on_job_completed(
|
|
1598
|
+
ctx.job_id, elapsed_ms, "CANCELLED"))
|
|
1265
1599
|
|
|
1600
|
+
async def _read_input(
|
|
1601
|
+
self, store: BlobStore, spec: HandlerSpec, req: job_pb2.JobRequest
|
|
1602
|
+
) -> Tuple[Optional[_Outcome], Any]:
|
|
1603
|
+
"""Fetch, decode and validate the input. Failures map to fixed table rows."""
|
|
1604
|
+
try:
|
|
1605
|
+
key = key_from_pointer(req.context_ptr)
|
|
1606
|
+
except Exception:
|
|
1607
|
+
return _CONTEXT_POINTER_INVALID, None
|
|
1608
|
+
try:
|
|
1609
|
+
payload = await self._with_timeout(store.get(key), "context fetch")
|
|
1610
|
+
size = len(payload) if payload is not None else 0
|
|
1611
|
+
except Exception:
|
|
1612
|
+
return _CONTEXT_FETCH_FAILED, None
|
|
1613
|
+
if payload is None:
|
|
1614
|
+
return _CONTEXT_NOT_FOUND, None
|
|
1615
|
+
if self._max_context_bytes is not None and size > self._max_context_bytes:
|
|
1616
|
+
return _CONTEXT_TOO_LARGE, None
|
|
1617
|
+
return self._decode_input(spec, payload)
|
|
1618
|
+
|
|
1619
|
+
async def _resolve_input(
|
|
1620
|
+
self,
|
|
1621
|
+
registry: ResourceRegistry,
|
|
1622
|
+
trusted: TrustedResourceContext,
|
|
1623
|
+
spec: HandlerSpec,
|
|
1624
|
+
req: job_pb2.JobRequest,
|
|
1625
|
+
) -> Tuple[Optional[_Outcome], Any]:
|
|
1626
|
+
"""Resolve context_ref through the registry; a refused ref is never fetched."""
|
|
1627
|
+
if not req.HasField("context_ref"):
|
|
1628
|
+
return _CONTEXT_REF_REQUIRED, None
|
|
1629
|
+
ref = req.context_ref
|
|
1630
|
+
if req.context_ptr:
|
|
1266
1631
|
try:
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
execution_ms=elapsed_ms,
|
|
1279
|
-
authority=authority,
|
|
1280
|
-
)
|
|
1281
|
-
return
|
|
1282
|
-
|
|
1283
|
-
result = job_pb2.JobResult(
|
|
1284
|
-
job_id=req.job_id,
|
|
1285
|
-
status=job_pb2.JOB_STATUS_SUCCEEDED,
|
|
1286
|
-
result_ptr=result_ptr,
|
|
1287
|
-
worker_id=self._sender_id,
|
|
1288
|
-
execution_ms=elapsed_ms,
|
|
1632
|
+
validate_resource_ref_compatibility(req.context_ptr, ref)
|
|
1633
|
+
except Exception:
|
|
1634
|
+
return _CONTEXT_REF_REFUSED, None
|
|
1635
|
+
if ref.media_type != _JSON_MEDIA_TYPE:
|
|
1636
|
+
return _CONTEXT_DECODE_FAILED, None
|
|
1637
|
+
limit = self._max_context_bytes
|
|
1638
|
+
if limit is not None and ref.size_bytes > limit:
|
|
1639
|
+
return _CONTEXT_TOO_LARGE, None
|
|
1640
|
+
try:
|
|
1641
|
+
resolved = await self._with_timeout(
|
|
1642
|
+
registry.resolve(ref, trusted), "context resolve"
|
|
1289
1643
|
)
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1644
|
+
except ResourceTooLargeError:
|
|
1645
|
+
return _CONTEXT_TOO_LARGE, None
|
|
1646
|
+
except ResourceBackendUnavailableError:
|
|
1647
|
+
return _CONTEXT_FETCH_FAILED, None
|
|
1648
|
+
except ResourceRegistryError:
|
|
1649
|
+
return _CONTEXT_REF_REFUSED, None
|
|
1650
|
+
except Exception:
|
|
1651
|
+
return _CONTEXT_FETCH_FAILED, None
|
|
1652
|
+
if limit is not None and len(resolved.content) > limit:
|
|
1653
|
+
return _CONTEXT_TOO_LARGE, None
|
|
1654
|
+
return self._decode_input(spec, resolved.content)
|
|
1655
|
+
|
|
1656
|
+
def _decode_input(self, spec: HandlerSpec, payload: bytes) -> Tuple[Optional[_Outcome], Any]:
|
|
1657
|
+
try:
|
|
1658
|
+
raw = json.loads(payload.decode("utf-8"))
|
|
1659
|
+
except Exception:
|
|
1660
|
+
return _CONTEXT_DECODE_FAILED, None
|
|
1661
|
+
try:
|
|
1662
|
+
return None, self._validate_input(spec, raw)
|
|
1663
|
+
except Exception:
|
|
1664
|
+
return _INPUT_INVALID, None
|
|
1665
|
+
|
|
1666
|
+
def _encode_result(self, output: Any) -> Tuple[Optional[_Outcome], bytes]:
|
|
1667
|
+
try:
|
|
1668
|
+
result_payload = self._serialize_output(output)
|
|
1669
|
+
except Exception:
|
|
1670
|
+
return _RESULT_ENCODE_FAILED, b""
|
|
1671
|
+
if self._max_result_bytes is not None and len(result_payload) > self._max_result_bytes:
|
|
1672
|
+
return _RESULT_TOO_LARGE, b""
|
|
1673
|
+
return None, result_payload
|
|
1674
|
+
|
|
1675
|
+
async def _externalize_artifact(
|
|
1676
|
+
self, req: job_pb2.JobRequest, authority: Optional[ProductionEventAuthority],
|
|
1677
|
+
name: str, media_type: str, content: bytes,
|
|
1678
|
+
) -> object:
|
|
1679
|
+
registry = self._resource_registry
|
|
1680
|
+
if registry is None:
|
|
1681
|
+
raise RuntimeError("artifact registry is unavailable")
|
|
1682
|
+
return await self._with_timeout(
|
|
1683
|
+
registry.externalize(
|
|
1684
|
+
self._result_backend_id, content, media_type=media_type,
|
|
1685
|
+
purpose=ARTIFACT_PURPOSE_PREFIX + name,
|
|
1686
|
+
expires_at=datetime.now(timezone.utc) + timedelta(seconds=self._result_ref_ttl),
|
|
1687
|
+
trusted=self._trusted_resource_context(req, authority),
|
|
1688
|
+
), "artifact externalize",
|
|
1689
|
+
)
|
|
1690
|
+
|
|
1691
|
+
async def _externalize_result(
|
|
1692
|
+
self, registry: ResourceRegistry, trusted: TrustedResourceContext, output: Any
|
|
1693
|
+
) -> Tuple[Optional[_Outcome], Optional[job_pb2.ResourceRef]]:
|
|
1694
|
+
"""Encode the output and externalize it; returns its ref or a fixed table row."""
|
|
1695
|
+
failure, result_payload = self._encode_result(output)
|
|
1696
|
+
if failure is not None:
|
|
1697
|
+
return failure, None
|
|
1698
|
+
try:
|
|
1699
|
+
expires_at = datetime.now(timezone.utc) + timedelta(seconds=self._result_ref_ttl)
|
|
1700
|
+
ref = await self._with_timeout(
|
|
1701
|
+
registry.externalize(
|
|
1702
|
+
self._result_backend_id,
|
|
1703
|
+
result_payload,
|
|
1704
|
+
media_type=_JSON_MEDIA_TYPE,
|
|
1705
|
+
purpose=_RESULT_PURPOSE,
|
|
1706
|
+
expires_at=expires_at,
|
|
1707
|
+
trusted=trusted,
|
|
1295
1708
|
),
|
|
1709
|
+
"result externalize",
|
|
1296
1710
|
)
|
|
1297
|
-
|
|
1298
|
-
|
|
1711
|
+
except ResourceTooLargeError:
|
|
1712
|
+
return _RESULT_TOO_LARGE, None
|
|
1713
|
+
except Exception:
|
|
1714
|
+
return _RESULT_WRITE_FAILED, None
|
|
1715
|
+
return None, ref
|
|
1716
|
+
|
|
1717
|
+
async def _write_result(
|
|
1718
|
+
self, store: BlobStore, req: job_pb2.JobRequest, output: Any
|
|
1719
|
+
) -> Tuple[Optional[_Outcome], str]:
|
|
1720
|
+
"""Encode and store the output; returns its pointer or a fixed table row."""
|
|
1721
|
+
failure, result_payload = self._encode_result(output)
|
|
1722
|
+
if failure is not None:
|
|
1723
|
+
return failure, ""
|
|
1724
|
+
result_key = f"res:{req.job_id}"
|
|
1725
|
+
try:
|
|
1726
|
+
await self._with_timeout(store.set(result_key, result_payload), "result write")
|
|
1727
|
+
except Exception:
|
|
1728
|
+
return _RESULT_WRITE_FAILED, ""
|
|
1729
|
+
return None, pointer_for_key(result_key)
|
|
1730
|
+
|
|
1731
|
+
def _start_process_span(
|
|
1732
|
+
self,
|
|
1733
|
+
msg: Any,
|
|
1734
|
+
spec: HandlerSpec,
|
|
1735
|
+
packet: buspacket_pb2.BusPacket,
|
|
1736
|
+
direct: bool,
|
|
1737
|
+
) -> Tuple[Optional[Any], MessagingSpan]:
|
|
1738
|
+
telemetry = self._telemetry
|
|
1739
|
+
if telemetry is None:
|
|
1740
|
+
return None, MessagingSpan()
|
|
1741
|
+
production = self._production_enabled()
|
|
1742
|
+
process = Process(
|
|
1743
|
+
subject=getattr(msg, "subject", "") or "",
|
|
1744
|
+
pool=spec.topic,
|
|
1745
|
+
# The direct worker.<id>.jobs subject is a plain subscription.
|
|
1746
|
+
queue_group="" if direct else spec.topic,
|
|
1747
|
+
production_verified=production,
|
|
1748
|
+
message_id=bytes(packet.signature_metadata.message_id) if production else b"",
|
|
1749
|
+
conversation_id=packet.trace_id if production else "",
|
|
1750
|
+
creation=extract(telemetry, getattr(msg, "headers", None)),
|
|
1751
|
+
)
|
|
1752
|
+
# An explicit empty parent: nats-py callbacks inherit the context that
|
|
1753
|
+
# was current at connect time, and a span there must never become the
|
|
1754
|
+
# job's parent. The sender's context is the parent and is linked.
|
|
1755
|
+
return start_process(telemetry, process, _empty_otel_context())
|
|
1299
1756
|
|
|
1300
1757
|
def _validate_input(self, spec: HandlerSpec, data: Any) -> Any:
|
|
1301
1758
|
if spec.input_model is None:
|
|
@@ -1324,21 +1781,23 @@ class Agent:
|
|
|
1324
1781
|
self,
|
|
1325
1782
|
ctx: Context,
|
|
1326
1783
|
req: job_pb2.JobRequest,
|
|
1327
|
-
|
|
1784
|
+
outcome: _Outcome,
|
|
1328
1785
|
execution_ms: int,
|
|
1329
1786
|
authority: Optional[ProductionEventAuthority] = None,
|
|
1330
1787
|
) -> None:
|
|
1331
1788
|
result = job_pb2.JobResult(
|
|
1332
1789
|
job_id=req.job_id,
|
|
1333
|
-
status=
|
|
1334
|
-
|
|
1790
|
+
status=outcome.status,
|
|
1791
|
+
error_code=outcome.error_code,
|
|
1792
|
+
error_code_enum=outcome.error_code_enum,
|
|
1793
|
+
error_message=outcome.error_message,
|
|
1335
1794
|
worker_id=self._sender_id,
|
|
1336
1795
|
execution_ms=execution_ms,
|
|
1337
1796
|
)
|
|
1338
1797
|
await self._publish_result(ctx, result, authority)
|
|
1339
1798
|
safe_metrics_call(
|
|
1340
1799
|
self._logger,
|
|
1341
|
-
lambda: self._metrics.on_job_failed(req.job_id,
|
|
1800
|
+
lambda: self._metrics.on_job_failed(req.job_id, outcome.error_message),
|
|
1342
1801
|
)
|
|
1343
1802
|
|
|
1344
1803
|
async def _publish_result(
|
|
@@ -1347,6 +1806,8 @@ class Agent:
|
|
|
1347
1806
|
result: job_pb2.JobResult,
|
|
1348
1807
|
authority: Optional[ProductionEventAuthority] = None,
|
|
1349
1808
|
) -> None:
|
|
1809
|
+
if ctx._events is not None:
|
|
1810
|
+
ctx._events.close()
|
|
1350
1811
|
if self._nc is None:
|
|
1351
1812
|
ctx.logger.error("NATS not initialized")
|
|
1352
1813
|
return
|
|
@@ -1359,14 +1820,98 @@ class Agent:
|
|
|
1359
1820
|
bound_result.CopyFrom(result)
|
|
1360
1821
|
if authority is not None:
|
|
1361
1822
|
bind_production_event(bound_result, authority)
|
|
1823
|
+
packet = self._event_envelope(ctx.packet)
|
|
1824
|
+
packet.job_result.CopyFrom(bound_result)
|
|
1825
|
+
raw = self._event_wire(packet, authority, SUBJECT_RESULT)
|
|
1826
|
+
request = authority if authority is not None else ctx.job
|
|
1827
|
+
dispatch = request.dispatch
|
|
1828
|
+
claim = (request.job_id, (dispatch.dispatch_id, dispatch.attempt, dispatch.assigned_worker_id))
|
|
1829
|
+
if ctx._dispatch_claim == claim:
|
|
1830
|
+
self._dispatch_fence.record(
|
|
1831
|
+
claim[0], claim[1], packet.trace_id, bound_result.SerializeToString(deterministic=True)
|
|
1832
|
+
)
|
|
1833
|
+
telemetry = self._telemetry
|
|
1834
|
+
if telemetry is None:
|
|
1835
|
+
await self._with_timeout(
|
|
1836
|
+
self._nc.publish(SUBJECT_RESULT, raw),
|
|
1837
|
+
"result publish",
|
|
1838
|
+
)
|
|
1839
|
+
return
|
|
1840
|
+
# A legacy trace_id is unauthenticated (spec/10), so it is not recorded.
|
|
1841
|
+
conversation_id = ctx.packet.trace_id if self._production_enabled() else ""
|
|
1842
|
+
span_context, span = start_publish(
|
|
1843
|
+
telemetry,
|
|
1844
|
+
Publish(subject=SUBJECT_RESULT, conversation_id=conversation_id),
|
|
1845
|
+
ctx.otel_context if ctx.otel_context is not None else _empty_otel_context(),
|
|
1846
|
+
)
|
|
1847
|
+
headers = inject_headers(telemetry, None, span_context)
|
|
1848
|
+
try:
|
|
1849
|
+
await self._with_timeout(
|
|
1850
|
+
self._nc.publish(SUBJECT_RESULT, raw, headers=headers),
|
|
1851
|
+
"result publish",
|
|
1852
|
+
)
|
|
1853
|
+
except Exception:
|
|
1854
|
+
span.fail(ErrorType.TRANSPORT_PUBLISH_FAILED)
|
|
1855
|
+
raise
|
|
1856
|
+
finally:
|
|
1857
|
+
span.end()
|
|
1858
|
+
|
|
1859
|
+
async def _replay_result(
|
|
1860
|
+
self, request: buspacket_pb2.BusPacket, authority: Optional[ProductionEventAuthority],
|
|
1861
|
+
recorded: RecordedResult,
|
|
1862
|
+
) -> None:
|
|
1863
|
+
if self._nc is None:
|
|
1864
|
+
self._logger.warning("dispatch replay dropped: NATS not initialized")
|
|
1865
|
+
return
|
|
1866
|
+
trace_id, raw_result = recorded
|
|
1867
|
+
result = job_pb2.JobResult.FromString(raw_result)
|
|
1868
|
+
if authority is not None:
|
|
1869
|
+
try:
|
|
1870
|
+
bind_production_event(result, authority)
|
|
1871
|
+
except ProductionEventConflictError:
|
|
1872
|
+
self._logger.warning("dispatch replay dropped: conflicting authority job_id=%s",
|
|
1873
|
+
_bounded_log_field(request.job_request.job_id))
|
|
1874
|
+
return
|
|
1875
|
+
packet = self._event_envelope(request)
|
|
1876
|
+
packet.trace_id = trace_id
|
|
1877
|
+
packet.job_result.CopyFrom(result)
|
|
1878
|
+
raw = self._event_wire(packet, authority, SUBJECT_RESULT)
|
|
1879
|
+
self._logger.info("dispatch replay: job_id=%s", _bounded_log_field(result.job_id))
|
|
1880
|
+
await self._with_timeout(self._nc.publish(SUBJECT_RESULT, raw), "result publish")
|
|
1881
|
+
|
|
1882
|
+
async def _publish_progress(
|
|
1883
|
+
self, request: buspacket_pb2.BusPacket, marker: str,
|
|
1884
|
+
authority: Optional[ProductionEventAuthority],
|
|
1885
|
+
) -> None:
|
|
1886
|
+
if self._nc is None:
|
|
1887
|
+
raise RuntimeError("NATS not initialized")
|
|
1888
|
+
if self._production_enabled() and authority is None:
|
|
1889
|
+
raise ProductionEventConflictError("production progress requires admitted request authority")
|
|
1890
|
+
progress = job_pb2.JobProgress(
|
|
1891
|
+
job_id=authority.job_id if authority is not None else request.job_request.job_id,
|
|
1892
|
+
status=job_pb2.JOB_STATUS_RUNNING, message=marker,
|
|
1893
|
+
)
|
|
1894
|
+
if authority is not None:
|
|
1895
|
+
bind_production_event(progress, authority)
|
|
1896
|
+
packet = self._event_envelope(request)
|
|
1897
|
+
packet.job_progress.CopyFrom(progress)
|
|
1898
|
+
raw = self._event_wire(packet, authority, SUBJECT_PROGRESS)
|
|
1899
|
+
await self._with_timeout(self._nc.publish(SUBJECT_PROGRESS, raw), "progress publish")
|
|
1900
|
+
|
|
1901
|
+
def _event_envelope(self, request: buspacket_pb2.BusPacket) -> buspacket_pb2.BusPacket:
|
|
1362
1902
|
packet = buspacket_pb2.BusPacket()
|
|
1363
|
-
packet.trace_id =
|
|
1903
|
+
packet.trace_id = request.trace_id
|
|
1364
1904
|
packet.sender_id = self._sender_id
|
|
1365
1905
|
packet.protocol_version = DEFAULT_PROTOCOL_VERSION
|
|
1366
1906
|
ts = timestamp_pb2.Timestamp()
|
|
1367
1907
|
ts.GetCurrentTime()
|
|
1368
1908
|
packet.created_at.CopyFrom(ts)
|
|
1369
|
-
packet
|
|
1909
|
+
return packet
|
|
1910
|
+
|
|
1911
|
+
def _event_wire(
|
|
1912
|
+
self, packet: buspacket_pb2.BusPacket,
|
|
1913
|
+
authority: Optional[ProductionEventAuthority], subject: str,
|
|
1914
|
+
) -> bytes:
|
|
1370
1915
|
if authority is not None:
|
|
1371
1916
|
packet.identity.CopyFrom(authority.identity)
|
|
1372
1917
|
packet.auth_token = self._outbound_session_token()
|
|
@@ -1380,7 +1925,7 @@ class Agent:
|
|
|
1380
1925
|
packet,
|
|
1381
1926
|
key=config.proof_private_key,
|
|
1382
1927
|
key_id=config.proof_key_id,
|
|
1383
|
-
audience=
|
|
1928
|
+
audience=subject,
|
|
1384
1929
|
)
|
|
1385
1930
|
else:
|
|
1386
1931
|
outgoing = finalize_packet(
|
|
@@ -1390,10 +1935,7 @@ class Agent:
|
|
|
1390
1935
|
)
|
|
1391
1936
|
raw = outgoing.SerializeToString(deterministic=True)
|
|
1392
1937
|
|
|
1393
|
-
|
|
1394
|
-
self._nc.publish(SUBJECT_RESULT, raw),
|
|
1395
|
-
"result publish",
|
|
1396
|
-
)
|
|
1938
|
+
return raw
|
|
1397
1939
|
|
|
1398
1940
|
async def _with_timeout(self, coro: Awaitable[TAny], label: str) -> TAny:
|
|
1399
1941
|
if self._io_timeout is None:
|