-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_observability_langfuse.py
More file actions
1949 lines (1759 loc) · 91.4 KB
/
Copy pathtest_observability_langfuse.py
File metadata and controls
1949 lines (1759 loc) · 91.4 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 §8): drives the Langfuse mapping
# fixtures (022 basic-trace, 023 generation-rendering, 024
# prompt-linkage) against the in-memory LangfuseObserver client.
# Sibling of test_observability.py (OTel mapping); shares no harness
# state with the OTel side — each fixture builds its own graph +
# observer instance.
#
# The harness also supports the graph-topology shapes used by
# 031/032/033 (subgraph / fan-out / detached-trace) via the
# cross-capability adapter.build_graph helper, but activation of
# those three fixtures is currently deferred — see the
# `_LANGFUSE_FIXTURES` frozenset comment for the gating questions.
"""Run spec observability Langfuse conformance fixtures."""
from __future__ import annotations
import copy
import json
from collections.abc import Callable, Mapping, Sequence
from contextvars import ContextVar
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, cast
import httpx
import pytest
import yaml
from openarmature.graph import END, BranchSpec, ExplicitMapping, GraphBuilder
from openarmature.llm import OpenAIProvider
from openarmature.llm.response import RuntimeConfig
from openarmature.observability.langfuse import (
InMemoryLangfuseClient,
LangfuseObservation,
LangfuseObserver,
LangfuseTrace,
)
from openarmature.prompts import (
Prompt,
PromptManager,
SamplingConfig,
TextPrompt,
TokenBudget,
)
from openarmature.prompts.context import with_active_prompt
from .adapter import build_graph, build_state_cls
CONFORMANCE_DIR = (
Path(__file__).resolve().parents[2] / "openarmature-spec" / "spec" / "observability" / "conformance"
)
_LANGFUSE_FIXTURES = frozenset(
{
"022-langfuse-basic-trace",
"023-langfuse-generation-rendering",
"024-langfuse-prompt-linkage",
# 027 — proposal 0034 (caller-supplied metadata propagation
# into ``trace.metadata`` + every ``observation.metadata``
# per §8.4.1 + §8.4.2).
"027-langfuse-caller-supplied-metadata",
# 031 / 032 / 033 — proposal 0035. Activated against spec
# v0.27.1, which patched the two fixture-vs-impl ambiguities
# raised in coord thread `clarify-subgraph-name-semantics`
# (msg 04): fixture 031's `outer_out` step corrected 2 → 3
# (graph-engine §6 shared-counter), and fixture 033's
# detached-trace inner namespace corrected to the wrapper
# node name (`["dispatch", "step"]`). The Option A
# subgraph_identity wiring on main satisfies both.
"031-langfuse-subgraph-span-hierarchy",
"032-langfuse-fan-out-per-instance-spans",
"033-langfuse-detached-trace-mode",
# 034 — proposal 0040 outermost-serial open-span update.
# Single-node graph; the ``augment_metadata`` directive on
# the node body injects a ``set_invocation_metadata`` call
# before the LLM call, exercising the §3.4 MUST that open
# spans in the augmenting context's lineage update in place.
"034-caller-metadata-open-span-update-serial",
# 037 — proposal 0043 (trace.input/output sourcing). The four
# decision-tree cases (default stub / disable_state_payload=False
# / hooks non-null / hooks null-fallthrough) activate via the
# caller-hook registry below; case 5 (resume re-fire) stays
# deferred to a follow-up PR — it needs the langfuse harness to
# grow checkpointer wiring + flaky-node test seam + two-phase
# multi-trace assertion. Listed individually in
# ``_DEFERRED_CASES`` rather than at the fixture level so the
# four other cases run.
"037-langfuse-trace-input-output",
# 035/036 — proposal 0039 caller-invocation-id -> trace.id derivation
# (UUID hex dashes-stripped / sha256-first-16 for a non-UUID). 059 —
# proposal 0052 implementation-attribution rows on trace.metadata.
# Wired here (the Langfuse conformance home) by the fixture-harness
# catch-up; previously unit-only.
"035-caller-invocation-id-uuid",
"036-caller-invocation-id-non-uuid",
"059-implementation-attribution-langfuse",
# 029 (fan-out per-instance): the fixture omits collect_field/
# target_field on the fan_out cfg and the inner subgraph omits a
# state: block, both required by the cross-cap adapter. The harness
# synthesizes the inner state (_infer_state_fields_from_nodes) and a
# throwaway aggregation sink (_synthesize_fan_out_aggregation) -- 029
# asserts per-instance span metadata + sibling isolation, never the
# collected results -- and augment_metadata_from_field drives the
# per-instance set_invocation_metadata.
"029-caller-metadata-fan-out-per-instance",
# 030 (parallel-branches per-branch): the LangfuseObserver now
# synthesizes the per-branch dispatch-span observation (§4.3 + §8.4.2 +
# proposal 0044) that inner branch nodes parent under, ported from the
# OTel observer's parallel_branches_branch_spans machinery.
"030-caller-metadata-parallel-branches-per-branch",
# 039 (nested-lineage augmentation, proposal 0045): the LangfuseObserver
# gained prefix-general fan-out-instance dispatch (so a fan-out under a
# serial wrapper parents correctly) and skips shared-parent NODEs in the
# augmentation walk (0045 §3.4 MUST-NOT). Case 3 (fan-out in a serial
# subgraph) is wired via the dedicated hand-built _build_039_graph runner;
# cases 1 + 2 are TEMPORARILY deferred via _DEFERRED_CASES pending the
# shared nested-dispatch-keying fix (see that note).
"039-nested-lineage-augmentation",
# 123 (proposal 0082): a structured_output_invalid failure renders the
# response-side surface (payload-gated output, usage, metadata.finish_reason)
# on the ERROR failed Generation. Drives the real failure path via
# calls_llm.response_schema + expected_error.
"123-langfuse-failed-generation-renders-output-usage-finish-reason",
# 130 (proposal 0083): a SUCCESSFUL completion whose prompt_tokens exceed
# the declared input_max_tokens renders the advisory WARNING level +
# statusMessage naming the breached bound, and maps the declared budget
# to metadata.token_budget.*. Drives the input-exceeded path via
# renders_prompt + the prompt's token_budget block.
"130-langfuse-token-budget-warning-level",
}
)
# Per-case deferrals within an otherwise-activated fixture. Each entry is
# ``(fixture_stem, case_name)``. The case-loop in the runner ``continue``s
# past matching cases — NOT ``pytest.skip``, which would skip the whole
# fixture's test invocation and hide the surrounding cases that DO run.
# Currently empty; the harness covers every activated case. Kept as a named hook
# so future per-case deferrals don't need to re-introduce the pattern.
_DEFERRED_CASES: frozenset[tuple[str, str]] = frozenset()
# Mocks the spec fixture 037 references for ``trace_input_from_state`` /
# ``trace_output_from_state`` caller hooks. Each YAML hook name maps to
# a Python callable matching the spec fixture's documented mock
# convention (see fixture 037's case 3 / case 4 / case 5 inline comments).
def _returns_job_input_summary(_state: Any) -> dict[str, Any]:
return {"summary": "job-input"}
def _returns_job_output_summary(_state: Any) -> dict[str, Any]:
return {"summary": "job-output"}
def _returns_null(_state: Any) -> None:
return None
def _returns_state_snapshot(state: Any) -> dict[str, Any]:
# Fixture 037 case 5: the hook captures the state's full field set
# at hook-fire time. ``model_dump()`` returns the JSON-able
# representation; the case asserts the trace's input/output exactly
# match the values present at first-invoke entry / first-invoke
# failure-exit / resumed-invoke entry / resumed-invoke exit.
return cast("dict[str, Any]", state.model_dump())
_TRACE_IO_HOOK_REGISTRY: dict[str, Callable[[Any], Any]] = {
"returns_job_input_summary": _returns_job_input_summary,
"returns_job_output_summary": _returns_job_output_summary,
"returns_null": _returns_null,
"returns_state_snapshot": _returns_state_snapshot,
}
def _resolve_trace_io_hook(name: str) -> Callable[[Any], Any]:
"""Look up a YAML-named trace_io hook in the registry. Raises a
clear KeyError when the fixture references a name the harness
hasn't mocked yet — surfaces missing-mock issues at test setup
rather than as a downstream None/AttributeError.
"""
try:
return _TRACE_IO_HOOK_REGISTRY[name]
except KeyError as exc:
raise KeyError(
f"trace_io hook {name!r} not registered; known: {sorted(_TRACE_IO_HOOK_REGISTRY)}"
) from exc
def _normalize_fan_out_subgraph_keys(spec: dict[str, Any]) -> None:
"""In-place rename of fan-out config keys that fixture 029 uses
but the cross-capability adapter doesn't:
- ``inner_subgraph`` → ``subgraph`` (within each ``fan_out`` block)
- top-level ``inner_subgraphs`` → ``subgraphs``
The directive intent is identical; only the key naming differs
across the spec fixture style and the cross-cap adapter's
parser. Keep the original keys intact in the source spec; this
function mutates a deepcopy in the harness wrapper.
"""
if "inner_subgraphs" in spec and "subgraphs" not in spec:
spec["subgraphs"] = spec.pop("inner_subgraphs")
for node_spec in cast("dict[str, Any]", spec.get("nodes") or {}).values():
if not isinstance(node_spec, dict):
continue
node_dict = cast("dict[str, Any]", node_spec)
fan_out_cfg = cast("dict[str, Any] | None", node_dict.get("fan_out"))
if fan_out_cfg is None:
continue
if "inner_subgraph" in fan_out_cfg and "subgraph" not in fan_out_cfg:
fan_out_cfg["subgraph"] = fan_out_cfg.pop("inner_subgraph")
def _synthesize_fan_out_aggregation(spec: dict[str, Any]) -> None:
"""Synthesize a throwaway aggregation sink for a ``fan_out`` block that omits
``collect_field`` / ``target_field`` (fixture 029): collect the inner
subgraph's ``stores_response_in`` value into a fresh outer list field, and
declare the adapter's other required fan-out fields (``item_field``, the
``items_field`` source, the inner state).
Call AFTER ``_normalize_fan_out_subgraph_keys`` so the ``subgraph(s)`` keys
are already resolved.
"""
# 029 asserts per-instance span metadata + sibling isolation, never the
# collected results, so the sink only satisfies the adapter's collect/target
# requirement. The inner subgraph (spec["subgraphs"]) is shared across a
# fixture's cases, so its state seed below uses setdefault to stay
# idempotent; the outer state / fan_out writes are per-case.
subgraphs = cast("dict[str, Any]", spec.get("subgraphs") or {})
state_block = cast("dict[str, Any]", spec.get("state") or {})
state_fields = cast("dict[str, Any]", state_block.get("fields") or {})
for node_name, node_spec in cast("dict[str, Any]", spec.get("nodes") or {}).items():
if not isinstance(node_spec, dict):
continue
fan_out_cfg = cast("dict[str, Any] | None", cast("dict[str, Any]", node_spec).get("fan_out"))
if fan_out_cfg is None or ("collect_field" in fan_out_cfg and "target_field" in fan_out_cfg):
continue
sub_name = cast("str | None", fan_out_cfg.get("subgraph"))
sub_spec = cast("dict[str, Any]", subgraphs.get(sub_name or "", {}))
inferred = _infer_state_fields_from_nodes(cast("dict[str, Any]", sub_spec.get("nodes") or {}))
# Any inferred field works as the collected value; the sink is never
# asserted, so the first one is fine.
collect_field = next(iter(inferred), None)
if collect_field is None:
continue
# The sink is node-scoped (one outer field per fan-out node). The item
# slot is a fixed inner-state field name on purpose: distinct fan-outs
# have distinct inner subgraphs, and a subgraph shared between two
# fan-outs reuses the one slot, so scoping it per node would mismatch.
sink = f"oa_fan_out_sink_{node_name}"
item_field = "oa_fan_out_item"
fan_out_cfg.setdefault("collect_field", collect_field)
fan_out_cfg.setdefault("target_field", sink)
# items_field mode also requires item_field (where the engine places
# each item in the inner state). The augment middleware reads the item
# back out of this slot at runtime.
fan_out_cfg.setdefault("item_field", item_field)
# Ensure the inner state declares item_field (+ the inferred response
# fields) whether or not the subgraph shipped its own state block --
# State is strict, so the engine's write to item_field needs it declared.
sub_state = cast("dict[str, Any]", sub_spec.setdefault("state", {}))
sub_fields = cast("dict[str, Any]", sub_state.setdefault("fields", {}))
for fname, fdef in inferred.items():
sub_fields.setdefault(fname, fdef)
sub_fields.setdefault(item_field, {"type": "dict", "default": {}})
state_fields[sink] = {"type": "list", "reducer": "append", "default": []}
# The items_field source (e.g. products) must be declared on the outer
# state; 029 ships it only via initial_state, so declare it here.
items_field = cast("str | None", fan_out_cfg.get("items_field"))
if items_field is not None:
state_fields.setdefault(items_field, {"type": "list<dict>", "default": []})
if state_fields:
state_block["fields"] = state_fields
spec["state"] = state_block
def _build_augment_middlewares(
case: Mapping[str, Any],
) -> tuple[
dict[str, list[Any]], # fan_out_instance_middleware: node_name -> [Middleware]
dict[str, dict[str, list[Any]]], # parallel_branches_branch_middleware: node -> branch -> [Middleware]
]:
"""Detect proposal-0040 augment directives in the case spec and
synthesize the middlewares that drive them via the adapter's
``fan_out_instance_middleware`` / ``parallel_branches_branch_middleware``
hooks.
- Fan-out ``augment_metadata_from_field: {key: field_path}`` →
one instance middleware that reads ``current_fan_out_index()``,
indexes into the parent's ``items_field`` list captured at
fixture-build time, and calls ``set_invocation_metadata(**entries)``
where entries are pulled from the per-instance item via field_path.
- Parallel-branches ``branches.<name>.augment_metadata: {key: value}``
→ per-branch middleware that calls
``set_invocation_metadata(**entries)`` once at branch entry.
"""
fan_out_mw: dict[str, list[Any]] = {}
branch_mw: dict[str, dict[str, list[Any]]] = {}
for node_name, node_spec_any in cast("dict[str, Any]", case.get("nodes") or {}).items():
if not isinstance(node_spec_any, dict):
continue
node_spec = cast("dict[str, Any]", node_spec_any)
fan_out_cfg = cast("dict[str, Any] | None", node_spec.get("fan_out"))
if fan_out_cfg is not None:
augment_field_map = cast("dict[str, str] | None", fan_out_cfg.get("augment_metadata_from_field"))
if augment_field_map:
item_field = cast("str | None", fan_out_cfg.get("item_field"))
if item_field is None:
raise ValueError(
f"fan-out node {node_name!r}: augment_metadata_from_field requires item_field"
)
fan_out_mw[node_name] = [_make_augment_instance_middleware(augment_field_map, item_field)]
pb_cfg = cast("dict[str, Any] | None", node_spec.get("parallel_branches"))
if pb_cfg is not None:
branches_cfg = cast("dict[str, dict[str, Any]]", pb_cfg.get("branches") or {})
per_branch: dict[str, list[Any]] = {}
for branch_name, branch_cfg in branches_cfg.items():
augment_entries = cast("dict[str, Any] | None", branch_cfg.get("augment_metadata"))
if augment_entries:
per_branch[branch_name] = [_make_augment_branch_middleware(augment_entries)]
if per_branch:
branch_mw[node_name] = per_branch
return fan_out_mw, branch_mw
def _make_augment_instance_middleware(field_map: dict[str, str], item_field: str) -> Any:
"""Per-instance fan-out middleware that reads the instance's own item from
the ``item_field`` slot of its subgraph state and calls
``set_invocation_metadata`` with the mapped entries."""
# Reads runtime state, not a build-time list indexed by
# current_fan_out_index(): instance middleware wraps the inner subgraph from
# OUTSIDE, but the fan_out_index ContextVar is set deeper (inside the inner
# node execution), so it is None here. The engine has already placed each
# item in item_field by the time the chain runs, and set_invocation_metadata
# lands before the inner spans open, so the instance's dispatch + inner spans
# all carry the augmentation.
class _AugmentInstanceMW:
async def __call__(self, state: Any, next_: Any, /) -> Any:
from openarmature.observability.metadata import ( # noqa: PLC0415
set_invocation_metadata,
)
item = getattr(state, item_field, None)
if isinstance(item, Mapping):
item_map = cast("Mapping[str, Any]", item)
entries = {key: item_map[field_path] for key, field_path in field_map.items()}
set_invocation_metadata(**entries)
return await next_(state)
return _AugmentInstanceMW()
def _make_augment_branch_middleware(entries: dict[str, Any]) -> Any:
"""Per-branch middleware that calls ``set_invocation_metadata``
once at branch entry. Captures ``entries`` at fixture-build
time so the call inside the middleware doesn't need to read
the case spec at runtime."""
class _AugmentBranchMW:
async def __call__(self, state: Any, next_: Any, /) -> Any:
from openarmature.observability.metadata import ( # noqa: PLC0415
set_invocation_metadata,
)
set_invocation_metadata(**entries)
return await next_(state)
return _AugmentBranchMW()
def _fixture_paths() -> list[Path]:
return sorted(p for p in CONFORMANCE_DIR.glob("[0-9][0-9][0-9]-*.yaml") if p.stem in _LANGFUSE_FIXTURES)
def _fixture_id(path: Path) -> str:
return path.stem
def _load(path: Path) -> dict[str, Any]:
return cast("dict[str, Any]", yaml.safe_load(path.read_text()))
# ---------------------------------------------------------------------------
# Mock LLM transport
# ---------------------------------------------------------------------------
def _build_mock_llm_handler(responses: list[dict[str, Any]]) -> httpx.MockTransport:
queue = list(responses)
def _handler(_request: httpx.Request) -> httpx.Response:
if not queue:
raise AssertionError("mock_llm queue exhausted")
spec_resp = queue.pop(0)
body = cast("dict[str, Any]", spec_resp.get("body") or {})
return httpx.Response(
int(spec_resp.get("status", 200)),
content=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
return httpx.MockTransport(_handler)
# ---------------------------------------------------------------------------
# Mock prompt backend (fixture 024)
# ---------------------------------------------------------------------------
class _MockPromptBackend:
"""Returns canned Prompts for fixture 024.
Two flavors per the fixture YAML's ``prompt_backend.type``:
- ``mock_with_langfuse_reference``: attaches the supplied
``langfuse_prompt_reference`` sentinel under
``Prompt.observability_entities['langfuse_prompt']``. Verifies
the Generation-linked-to-Prompt-entity case.
- ``filesystem``: no Langfuse reference attached. Verifies the
metadata-only case.
"""
def __init__(self, prompts: dict[str, dict[str, Any]], *, with_langfuse_reference: bool) -> None:
self._prompts: dict[str, Prompt] = {}
now = datetime.now(UTC)
for prompt_name, spec in prompts.items():
observability_entities: dict[str, Any] | None = None
if with_langfuse_reference and "langfuse_prompt_reference" in spec:
observability_entities = {"langfuse_prompt": spec["langfuse_prompt_reference"]}
# Proposal 0083: the prompt's token_budget block propagates onto the
# TextPrompt so PromptManager.render carries it to the PromptResult
# (and thence the typed event). An empty / all-null budget collapses
# to None, mirroring the real backends.
token_budget_spec = cast("dict[str, Any] | None", spec.get("token_budget"))
token_budget = TokenBudget(**token_budget_spec) if token_budget_spec is not None else None
if (
token_budget is not None
and token_budget.input_max_tokens is None
and token_budget.total_max_tokens is None
):
token_budget = None
self._prompts[prompt_name] = TextPrompt(
name=spec["name"],
version=spec["version"],
label=spec["label"],
template=spec["template"],
template_hash=spec["template_hash"],
fetched_at=now,
observability_entities=observability_entities,
token_budget=token_budget,
)
async def fetch(
self, name: str, label: str = "production", *, cache_ttl_seconds: int | None = None
) -> Prompt:
return self._prompts[name]
# ---------------------------------------------------------------------------
# Fixture runner
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("fixture_path", _fixture_paths(), ids=_fixture_id)
async def test_langfuse_fixture(fixture_path: Path) -> None:
spec = _load(fixture_path)
fixture_stem = fixture_path.stem
if "cases" in spec:
# Fold fixture-level ``subgraphs`` / ``inner_subgraphs`` into
# each case so the per-case runner sees them locally. Fixture
# 030 declares its branch subgraphs at fixture-level (alongside
# ``cases:``); without this fold the per-case build can't
# resolve ``branches.fraud_check.subgraph: fraud_check``.
fixture_subgraphs = cast("dict[str, Any] | None", spec.get("subgraphs"))
fixture_inner_subgraphs = cast("dict[str, Any] | None", spec.get("inner_subgraphs"))
for case in cast("list[dict[str, Any]]", spec["cases"]):
case_name = cast("str", case.get("name") or "<unnamed>")
if (fixture_stem, case_name) in _DEFERRED_CASES:
# Per-case deferral. Skipping inside the loop rather
# than emitting a separate pytest.skip lets us keep the
# surrounding cases running under the same parametrized
# test id.
continue
if fixture_subgraphs is not None and "subgraphs" not in case:
case["subgraphs"] = fixture_subgraphs
if fixture_inner_subgraphs is not None and "inner_subgraphs" not in case:
case["inner_subgraphs"] = fixture_inner_subgraphs
try:
await _run_case(case, fixture_stem=fixture_stem)
except AssertionError as e:
raise AssertionError(f"case {case_name!r}: {e}") from e
else:
await _run_case(spec, fixture_stem=fixture_stem)
def _has_topology_constructs(case: Mapping[str, Any]) -> bool:
"""Return True when the fixture uses subgraph / fan_out / parallel_branches
constructs. Such fixtures need the full ``adapter.build_graph`` machinery
rather than the simpler per-node hand-rolled path used for the
LLM/prompt-only fixtures."""
if "subgraph" in case or "subgraphs" in case:
return True
nodes_spec = cast("dict[str, Any]", case.get("nodes") or {})
for node_spec in nodes_spec.values():
if not isinstance(node_spec, dict):
continue
node_dict = cast("dict[str, Any]", node_spec)
if "subgraph" in node_dict or "fan_out" in node_dict or "parallel_branches" in node_dict:
return True
return False
def _patch_unsupported_directives(spec: Mapping[str, Any]) -> None:
"""Replace inner-node test-seam directives the cross-capability
adapter doesn't translate (``update_pure_from_state``) with a
benign ``update_pure: {}`` no-op. The topology fixtures assert
observation structure (parenting, trace ids, subgraph_name,
correlation_id), not computed state values, so the swap is safe.
Mirrors the OTel harness's helper of the same name."""
def patch_nodes(graph_block: Mapping[str, Any] | None) -> None:
if not graph_block:
return
nodes = cast("dict[str, Any]", graph_block.get("nodes") or {})
for node_spec_any in nodes.values():
if not isinstance(node_spec_any, dict):
continue
node_spec = cast("dict[str, Any]", node_spec_any)
if "update_pure_from_state" in node_spec:
node_spec.pop("update_pure_from_state")
node_spec.setdefault("update_pure", {})
patch_nodes(spec)
if "subgraph" in spec:
patch_nodes(cast("Mapping[str, Any]", spec["subgraph"]))
for sub in cast("dict[str, Any]", spec.get("subgraphs") or {}).values():
patch_nodes(cast("Mapping[str, Any]", sub))
def _compile_subgraphs(
spec: Mapping[str, Any],
*,
provider: OpenAIProvider | None = None,
prompt_manager: PromptManager | None = None,
render_variables: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Build any subgraphs declared by the fixture and return a
name→compiled-graph registry the adapter consumes. Mirrors the
OTel-side helper in ``test_observability.py``.
When ``provider`` is supplied, inner subgraph nodes carrying the
``calls_llm:`` / ``renders_prompt:`` directives (fixtures 029 /
030) are built via the langfuse-specific
:func:`_build_node_body` rather than the cross-cap adapter — the
adapter doesn't model LLM directives. Outer subgraphs without
LLM directives still resolve through ``build_graph`` so the
existing 031/032/033 wiring is unchanged.
"""
subgraph_specs: dict[str, Any] = {}
if "subgraph" in spec:
single = cast("Mapping[str, Any]", spec["subgraph"])
name = single.get("name") or "subgraph"
subgraph_specs[name] = single
if "subgraphs" in spec:
for k, v in cast("dict[str, Any]", spec["subgraphs"]).items():
subgraph_specs[k] = v
compiled_subgraphs: dict[str, Any] = {}
for name, sub_spec in subgraph_specs.items():
if provider is not None and _has_llm_nodes(sub_spec):
compiled_subgraphs[name] = _build_inner_subgraph_with_llm(
sub_spec,
provider=provider,
prompt_manager=prompt_manager,
render_variables=render_variables or {},
)
else:
sub_built = build_graph(sub_spec, trace=[])
compiled_subgraphs[name] = sub_built.builder.compile()
return compiled_subgraphs
def _has_llm_nodes(spec: Mapping[str, Any]) -> bool:
"""True iff any node in the subgraph spec declares an LLM
directive (``calls_llm`` / ``renders_prompt``) — those need the
langfuse-specific node body builder rather than the cross-cap
adapter."""
nodes_spec = cast("dict[str, Any]", spec.get("nodes") or {})
for node_spec in nodes_spec.values():
if not isinstance(node_spec, dict):
continue
node_dict = cast("dict[str, Any]", node_spec)
if "calls_llm" in node_dict or "renders_prompt" in node_dict:
return True
return False
def _infer_state_fields_from_nodes(nodes_spec: dict[str, Any]) -> dict[str, dict[str, Any]]:
"""Build a minimal state-fields block from nodes' partial-update
targets so an inner subgraph without an explicit ``state:`` block
(fixture 029) still compiles. Walks ``stores_response_in``
directives on ``calls_llm`` blocks; defaults each inferred field
to ``string``."""
fields: dict[str, dict[str, Any]] = {}
for node_spec_any in nodes_spec.values():
if not isinstance(node_spec_any, dict):
continue
node_spec = cast("dict[str, Any]", node_spec_any)
calls_llm = cast("dict[str, Any] | None", node_spec.get("calls_llm"))
if calls_llm is None:
continue
stores_in = cast("str | None", calls_llm.get("stores_response_in"))
if stores_in is not None and stores_in not in fields:
fields[stores_in] = {"type": "string", "default": ""}
return fields
def _build_inner_subgraph_with_llm(
spec: Mapping[str, Any],
*,
provider: OpenAIProvider,
prompt_manager: PromptManager | None,
render_variables: dict[str, Any],
) -> Any:
"""Compile an inner subgraph spec into a CompiledGraph using the
langfuse-specific node body builder so ``calls_llm`` / ``renders_prompt``
directives resolve correctly. Used by fixtures 029 / 030 whose
branch / per-instance subgraphs each make an LLM call."""
# Some inner-subgraph specs (fixture 029) omit a ``state:`` block.
# Synthesize one from ``stores_response_in`` directives so the
# partial update each node returns has a corresponding field on
# the state class. Default field type is ``string`` with empty
# default, matching the canonical fixture convention.
state_block = cast("dict[str, Any] | None", spec.get("state"))
if state_block is not None:
state_fields = cast("dict[str, dict[str, Any]]", state_block["fields"])
else:
state_fields = _infer_state_fields_from_nodes(cast("dict[str, Any]", spec.get("nodes") or {}))
state_cls = build_state_cls("InnerSubgraphState", state_fields)
nodes_spec = cast("dict[str, Any]", spec["nodes"])
entry = cast("str", spec["entry"])
edges = cast("list[dict[str, str]]", spec["edges"])
builder = GraphBuilder(state_cls)
for node_name, node_spec in nodes_spec.items():
node_body = _build_node_body(
node_name=node_name,
node_spec=cast("dict[str, Any]", node_spec),
provider=provider,
prompt_manager=prompt_manager,
render_variables=render_variables,
)
builder.add_node(node_name, node_body)
for edge in edges:
target_raw = edge["to"]
target = END if target_raw == "END" else target_raw
builder.add_edge(edge["from"], target)
builder.set_entry(entry)
return builder.compile()
# Fixture 039 (nested-lineage augmentation) declares nested fan-out graphs the
# generic cross-cap adapter can't construct (a fan-out inside a subgraph wrapper
# / another fan-out, and a per-item sub-field as the inner fan-out's items
# source). Each case is hand-built here against the engine's GraphBuilder --
# mirroring the dedicated 044 builder on the OTel side -- then driven through the
# shared observer + assertion path. The expected langfuse_trace in the YAML
# stays the oracle.
_FIXTURE_039 = "039-nested-lineage-augmentation"
def _build_039_graph(
case: Mapping[str, Any],
*,
provider: OpenAIProvider | None,
prompt_manager: PromptManager | None,
) -> tuple[Any, Any]:
"""Dispatch a 039 case to its hand-built graph; return (graph, factory)."""
name = cast("str", case.get("name"))
if name == "inner_fan_out_augmenter_propagates_to_outer_dispatch_span":
return _build_039_case1(case, provider=provider, prompt_manager=prompt_manager)
if name == "parallel_branch_augmenter_propagates_to_outer_fan_out_instance":
return _build_039_case2(case, provider=provider, prompt_manager=prompt_manager)
if name == "fan_out_in_serial_subgraph_augmenter_propagates_to_wrapper_span":
return _build_039_case3(case, provider=provider, prompt_manager=prompt_manager)
raise NotImplementedError(f"039 case not yet wired: {name!r}")
def _make_039_inner_seed_extractor(outer_item_field: str, seed_field: str, seed_subkey: str) -> Any:
# Case 1 outer fan-out instance middleware: the inner fan-out's items_field
# (inner_seed) is a SUB-FIELD of the outer product item, which the engine's
# flat item_field / inputs projection can't reach. Read the outer item from
# its slot and inject the sub-field into the per_product instance state so the
# inner fan-out can fan over it.
async def _extract(state: Any, next_: Any) -> Any:
item = getattr(state, outer_item_field, None)
if isinstance(item, Mapping):
state = state.model_copy(update={seed_field: cast("Mapping[str, Any]", item)[seed_subkey]})
return await next_(state)
return _extract
def _build_039_case1(
case: Mapping[str, Any],
*,
provider: OpenAIProvider | None,
prompt_manager: PromptManager | None,
) -> tuple[Any, Any]:
# Case 1: fan-out inside a fan-out instance. The inner fan-out
# (per_product.inner_fan_out) fans over each product's inner_seed sub-field
# and augments note=<inner_seed.value>; per 0045 that note reaches the OUTER
# instance dispatch span (one level up) but NOT the shared fan-out NODEs.
assert provider is not None, "039 cases declare mock_llm, so the provider must be set"
per_category_spec = copy.deepcopy(cast("dict[str, Any]", case["inner_subgraphs"]["per_category"]))
per_category_spec.setdefault("state", {}).setdefault("fields", {}).setdefault(
"oa_fan_out_item", {"type": "dict", "default": {}}
)
per_category = _build_inner_subgraph_with_llm(
per_category_spec, provider=provider, prompt_manager=prompt_manager, render_variables={}
)
per_product_state = build_state_cls(
"PerProduct039C1",
{
"score": {"type": "string", "default": ""},
"inner_seed": {"type": "list<dict>", "default": []},
"oa_outer_item": {"type": "dict", "default": {}},
"inner_picks": {"type": "list", "reducer": "append", "default": []},
},
)
pp_builder: GraphBuilder[Any] = GraphBuilder(per_product_state)
pp_builder.set_entry("inner_fan_out")
pp_builder.add_fan_out_node(
"inner_fan_out",
subgraph=per_category,
items_field="inner_seed",
item_field="oa_fan_out_item",
collect_field="picked",
target_field="inner_picks",
instance_middleware=[_make_augment_instance_middleware({"note": "value"}, "oa_fan_out_item")],
)
pp_builder.add_edge("inner_fan_out", END)
per_product = pp_builder.compile()
outer_state = build_state_cls(
"Outer039C1",
{
"results": {"type": "list", "reducer": "append", "default": []},
"products": {"type": "list<dict>", "default": []},
},
)
outer_builder: GraphBuilder[Any] = GraphBuilder(outer_state)
outer_builder.set_entry("outer_fan_out")
outer_builder.add_fan_out_node(
"outer_fan_out",
subgraph=per_product,
items_field="products",
item_field="oa_outer_item",
collect_field="inner_picks",
target_field="results",
# concurrency=1 while the observer's NODE-key collision under concurrent
# nested fan-out is fixed (inner nodes of different outer instances share
# a _key_for and dedup, dropping spans). The engine produces correct
# results at any concurrency; this is an observability-only constraint.
concurrency=1,
instance_middleware=[_make_039_inner_seed_extractor("oa_outer_item", "inner_seed", "inner_seed")],
)
outer_builder.add_edge("outer_fan_out", END)
graph = outer_builder.compile()
initial = cast("dict[str, Any]", case.get("initial_state") or {})
return graph, (lambda: outer_state(**initial))
def _build_039_case2(
case: Mapping[str, Any],
*,
provider: OpenAIProvider | None,
prompt_manager: PromptManager | None,
) -> tuple[Any, Any]:
# Case 2: parallel-branches NODE inside a fan-out instance. Only the `probe`
# branch augments note=<outer product id> via augment_metadata_from_outer_item;
# per 0045 that note reaches the probe branch dispatch AND the OUTER fan-out
# instance dispatch, but NOT the baseline branch, the pb NODE, or the fan-out
# NODE.
assert provider is not None, "039 cases declare mock_llm, so the provider must be set"
subgraphs = cast("dict[str, Any]", case["subgraphs"])
probe_spec = copy.deepcopy(cast("dict[str, Any]", subgraphs["probe"]))
probe_spec.setdefault("state", {}).setdefault("fields", {}).setdefault(
"oa_outer_item", {"type": "dict", "default": {}}
)
probe = _build_inner_subgraph_with_llm(
probe_spec, provider=provider, prompt_manager=prompt_manager, render_variables={}
)
baseline = _build_inner_subgraph_with_llm(
cast("Mapping[str, Any]", subgraphs["baseline"]),
provider=provider,
prompt_manager=prompt_manager,
render_variables={},
)
per_product_state = build_state_cls(
"PerProduct039C2",
{
"outcome": {"type": "string", "default": ""},
"oa_outer_item": {"type": "dict", "default": {}},
},
)
pp_builder: GraphBuilder[Any] = GraphBuilder(per_product_state)
pp_builder.set_entry("dispatcher")
pp_builder.add_parallel_branches_node(
"dispatcher",
branches={
"probe": BranchSpec(
subgraph=probe,
inputs={"oa_outer_item": "oa_outer_item"},
middleware=(_make_augment_instance_middleware({"note": "id"}, "oa_outer_item"),),
),
"baseline": BranchSpec(subgraph=baseline),
},
)
pp_builder.add_edge("dispatcher", END)
per_product = pp_builder.compile()
outer_state = build_state_cls(
"Outer039C2",
{
"results": {"type": "list", "reducer": "append", "default": []},
"products": {"type": "list<dict>", "default": []},
},
)
outer_builder: GraphBuilder[Any] = GraphBuilder(outer_state)
outer_builder.set_entry("outer_fan_out")
outer_builder.add_fan_out_node(
"outer_fan_out",
subgraph=per_product,
items_field="products",
item_field="oa_outer_item",
collect_field="outcome",
target_field="results",
)
outer_builder.add_edge("outer_fan_out", END)
graph = outer_builder.compile()
initial = cast("dict[str, Any]", case.get("initial_state") or {})
return graph, (lambda: outer_state(**initial))
def _build_039_case3(
case: Mapping[str, Any],
*,
provider: OpenAIProvider | None,
prompt_manager: PromptManager | None,
) -> tuple[Any, Any]:
# Case 3: a serial subgraph wrapper (`wrap`) descends into `wrapped_fan_out`,
# whose `pick` fan-out runs per-product; each instance augments note=<id>.
# The wrapper span must carry the augmentation (last-writer) per 0045's
# lineage-aware rule, the fan-out NODE must not.
# The fan-out places each outer product into per_product's item_field slot;
# the augment middleware reads <id> from it. per_product's declared state
# ({picked}) lacks the slot, so inject it (mirrors _synthesize_fan_out_
# aggregation on the generic 029 path).
assert provider is not None, "039 cases declare mock_llm, so the provider must be set"
per_product_spec = copy.deepcopy(cast("dict[str, Any]", case["inner_subgraphs"]["per_product"]))
per_product_spec.setdefault("state", {}).setdefault("fields", {}).setdefault(
"oa_fan_out_item", {"type": "dict", "default": {}}
)
per_product = _build_inner_subgraph_with_llm(
per_product_spec,
provider=provider,
prompt_manager=prompt_manager,
render_variables={},
)
wrap_state_cls = build_state_cls(
"Wrapped039C3",
{
"picks": {"type": "list", "reducer": "append", "default": []},
"products": {"type": "list<dict>", "default": []},
"oa_fan_out_item": {"type": "dict", "default": {}},
},
)
wrap_builder: GraphBuilder[Any] = GraphBuilder(wrap_state_cls)
wrap_builder.set_entry("pick")
wrap_builder.add_fan_out_node(
"pick",
subgraph=per_product,
items_field="products",
item_field="oa_fan_out_item",
collect_field="picked",
target_field="picks",
instance_middleware=[_make_augment_instance_middleware({"note": "id"}, "oa_fan_out_item")],
)
wrap_builder.add_edge("pick", END)
wrapped_fan_out = wrap_builder.compile()
outer_state_cls = build_state_cls(
"Outer039C3",
{"result": {"type": "list", "default": []}, "products": {"type": "list<dict>", "default": []}},
)
outer_builder: GraphBuilder[Any] = GraphBuilder(outer_state_cls)
outer_builder.set_entry("wrap")
outer_builder.add_subgraph_node(
"wrap",
wrapped_fan_out,
ExplicitMapping(inputs={"products": "products"}, outputs={"result": "picks"}),
)
outer_builder.add_edge("wrap", END)
graph = outer_builder.compile()
initial = cast("dict[str, Any]", case.get("initial_state") or {})
return graph, (lambda: outer_state_cls(**initial))
# Proposal 0045 §3.4: a key set via set_invocation_metadata inside a fan-out
# instance / parallel-branches branch lands ONLY on the dispatch ancestors on
# the augmenter's call-stack path -- NOT on the shared fan-out/pb NODE, sibling
# instances, or (inside a dispatch) the Trace. The tree asserter is subset-based
# (extra keys tolerated), which can't catch a MUST-NOT violation, so 039
# additionally enforces that augmented keys absent from an observation's expected
# metadata are absent in the actual. Scoped to 039 via this ContextVar so the
# established subset semantics for the other fixtures are unchanged.
_AUGMENT_KEYS_UNDER_TEST: ContextVar[frozenset[str]] = ContextVar(
"augment_keys_under_test", default=frozenset()
)
def _collect_augment_keys(case: Mapping[str, Any]) -> frozenset[str]:
"""Collect the metadata keys augment directives set, anywhere in the case's
topology (fan-out / parallel-branches augment blocks at any nesting)."""
keys: set[str] = set()
directives = ("augment_metadata_from_field", "augment_metadata_from_outer_item", "augment_metadata")
def _harvest(block: Any) -> None:
if not isinstance(block, dict):
return
for directive in directives:
mapping = cast("dict[str, Any]", block).get(directive)
if isinstance(mapping, dict):
keys.update(cast("dict[str, Any]", mapping).keys())
def _walk(spec: Mapping[str, Any]) -> None:
for node in cast("dict[str, Any]", spec.get("nodes") or {}).values():
if not isinstance(node, dict):
continue
node_dict = cast("dict[str, Any]", node)
_harvest(node_dict.get("fan_out"))
pb = cast("dict[str, Any] | None", node_dict.get("parallel_branches"))
for branch in cast("dict[str, Any]", (pb or {}).get("branches") or {}).values():
_harvest(branch)
for collection in ("subgraphs", "inner_subgraphs"):
for sub in cast("dict[str, Any]", spec.get(collection) or {}).values():
if isinstance(sub, dict):
_walk(cast("Mapping[str, Any]", sub))
_walk(case)
return frozenset(keys)
def _assert_augment_keys_not_leaked(
label: str, actual: Mapping[str, Any], expected: Mapping[str, Any]
) -> None:
# Proposal 0045 §3.4 MUST-NOT: an augmented key absent from the expected
# metadata (a shared fan-out/pb NODE, a sibling, or the Trace inside a
# dispatch) MUST also be absent in the actual. Complements the subset matcher.
for key in _AUGMENT_KEYS_UNDER_TEST.get():
if key not in expected:
assert key not in actual, (
f"{label}: MUST NOT carry augmented key {key!r} (proposal 0045 §3.4); got {actual.get(key)!r}"
)
def _resolve_detached_wrapper_names(case: Mapping[str, Any]) -> frozenset[str]:
"""Translate fixture-level ``detached_subgraphs`` (a list of SUBGRAPH
IDENTITY names) into the set of WRAPPER NODE names the observer keys
on. The fixture identifies detached subgraphs by their declaration name
in ``subgraphs:`` (e.g., ``long_running_workflow``), but the
LangfuseObserver matches by the wrapper node name in the parent graph
that references the subgraph (e.g., ``dispatch``).
"""
detached_identities = set(cast("list[str]", case.get("detached_subgraphs") or []))
if not detached_identities:
return frozenset()
nodes_spec = cast("dict[str, Any]", case.get("nodes") or {})
wrappers: set[str] = set()
for wrapper_name, node_spec in nodes_spec.items():
if not isinstance(node_spec, dict):
continue
sub_id = cast("dict[str, Any]", node_spec).get("subgraph")
if isinstance(sub_id, str) and sub_id in detached_identities:
wrappers.add(wrapper_name)
return frozenset(wrappers)
async def _run_case(case: Mapping[str, Any], *, fixture_stem: str | None = None) -> None:
# 039 additionally enforces proposal 0045's MUST-NOT scoping (an augmented
# key absent from an observation's expected metadata must be absent in the
# actual); other fixtures keep the established subset semantics.
_AUGMENT_KEYS_UNDER_TEST.set(_collect_augment_keys(case) if fixture_stem == _FIXTURE_039 else frozenset())
# ---- Mock LLM transport (if the graph has an LLM call)
mock_responses = cast("list[dict[str, Any]] | None", case.get("mock_llm"))
transport = _build_mock_llm_handler(mock_responses) if mock_responses else None
provider: OpenAIProvider | None = None
if transport is not None: