-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver.py
More file actions
2648 lines (2480 loc) · 128 KB
/
Copy pathobserver.py
File metadata and controls
2648 lines (2480 loc) · 128 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Spec mapping (observability):
# - Observer-driven span lifecycle realizes §6 (RECOMMENDED path).
# - Span status comes from §4.2 error-category mapping.
# - Internal span maps are keyed by ``invocation_id``, which is also
# surfaced as the ``openarmature.invocation_id`` span attribute per
# §5.1.
# - Subgraph dispatch span names come from §4.5 (parent graph's
# SubgraphNode name); hierarchy from §4.1/§4.3; detached trace mode
# from §4.4.
# - ``correlation_id`` cross-run join key surfaces as the
# ``openarmature.correlation_id`` span attribute (§3.1).
# - Private TracerProvider per §6 isolation requirement (prevents
# global-provider auto-instrumentation libraries from emitting
# duplicate spans alongside ours).
"""OTelObserver: observer-driven span lifecycle.
The observer subscribes to all three node-event phases (``started``,
``completed``, ``checkpoint_saved``) plus the LLM-provider events the
``OpenAIProvider`` enqueues from inside node bodies. On a ``started``
event it opens a leaf span and pushes it onto an in-flight map keyed
by ``(namespace, attempt_index, fan_out_index)``; on the matching
``completed`` event it pops the span, applies the status mapping, and
closes it.
**Per-invocation state isolation.** All internal span maps are
outer-keyed by ``invocation_id`` (each invocation has a fresh
framework-minted UUIDv4). A single observer can be safely shared
across concurrent invocations (e.g., an ASGI service running
``asyncio.gather([invoke(), invoke()])`` on one observer); each
invocation's spans live in their own sub-dict, lazy-allocated on
first event. The ``correlation_id`` is the cross-run join key set as
the ``openarmature.correlation_id`` attribute on every span; it is
*not* the state-scoping key, because resume runs preserve the
correlation_id and would (incorrectly) cause the resumed run's spans
to inherit the prior invocation's trace.
**No cross-event OTel context tokens.** Parent spans are resolved
from the observer's own internal maps within a single event
handler's scope; never from ``opentelemetry.context.get_current()``.
Spans are opened with ``context=set_span_in_context(parent_span)``
directly rather than ``attach()``-ing tokens that would have to be
``detach()``-ed on the matching completed event. This eliminates
LIFO-violation hazards under interleaved fan-out events and makes
the observer robust to dispatch ordering.
Subtree isolation lives in dedicated dicts rather than the leaf-span
key:
- ``subgraph_spans``: synthetic subgraph dispatch spans (the engine
wrapper is transparent but the observer mints a span anyway).
Keyed by namespace prefix. Open lazily on the first deeper-
namespace event, close when subsequent events leave the prefix.
- ``detached_roots``: root spans for detached subgraphs and per-
instance detached fan-out roots. Each lives in its own fresh
``trace_id``; the parent's dispatch span carries an OTel
:class:`Link` to the detached trace.
- ``_invocation_span``: root invocation span keyed by
``invocation_id``. Closed via :meth:`close_invocation` /
:meth:`shutdown`.
Spans are emitted through a **private** :class:`TracerProvider`
constructed by this observer; never the OTel global. Registering
globally would cause every auto-instrumentation library that writes
to the global provider (OpenInference,
opentelemetry-instrumentation-openai, LiteLLM, etc.) to emit
duplicate spans alongside ours.
Detached trace mode is implemented by minting a fresh
:class:`SpanContext` with a new ``trace_id`` when entering a
configured-detached subgraph or fan-out; the parent's dispatch span
carries an OTel :class:`Link` to the detached trace.
"""
from __future__ import annotations
import json
import time
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, cast
from opentelemetry import context as otel_context
from opentelemetry import metrics as otel_metrics
from opentelemetry import trace as otel_trace
from opentelemetry.metrics import Histogram, Meter, MeterProvider
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
from opentelemetry.sdk.trace.id_generator import RandomIdGenerator
from opentelemetry.trace import (
Link,
NonRecordingSpan,
Span,
SpanContext,
SpanKind,
Status,
StatusCode,
TraceFlags,
)
from opentelemetry.trace.propagation import set_span_in_context
from openarmature.graph.events import (
FailureIsolatedEvent,
InvocationCompletedEvent,
InvocationStartedEvent,
LlmCompletionEvent,
LlmFailedEvent,
LlmRetryAttemptEvent,
MetadataAugmentationEvent,
NodeEvent,
ToolCallEvent,
ToolCallFailedEvent,
)
from openarmature.observability.lineage import is_strict_prefix
from openarmature.observability.llm_event import serialize_tool_calls
# Span-stack key shape:
# ``(namespace, attempt_index, fan_out_index, branch_name)`` — these
# four fields jointly identify any node attempt within an invocation.
# ``branch_name`` discriminates concurrent same-named inner nodes
# across sibling parallel-branches branches (pipeline-utilities §11);
# without it the two inner ``ask`` nodes of two branches with the
# same namespace + fan_out_index would collide on the same key.
_StackKey = tuple[tuple[str, ...], int, int | None, str | None]
# §5.5.5 truncation marker. The leading character is U+2026 HORIZONTAL
# ELLIPSIS (3 bytes UTF-8); the marker is a fixed UTF-8 string and is
# appended as a whole unit so no boundary backtracking is needed past
# the prefix cut.
_TRUNCATION_MARKER_TEMPLATE = "…[truncated, {m} bytes total]"
# §5.5.5 minimum-cap rule: any payload byte cap configuration below
# 256 bytes is rejected at observer construction time. Rationale (spec
# verbatim): "256 bytes leaves room for the worst-case marker (~36
# bytes) plus a diagnostically useful payload preview; caps below this
# would produce attributes that are almost entirely marker with little
# or no preview value."
_PAYLOAD_MIN_BYTES = 256
# §5.5 default truncation cap — 64 KiB per the spec's preferred
# default. Implementations MAY configure; ours sits on a constructor
# field.
_PAYLOAD_DEFAULT_BYTES = 65536
# §11.2 (proposal 0067) explicit bucket-boundary advisories for the two
# GenAI metric histograms, mirroring the upstream gen_ai.client.* bucket
# advisories so a future stable cutover is a mechanical prefix-strip.
# Token usage in {token}; operation duration in seconds.
_TOKEN_USAGE_BUCKETS: list[float] = [
1,
4,
16,
64,
256,
1024,
4096,
16384,
65536,
262144,
1048576,
4194304,
16777216,
67108864,
]
_DURATION_BUCKETS: list[float] = [
0.01,
0.02,
0.04,
0.08,
0.16,
0.32,
0.64,
1.28,
2.56,
5.12,
10.24,
20.48,
40.96,
81.92,
]
def _read_spec_version() -> str:
"""Read the spec version pinned at package level. Lazy import
avoids a circular at module-load time (the package's ``__init__``
imports submodules that may import the observability stack)."""
from openarmature import __spec_version__
return __spec_version__
# Proposal 0052: implementation attribution attributes sourced from
# the package's identity constants. Same lazy-import discipline as
# ``_read_spec_version`` to avoid a load-time cycle.
def _read_implementation_name() -> str:
from openarmature import __implementation_name__
return __implementation_name__
def _read_implementation_version() -> str:
from openarmature import __version__
return __version__
def _apply_caller_metadata(attrs: dict[str, Any], metadata: Mapping[str, Any]) -> None:
"""Merge caller-supplied invocation metadata into a span's
attribute dict as ``openarmature.user.<key>`` entries.
Called at every span-emission site so the metadata family is
cross-cutting (invocation span, every node span, subgraph
dispatch, fan-out instance dispatch, LLM provider span,
detached roots). Source values may come from
``NodeEvent.caller_invocation_metadata`` for graph events or
from the typed LLM events' (LlmCompletionEvent / LlmFailedEvent)
caller_invocation_metadata field for LLM events; both are
dispatch-time snapshots.
"""
for key, value in metadata.items():
attrs[f"openarmature.user.{key}"] = value
def _subgraph_identity_at(event: NodeEvent, depth: int) -> str:
"""Return the compiled-subgraph identity for the wrapper at the
given 1-based namespace depth, or the empty string when no
identity is tracked at that depth.
The empty-string fallback is the "no identity tracked" case, for
callers using ``SubgraphNode(name=..., compiled=...)`` without
supplying ``subgraph_identity``.
"""
# Spec observability §5.3 (coord thread
# clarify-subgraph-name-semantics).
idx = depth - 1
if 0 <= idx < len(event.subgraph_identities):
identity = event.subgraph_identities[idx]
if identity is not None:
return identity
return ""
def _empty_str_frozenset() -> frozenset[str]:
"""Typed empty frozenset factory for ``detached_subgraphs`` /
``detached_fan_outs`` defaults."""
return frozenset()
@dataclass
class _OpenSpan:
"""An in-flight span. No OTel context token: the new architecture
resolves parents from the observer's internal maps within a
single event handler's scope, so no token needs to live across
events.
Carries the span's own ``fan_out_index_chain`` and
``branch_name_chain`` so the augmentation walk can apply the
lineage-aware boundary rule without re-deriving the chain from
successive events."""
span: Span
fan_out_index_chain: tuple[int | None, ...] = ()
branch_name_chain: tuple[str | None, ...] = ()
def _span_chain_on_path(
open_span: _OpenSpan,
aug_fi_chain: tuple[int | None, ...],
aug_bn_chain: tuple[str | None, ...],
) -> bool:
"""Return True iff ``open_span``'s chain is a prefix-match of the
augmenter's chain — i.e., the span sits on the augmenter's
call-stack ancestor path:
- A span shorter than the augmenter (chain prefix-matches) is an
ancestor on the path.
- A span at the same depth (chain exact-matches) is the augmenter
itself (or a descendant sharing the mutated mapping).
- A span deeper than the augmenter, OR with a position-mismatch
anywhere, is a sibling and MUST NOT be updated.
"""
# Spec observability §3.4 (proposal 0045): lineage-aware boundary.
span_fi = open_span.fan_out_index_chain
span_bn = open_span.branch_name_chain
if len(span_fi) > len(aug_fi_chain):
return False
if len(span_bn) > len(aug_bn_chain):
return False
for i in range(len(span_fi)):
if span_fi[i] != aug_fi_chain[i]:
return False
for i in range(len(span_bn)):
if span_bn[i] != aug_bn_chain[i]:
return False
return True
# Sorted object keys, no insignificant whitespace, UTF-8 output (per
# observability §5.5.1 / §5.5.6). Within-impl determinism for identical
# inputs is required; cross-impl bytewise stability is NOT required by
# v0.17.0 — conformance fixtures use parse-shape assertions, not
# bytewise equality.
def _serialize_for_attribute(value: Any) -> str:
"""JSON-encode ``value`` for emission as an OTel string attribute.
``default=str`` is a safety net so a value JSON can't natively encode
renders via its ``str()`` rather than raising inside the observer
(which would lose the whole span). It is a no-op for the
already-encodable payloads (messages, params); it matters for the
proposal 0063 tool ``result``, which is an opaque, language-idiomatic
value the tool produced (a model, dataclass, datetime, ...)."""
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
# §5.5.5 truncation algorithm:
# 1. Compute M, the pre-truncation byte length.
# 2. Format the marker with M substituted; compute L_marker.
# 3. Compute target prefix size N = cap_bytes - L_marker.
# 4. Backtrack to a UTF-8 code-point boundary ≤ N (avoid splitting
# multi-byte sequences — CJK, emoji, combining marks).
# 5. Emit first N' bytes + marker.
# The resulting string is at most cap_bytes UTF-8 bytes (may be strictly
# less due to step-4 backtracking). The marker leading char is U+2026
# HORIZONTAL ELLIPSIS (3 bytes UTF-8); appended as a whole unit so no
# further boundary concerns beyond step 4.
def _truncate_for_attribute(serialized: str, cap_bytes: int) -> str:
"""Truncate ``serialized`` to fit within ``cap_bytes`` UTF-8 bytes,
returning the original string unchanged if it already fits."""
encoded = serialized.encode("utf-8")
full_length = len(encoded)
if full_length <= cap_bytes:
return serialized
marker = _TRUNCATION_MARKER_TEMPLATE.format(m=full_length)
marker_bytes = marker.encode("utf-8")
target = cap_bytes - len(marker_bytes)
if target <= 0:
# Cap is smaller than the marker itself — the __post_init__
# validation guards against this (256-byte minimum allows a
# ~36-byte marker plus preview), but be defensive.
return marker
# UTF-8 lead-byte detection: a byte is a continuation byte when its
# top two bits are 10. Backtrack from ``target`` until we land on a
# lead byte (or hit 0). This is the cheapest correct way to find
# the largest code-point boundary ≤ target without round-tripping
# through ``str``.
boundary = target
while boundary > 0 and (encoded[boundary] & 0b1100_0000) == 0b1000_0000:
boundary -= 1
return encoded[:boundary].decode("utf-8", errors="strict") + marker
@dataclass
class _InvState:
"""Per-invocation span state. One instance per concurrent
invocation — the outer ``OTelObserver`` keys these by
``invocation_id`` so concurrent invocations (and resumed runs of
the same correlation_id) don't collide."""
open_spans: dict[_StackKey, _OpenSpan] = field(default_factory=dict[_StackKey, _OpenSpan])
subgraph_spans: dict[tuple[str, ...], _OpenSpan] = field(default_factory=dict[tuple[str, ...], _OpenSpan])
detached_roots: dict[tuple[str, ...], _OpenSpan] = field(default_factory=dict[tuple[str, ...], _OpenSpan])
# Proposal 0061 (observability §4.4): a detached trace roots in its
# own ``openarmature.invocation`` span carrying the parent's
# invocation_id; the detached subgraph / fan-out-instance span in
# ``detached_roots`` nests under it. Keyed identically to
# ``detached_roots`` (the prefix for a detached subgraph, ``prefix +
# (str(fan_out_index),)`` for a detached fan-out instance) so the
# two close together as a coterminous parent/child pair.
detached_invocation_spans: dict[tuple[str, ...], _OpenSpan] = field(
default_factory=dict[tuple[str, ...], _OpenSpan]
)
# Proposal 0061 §4.2: keys (matching ``detached_roots`` /
# ``detached_invocation_spans``, and the detached prefix in
# ``subgraph_spans``) whose spans the detached-error propagation
# marked ERROR. The synthetic close paths consult this to SKIP their
# default ``set_status(OK)``: the OTel SDK treats OK as final and
# lets it OVERRIDE a prior ERROR (only a set to UNSET is ignored), so
# an unconditional OK at close would erase the detached-trace ERROR.
errored_detached_keys: set[tuple[str, ...]] = field(default_factory=set[tuple[str, ...]])
fan_out_instance_root_prefixes: set[tuple[str, ...]] = field(default_factory=set[tuple[str, ...]])
# Per spec §5.4 + proposal 0013 (v0.10.0): non-detached fan-outs
# synthesize per-instance dispatch spans nested between the fan-out
# node span and the inner-node spans. Keyed by ``prefix +
# (str(fan_out_index),)`` mirroring the detached path's keying in
# ``detached_roots``. Lives in the parent trace (not a fresh
# trace_id, unlike detached). Closed when the fan-out node's
# ``completed`` event fires.
fan_out_instance_spans: dict[tuple[str, ...], _OpenSpan] = field(
default_factory=dict[tuple[str, ...], _OpenSpan]
)
# ``parent_node_name`` cache (per spec proposal 0013 correction #4):
# the fan-out node's name surfaces on its own ``started`` event via
# ``NodeEvent.fan_out_config.parent_node_name``. The observer caches
# it keyed by the fan-out node's namespace prefix so when
# ``_open_fan_out_instance_dispatch_span`` synthesizes a per-instance
# dispatch span, it can attach
# ``openarmature.fan_out.parent_node_name`` even though the inner
# event itself doesn't carry ``fan_out_config``.
fan_out_parent_node_name: dict[tuple[str, ...], str] = field(default_factory=dict[tuple[str, ...], str])
# Per proposal 0044 (observability §5.7, v0.36.0): synthesize
# per-branch dispatch spans nested between the parallel-branches
# node span and the inner-branch spans (mirroring fan-out's
# per-instance synthesis above). Keyed by
# ``prefix + (branch_name,)``. Closed when the parallel-branches
# node's ``completed`` event fires.
parallel_branches_branch_spans: dict[tuple[str, ...], _OpenSpan] = field(
default_factory=dict[tuple[str, ...], _OpenSpan]
)
# ``parent_node_name`` cache for parallel-branches (mirrors the
# ``fan_out_parent_node_name`` cache above). Surfaces from the
# parallel-branches NODE's ``started`` event via
# ``NodeEvent.parallel_branches_config.parent_node_name``; cached
# per-namespace-prefix so the per-branch dispatch synthesizer can
# attach ``openarmature.parallel_branches.parent_node_name``
# without re-reading the inner event (which only carries
# ``branch_name``).
parallel_branches_parent_node_name: dict[tuple[str, ...], str] = field(
default_factory=dict[tuple[str, ...], str]
)
# Per proposal 0044 (v0.36.0): cached branch-name set per
# parallel-branches NODE namespace. Lets the per-branch dispatch
# synthesizer reject events whose ``branch_name`` belongs to a
# DIFFERENT parallel-branches node (nested case: an inner pb's
# branch event walks past outer pbs in the synthesis loop; outer
# pbs MUST NOT synthesize a phantom dispatch span for a branch
# name they don't actually own).
parallel_branches_branch_names: dict[tuple[str, ...], frozenset[str]] = field(
default_factory=dict[tuple[str, ...], frozenset[str]]
)
@dataclass
class OTelObserver:
"""Observer-driven OTel span lifecycle.
Construct with a :class:`SpanProcessor` (typically a
:class:`BatchSpanProcessor` wrapping a real exporter, or a
:class:`SimpleSpanProcessor` wrapping :class:`InMemorySpanExporter`
for tests). The observer instantiates its own private
:class:`TracerProvider` from the supplied processor; callers
MUST NOT pre-register the provider globally.
Constructor knobs:
- ``span_processor``: a single :class:`SpanProcessor` or a sequence
of them. Every processor is registered on the private
:class:`TracerProvider`; spans flow to each.
- ``resource``: optional :class:`Resource` passed to the private
:class:`TracerProvider`. Sets ``service.name`` / ``service.version``
/ etc. without relying on environment variables.
- ``detached_subgraphs``: set of subgraph wrapper node names that
run in their own trace. One detached trace per such subgraph.
- ``detached_fan_outs``: set of fan-out node names whose instances
each get their own trace. One detached trace per instance.
- ``disable_llm_spans``: when ``True`` the observer skips the LLM
provider span; all other spans emit normally.
- ``disable_provider_payload``: default ``True``. Gates the LLM input/
output payload attributes (``openarmature.llm.input.messages``,
``openarmature.llm.output.content``,
``openarmature.llm.request.extras``). The name carries the broadened
provider-payload scope; LLM completion is the only provider-call
payload OA emits today.
- ``disable_genai_semconv``: default ``False``. Gates the
``gen_ai.*`` attribute set on the LLM span.
- ``payload_max_bytes``: per-attribute byte cap for the LLM payload
attributes. Default 64 KiB; minimum 256 bytes (rejected at
construction time below that).
- ``attribute_enrichers``: optional sequence of callables run just
before the observer ends each span. Each receives the live
:class:`Span` plus the :class:`NodeEvent` or
:class:`LlmCompletionEvent` that triggered the close (or
``None`` on synthetic close sites). Exceptions are caught and
warned; never propagated.
- ``spec_version``: string surfaced as
``openarmature.graph.spec_version`` on the invocation span.
- ``implementation_name``: string surfaced as
``openarmature.implementation.name`` on the invocation span.
Defaults to the package's ``__implementation_name__``
(``"openarmature-python"``). Configurable for test
parameterization.
- ``implementation_version``: string surfaced as
``openarmature.implementation.version`` on the invocation span.
Defaults to ``openarmature.__version__``. Always-emit invariant:
not gated by any privacy knob.
Safe to share across concurrent invocations and across resumes of
the same correlation_id; every internal span map is outer-keyed by
``invocation_id``, and parent resolution stays within a single
event handler's scope.
"""
# Spec observability §6 (observer-driven span lifecycle).
# span_processor accepts a single processor or a sequence per
# observability friction-roundup #5. The dataclass field type is
# the union; ``__post_init__`` normalizes to a tuple internally.
span_processor: SpanProcessor | Sequence[SpanProcessor]
# Optional Resource per friction-roundup #4. Default behavior
# (resource=None) falls through to OTel's default Resource (reads
# OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES env vars at
# construction time).
resource: Resource | None = None
detached_subgraphs: frozenset[str] = field(default_factory=_empty_str_frozenset)
detached_fan_outs: frozenset[str] = field(default_factory=_empty_str_frozenset)
disable_llm_spans: bool = False
# disable_provider_payload defaults to True per observability §5.5.4.
# Default-off because the payload may contain PII the user hasn't
# audited — opting in is a deliberate second choice. Naming inverts
# the natural reading ("default-off via True") to keep symmetry
# with the existing disable_llm_spans parameter family.
disable_provider_payload: bool = True
# disable_genai_semconv defaults to False (emit) per §5.5.4. The
# value proposition of installing the OTel observer is that
# LLM-aware backends (Langfuse, Phoenix, Honeycomb's LLM lens)
# render correctly out of the box, which keys off gen_ai.*.
disable_genai_semconv: bool = False
# Proposal 0067 (observability §11): opt-in GenAI metrics. Default
# off; the flag name is normative. When True, __post_init__ creates
# the two histogram instruments and provider-call events record token
# + duration measurements. Independent of span emission (§11.1) — the
# disable_llm_spans / disable_provider_payload / disable_genai_semconv
# flags govern spans only.
enable_metrics: bool = False
# The MeterProvider the metric instruments are obtained from. None
# (default) falls back to the configured OTel global MeterProvider,
# which is the no-op meter when none is set up (§11.1: recording is a
# silent no-op, never raises). Injectable so tests (and callers who
# keep a private MeterProvider) can capture measurements without
# mutating the OTel global. Unlike the span side's private
# TracerProvider, metrics use the *configured* provider per §11.1.
meter_provider: MeterProvider | None = None
# Per-attribute byte cap for the §5.5.1 payload attributes. Default
# 64 KiB; minimum 256 bytes (§5.5.5), validated in __post_init__.
payload_max_bytes: int = _PAYLOAD_DEFAULT_BYTES
# attribute_enrichers per friction-roundup #7p2 — runs before every
# span.end() the observer issues. NodeEvent is None on synthetic
# close sites (subgraph dispatch, detached root, fan-out instance,
# invocation span, shutdown drain).
attribute_enrichers: Sequence[
Callable[
[
Span,
NodeEvent
| LlmCompletionEvent
| LlmFailedEvent
| LlmRetryAttemptEvent
| ToolCallEvent
| ToolCallFailedEvent
| None,
],
None,
]
] = ()
# Read from the package's ``__spec_version__`` (one of the three
# places the spec version is pinned per CLAUDE.md). Bumping the
# spec submodule + the two version fields automatically updates
# the value reported on every invocation span.
spec_version: str = field(default_factory=_read_spec_version)
# Proposal 0052 (spec v0.44.0): implementation identity emitted on
# every invocation span. ``implementation_name`` is the package
# registry name (``openarmature-python``);
# ``implementation_version`` is ``openarmature.__version__``.
# Configurable for test parameterization but defaults to the
# package-pinned values; the always-emit invariant means neither
# ``disable_state_payload``, ``disable_provider_payload``, nor any
# other privacy knob gates them.
implementation_name: str = field(default_factory=_read_implementation_name)
implementation_version: str = field(default_factory=_read_implementation_version)
# Internal state, populated in __post_init__ and during invocation.
_provider: TracerProvider = field(init=False, repr=False)
_tracer: otel_trace.Tracer = field(init=False, repr=False)
# §11 metric instruments — created in __post_init__ only when
# enable_metrics is True; None otherwise (and recording is skipped).
_meter: Meter | None = field(init=False, repr=False, default=None)
_token_histogram: Histogram | None = field(init=False, repr=False, default=None)
_duration_histogram: Histogram | None = field(init=False, repr=False, default=None)
# Per-invocation_id span state — concurrent invocations on a
# shared observer each get their own ``_InvState`` so internal
# maps never collide.
_inv_states: dict[str, _InvState] = field(init=False, repr=False, default_factory=dict[str, _InvState])
# Root invocation spans, keyed by invocation_id. Opened lazily on
# the first event for a new invocation_id; closed via
# ``close_invocation`` / ``shutdown``.
_invocation_span: dict[str, _OpenSpan] = field(
init=False, repr=False, default_factory=dict[str, _OpenSpan]
)
def __post_init__(self) -> None:
# §5.5.5 minimum-cap validation. Reject misconfigurations at
# construction time rather than emitting silently broken
# attributes.
if self.payload_max_bytes < _PAYLOAD_MIN_BYTES:
raise ValueError(
f"payload_max_bytes={self.payload_max_bytes} below the spec §5.5.5 "
f"minimum cap of {_PAYLOAD_MIN_BYTES} bytes"
)
# Private provider per spec §6 TracerProvider isolation —
# MUST NOT be registered globally. Resource set on the
# provider when supplied; otherwise OTel's default Resource
# (which reads OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES
# env vars at construction time) applies.
if self.resource is not None:
self._provider = TracerProvider(resource=self.resource)
else:
self._provider = TracerProvider()
# Multi-processor: a sequence registers every entry; a single
# processor wraps in a 1-tuple. ``SpanProcessor`` is itself a
# class so we can't use isinstance against ``Sequence`` first
# (Sequence matches strings too); compare against the explicit
# union arms.
if isinstance(self.span_processor, SpanProcessor):
processors: Sequence[SpanProcessor] = (self.span_processor,)
else:
processors = tuple(self.span_processor)
for proc in processors:
self._provider.add_span_processor(proc)
self._tracer = self._provider.get_tracer("openarmature")
# §11.1 metrics: opt-in. When enabled, obtain a Meter from the
# configured MeterProvider (injected, else the OTel global, which
# is the no-op meter when none is set up) and create the two
# histograms with the §11.2 explicit bucket advisories. When
# disabled, no instrument is created and nothing records.
if self.enable_metrics:
meter_provider = (
self.meter_provider if self.meter_provider is not None else otel_metrics.get_meter_provider()
)
self._meter = meter_provider.get_meter("openarmature")
self._token_histogram = self._meter.create_histogram(
"openarmature.gen_ai.client.token.usage",
unit="{token}",
explicit_bucket_boundaries_advisory=_TOKEN_USAGE_BUCKETS,
)
self._duration_histogram = self._meter.create_histogram(
"openarmature.gen_ai.client.operation.duration",
unit="s",
explicit_bucket_boundaries_advisory=_DURATION_BUCKETS,
)
# ------------------------------------------------------------------
# Enricher invocation (friction-roundup #7p2)
# ------------------------------------------------------------------
# Exception isolation mirrors the observer-error-isolation contract
# in ``openarmature.graph.observer`` — enricher raises are caught +
# warned, never propagated to the dispatch worker.
# ``event`` is None on synthetic close sites (subgraph dispatch,
# detached root, fan-out instance, invocation span, orphan drain).
def _run_enrichers(
self,
span: Span,
event: NodeEvent
| LlmCompletionEvent
| LlmFailedEvent
| LlmRetryAttemptEvent
| ToolCallEvent
| ToolCallFailedEvent
| None,
) -> None:
"""Invoke configured enrichers against ``span`` before
``span.end()`` is called."""
if not self.attribute_enrichers:
return
import warnings
for enricher in self.attribute_enrichers:
try:
enricher(span, event)
except Exception as e: # noqa: BLE001
warnings.warn(
f"attribute_enricher raised {type(e).__name__}: {e}",
stacklevel=2,
)
# ------------------------------------------------------------------
# Per-invocation state lookup
# ------------------------------------------------------------------
def _inv_state_for(self, invocation_id: str) -> _InvState:
"""Get-or-create the state container for an invocation_id."""
state = self._inv_states.get(invocation_id)
if state is None:
state = _InvState()
self._inv_states[invocation_id] = state
return state
# ------------------------------------------------------------------
# Observer protocol — async callable accepting node events + the
# proposal-0040 metadata-augmentation event variant + the
# proposal-0043 invocation-boundary events (no-op on the OTel
# mapping; OTel has no Trace-level input/output concept per the
# proposal's Out-of-Scope section).
# ------------------------------------------------------------------
async def __call__(
self,
event: (
NodeEvent
| MetadataAugmentationEvent
| InvocationStartedEvent
| InvocationCompletedEvent
| LlmCompletionEvent
| LlmFailedEvent
| LlmRetryAttemptEvent
| FailureIsolatedEvent
| ToolCallEvent
| ToolCallFailedEvent
),
) -> None:
# Proposal 0043 invocation-boundary events: OTel has no
# Trace-level input/output payload concept (a trace is a
# collection of Spans sharing a trace_id; no Trace-level
# payload field). No-op gates here; isinstance early-return
# before any node-specific logic runs.
if isinstance(event, InvocationStartedEvent | InvocationCompletedEvent):
return
# Proposal 0050 per-attempt LLM span surface: the
# openarmature.llm.complete span(s) render from the per-attempt
# LlmRetryAttemptEvent — one span per attempt under call-level
# retry (attempt_index 0..N-1), one for a no-retry call.
if isinstance(event, LlmRetryAttemptEvent):
# §11 metrics record per attempt, independent of span emission
# (§11.1) — so this runs regardless of disable_llm_spans.
if self.enable_metrics:
self._record_llm_metrics(event)
if not self.disable_llm_spans:
self._handle_typed_llm_retry_attempt(event)
return
# The terminal LlmCompletionEvent / LlmFailedEvent no longer
# drive the OTel span (the per-attempt event does); they stay on
# the queue for the Langfuse mapping and payload/latency
# consumers, so the OTel observer ignores them here.
if isinstance(event, LlmCompletionEvent | LlmFailedEvent):
return
# Proposal 0063 tool-execution observability: emit the
# openarmature.tool.call span from the typed tool events.
# Independent of disable_llm_spans (that flag is scoped to LLM
# completion spans per §5.5.4).
if isinstance(event, ToolCallEvent | ToolCallFailedEvent):
self._handle_tool_call(event)
return
# Proposal 0050 §6.3 framework-emitted failure-isolation event.
if isinstance(event, FailureIsolatedEvent):
self._handle_failure_isolated(event)
return
if isinstance(event, MetadataAugmentationEvent):
self._handle_metadata_augmentation(event)
return
if event.phase == "checkpoint_saved":
self._emit_checkpoint_save_span(event)
return
if event.phase == "checkpoint_migrated":
self._emit_checkpoint_migrate_span(event)
return
if event.phase == "started":
# Idempotent — short-circuits inside ``_open_started_span``
# if ``prepare_sync`` already opened the span synchronously
# in the engine task. Falls through (and opens the span)
# for observers attached after the engine started, or for
# test paths that bypass ``prepare_sync``.
self._open_started_span(event)
elif event.phase == "completed":
self._handle_completed(event)
# ------------------------------------------------------------------
# Started / completed pairing
# ------------------------------------------------------------------
def prepare_sync(self, event: NodeEvent) -> None:
"""Synchronous engine-task entry point: open the span for this
attempt AND publish it via ``current_active_observer_span`` so
the engine's ``innermost`` can attach it into the OTel context
before the node body runs.
Called by ``_dispatch`` BEFORE ``queue.put_nowait`` for
``"started"``-phase events. The async ``__call__`` later sees
the span already in ``inv_state.open_spans`` and short-circuits.
Skipped for non-``"started"`` phases and for the LLM sentinel
namespace; only graph-node started events participate in the
engine-side attach. Errors don't leak: ``_dispatch`` wraps this
call in try/except + ``warnings.warn`` matching the async path.
"""
if event.phase != "started":
return
from openarmature.observability.correlation import (
_set_active_observer_span,
current_invocation_id,
)
self._open_started_span(event)
invocation_id = current_invocation_id()
if invocation_id is None:
return
inv_state = self._inv_states.get(invocation_id)
if inv_state is None:
return
open_span = inv_state.open_spans.get(self._key_for(event))
if open_span is None:
# Proposal 0075: a callable parallel-branch has no leaf — its span
# is the per-branch dispatch span opened in ``_open_started_span``.
# Publish that so a provider call inside the callable nests under
# the branch span.
if event.branch_name is not None and event.parallel_branches_config is None:
dispatch = inv_state.parallel_branches_branch_spans.get(
event.namespace + (event.branch_name,)
)
if dispatch is not None:
_set_active_observer_span(dispatch.span)
return
# Publish the span to the engine via the ContextVar. Discard
# the Token — last-writer-wins is the documented contract
# (next ``prepare_sync`` overwrites; task-local context dies
# with the invocation task).
_set_active_observer_span(open_span.span)
def _open_started_span(self, event: NodeEvent) -> None:
"""Sync core: create the span + mutate ``inv_state.open_spans``.
Idempotent — short-circuits if a span already exists for this
event's ``_StackKey``. That covers the common case where
``prepare_sync`` opened the span synchronously in the engine
task and the async ``__call__`` later re-fires for the same
event; the second call becomes a true no-op rather than
opening a duplicate span.
"""
from openarmature.observability.correlation import (
current_correlation_id,
current_invocation_id,
)
invocation_id = current_invocation_id()
if invocation_id is None:
return
inv_state = self._inv_state_for(invocation_id)
# Idempotency: a span already exists for this attempt — likely
# opened by ``prepare_sync`` in the engine task. No-op to avoid
# duplicates.
if self._key_for(event) in inv_state.open_spans:
return
correlation_id = current_correlation_id()
# Lazily open the invocation span on the first event we see
# for this invocation_id. Per-invocation_id scoping means
# resumed runs of the same correlation_id (each with a fresh
# invocation_id per §5.1) get their own invocation span and
# therefore their own trace_id.
if invocation_id not in self._invocation_span:
self._open_invocation_span(invocation_id, correlation_id, event)
# Per spec proposal 0013 (v0.10.0): cache the fan-out node's
# ``parent_node_name`` from its ``started`` event so
# ``_open_fan_out_instance_dispatch_span`` can attach
# ``openarmature.fan_out.parent_node_name`` to per-instance
# spans. Inner events from inside the fan-out's instances
# don't carry ``fan_out_config`` themselves; the cache bridges.
# ``fan_out_config`` is only populated on the NODE's OWN
# events, so the presence check is sufficient — we don't
# additionally filter on ``fan_out_index is None`` because
# when a fan-out is nested inside another fan-out or a pb
# branch, the NODE's own event carries the OUTER axis values.
if event.fan_out_config is not None:
inv_state.fan_out_parent_node_name[event.namespace] = event.fan_out_config.parent_node_name
# Per proposal 0044 (v0.36.0): mirror cache for the parallel-
# branches NODE. Same logic as the fan-out cache: rely on
# ``parallel_branches_config`` being populated only on the
# NODE's own events; don't additionally filter on
# ``branch_name is None`` (which would skip caching for a pb
# nested inside another pb's branch).
if event.parallel_branches_config is not None:
inv_state.parallel_branches_parent_node_name[event.namespace] = (
event.parallel_branches_config.parent_node_name
)
inv_state.parallel_branches_branch_names[event.namespace] = frozenset(
event.parallel_branches_config.branch_names
)
# Synthesize subgraph dispatch spans for any ancestor namespace
# prefix that doesn't have one yet (per observability §4.5).
# Also closes subgraph spans we've left.
self._sync_subgraph_spans(inv_state, invocation_id, correlation_id, event)
# Proposal 0075 (observability §5.7): a callable parallel-branch emits
# its started/completed pair at the pb NODE's own namespace, tagged
# with branch_name and (unlike the NODE's own events) no
# parallel_branches_config. It IS the unit, so render it as the
# branch's per-branch dispatch span (keyed by branch_name, parented
# under the NODE span) with NO inner-node leaf. A subgraph branch's
# inner-node events are always one level deeper, so this never
# misfires for them. The dispatch span is closed when the NODE's own
# completed event fires (children-before-parents), like any branch
# dispatch span; this branch's completed event is then a no-op pop.
if (
event.branch_name is not None
and event.parallel_branches_config is None
and event.namespace in inv_state.parallel_branches_parent_node_name
):
branch_key = event.namespace + (event.branch_name,)
if branch_key not in inv_state.parallel_branches_branch_spans:
self._open_parallel_branches_branch_dispatch_span(
inv_state, correlation_id, event.namespace, event
)
return
parent_ctx = self._resolve_parent_context(inv_state, invocation_id, event)
span = self._tracer.start_span(
name=event.node_name,
context=cast("Any", parent_ctx),
kind=SpanKind.INTERNAL,
attributes=self._node_attrs(event, correlation_id),
)
inv_state.open_spans[self._key_for(event)] = _OpenSpan(
span=span,
fan_out_index_chain=event.fan_out_index_chain,
branch_name_chain=event.branch_name_chain,
)
def _handle_completed(self, event: NodeEvent) -> None:
"""Close the matching span, applying the status mapping."""
from openarmature.observability.correlation import current_invocation_id
invocation_id = current_invocation_id()
if invocation_id is None:
return
inv_state = self._inv_states.get(invocation_id)
if inv_state is None:
return
# If this is the fan-out node's own completion AND the
# fan-out is configured detached, close all per-instance
# detached roots that this fan-out spawned. Done BEFORE the
# regular pop so the close ordering is parents-after-children.
if event.fan_out_index is None and event.namespace and event.namespace[0] in self.detached_fan_outs:
for key in list(inv_state.detached_roots.keys()):
if len(key) > len(event.namespace) and key[: len(event.namespace)] == event.namespace:
self._close_detached_root(inv_state, key)
# Per spec proposal 0013 (v0.10.0): if this is the fan-out
# node's own completion (non-detached path), close all
# per-instance dispatch spans synthesized for this fan-out.
# Children-before-parents close ordering: per-instance
# dispatch spans before the fan-out node's own span.
# ``fan_out_config`` is only populated on the NODE's OWN
# events, so the presence check is sufficient — we don't
# additionally filter on ``fan_out_index is None`` because
# when a fan-out is nested inside another fan-out's instance
# or a pb's branch, the NODE's own completion event carries
# the OUTER axis values.
if event.fan_out_config is not None:
for key in list(inv_state.fan_out_instance_spans.keys()):
if len(key) > len(event.namespace) and key[: len(event.namespace)] == event.namespace:
self._close_fan_out_instance_dispatch_span(inv_state, key)
inv_state.fan_out_parent_node_name.pop(event.namespace, None)
# Per proposal 0044 (v0.36.0): if this is the parallel-branches
# node's own completion, close all per-branch dispatch spans
# synthesized for it. Children-before-parents close ordering
# (per-branch dispatch spans before the parallel-branches node
# span itself). Same logic as the fan-out close above: rely
# on ``parallel_branches_config`` being populated only on the
# NODE's own events; don't additionally filter on
# ``branch_name is None`` (which would skip close for a pb
# nested inside another pb's branch).
if event.parallel_branches_config is not None:
for key in list(inv_state.parallel_branches_branch_spans.keys()):
if len(key) > len(event.namespace) and key[: len(event.namespace)] == event.namespace:
self._close_parallel_branches_branch_dispatch_span(inv_state, key)
inv_state.parallel_branches_parent_node_name.pop(event.namespace, None)
inv_state.parallel_branches_branch_names.pop(event.namespace, None)
key = self._key_for(event)
open_span = inv_state.open_spans.pop(key, None)
if open_span is None:
# Started event was never delivered (e.g., observer was
# attached mid-invocation). Nothing to close.
return
span = open_span.span
if event.error is not None:
span.set_status(Status(StatusCode.ERROR, description=event.error.category))
span.record_exception(event.error)
span.set_attribute("openarmature.error.category", event.error.category)
# Per spec §4.2 / fixture 003: the invocation span MUST
# end with ERROR status when any child node errors. OTel
# doesn't auto-propagate child status to parents — we set
# it explicitly here. This ERROR survives to export because
# ``_close_invocation_span`` deliberately never calls
# ``set_status(OK)`` on the clean-completion path (it leaves
# the status UNSET, which exporters map to OK). That matters
# because the OTel SDK treats OK as FINAL and lets a later
# OK OVERRIDE a prior ERROR (only a set to UNSET is ignored)
# — an unconditional OK at a close site would erase this,
# the same hazard the §4.2 detached-error propagation guards
# against via ``errored_detached_keys``.
inv_open = self._invocation_span.get(invocation_id)
if inv_open is not None:
inv_open.span.set_status(Status(StatusCode.ERROR, description=event.error.category))
# Proposal 0061 §4.2: when the erroring node is inside a