-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_observability_otel.py
More file actions
3936 lines (3441 loc) · 156 KB
/
Copy pathtest_observability_otel.py
File metadata and controls
3936 lines (3441 loc) · 156 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
"""OTel-specific observability unit tests (extras-gated).
Skipped cleanly when the ``otel`` extras aren't installed — the
import-time check in
``openarmature.observability.otel.__init__`` raises ImportError on
missing deps.
These tests fill the gaps the conformance harness defers:
- TracerProvider isolation — the load-bearing "spans don't leak
into the OTel global provider" guarantee.
- attribute population on every span type.
- status mapping for every error category.
- LLM provider span via the ContextVar dispatch hook (queue-
mediated; no synchronous direct dispatch).
- detached trace mode key separation in the span stack.
- checkpoint_saved → ``openarmature.checkpoint.save`` zero-
duration span.
- log bridge filter + correlation_id injection.
"""
from __future__ import annotations
import logging
from pathlib import Path
import pytest
from pydantic import Field
# Skip the entire module if otel extras aren't installed.
pytest.importorskip("opentelemetry.sdk.trace")
from typing import Annotated, Any, cast
from opentelemetry import trace as otel_trace
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
from openarmature.checkpoint import InMemoryCheckpointer
from openarmature.graph import (
END,
GraphBuilder,
NodeException,
State,
append,
)
from openarmature.observability.otel import OTelObserver, install_log_bridge
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
class _LinearState(State):
a: int = 0
b: int = 0
async def _node_a(_s: _LinearState) -> dict[str, int]:
return {"a": 1}
async def _node_b(_s: _LinearState) -> dict[str, int]:
return {"b": 2}
def _build_linear_graph(
observer: OTelObserver | None = None,
) -> tuple[
object,
InMemorySpanExporter,
]:
"""Build a 2-node linear graph wired to a fresh OTelObserver +
in-memory exporter; returns (compiled_graph, exporter)."""
exporter = InMemorySpanExporter()
if observer is None:
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g = (
GraphBuilder(_LinearState)
.add_node("node_a", _node_a)
.add_node("node_b", _node_b)
.add_edge("node_a", "node_b")
.add_edge("node_b", END)
.set_entry("node_a")
.compile()
)
g.attach_observer(observer)
return g, exporter
# ---------------------------------------------------------------------------
# §6 TracerProvider isolation
# ---------------------------------------------------------------------------
# OTel SDK 1.x makes ``set_tracer_provider`` one-shot: once a non-default
# provider is set, subsequent ``set_tracer_provider`` calls are no-ops
# (the SDK logs a warning and returns). The set is guarded by a ``Once``
# primitive at ``opentelemetry.trace._TRACER_PROVIDER_SET_ONCE``, not
# just by the value of ``_TRACER_PROVIDER``. Restoring via the public
# API silently fails after a prior set, leaking the test's global
# provider into subsequent tests that also touch the OTel global (e.g.,
# the conformance fixture 005 sub-case verifying private/global
# isolation). Tests that need to manipulate the global provider use
# this helper to reset BOTH the value and the Once.
def _reset_otel_global_tracer_provider(restore_to: object) -> None:
once = otel_trace._TRACER_PROVIDER_SET_ONCE # type: ignore[attr-defined]
with once._lock: # pyright: ignore[reportPrivateUsage]
if isinstance(restore_to, otel_trace.ProxyTracerProvider):
# No real provider was set before this test; return the
# global to "unset" state so the next set_tracer_provider
# call works as if it were the first.
otel_trace._TRACER_PROVIDER = None # type: ignore[attr-defined]
once._done = False # pyright: ignore[reportPrivateUsage]
else:
otel_trace._TRACER_PROVIDER = restore_to # type: ignore[attr-defined]
once._done = True # pyright: ignore[reportPrivateUsage]
async def test_observer_uses_private_provider_not_global() -> None:
"""TracerProvider isolation: the OTelObserver MUST use a
PRIVATE TracerProvider; spans MUST NOT appear on the OTel global
provider's exporter (this is the load-bearing guarantee against
duplicate spans from external auto-instrumentation libraries)."""
# Save prior global state and install a separate exporter on the
# OTel global provider. Pytest fixture-scoping doesn't cover the
# OTel global, so we restore it manually in the finally block.
prior_global = otel_trace.get_tracer_provider()
global_exporter = InMemorySpanExporter()
global_provider = TracerProvider()
global_provider.add_span_processor(SimpleSpanProcessor(global_exporter))
otel_trace.set_tracer_provider(global_provider)
try:
# Drive a graph through OTelObserver.
private_exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(private_exporter))
g, _ = _build_linear_graph(observer)
await g.invoke(_LinearState()) # type: ignore[attr-defined]
await g.drain() # type: ignore[attr-defined]
observer.shutdown()
private_spans = private_exporter.get_finished_spans()
global_spans = global_exporter.get_finished_spans()
assert len(private_spans) > 0, "private provider must have received spans"
assert len(global_spans) == 0, (
f"global provider MUST NOT receive openarmature spans; got {[s.name for s in global_spans]}"
)
finally:
_reset_otel_global_tracer_provider(prior_global)
# ---------------------------------------------------------------------------
# §5 attribute population
# ---------------------------------------------------------------------------
async def test_node_span_carries_required_attributes() -> None:
"""Every node span MUST carry the four ``openarmature.node.*``
base attributes."""
g, exporter = _build_linear_graph()
await g.invoke(_LinearState(), correlation_id="test-cid") # type: ignore[attr-defined]
await g.drain() # type: ignore[attr-defined]
spans = exporter.get_finished_spans()
node_spans = [s for s in spans if s.name in {"node_a", "node_b"}]
assert len(node_spans) == 2
for span in node_spans:
attrs = dict(span.attributes or {})
assert attrs.get("openarmature.node.name") == span.name
assert isinstance(attrs.get("openarmature.node.namespace"), tuple | list)
assert isinstance(attrs.get("openarmature.node.step"), int)
assert attrs.get("openarmature.node.attempt_index") == 0
# Cross-cutting correlation_id (§5.6).
assert attrs.get("openarmature.correlation_id") == "test-cid"
async def test_invocation_span_carries_required_attributes() -> None:
"""Invocation span MUST carry ``openarmature.graph.entry_node`` +
``openarmature.graph.spec_version``."""
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g, _ = _build_linear_graph(observer)
await g.invoke(_LinearState()) # type: ignore[attr-defined]
await g.drain() # type: ignore[attr-defined]
# Invocation span closes on observer shutdown — the engine has
# no per-invocation lifecycle hook on observers, so the user
# closes the observer when done with their batch of invocations.
observer.shutdown()
spans = exporter.get_finished_spans()
inv = next((s for s in spans if s.name == "openarmature.invocation"), None)
assert inv is not None
attrs = dict(inv.attributes or {})
assert attrs.get("openarmature.graph.entry_node") == "node_a"
assert isinstance(attrs.get("openarmature.graph.spec_version"), str)
# Spec §5.1 / proposal 0052: invocation span MUST carry
# ``openarmature.implementation.name`` and
# ``openarmature.implementation.version`` as non-empty strings; name
# matches the package-registry canonical value (``openarmature-python``).
# Inner-node spans MUST NOT carry them — the attributes live in §5.1,
# not the cross-cutting §5.6 family.
async def test_invocation_span_carries_implementation_attribution_attributes() -> None:
from openarmature import __version__
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g, _ = _build_linear_graph(observer)
await g.invoke(_LinearState()) # type: ignore[attr-defined]
await g.drain() # type: ignore[attr-defined]
observer.shutdown()
spans = exporter.get_finished_spans()
inv = next((s for s in spans if s.name == "openarmature.invocation"), None)
assert inv is not None
inv_attrs = dict(inv.attributes or {})
assert inv_attrs.get("openarmature.implementation.name") == "openarmature-python"
assert inv_attrs.get("openarmature.implementation.version") == __version__
assert isinstance(inv_attrs["openarmature.implementation.name"], str)
assert inv_attrs["openarmature.implementation.name"] # non-empty
assert isinstance(inv_attrs["openarmature.implementation.version"], str)
assert inv_attrs["openarmature.implementation.version"] # non-empty
# Inner-node spans MUST NOT carry the attribution attributes.
inner_spans = [s for s in spans if s.name != "openarmature.invocation"]
assert inner_spans, "expected at least one inner node span"
for span in inner_spans:
span_attrs = dict(span.attributes or {})
assert "openarmature.implementation.name" not in span_attrs, (
f"inner span {span.name!r} unexpectedly carries implementation.name"
)
assert "openarmature.implementation.version" not in span_attrs, (
f"inner span {span.name!r} unexpectedly carries implementation.version"
)
# Spec §5.1 / proposal 0052: always-emit invariant. The attribution
# attributes describe runtime identity, not runtime data, so the
# privacy knobs that gate payload-shaped attributes (LLM payload,
# state payload, GenAI semconv) MUST NOT gate the attribution. This
# pins the OTel side of the contract; the Langfuse-side equivalent
# lives in test_observability_langfuse.py against
# disable_state_payload=True.
async def test_invocation_span_attribution_emits_under_disable_provider_payload() -> None:
exporter = InMemorySpanExporter()
observer = OTelObserver(
span_processor=SimpleSpanProcessor(exporter),
disable_provider_payload=True,
disable_genai_semconv=True,
disable_llm_spans=True,
)
g, _ = _build_linear_graph(observer)
await g.invoke(_LinearState()) # type: ignore[attr-defined]
await g.drain() # type: ignore[attr-defined]
observer.shutdown()
spans = exporter.get_finished_spans()
inv = next((s for s in spans if s.name == "openarmature.invocation"), None)
assert inv is not None
attrs = dict(inv.attributes or {})
assert attrs.get("openarmature.implementation.name") == "openarmature-python"
assert isinstance(attrs.get("openarmature.implementation.version"), str)
assert attrs["openarmature.implementation.version"]
# Spec §5.1 / proposal 0052: every invocation span carries the
# attribution attributes. An observer reused across multiple
# invocations on the same compiled graph MUST emit the attributes on
# every invocation's span — not just the first. The dataclass-field
# defaults are computed once at observer construction, so a regression
# where the values were instance-scoped (read-once) instead of
# emit-each-time would silently break this contract.
async def test_invocation_span_attribution_emits_on_every_invocation() -> None:
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g, _ = _build_linear_graph(observer)
for _ in range(3):
await g.invoke(_LinearState()) # type: ignore[attr-defined]
await g.drain() # type: ignore[attr-defined]
observer.shutdown()
spans = exporter.get_finished_spans()
inv_spans = [s for s in spans if s.name == "openarmature.invocation"]
assert len(inv_spans) == 3, f"expected three invocation spans, got {len(inv_spans)}"
for span in inv_spans:
attrs = dict(span.attributes or {})
assert attrs.get("openarmature.implementation.name") == "openarmature-python"
assert isinstance(attrs.get("openarmature.implementation.version"), str)
assert attrs["openarmature.implementation.version"]
# ---------------------------------------------------------------------------
# §4.2 status mapping
# ---------------------------------------------------------------------------
class _FailState(State):
a: int = 0
async def _failing_node(_s: _FailState) -> dict[str, int]:
raise RuntimeError("boom")
async def test_failing_node_span_carries_error_status() -> None:
"""A node-exception failure produces a span with
ERROR status, an exception event recorded, and the
``openarmature.error.category`` attribute on the span."""
from opentelemetry.trace import StatusCode
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g = (
GraphBuilder(_FailState)
.add_node("flaky", _failing_node)
.add_edge("flaky", END)
.set_entry("flaky")
.compile()
)
g.attach_observer(observer)
with pytest.raises(NodeException):
await g.invoke(_FailState())
await g.drain()
observer.shutdown()
spans = exporter.get_finished_spans()
flaky = next((s for s in spans if s.name == "flaky"), None)
assert flaky is not None
assert flaky.status.status_code == StatusCode.ERROR
attrs = dict(flaky.attributes or {})
assert attrs.get("openarmature.error.category") == "node_exception"
# ---------------------------------------------------------------------------
# §10.8 checkpoint_saved → 0-duration span
# ---------------------------------------------------------------------------
async def test_checkpoint_migrate_emits_span_with_chain_metadata(tmp_path: Path) -> None:
"""A versioned resume whose migration chain runs SHOULD emit an
``openarmature.checkpoint.migrate`` span carrying
``from_version`` / ``to_version`` (final) / ``chain_length``."""
from openarmature.checkpoint import (
CheckpointRecord,
SQLiteCheckpointer,
)
# JSON-mode SQLite is migration-eligible (the dict-state form the
# registry consumes is what the load path produces).
cp = SQLiteCheckpointer(tmp_path / "ck.db", serialization="json")
class _MigState(State):
schema_version = "v2"
x: int = 0
new_field: str = "v2_default"
async def _noop(_s: _MigState) -> dict[str, int]:
return {}
# Seed a v1 record so the resume triggers the v1→v2 migration.
invocation_id = "mig-resume"
await cp.save(
invocation_id,
CheckpointRecord(
invocation_id=invocation_id,
correlation_id="cid",
state={"x": 9},
completed_positions=(),
parent_states=(),
last_saved_at=0.0,
schema_version="v1",
),
)
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g = (
GraphBuilder(_MigState)
.add_node("noop", _noop)
.add_edge("noop", END)
.set_entry("noop")
.with_checkpointer(cp)
.with_state_migration("v1", "v2", lambda s: {**s, "new_field": "v2_default"})
.compile()
)
g.attach_observer(observer, phases={"started", "completed", "checkpoint_migrated"})
await g.invoke(
_MigState.model_construct(),
resume_invocation=invocation_id,
)
await g.drain()
observer.shutdown()
migrate_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.checkpoint.migrate"]
assert len(migrate_spans) == 1
span = migrate_spans[0]
attrs = dict(span.attributes or {})
assert attrs.get("openarmature.checkpoint.migrate.from_version") == "v1"
assert attrs.get("openarmature.checkpoint.migrate.to_version") == "v2"
assert attrs.get("openarmature.checkpoint.migrate.chain_length") == 1
async def test_checkpoint_migrate_span_absent_on_version_match(tmp_path: Path) -> None:
"""Fast path: when the saved record's schema_version equals the
current state class's schema_version, the migration
registry is NOT consulted. The OTel observer MUST NOT emit a
``openarmature.checkpoint.migrate`` span in that case."""
from openarmature.checkpoint import CheckpointRecord, SQLiteCheckpointer
cp = SQLiteCheckpointer(tmp_path / "ck.db", serialization="json")
class _MatchState(State):
schema_version = "v1"
x: int = 0
async def _noop(_s: _MatchState) -> dict[str, int]:
return {}
invocation_id = "match-resume"
await cp.save(
invocation_id,
CheckpointRecord(
invocation_id=invocation_id,
correlation_id="cid",
state={"x": 7},
completed_positions=(),
parent_states=(),
last_saved_at=0.0,
schema_version="v1", # matches current class
),
)
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g = (
GraphBuilder(_MatchState)
.add_node("noop", _noop)
.add_edge("noop", END)
.set_entry("noop")
.with_checkpointer(cp)
.compile()
)
g.attach_observer(observer, phases={"started", "completed", "checkpoint_migrated"})
await g.invoke(_MatchState.model_construct(), resume_invocation=invocation_id)
await g.drain()
observer.shutdown()
migrate_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.checkpoint.migrate"]
assert migrate_spans == []
async def test_checkpoint_save_emits_zero_duration_span() -> None:
"""A checkpoint save SHOULD emit an observer event surfaced as a
span. Our implementation emits a
``openarmature.checkpoint.save`` span on every save."""
cp = InMemoryCheckpointer()
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
g = (
GraphBuilder(_LinearState)
.add_node("node_a", _node_a)
.add_edge("node_a", END)
.set_entry("node_a")
.with_checkpointer(cp)
.compile()
)
# Subscribe to the checkpoint_saved phase (default subscription
# excludes it; OTelObserver attaches with the explicit set).
g.attach_observer(observer, phases={"started", "completed", "checkpoint_saved"})
await g.invoke(_LinearState())
await g.drain()
observer.shutdown()
spans = exporter.get_finished_spans()
save_spans = [s for s in spans if s.name == "openarmature.checkpoint.save"]
assert len(save_spans) == 1
save_span = save_spans[0]
# Zero-duration: end_time - start_time near 0 (exact equality
# depends on monotonic clock resolution; permit small jitter).
end_t = save_span.end_time
start_t = save_span.start_time
assert end_t is not None and start_t is not None
duration = end_t - start_t
assert duration < 1_000_000, f"expected near-zero duration; got {duration}ns"
# ---------------------------------------------------------------------------
# §5.5 disable_llm_spans
# ---------------------------------------------------------------------------
async def test_active_prompt_propagates_to_llm_span_attributes() -> None:
"""When an LLM call fires inside a ``with_active_prompt`` context,
the OTel observer MUST surface
``openarmature.prompt.*`` attributes on the LLM-call span.
``with_active_prompt_group`` adds ``openarmature.prompt.group_name``."""
from datetime import UTC, datetime
from openarmature.llm.messages import UserMessage
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
from openarmature.prompts import (
PromptGroup,
PromptResult,
TextPrompt,
)
from tests._helpers.typed_event import make_retry_attempt_event
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
now = datetime.now(UTC)
prompt = TextPrompt(
name="greeting",
version="v1",
label="production",
template="Hello, {{ user }}!",
template_hash="sha256:tpl",
fetched_at=now,
)
result = PromptResult(
name=prompt.name,
version=prompt.version,
label=prompt.label,
template_hash=prompt.template_hash,
rendered_hash="sha256:rendered",
messages=[UserMessage(content="Hello, Alice!")],
variables={"user": "Alice"},
fetched_at=now,
rendered_at=now,
)
group = PromptGroup(group_name="classifier_chain", members=[result, result])
token = _set_invocation_id("inv-1")
try:
# Proposal 0024 / friction-roundup #3: the provider captures
# ``current_prompt_result()`` and ``current_prompt_group()``
# at dispatch time and puts them on the LlmCompletionEvent.
# The observer reads from the typed event, NOT from the live
# ContextVar — that ContextVar is unreachable from the
# dispatch worker's task-local Context.
await observer(make_retry_attempt_event(active_prompt=result, active_prompt_group=group))
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert len(llm_spans) == 1
attrs = llm_spans[0].attributes or {}
assert attrs.get("openarmature.prompt.name") == "greeting"
assert attrs.get("openarmature.prompt.version") == "v1"
assert attrs.get("openarmature.prompt.label") == "production"
assert attrs.get("openarmature.prompt.template_hash") == "sha256:tpl"
assert attrs.get("openarmature.prompt.rendered_hash") == "sha256:rendered"
assert attrs.get("openarmature.prompt.group_name") == "classifier_chain"
async def test_llm_span_has_no_prompt_attributes_when_no_active_prompt() -> None:
"""Without ``with_active_prompt``, the LLM-call span MUST NOT carry
``openarmature.prompt.*`` attributes."""
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
from tests._helpers.typed_event import make_retry_attempt_event
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
token = _set_invocation_id("inv-2")
try:
await observer(make_retry_attempt_event())
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert len(llm_spans) == 1
attrs = llm_spans[0].attributes or {}
assert not any(k.startswith("openarmature.prompt.") for k in attrs)
async def test_otel_observer_ignores_terminal_llm_events() -> None:
"""Feeding a terminal LlmCompletionEvent or LlmFailedEvent to the
OTel observer produces no ``openarmature.llm.complete`` span; the
per-attempt event is the sole span source."""
# Proposal 0050: the OTel span renders only from LlmRetryAttemptEvent.
# The terminal events stay on the queue for the Langfuse mapping +
# payload consumers; this guards against reintroducing the
# terminal-event span path (which would double-emit alongside the
# per-attempt span).
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
from tests._helpers.typed_event import make_failed_event, make_typed_event
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
token = _set_invocation_id("inv-terminal")
try:
await observer(make_typed_event())
await observer(make_failed_event())
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert llm_spans == []
async def _drive_llm_span_with_cached_tokens(
*,
cached_tokens: int | None,
cache_creation_tokens: int | None = None,
) -> dict[str, Any]:
"""Drive the OTel observer through a per-attempt LlmRetryAttemptEvent
carrying the supplied cache-stat fields on the event's Usage
record. Returns the LLM-span's attribute map.
"""
from openarmature.llm.response import Usage
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
from tests._helpers.typed_event import make_retry_attempt_event
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
token = _set_invocation_id("inv-cache")
try:
await observer(
make_retry_attempt_event(
usage=Usage(
prompt_tokens=100,
completion_tokens=5,
total_tokens=105,
cached_tokens=cached_tokens,
cache_creation_tokens=cache_creation_tokens,
),
)
)
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert len(llm_spans) == 1
return dict(llm_spans[0].attributes or {})
async def test_llm_span_emits_cache_read_attribute_when_provider_reports_hit() -> None:
# Proposal 0047 §5.5.3.1: openarmature.llm.cache_read.input_tokens
# is set on the LLM span when the payload carries a non-None
# cached_tokens value sourced from Response.usage.cached_tokens.
attrs = await _drive_llm_span_with_cached_tokens(cached_tokens=42)
assert attrs.get("openarmature.llm.cache_read.input_tokens") == 42
assert "openarmature.llm.cache_creation.input_tokens" not in attrs
async def test_llm_span_emits_cache_read_attribute_with_reported_zero() -> None:
# The absent-vs-reported-zero distinction is observable on the
# span: a payload with cached_tokens=0 produces the attribute
# with value 0 (not omitted).
attrs = await _drive_llm_span_with_cached_tokens(cached_tokens=0)
assert attrs.get("openarmature.llm.cache_read.input_tokens") == 0
async def test_llm_span_omits_cache_attribute_when_provider_silent() -> None:
# When the provider doesn't report cache stats (cached_tokens=None
# on the payload), the OTel observer does NOT emit the attribute
# per the §5.5.3 conditional-emission convention.
attrs = await _drive_llm_span_with_cached_tokens(cached_tokens=None)
assert "openarmature.llm.cache_read.input_tokens" not in attrs
assert "openarmature.llm.cache_creation.input_tokens" not in attrs
async def test_llm_span_emits_cache_creation_attribute_when_payload_carries_it() -> None:
# The OpenAI-compatible mapping never sources cache_creation_tokens
# (per spec §8.1.2), but the observer side honors the field when
# any future provider populates it.
attrs = await _drive_llm_span_with_cached_tokens(cached_tokens=20, cache_creation_tokens=5)
assert attrs.get("openarmature.llm.cache_read.input_tokens") == 20
assert attrs.get("openarmature.llm.cache_creation.input_tokens") == 5
async def test_disable_llm_spans_skips_llm_provider_span() -> None:
"""``disable_llm_spans=True`` MUST suppress the LLM-provider span
emission while leaving all other spans intact."""
from openarmature.graph.events import NodeEvent
# We don't drive a real provider here; instead we emit a synthetic
# LLM event through the observer's __call__ and assert no span was
# produced. This isolates the disable_llm_spans branch from the
# provider's own queue-dispatch wiring.
from openarmature.observability.llm_event import LlmEventPayload
exporter = InMemorySpanExporter()
observer = OTelObserver(
span_processor=SimpleSpanProcessor(exporter),
disable_llm_spans=True,
)
# ``step=-1`` mirrors the synthetic value ``OpenAIProvider._llm_event``
# mints (openai.py:643) — LLM-provider events aren't tied to graph step
# sequencing.
started = NodeEvent(
node_name="openarmature.llm.complete",
namespace=("openarmature.llm.complete",),
step=-1,
phase="started",
pre_state=LlmEventPayload(call_id="test-call-1", model="test-m"),
post_state=None,
error=None,
parent_states=(),
)
completed = NodeEvent(
node_name="openarmature.llm.complete",
namespace=("openarmature.llm.complete",),
step=-1,
phase="completed",
pre_state=LlmEventPayload(call_id="test-call-1", model="test-m", finish_reason="stop"),
post_state=None,
error=None,
parent_states=(),
)
await observer(started)
await observer(completed)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert llm_spans == []
async def test_llm_span_duration_matches_typed_event_latency() -> None:
# Proposal 0049 + PR 3b: the success-path span's duration is
# back-dated using LlmCompletionEvent.latency_ms, so observers see
# the adapter-boundary measurement instead of dispatcher queue
# delay. Verify the span's end-minus-start lands within tolerance
# of the typed event's latency_ms.
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
from tests._helpers.typed_event import make_retry_attempt_event
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
latency_ms = 123.456
token = _set_invocation_id("inv-duration")
try:
await observer(make_retry_attempt_event(latency_ms=latency_ms))
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert len(llm_spans) == 1
span = llm_spans[0]
assert span.start_time is not None and span.end_time is not None
duration_ms = (span.end_time - span.start_time) / 1_000_000
# Tolerance covers integer-nanosecond truncation and float->int
# rounding; the back-date is exact apart from those.
assert abs(duration_ms - latency_ms) < 1.0
async def _drive_llm_span_with_tool_calls(
tool_calls: list[Any],
*,
disable_provider_payload: bool = True,
) -> dict[str, Any]:
"""Drive one per-attempt LLM event carrying ``output_tool_calls``
through the OTel observer; return the openarmature.llm.complete
span's attribute dict. ``disable_provider_payload`` mirrors the
observer's default-on payload gate (the OTel span renders from the
per-attempt LlmRetryAttemptEvent)."""
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
from tests._helpers.typed_event import make_retry_attempt_event
exporter = InMemorySpanExporter()
observer = OTelObserver(
span_processor=SimpleSpanProcessor(exporter),
disable_provider_payload=disable_provider_payload,
)
token = _set_invocation_id("inv-tool-calls")
try:
await observer(
make_retry_attempt_event(
finish_reason="tool_calls" if tool_calls else "stop",
output_tool_calls=tool_calls,
)
)
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
assert len(llm_spans) == 1
return dict(llm_spans[0].attributes or {})
async def test_llm_span_emits_output_tool_call_identity_projections() -> None:
# Proposal 0076 §5.5.10 (mirrors fixture 085): a completion
# requesting two tools emits count / names / ids on the span,
# index-aligned and in request order. The default payload-off
# posture applies, so the gated full serialization is absent.
from openarmature.llm.messages import ToolCall
attrs = await _drive_llm_span_with_tool_calls(
[
ToolCall(id="call_a", name="get_weather", arguments={"city": "NYC"}),
ToolCall(id="call_b", name="get_time", arguments={"tz": "EST"}),
]
)
assert attrs.get("openarmature.llm.output.tool_calls.count") == 2
assert list(attrs.get("openarmature.llm.output.tool_calls.names") or ()) == ["get_weather", "get_time"]
assert list(attrs.get("openarmature.llm.output.tool_calls.ids") or ()) == ["call_a", "call_b"]
assert "openarmature.llm.output.tool_calls" not in attrs
async def test_llm_span_omits_output_tool_calls_when_none_requested() -> None:
# Proposal 0076 (mirrors fixture 086): a completion with no tool
# calls emits NONE of the family — absence means "no tools
# requested", distinct from count = 0 / empty arrays.
attrs = await _drive_llm_span_with_tool_calls([])
for name in (
"openarmature.llm.output.tool_calls",
"openarmature.llm.output.tool_calls.count",
"openarmature.llm.output.tool_calls.names",
"openarmature.llm.output.tool_calls.ids",
):
assert name not in attrs
async def test_llm_span_output_tool_calls_payload_gating() -> None:
# Proposal 0076 §5.5.1 / §5.5.10 (mirrors fixture 087): the identity
# projections are ungated (render with payload off); the gated full
# [{id, name, arguments}] serialization is suppressed with payload
# off and present (carrying the arguments) with payload on.
import json
from openarmature.llm.messages import ToolCall
calls = [ToolCall(id="call_x", name="search_db", arguments={"q": "secret query"})]
off = await _drive_llm_span_with_tool_calls(calls, disable_provider_payload=True)
assert off.get("openarmature.llm.output.tool_calls.count") == 1
assert list(off.get("openarmature.llm.output.tool_calls.names") or ()) == ["search_db"]
assert list(off.get("openarmature.llm.output.tool_calls.ids") or ()) == ["call_x"]
assert "openarmature.llm.output.tool_calls" not in off
on = await _drive_llm_span_with_tool_calls(calls, disable_provider_payload=False)
assert on.get("openarmature.llm.output.tool_calls.count") == 1
assert list(on.get("openarmature.llm.output.tool_calls.names") or ()) == ["search_db"]
assert list(on.get("openarmature.llm.output.tool_calls.ids") or ()) == ["call_x"]
serialized = on.get("openarmature.llm.output.tool_calls")
assert isinstance(serialized, str)
# Parses to the §5.5.5 [{id, name, arguments}] encoding (structure,
# not bytewise — _serialize_for_attribute sorts keys).
assert json.loads(serialized) == [
{"id": "call_x", "name": "search_db", "arguments": {"q": "secret query"}}
]
# ---------------------------------------------------------------------------
# Proposal 0067 — GenAI metrics (observability §11)
# ---------------------------------------------------------------------------
def _collect_metric_points(reader: Any) -> list[tuple[str, float, int, dict[str, Any]]]:
"""Flatten an InMemoryMetricReader's collected data into
``(instrument_name, point_sum, point_count, point_attributes)``
tuples. Histogram observations with identical attribute sets
aggregate into one data point (sum + count), so per-attempt tests
assert on ``count``, not point cardinality."""
data = reader.get_metrics_data()
points: list[tuple[str, float, int, dict[str, Any]]] = []
if data is None:
return points
for resource_metric in data.resource_metrics:
for scope_metric in resource_metric.scope_metrics:
for metric in scope_metric.metrics:
for pt in metric.data.data_points:
points.append((metric.name, pt.sum, pt.count, dict(pt.attributes)))
return points
async def _drive_metrics_events(
events: list[Any],
*,
enable_metrics: bool = True,
disable_llm_spans: bool = False,
) -> tuple[list[tuple[str, float, int, dict[str, Any]]], list[Any]]:
"""Feed LlmRetryAttemptEvents through an OTelObserver wired to a
private MeterProvider + InMemoryMetricReader; return the captured
``(metric_points, llm_complete_spans)``."""
from opentelemetry.sdk.metrics import MeterProvider as SdkMeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from openarmature.observability.correlation import (
_reset_invocation_id,
_set_invocation_id,
)
reader = InMemoryMetricReader()
meter_provider = SdkMeterProvider(metric_readers=[reader])
exporter = InMemorySpanExporter()
observer = OTelObserver(
span_processor=SimpleSpanProcessor(exporter),
enable_metrics=enable_metrics,
disable_llm_spans=disable_llm_spans,
meter_provider=meter_provider,
)
token = _set_invocation_id("inv-metrics")
try:
for event in events:
await observer(event)
finally:
_reset_invocation_id(token)
observer.shutdown()
llm_spans = [s for s in exporter.get_finished_spans() if s.name == "openarmature.llm.complete"]
return _collect_metric_points(reader), llm_spans
async def test_metrics_records_token_and_duration() -> None:
# Proposal 0067 §11 (mirrors fixture 088): a successful LLM attempt
# with usage {input 5, output 1} records two token.usage observations
# (input + output) and one duration observation, with the §11.3
# dimensions. Duration value is not asserted (§11.4).
from openarmature.llm.response import Usage
from tests._helpers.typed_event import make_retry_attempt_event
event = make_retry_attempt_event(
model="test-model",
provider="openai",
latency_ms=12.0,
usage=Usage(prompt_tokens=5, completion_tokens=1, total_tokens=6),
)
points, _ = await _drive_metrics_events([event])
token_points = [p for p in points if p[0] == "openarmature.gen_ai.client.token.usage"]
duration_points = [p for p in points if p[0] == "openarmature.gen_ai.client.operation.duration"]
by_type = {p[3]["openarmature.gen_ai.token.type"]: p for p in token_points}
assert by_type["input"][1] == 5
assert by_type["output"][1] == 1
for ttype in ("input", "output"):
dims = by_type[ttype][3]
assert dims["openarmature.gen_ai.operation"] == "chat"
assert dims["gen_ai.request.model"] == "test-model"
assert dims["gen_ai.system"] == "openai"
assert len(duration_points) == 1
ddims = duration_points[0][3]
assert ddims["openarmature.gen_ai.operation"] == "chat"
assert ddims["gen_ai.request.model"] == "test-model"
assert ddims["gen_ai.system"] == "openai"
assert "error.type" not in ddims
async def test_metrics_records_duration_with_error_type_on_failure() -> None:
# Proposal 0067 §11.2 / §11.3 (mirrors fixture 090): a failed attempt
# records a duration observation carrying error.type, and NO
# token.usage observation (a failed attempt returned no usage).
from tests._helpers.typed_event import make_retry_attempt_event
event = make_retry_attempt_event(
model="test-model",
provider="openai",
latency_ms=8.0,
finish_reason=None,
usage=None,
error_category="provider_unavailable",
error_type="ProviderUnavailable",
error_message="down",
)
points, _ = await _drive_metrics_events([event])
token_points = [p for p in points if p[0] == "openarmature.gen_ai.client.token.usage"]
duration_points = [p for p in points if p[0] == "openarmature.gen_ai.client.operation.duration"]
assert token_points == []
assert len(duration_points) == 1
assert duration_points[0][3]["error.type"] == "provider_unavailable"
assert duration_points[0][3]["openarmature.gen_ai.operation"] == "chat"
async def test_metrics_disabled_records_nothing() -> None:
# Proposal 0067 §11.1 (mirrors fixture 091): enable_metrics off (the
# default) creates no instrument and records nothing.
from openarmature.llm.response import Usage
from tests._helpers.typed_event import make_retry_attempt_event
event = make_retry_attempt_event(usage=Usage(prompt_tokens=5, completion_tokens=1, total_tokens=6))
points, _ = await _drive_metrics_events([event], enable_metrics=False)
assert points == []
async def test_metrics_independent_of_disable_llm_spans() -> None:
# Proposal 0067 §11.1: metrics record even with spans disabled — the
# disable_llm_spans flag governs span emission only.
from openarmature.llm.response import Usage