-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_observability.py
More file actions
5046 lines (4451 loc) · 225 KB
/
Copy pathtest_observability.py
File metadata and controls
5046 lines (4451 loc) · 225 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
"""Run spec observability conformance fixtures (001-011) against OTelObserver.
Driven fixtures:
- **001-basic-trace** — full span shape.
- **002-subgraph-hierarchy** — synthetic dispatch span +
inner-node parenting.
- **003-error-status** — ERROR status mapping for the
``node_exception`` case.
- **005-llm-provider-span-nested** — LLM span +
``disable_llm_spans`` opt-out + TracerProvider isolation.
- **007-retry-attempt-spans** — sibling attempt spans with
per-attempt ``attempt_index`` under retry middleware.
- **008-detached-trace-mode** — detached subgraph
+ detached fan-out + cross-trace ``correlation_id``.
- **009-correlation-id-cross-cutting** — every span
carries ``openarmature.correlation_id``; back-to-back
invocations get distinct UUIDv4s.
- **010-log-correlation** — log records emitted from
inside node bodies pick up the active node span's
``trace_id``/``span_id`` via the engine-side
``prepare_sync`` → OTel context attach pipeline; both nested
and detached-trace cases.
- **011-determinism** — deterministic span content
(hierarchy, names, status, attributes minus the canonical
non-deterministic-by-design list) is identical across runs.
Per-fixture wiring notes live in
``docs/phase-6-1-conformance-fillin.md``.
"""
from __future__ import annotations
import copy
import re
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
import pytest
import yaml
# Skip the entire module if the ``otel`` extras aren't installed —
# importing ``openarmature.observability.otel`` raises ImportError at
# import time when the extras are missing, which would fail
# collection rather than skipping cleanly. Mirrors the pattern in
# ``tests/unit/test_observability_otel.py``.
pytest.importorskip("opentelemetry.sdk.trace")
from openarmature.observability.otel import OTelObserver # noqa: E402
from .adapter import build_graph # noqa: E402
if TYPE_CHECKING:
from opentelemetry.sdk.trace import ReadableSpan
from openarmature.llm.response import RuntimeConfig
# OTel SDK 1.x makes ``set_tracer_provider`` one-shot: once a non-default
# provider is set, subsequent 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. This helper resets
# BOTH the value and the Once via the SDK's private API so a sibling
# test running after this one starts from a clean global state.
def _reset_otel_global_tracer_provider(restore_to: object) -> None:
from opentelemetry import trace as otel_trace
once = otel_trace._TRACER_PROVIDER_SET_ONCE # type: ignore[attr-defined]
with once._lock: # pyright: ignore[reportPrivateUsage]
if isinstance(restore_to, otel_trace.ProxyTracerProvider):
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]
CONFORMANCE_DIR = (
Path(__file__).resolve().parents[2] / "openarmature-spec" / "spec" / "observability" / "conformance"
)
_SUPPORTED_FIXTURES = frozenset(
{
# v0.36.0 — proposal 0044 (parallel-branches OTel dispatch
# span). Asserts the per-branch dispatch span synthesis +
# §5.7 attribute surface end-to-end against a two-branch
# parallel-branches graph with calls_llm in each branch.
"038-otel-parallel-branches-dispatch-span",
# v0.42.0 — proposal 0050 call-level-retry per-attempt LLM span
# surface. Single-attempt default: one span, attempt_index 0.
"057-llm-attempt-index-single-attempt-default",
"001-otel-basic-trace",
"002-otel-subgraph-hierarchy",
"003-otel-error-status",
"004-otel-routing-error-attribution",
"005-otel-llm-provider-span-nested",
"006-otel-fan-out-instance-attribution",
"007-otel-retry-attempt-spans",
"008-otel-detached-trace-mode",
"009-otel-correlation-id-cross-cutting",
"010-otel-log-correlation",
"011-otel-determinism",
# v0.17.0 — proposal 0024 (friction-roundup #1, #2, #6).
"012-otel-llm-payload-default-off",
"013-otel-llm-payload-enabled",
"014-otel-llm-payload-truncation",
"015-otel-llm-payload-image-redaction",
"016-otel-llm-request-params",
"017-otel-llm-request-params-partial",
"018-otel-llm-request-extras",
"019-otel-llm-genai-semconv",
"020-otel-llm-genai-system-override",
"021-otel-llm-disable-genai-semconv",
# v0.24.0 — proposal 0032 (three new declared RuntimeConfig
# fields surfaced as gen_ai.request.* attributes).
"025-otel-llm-request-params-extended",
# v0.10.0 — proposal 0034 (caller-supplied invocation metadata
# cross-cutting on every span). 026 verifies the
# ``openarmature.user.*`` attribute family lands on the
# invocation span, every node span, and the LLM provider span.
"026-otel-caller-supplied-metadata",
# 028 — proposal 0034 API-boundary rejection: caller-supplied
# metadata keys under reserved namespaces (openarmature.*,
# gen_ai.*) MUST raise at the ``invoke()`` boundary before
# any work begins. Two cases (one per reserved prefix).
"028-caller-metadata-namespace-rejection",
# v0.41.0 — proposal 0047 (§5.5.3.1 OA-namespace cache
# attributes). Three fixtures cover cache-hit emission (040),
# absence (041 — no prompt_tokens_details on the wire), and
# reported-zero (042 — distinct from absent).
"040-llm-cache-attribute-emission",
"041-llm-cache-attribute-absence",
"042-llm-cache-attribute-reported-zero",
# v0.41.0 — proposal 0049 (typed LlmCompletionEvent variant on
# the observer event union). Seven fixtures exercise dispatch
# shape (050), type discrimination (051), opt-in caller
# metadata (052), success-only scope on failure paths (053),
# fan_out_index / branch_name population (054 / 055), and
# strict-serial arrival ordering (056).
"050-llm-completion-event-dispatch",
"051-llm-completion-event-type-discrimination",
"052-llm-completion-event-caller-metadata-opt-in",
"053-llm-completion-event-no-event-on-failure",
"054-llm-completion-event-fan-out-index-population",
"055-llm-completion-event-branch-name-population",
"056-llm-completion-event-strict-serial-ordering",
# proposal 0057 LlmCompletionEvent field population (060-068) +
# proposal 0058 LlmFailedEvent (069-073). Driven through the typed-
# event-collector runner (the same machinery as 050-056) plus a
# multi-node-chain variant for 067/071. Fixture-harness catch-up
# tier 1. Four of the family stay unit-tested for now (see
# _UNIT_TESTED_FIXTURES): 066 (corrected >=2-member group ships at spec
# v0.74.1, picked up at the v0.16.0 pin), 069 (asserts a request model
# the fixture doesn't declare), 070 (missing-tool_call_id message is
# non-constructible in python -- enforced at construction, not the
# complete() boundary), 073 (fixture asserts the vendor body error.type
# verbatim, but python's error_type is the OA exception class name).
"060-llm-completion-event-input-messages-populated",
"061-llm-completion-event-output-content-populated",
"062-llm-completion-event-request-params-populated",
"063-llm-completion-event-request-extras-populated",
"064-llm-completion-event-active-prompt-populated",
"065-llm-completion-event-active-prompt-null",
"067-llm-completion-event-call-id-always-present-and-distinct",
"068-llm-completion-event-response-model-distinct-from-request",
"071-llm-failure-event-call-id-distinct-from-completion-event",
"072-llm-failure-event-mutual-exclusion-with-completion-event",
# proposal 0052 attribution fixture (case 1) + proposal 0061
# (case 2: the §5.1 attribution lands on the detached trace's own
# openarmature.invocation span). Wired together now that 0061
# (v0.61.0) resolves the detached-invocation-span shape case 2
# presupposed — the whole fixture was unwired pending that.
"058-implementation-attribution-otel",
# v0.62.0 — proposal 0064 (Langfuse trace.sessionId / trace.userId
# population). Cases 2/3/4 (not session-bound + userId promotion)
# run; session-bound cases 1/5 defer until the sessions capability
# (0020) supplies openarmature.session_id.
"084-langfuse-session-user-promotion",
# v0.67.0 — proposal 0076 (tool-call request observability on the
# LLM span). The model's output tool calls surface as ungated
# identity (count / names / ids) plus a gated full serialization
# on openarmature.llm.complete. Driven through the generic
# LLM-payload fixture runner.
"085-llm-tool-call-request-attributes",
"086-llm-tool-call-request-absent",
"087-llm-tool-call-request-survives-payload-gating",
# v0.68.0 — proposal 0067 (GenAI metrics, observability §11). The
# LLM-path fixtures: token + duration histograms (088), error.type
# on duration (090), and the enable_metrics-off no-op (091).
# Captured via a private MeterProvider + InMemoryMetricReader (the
# §6.9 metric-capture primitive). 089 (embeddings) is deferred.
"088-llm-metrics-token-and-duration",
"090-metrics-error-type-on-duration",
"091-metrics-disabled-no-measurements",
# v0.69.0 — proposal 0063 (tool-execution observability). A
# calls_tool node enters the with_tool_call scope; the typed
# ToolCallEvent / ToolCallFailedEvent drive the OTel tool span +
# the Langfuse Tool observation.
"092-tool-call-event-dispatch",
"093-tool-call-failed-event-dispatch",
"094-tool-call-event-mutual-exclusion",
"095-tool-call-id-links-to-llm-request",
"096-tool-call-payload-gating",
"097-otel-tool-span-attributes",
"098-langfuse-tool-observation",
# v0.70.1 — proposal 0075 callable-branch span shape (observability
# §5.7). The ORIGINAL fixture 110 (span shape + skip-emits-no-span);
# the branch_count assertion arrives with the v0.73.1 pin (v0.16.0).
"110-otel-callable-branch-span",
}
)
_EMBEDDING_DEFER = (
"embedding capability (proposal 0059) unimplemented until v0.16.0; "
"no embedding event/provider to record from"
)
_RERANK_DEFER = (
"rerank capability (proposal 0060) unimplemented until v0.16.0; no rerank event/provider to record from"
)
# Pinned observability fixtures NOT run by this YAML harness, each with an
# explicit reason. The coverage guard (test_observability_fixture_coverage_
# is_complete) fails on any pinned fixture absent from _SUPPORTED_FIXTURES +
# the three sets below, so a future unwired spec fixture cannot silently
# pytest.skip past CI.
#
# _DEFERRED_FIXTURES — not run because the capability is unimplemented.
_DEFERRED_FIXTURES: dict[str, str] = {
# Proposal 0045 IS implemented (v0.11.0), but the nested-case Langfuse
# fixture stays deferred: it needs runtime-state item-list lookup for
# nested fan-outs plus an augment_metadata_from_outer_item directive
# the harness doesn't model yet.
"039-nested-lineage-augmentation": (
"nested-case Langfuse harness wiring not yet implemented (proposal 0045 nested fan-out)"
),
# Embedding observability (proposals 0059 / 0067 §11). The embedding
# capability is unshipped until v0.16.0; the LLM-path equivalents run.
**{
fixture_id: _EMBEDDING_DEFER
for fixture_id in (
"074-embedding-event-dispatch",
"075-embedding-failure-event-dispatch-on-provider-unavailable",
"076-embedding-event-mutual-exclusion",
"077-embedding-event-call-id-distinct",
"078-embedding-event-input-strings-populated",
"079-embedding-event-request-params-populated",
"080-embedding-event-input-count-and-dimensions-populated",
"081-embedding-event-active-prompt-populated",
"082-otel-embedding-span-attributes",
"083-langfuse-embedding-observation",
"089-embedding-metrics-token-and-duration",
)
},
# Rerank observability (proposal 0060, v0.70.0). The rerank protocol is
# unshipped in python until v0.16.0; no rerank provider/event exists.
**{
fixture_id: _RERANK_DEFER
for fixture_id in (
"099-rerank-event-dispatch",
"100-rerank-failure-event-dispatch-on-provider-unavailable",
"101-rerank-event-mutual-exclusion",
"102-rerank-event-call-id-distinct",
"103-rerank-event-query-and-documents-populated",
"104-rerank-event-request-params-populated",
"105-rerank-event-top-k-and-result-count-populated",
"106-rerank-event-active-prompt-populated",
"107-otel-rerank-span-attributes",
"108-langfuse-rerank-observation",
"109-rerank-metrics-token-and-duration",
)
},
}
# _LANGFUSE_HARNESS_FIXTURES — Langfuse-mapping fixtures fixture-tested by the
# sibling conformance runner tests/conformance/test_observability_langfuse.py
# (NOT unit tests). They are skipped here and asserted there; the coverage guard
# counts them as accounted. 035/036 (invocation-id) + 059 (attribution) were
# relocated here from this file by the fixture-harness catch-up; 029 (fan-out
# per-instance) was un-deferred into the sibling runner the same way.
_LANGFUSE_HARNESS_FIXTURES: frozenset[str] = frozenset(
{
"022-langfuse-basic-trace",
"023-langfuse-generation-rendering",
"024-langfuse-prompt-linkage",
"027-langfuse-caller-supplied-metadata",
"029-caller-metadata-fan-out-per-instance",
"031-langfuse-subgraph-span-hierarchy",
"032-langfuse-fan-out-per-instance-spans",
"033-langfuse-detached-trace-mode",
"034-caller-metadata-open-span-update-serial",
"035-caller-invocation-id-uuid",
"036-caller-invocation-id-non-uuid",
"037-langfuse-trace-input-output",
"059-implementation-attribution-langfuse",
}
)
# _UNIT_TESTED_FIXTURES — implemented behavior covered by the dedicated unit
# suite rather than wired into this YAML harness. Value names the proposal +
# the covering file.
_UNIT_TESTED_FIXTURES: dict[str, str] = {
fixture_id: reason
for fixture_ids, reason in (
# The Langfuse-mapping fixtures are fixture-tested by the sibling
# conformance runner test_observability_langfuse.py -- see
# _LANGFUSE_HARNESS_FIXTURES, NOT here (they are not unit-only). 030 stays
# below: deferred in that file (needs a LangfuseObserver per-branch
# dispatch-span src change), unit-tested for now.
(
("030-caller-metadata-parallel-branches-per-branch",),
"proposal 0040 per-branch caller metadata; covered by "
"test_observability_otel.py; deferred in test_observability_langfuse.py",
),
(
(
"043-get-invocation-metadata-roundtrip",
"044-get-invocation-metadata-fan-out-scoping",
"045-get-invocation-metadata-retry-scoping",
"046-get-invocation-metadata-outside-invocation",
),
"proposal 0048 get_invocation_metadata; covered by test_observability_metadata.py",
),
# Fixture-harness catch-up tier 1 wired the rest of the 0057/0058
# family into _SUPPORTED_FIXTURES; these three stay here, each blocked
# on a spec-side fixture change that python picks up at the v0.16.0 pin
# bump.
(
("066-llm-completion-event-active-prompt-group-populated",),
# At the current v0.70.1 pin the fixture's group has a single
# member, which python's PromptGroup (prompt-management §10,
# >=2 members) correctly rejects. The corrected >=2-member fixture
# ships at spec v0.74.1; wire it with the v0.16.0 pin bump.
"proposal 0057 active_prompt_group; corrected >=2-member fixture "
"ships at spec v0.74.1, wired with the v0.16.0 pin bump; covered by "
"test_llm_provider.py",
),
(
("069-llm-failure-event-dispatch-on-provider-unavailable",),
# Asserts model "gpt-test" on the failed event but declares no
# request-side model the harness can bind (no calls_llm.model, and
# the 503 body carries no model). Needs a spec fixture fix to
# declare the request model, cf. 068.
"proposal 0058 LlmFailedEvent; fixture asserts a request model it "
"doesn't declare; covered by test_llm_provider.py",
),
(
("070-llm-failure-event-dispatch-on-provider-invalid-request",),
# The fixture's malformed message (tool role, no tool_call_id) is
# non-constructible in python: ToolMessage.tool_call_id is a required
# field, so the "MUST be present" rule (llm-provider §3) is enforced
# at construction, not the complete() boundary. python drives
# provider_invalid_request via the unmatched-tool_call_id shape.
"proposal 0058 provider_invalid_request; fixture's missing-"
"tool_call_id message is non-constructible in python; covered by "
"test_llm_provider.py",
),
(
("073-llm-failure-event-error-type-vendor-specific",),
# The fixture asserts the vendor body ``error.type`` verbatim per
# case (rate_limit_exceeded / RateLimitError) plus a null case.
# python deliberately sources error_type from the OA exception
# class name (e.g. "ProviderRateLimit") -- a spec-permitted
# "exception class name" style, but it never echoes the body type
# nor emits null. The behavior is contract-conformant; the fixture
# over-constrains beyond the permissive field contract.
"proposal 0058 LlmFailedEvent.error_type; python uses the exception "
"class name, the fixture asserts the vendor body error.type; covered "
"by test_llm_provider.py",
),
)
for fixture_id in fixture_ids
}
# _CONVENTION_ONLY_FIXTURES — proposal 0048 §9 queryable-observer pattern is
# convention-only (no new abstract surface on Observer), satisfied via
# docs/concepts/observability.md, so there is no library API to assert.
_CONVENTION_ONLY_FIXTURES: dict[str, str] = {
fixture_id: (
"proposal 0048 §9 queryable-observer pattern is convention-only "
"(no library surface); satisfied by docs/concepts/observability.md"
)
for fixture_id in (
"047-queryable-observer-pattern",
"048-queryable-observer-async-safety",
"049-queryable-observer-lifecycle-drop",
)
}
# UUIDv4 canonical form: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx (where y in {8,9,a,b}).
_UUIDV4_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
re.IGNORECASE,
)
def _fixture_paths() -> list[Path]:
return sorted(CONFORMANCE_DIR.glob("[0-9][0-9][0-9]-*.yaml"))
def _fixture_id(path: Path) -> str:
return path.stem
def _load(path: Path) -> dict[str, Any]:
with path.open() as f:
return cast("dict[str, Any]", yaml.safe_load(f))
def test_observability_fixture_coverage_is_complete() -> None:
# Fail-on-unknown guard. Every pinned observability conformance fixture
# MUST be either run (_SUPPORTED_FIXTURES) or explicitly accounted for:
# _DEFERRED_FIXTURES (future capability), _UNIT_TESTED_FIXTURES (covered
# by the unit suite, not this YAML harness), or _CONVENTION_ONLY_FIXTURES
# (doc-satisfied, no library surface). A new spec fixture that is none of
# these fails HERE rather than silently pytest.skip-ping past CI.
all_ids = {p.stem for p in _fixture_paths()}
accounted = (
set(_SUPPORTED_FIXTURES)
| _DEFERRED_FIXTURES.keys()
| _UNIT_TESTED_FIXTURES.keys()
| _CONVENTION_ONLY_FIXTURES.keys()
| _LANGFUSE_HARNESS_FIXTURES
)
unaccounted = sorted(all_ids - accounted)
assert not unaccounted, (
"unaccounted observability conformance fixtures: wire each into "
"_SUPPORTED_FIXTURES once it runs, or document it in _DEFERRED_FIXTURES "
"(future capability) / _UNIT_TESTED_FIXTURES (covered by the unit suite) "
f"/ _CONVENTION_ONLY_FIXTURES (doc-satisfied): {unaccounted}"
)
# An accounting entry whose fixture no longer exists on disk (renamed at
# a pin bump) should be removed.
stale = sorted(accounted - all_ids)
assert not stale, f"accounting entries with no fixture file (remove): {stale}"
# A fixture cannot be both run and documented-as-not-run.
not_run = (
_DEFERRED_FIXTURES.keys()
| _UNIT_TESTED_FIXTURES.keys()
| _CONVENTION_ONLY_FIXTURES.keys()
| _LANGFUSE_HARNESS_FIXTURES
)
overlap = sorted(set(_SUPPORTED_FIXTURES) & not_run)
assert not overlap, f"fixtures both run and documented-as-not-run (pick one): {overlap}"
# ---------------------------------------------------------------------------
# Per-fixture dispatcher
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("fixture_path", _fixture_paths(), ids=_fixture_id)
async def test_observability_fixture(fixture_path: Path) -> None:
fixture_id = fixture_path.stem
if fixture_id in _LANGFUSE_HARNESS_FIXTURES:
pytest.skip(f"{fixture_id}: fixture-tested by tests/conformance/test_observability_langfuse.py")
skip_reason = (
_DEFERRED_FIXTURES.get(fixture_id)
or _UNIT_TESTED_FIXTURES.get(fixture_id)
or _CONVENTION_ONLY_FIXTURES.get(fixture_id)
)
if skip_reason is not None:
pytest.skip(f"{fixture_id}: {skip_reason}")
if fixture_id not in _SUPPORTED_FIXTURES:
# Unaccounted: neither wired nor documented. The coverage guard
# (test_observability_fixture_coverage_is_complete) fails loudly
# listing every such fixture; the individual case skips here.
pytest.skip(f"{fixture_id}: unaccounted -- see the coverage guard")
spec = _load(fixture_path)
if fixture_id == "001-otel-basic-trace":
await _run_fixture_001(spec)
elif fixture_id == "002-otel-subgraph-hierarchy":
await _run_fixture_002(spec)
elif fixture_id == "003-otel-error-status":
await _run_fixture_003(spec)
elif fixture_id == "004-otel-routing-error-attribution":
await _run_fixture_004(spec)
elif fixture_id == "005-otel-llm-provider-span-nested":
await _run_fixture_005(spec)
elif fixture_id == "006-otel-fan-out-instance-attribution":
await _run_fixture_006(spec)
elif fixture_id == "007-otel-retry-attempt-spans":
await _run_fixture_007(spec)
elif fixture_id == "008-otel-detached-trace-mode":
await _run_fixture_008(spec)
elif fixture_id == "009-otel-correlation-id-cross-cutting":
await _run_fixture_009(spec)
elif fixture_id == "010-otel-log-correlation":
await _run_fixture_010(spec)
elif fixture_id == "011-otel-determinism":
await _run_fixture_011(spec)
elif fixture_id == "028-caller-metadata-namespace-rejection":
await _run_fixture_028(spec)
elif fixture_id == "038-otel-parallel-branches-dispatch-span":
await _run_fixture_038(spec)
elif fixture_id == "110-otel-callable-branch-span":
await _run_fixture_110(spec)
elif fixture_id in {
"040-llm-cache-attribute-emission",
"041-llm-cache-attribute-absence",
"042-llm-cache-attribute-reported-zero",
}:
await _run_llm_cache_fixture(spec)
elif fixture_id == "050-llm-completion-event-dispatch":
await _run_fixture_050(spec)
elif fixture_id == "051-llm-completion-event-type-discrimination":
await _run_fixture_051(spec)
elif fixture_id == "052-llm-completion-event-caller-metadata-opt-in":
await _run_fixture_052(spec)
elif fixture_id == "053-llm-completion-event-no-event-on-failure":
await _run_fixture_053(spec)
elif fixture_id == "054-llm-completion-event-fan-out-index-population":
await _run_fixture_054(spec)
elif fixture_id == "055-llm-completion-event-branch-name-population":
await _run_fixture_055(spec)
elif fixture_id == "056-llm-completion-event-strict-serial-ordering":
await _run_fixture_056(spec)
elif fixture_id in {
"060-llm-completion-event-input-messages-populated",
"061-llm-completion-event-output-content-populated",
"062-llm-completion-event-request-params-populated",
"063-llm-completion-event-request-extras-populated",
"064-llm-completion-event-active-prompt-populated",
"065-llm-completion-event-active-prompt-null",
"068-llm-completion-event-response-model-distinct-from-request",
}:
await _run_typed_event_cases(spec)
elif fixture_id == "072-llm-failure-event-mutual-exclusion-with-completion-event":
await _run_typed_event_cases(spec, expect_failure=True)
elif fixture_id == "067-llm-completion-event-call-id-always-present-and-distinct":
await _run_typed_event_chain_cases(spec)
elif fixture_id == "071-llm-failure-event-call-id-distinct-from-completion-event":
await _run_typed_event_chain_cases(spec, expect_failure=True)
elif fixture_id == "058-implementation-attribution-otel":
await _run_fixture_058(spec)
elif fixture_id == "084-langfuse-session-user-promotion":
await _run_fixture_084(spec)
elif fixture_id in {
"012-otel-llm-payload-default-off",
"013-otel-llm-payload-enabled",
"014-otel-llm-payload-truncation",
"015-otel-llm-payload-image-redaction",
"016-otel-llm-request-params",
"017-otel-llm-request-params-partial",
"018-otel-llm-request-extras",
"019-otel-llm-genai-semconv",
"020-otel-llm-genai-system-override",
"021-otel-llm-disable-genai-semconv",
"025-otel-llm-request-params-extended",
"026-otel-caller-supplied-metadata",
"057-llm-attempt-index-single-attempt-default",
"085-llm-tool-call-request-attributes",
"086-llm-tool-call-request-absent",
"087-llm-tool-call-request-survives-payload-gating",
}:
await _run_llm_payload_fixture(spec)
elif fixture_id in {
"088-llm-metrics-token-and-duration",
"090-metrics-error-type-on-duration",
"091-metrics-disabled-no-measurements",
}:
await _run_metrics_fixture(spec)
elif fixture_id in {
"092-tool-call-event-dispatch",
"093-tool-call-failed-event-dispatch",
"094-tool-call-event-mutual-exclusion",
"095-tool-call-id-links-to-llm-request",
"096-tool-call-payload-gating",
"097-otel-tool-span-attributes",
"098-langfuse-tool-observation",
}:
await _run_tool_fixture(spec)
else:
raise AssertionError(f"no driver for supported fixture {fixture_id!r}")
# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------
def _build_observer() -> tuple[OTelObserver, Any]:
"""Build a fresh OTelObserver + InMemorySpanExporter pair."""
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
InMemorySpanExporter,
)
exporter = InMemorySpanExporter()
observer = OTelObserver(span_processor=SimpleSpanProcessor(exporter))
return observer, exporter
async def _run_graph(
spec: Mapping[str, Any],
observer: OTelObserver,
*,
correlation_id: str | None = None,
) -> Any:
"""Build + invoke a graph from a fixture spec; return the final
state. Caller is responsible for calling ``observer.shutdown()``
afterwards."""
trace: list[str] = []
built = build_graph(spec, trace=trace)
compiled = built.builder.compile()
compiled.attach_observer(observer)
initial_state = built.initial_state(spec.get("initial_state", {}))
final = await compiled.invoke(initial_state, correlation_id=correlation_id)
await compiled.drain()
return final
def _all_correlation_ids(spans: Any) -> set[str]:
"""Pull the ``openarmature.correlation_id`` attribute off every
span; returns the unique set. Accepts any iterable of spans
(``InMemorySpanExporter.get_finished_spans`` returns a tuple)."""
return {cast("str", dict(s.attributes or {}).get("openarmature.correlation_id")) for s in spans}
# ---------------------------------------------------------------------------
# Fixture 001 — basic trace shape
# ---------------------------------------------------------------------------
async def _run_fixture_001(spec: Mapping[str, Any]) -> None:
observer, exporter = _build_observer()
final = await _run_graph(spec, observer, correlation_id=spec.get("caller_correlation_id"))
observer.shutdown()
spans = exporter.get_finished_spans()
assert len(spans) == 4, (
f"expected 4 spans (invocation + 3 nodes); got {len(spans)}: {[s.name for s in spans]}"
)
by_name = {s.name: s for s in spans}
assert "openarmature.invocation" in by_name
inv = by_name["openarmature.invocation"]
assert inv.parent is None
inv_attrs = dict(inv.attributes or {})
assert inv_attrs.get("openarmature.graph.entry_node") == spec["entry"]
cid = inv_attrs.get("openarmature.correlation_id")
assert isinstance(cid, str) and len(cid) > 0
inv_ctx = inv.context
assert inv_ctx is not None
invocation_span_id = inv_ctx.span_id
for node_name in spec["nodes"]:
assert node_name in by_name, f"missing span for {node_name!r}"
node_span = by_name[node_name]
node_parent = node_span.parent
assert node_parent is not None and node_parent.span_id == invocation_span_id
node_attrs = dict(node_span.attributes or {})
assert node_attrs.get("openarmature.node.name") == node_name
assert list(node_attrs.get("openarmature.node.namespace") or []) == [node_name]
assert isinstance(node_attrs.get("openarmature.node.step"), int)
assert node_attrs.get("openarmature.node.attempt_index") == 0
assert node_attrs.get("openarmature.correlation_id") == cid
expected_trace = ["a", "b", "c"]
assert final.trace == expected_trace # type: ignore[attr-defined]
# ---------------------------------------------------------------------------
# Fixture 002 — subgraph hierarchy
# ---------------------------------------------------------------------------
async def _run_fixture_002(spec: Mapping[str, Any]) -> None:
"""The subgraph wrapper synthesizes a dispatch span;
inner-node spans parent under it; the dispatch span parents
under the invocation."""
observer, exporter = _build_observer()
subgraphs = _compile_subgraphs(spec)
trace_log: list[str] = []
built = build_graph(spec, subgraphs=subgraphs, trace=trace_log)
compiled = built.builder.compile()
compiled.attach_observer(observer)
initial_state = built.initial_state(spec.get("initial_state", {}))
await compiled.invoke(initial_state)
await compiled.drain()
observer.shutdown()
spans = exporter.get_finished_spans()
by_name: dict[str, list[Any]] = {}
for s in spans:
by_name.setdefault(s.name, []).append(s)
# Invocation span at the root.
inv_list = by_name.get("openarmature.invocation") or []
assert len(inv_list) == 1, f"expected 1 invocation span; got {len(inv_list)}"
inv = inv_list[0]
assert inv.parent is None
assert inv.context is not None
invocation_span_id = inv.context.span_id
# Top-level outer nodes parent under invocation.
for outer_node in ("outer_in", "outer_out"):
outer_spans = by_name.get(outer_node) or []
assert len(outer_spans) == 1, f"expected 1 span for {outer_node!r}; got {len(outer_spans)}"
node = outer_spans[0]
assert node.parent is not None and node.parent.span_id == invocation_span_id, (
f"{outer_node!r} MUST parent under invocation span"
)
# The subgraph wrapper synthesizes a dispatch span at namespace
# ("outer_sub",); its parent is the invocation span.
sub_dispatch_spans = by_name.get("outer_sub") or []
assert len(sub_dispatch_spans) == 1, (
f"expected 1 synthetic subgraph dispatch span for outer_sub; got {len(sub_dispatch_spans)}"
)
sub_dispatch = sub_dispatch_spans[0]
assert sub_dispatch.parent is not None and sub_dispatch.parent.span_id == invocation_span_id, (
"subgraph dispatch span MUST parent under the invocation span per §4.5"
)
assert sub_dispatch.context is not None
sub_dispatch_id = sub_dispatch.context.span_id
sub_dispatch_attrs = dict(sub_dispatch.attributes or {})
# Per observability §5.3 + coord thread `clarify-subgraph-name-
# semantics` Option A: `openarmature.subgraph.name` carries the
# compiled subgraph's identity, NOT the wrapper node name. The
# conformance adapter sets ``subgraph_identity = "inner"`` when
# compiling the fixture's ``subgraph: { name: inner }`` block.
assert sub_dispatch_attrs.get("openarmature.subgraph.name") == "inner"
# Inner-node spans parent under the subgraph dispatch span and
# carry the nested namespace.
for inner_node in ("inner_x", "inner_y"):
inner_spans = by_name.get(inner_node) or []
assert len(inner_spans) == 1, f"expected 1 span for {inner_node!r}; got {len(inner_spans)}"
inner = inner_spans[0]
assert inner.parent is not None and inner.parent.span_id == sub_dispatch_id, (
f"{inner_node!r} MUST parent under the subgraph dispatch span per §4.5"
)
inner_attrs = dict(inner.attributes or {})
assert list(inner_attrs.get("openarmature.node.namespace") or []) == ["outer_sub", inner_node], (
f"{inner_node!r} namespace MUST be ['outer_sub', '{inner_node}']; got "
f"{inner_attrs.get('openarmature.node.namespace')!r}"
)
# ---------------------------------------------------------------------------
# Fixture 003 — error status mapping (node_exception case)
# ---------------------------------------------------------------------------
async def _run_fixture_003(spec: Mapping[str, Any]) -> None:
"""A node-exception failure produces an ERROR span
with the canonical category in the description, an exception
event recorded, and the ``openarmature.error.category``
attribute. Sibling spans before the failure stay OK; the
invocation span ends ERROR (OTel doesn't auto-propagate child
status to parents, so the OTelObserver explicitly sets ERROR
on the invocation span when any child errors per
``_handle_completed``)."""
from opentelemetry.trace import StatusCode
from openarmature.graph import RuntimeGraphError
observer, exporter = _build_observer()
trace_log: list[str] = []
built = build_graph(spec, trace=trace_log)
compiled = built.builder.compile()
compiled.attach_observer(observer)
initial_state = built.initial_state(spec.get("initial_state", {}))
with pytest.raises(RuntimeGraphError):
await compiled.invoke(initial_state)
await compiled.drain()
observer.shutdown()
spans = exporter.get_finished_spans()
by_name = {s.name: s for s in spans}
ok_node = by_name.get("ok_node")
assert ok_node is not None
assert ok_node.status.status_code == StatusCode.OK, (
f"ok_node status MUST be OK; got {ok_node.status.status_code}"
)
fail_node = by_name.get("fail_node")
assert fail_node is not None
assert fail_node.status.status_code == StatusCode.ERROR, (
f"fail_node status MUST be ERROR; got {fail_node.status.status_code}"
)
assert fail_node.status.description == "node_exception", (
f"fail_node status_description MUST be 'node_exception'; got {fail_node.status.description!r}"
)
fail_attrs = dict(fail_node.attributes or {})
assert fail_attrs.get("openarmature.error.category") == "node_exception"
# Exception event recorded on the span via record_exception.
exception_events = [e for e in fail_node.events if e.name == "exception"]
event_names = [e.name for e in fail_node.events]
assert len(exception_events) >= 1, (
f"fail_node MUST have at least one 'exception' event recorded; got {event_names}"
)
# Invocation span ends ERROR when any child errors per spec
# §4.2 / fixture 003. The OTelObserver sets ERROR explicitly in
# ``_handle_completed`` (OTel doesn't auto-propagate child status
# to parents).
inv = by_name.get("openarmature.invocation")
assert inv is not None
assert inv.status.status_code == StatusCode.ERROR, (
f"invocation span status MUST be ERROR when a child errored; got {inv.status.status_code}"
)
# ---------------------------------------------------------------------------
# Fixture 004 — routing-error attribution (proposal 0012 / spec v0.9.0)
# ---------------------------------------------------------------------------
async def _run_fixture_004(spec: Mapping[str, Any]) -> None:
"""Routing errors land on the preceding node's ``completed`` event
with ``error`` populated
(sharing the started/completed pair rather than producing a
separate one). The OTel observer's existing
``_handle_completed`` ERROR-mapping path picks this up
automatically — no observer-side change needed for the swap.
Driver verifies: the ``pick`` node's span ends ERROR with
``status_description == "routing_error"``, an ``exception``
event recorded, and the ``openarmature.error.category``
attribute. No span for the edge function (no ``edge_spans``) —
edge logic is folded into the preceding node span."""
from opentelemetry.trace import StatusCode
from openarmature.graph import RuntimeGraphError
observer, exporter = _build_observer()
trace_log: list[str] = []
built = build_graph(spec, trace=trace_log)
compiled = built.builder.compile()
compiled.attach_observer(observer)
initial_state = built.initial_state(spec.get("initial_state", {}))
with pytest.raises(RuntimeGraphError) as excinfo:
await compiled.invoke(initial_state)
assert excinfo.value.category == "routing_error"
await compiled.drain()
observer.shutdown()
spans = exporter.get_finished_spans()
by_name = {s.name: s for s in spans}
pick = by_name.get("pick")
assert pick is not None
assert pick.status.status_code == StatusCode.ERROR, (
f"preceding node 'pick' span MUST be ERROR; got {pick.status.status_code}"
)
assert pick.status.description == "routing_error", (
f"preceding node 'pick' span status_description MUST be 'routing_error'; "
f"got {pick.status.description!r}"
)
pick_attrs = dict(pick.attributes or {})
assert pick_attrs.get("openarmature.error.category") == "routing_error"
# Exception event recorded on the span via record_exception.
exception_events = [e for e in pick.events if e.name == "exception"]
event_names = [e.name for e in pick.events]
assert len(exception_events) >= 1, (
f"'pick' MUST have at least one 'exception' event recorded; got {event_names}"
)
# Per fixture 004's "no_edge_spans: true" — the edge function
# itself does not produce a separate span; the routing error is
# folded into the preceding node's span.
edge_span_names = {"edge", "openarmature.edge", "edge_function"}
edge_spans = [s for s in spans if s.name in edge_span_names]
assert edge_spans == [], (
f"there MUST be no separate edge-function spans per §4.2; got {[s.name for s in edge_spans]}"
)
# Unreachable nodes never fire spans (they were unreached).
for unreachable in ("unreachable_a", "unreachable_b"):
assert unreachable not in by_name, f"{unreachable!r} MUST not produce a span — never reached"
# Invocation span ends ERROR per the §4.2 invocation-status
# propagation contract.
inv = by_name.get("openarmature.invocation")
assert inv is not None
assert inv.status.status_code == StatusCode.ERROR, (
f"invocation span MUST end ERROR when a child errors; got {inv.status.status_code}"
)
# ---------------------------------------------------------------------------
# Fixture 007 — retry attempt spans
# ---------------------------------------------------------------------------
async def _run_fixture_006(spec: Mapping[str, Any]) -> None:
"""Non-detached fan-out instances synthesize per-instance dispatch
spans nested between
the fan-out node span and the inner-node spans. The fan-out node
span carries ``item_count`` / ``concurrency`` / ``error_policy``
from ``NodeEvent.fan_out_config``; per-instance spans carry
``fan_out_index`` and ``parent_node_name``."""
# Subgraphs declared at the spec level (outside ``cases:``) — the
# ``worker`` subgraph used by every case in this fixture lives
# there. Compile once and reuse across cases.
_patch_unsupported_directives(spec)
subgraphs = _compile_subgraphs(spec)
cases = cast("list[dict[str, Any]]", spec["cases"])
for case in cases:
case_name = cast("str", case["name"])
try:
await _run_fixture_006_case(case, subgraphs)
except AssertionError as e:
raise AssertionError(f"case {case_name!r}: {e}") from e
async def _run_fixture_006_case(case: Mapping[str, Any], subgraphs: Mapping[str, Any]) -> None:
_patch_unsupported_directives(case)
observer, exporter = _build_observer()
trace_log: list[str] = []
built = build_graph(case, subgraphs=dict(subgraphs), trace=trace_log)
compiled = built.builder.compile()
compiled.attach_observer(observer)
initial_state = built.initial_state(case.get("initial_state", {}))
await compiled.invoke(initial_state)
await compiled.drain()
observer.shutdown()
spans = exporter.get_finished_spans()
# Span-tree shape per fixture:
# invocation
# └─ process (fan-out NODE) — item_count=3, concurrency=2, error_policy="collect"
# ├─ process (instance, fan_out_index=0) — parent_node_name="process"
# │ └─ compute
# ├─ process (instance, fan_out_index=1) — parent_node_name="process"
# │ └─ compute
# └─ process (instance, fan_out_index=2) — parent_node_name="process"
# └─ compute
process_spans = [s for s in spans if s.name == "process"]
# Expect 4: 1 fan-out node + 3 per-instance dispatch spans.
assert len(process_spans) == 4, (
f"expected 4 'process' spans (1 fan-out node + 3 per-instance dispatch); got {len(process_spans)}"
)
# Fan-out node span carries the three §5.4 attributes.
fan_out_node_spans = [
s
for s in process_spans
if dict(s.attributes or {}).get("openarmature.fan_out.item_count") is not None
]
assert len(fan_out_node_spans) == 1, (
f"expected exactly 1 fan-out NODE span (with item_count attribute); got {len(fan_out_node_spans)}"
)
fan_out_node_span = fan_out_node_spans[0]
fan_out_attrs = dict(fan_out_node_span.attributes or {})
assert fan_out_attrs.get("openarmature.fan_out.item_count") == 3
assert fan_out_attrs.get("openarmature.fan_out.concurrency") == 2
assert fan_out_attrs.get("openarmature.fan_out.error_policy") == "collect"
# Per-instance dispatch spans: 3 of them, each with
# fan_out_index 0..2 and parent_node_name "process".
per_instance_spans = [s for s in process_spans if s != fan_out_node_span]
assert len(per_instance_spans) == 3
fan_out_indices: set[int] = set()
for s in per_instance_spans:
attrs = dict(s.attributes or {})
idx = attrs.get("openarmature.node.fan_out_index")
assert isinstance(idx, int), f"per-instance span MUST carry fan_out_index; got attrs={attrs}"
fan_out_indices.add(idx)
assert attrs.get("openarmature.fan_out.parent_node_name") == "process", (
f"per-instance span MUST carry parent_node_name='process'; got {attrs}"
)
# Each per-instance dispatch span parents under the fan-out
# node span (proposal 0013 + §5.4 nesting).
assert s.parent is not None and s.parent.span_id == fan_out_node_span.context.span_id, (
"per-instance dispatch span MUST parent under the fan-out node span"
)
assert fan_out_indices == {0, 1, 2}, (
f"per-instance fan_out_index range MUST be 0..2; got {sorted(fan_out_indices)}"
)
# Each per-instance dispatch span has a 'compute' child (the
# inner-node work).
per_instance_ids = {s.context.span_id for s in per_instance_spans}
compute_spans = [s for s in spans if s.name == "compute"]
assert len(compute_spans) == 3, f"expected 3 compute spans; got {len(compute_spans)}"
for cs in compute_spans:
assert cs.parent is not None and cs.parent.span_id in per_instance_ids, (
"compute span MUST parent under a per-instance dispatch span"
)
async def _run_fixture_007(spec: Mapping[str, Any]) -> None:
"""Two sub-cases:
1. ``three_attempts_third_succeeds`` — retry succeeds on
attempt 2; expect 3 sibling attempt spans (ERROR, ERROR, OK).
2. ``retry_exhausts_all_three_spans_error`` — retry exhausts;
expect 3 sibling attempt spans (all ERROR); invoke raises.