diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..b746aee --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +## 0.8.0 + +Langfuse import (`pull langfuse` and `sync langfuse`): + +- **Every cost-bearing observation.** Besides `GENERATION`, any `EMBEDDING`, + `AGENT`, `TOOL`, `CHAIN`, `RETRIEVER`, `EVALUATOR` or `GUARDRAIL` + observation that names a model and carries usage or a cost is imported. + Each row carries `observation_type`. +- **Provider resolution.** Resolved from the observation's metadata + (`provider`, `ls_provider`, `gen_ai.system`, `gen_ai.provider.name`) or the + model name: Bedrock model ids and ARNs, Vertex resource paths and + Anthropic-on-Vertex versions, gateway prefixes and more model families + (`o4-`, Mistral, Llama, Cohere, Grok, Qwen, Kimi). A stripped gateway prefix + keeps the original model as `langfuse_model`. +- **Langfuse's cost** is kept on every row as `reported_cost_usd`, with the + per-bucket `reported_cost_details`. +- **Tags land.** Each Langfuse tag is one `tags` pair, + `langfuse.tag.: "true"`. They used to be sent as one list, which + metergraph drops because it keeps only string values. `tags` also carries + `langfuse.release`, `langfuse.version`, `langfuse.prompt.name`, + `langfuse.prompt.version` and the metadata as `langfuse.metadata.` + (scalar values as strings, without SDK-written keys), at most 32 pairs with + Langfuse tags first. +- **Timing and attribution.** Rows carry `latency_ms`, `ttft_ms`, `user_id`, + `trace_name`, `release`, `version`, `prompt_name`, `prompt_version` and + `model_parameters` when Langfuse has them. +- **Rate limits.** HTTP 429, 502, 503 and 504 are retried up to six times, + after `Retry-After` when present, else with doubling waits capped at two + minutes. `sync` renews its lease after each wait. +- **Selectors.** `--user-id`, `--session-id` and repeatable + `--metadata KEY=VALUE` on `pull` and `sync`. +- **Content.** `pull langfuse --exclude-content` leaves input and output in + Langfuse (`--include-content`, the default, says so explicitly). The + `sync langfuse` help no longer claims content is uploaded with no opt-out. +- **Re-pulls deduplicate.** `pull langfuse` rows now carry the same import + identity as `sync` rows (`import_source`, `import_source_scope`, + `import_event_id` = the observation id), so pushing an overlapping pull + again stores nothing twice. The scope defaults to a digest of the host and + public key; `--source-scope` sets it, for example to match `sync`. + +For library callers: `build_base_params` still requests `GENERATION` alone +unless given `observation_types`; pass `COST_BEARING_TYPES` and keep rows with +`is_importable_observation` to import the other types. diff --git a/README.md b/README.md index 2bec2ba..4e11f19 100644 --- a/README.md +++ b/README.md @@ -154,12 +154,14 @@ buckets; add a provider there, not in an adapter. ## Pull from Langfuse -Import Langfuse **GENERATION** observations (the LLM call records -Langfuse captures) into the same metergraph-native JSONL shape as -`pull openai`. Only `GENERATION` observations are imported — Langfuse -`SPAN`/`EVENT` observations and Scores/evals are never imported. -Requires Langfuse Cloud or **self-hosted v4+** (the version serving the -v2 Observations API); older self-hosted deployments are not supported. +Import the Langfuse observations that record an LLM call into the same +metergraph-native JSONL shape as `pull openai`: every `GENERATION`, and +any `EMBEDDING`, `AGENT`, `TOOL`, `CHAIN`, `RETRIEVER`, `EVALUATOR` or +`GUARDRAIL` observation that names a model and carries usage or a cost +(each row keeps its `observation_type`). Structural spans with no model, +`SPAN`/`EVENT` observations and scores are not imported. Requires +Langfuse Cloud or **self-hosted v4+** (the version serving the v2 +Observations API); older self-hosted deployments are not supported. **Setup:** add your Langfuse keys to `.env`: @@ -176,37 +178,75 @@ set `LANGFUSE_BASE_URL` in `.env` (or pass `--base-url` per-command): metergraphrelay pull langfuse -n 25 --output traces.jsonl metergraphrelay push traces.jsonl -With no other flags, this imports the latest 100 `GENERATION` -observations overall (not 100 distinct traces). +With no other flags, this imports the latest 100 observations overall +(not 100 distinct traces). **Narrowing what gets pulled**, beyond `-n`/`--count`: metergraphrelay pull langfuse --since 2026-08-01T00:00:00Z --until 2026-08-07T00:00:00Z metergraphrelay pull langfuse --trace-name support-bot-reply --trace-name billing-bot-reply --tag prod --tag tier-1 + metergraphrelay pull langfuse --user-id user-42 --session-id chat-7 --metadata feature=support-triage -- `--trace-name` matches Langfuse's trace name — the closest Langfuse +- `--trace-name` matches Langfuse's trace name, the closest Langfuse concept to a workflow or use case (e.g. `"support-bot-reply"`). It's repeatable; multiple `--trace-name` values are **OR'd** together (any match). -- `--tag` matches Langfuse trace tags — commonly used as customer-defined +- `--tag` matches Langfuse trace tags, commonly used as customer-defined categories (a tenant, an experiment cohort, a priority tier); this is a convention, not something Langfuse enforces. It's repeatable; multiple `--tag` values require **all** of them to be present (AND). `--tag` only matches tags that already exist on your historical - data — it can't require a tag that was never set, and if you don't + data: it can't require a tag that was never set, and if you don't pass `--tag` at all, there's no tag-based narrowing (not "untagged only"). -- `--trace-name`, `--tag`, `--environment`, and `--since`/`--until` all - combine with each other using AND. -- `--count` is always a cap on the number of **GENERATION observations** - imported, never a count of distinct traces. - -**Before running this against your own data:** `pull langfuse` -transfers every matched generation's prompt/response content from -Langfuse into your local JSONL file, and from there into metergraph via -`push`, with no separate opt-in step — unlike `pull openai`'s -`--include-content` flag, there is no way to pull Langfuse generations -without their content. +- `--user-id` and `--session-id` match Langfuse's user and session ids + exactly; `--metadata KEY=VALUE` matches one metadata key exactly and is + repeatable (AND). +- Every selector, `--environment` and `--since`/`--until` combine with + each other using AND. +- `--count` is always a cap on the number of **observations** imported, + never a count of distinct traces. + +**What each row carries.** The provider is resolved from the +observation's metadata (`provider`, LangChain's `ls_provider`, OTel +`gen_ai.system`) or from the model name: Bedrock ids and ARNs +(`us.anthropic.claude-...`), Vertex resource paths, gateway prefixes +(`openai/gpt-4o` becomes provider `openai`, model `gpt-4o`, with the +original kept as `langfuse_model`) and model families (`gpt-`, `o4-`, +`claude-`, `gemini-`, `mistral-`, `llama-`...). Langfuse's own cost is +always kept as `reported_cost_usd` (with `reported_cost_details`), so a +model metergraph's catalog cannot price still has Langfuse's figure. +Each Langfuse tag lands in `tags` as its own pair, +`langfuse.tag.: "true"`, followed by `langfuse.release`, +`langfuse.version`, `langfuse.prompt.name`, `langfuse.prompt.version` and +the observation's metadata as `langfuse.metadata.` (scalar values as +strings; SDK-written keys such as `resourceAttributes.*` are left out), at +most 32 pairs with Langfuse tags kept first. These are the key names +metergraph's SDK uses for Langfuse spans, so a call lands the same way on +either path. Rows also carry `latency_ms`, `ttft_ms`, `user_id`, +`session_id`, `trace_name`, `release`, `version`, `prompt_name`, +`prompt_version` and `model_parameters` when Langfuse has them. + +**Rate limits.** HTTP 429 and gateway errors (502, 503, 504) are retried +up to six times, after Langfuse's `Retry-After` when it sends one, else +after 2, 4, 8... seconds, never more than two minutes at a time. + +**Content.** By default `pull langfuse` copies every matched +observation's input and output from Langfuse into your local JSONL file, +and from there into metergraph via `push`. Pass `--exclude-content` to +leave it in Langfuse: the rows then carry usage, cost, timing and +attribution only, marked `content_opted_in: false`. (`--include-content` +states the default explicitly.) `sync langfuse` is the other way round: +content is uploaded only with `--include-content`. + +**Re-pulling is safe.** Every row carries an import identity: the +Langfuse observation id plus a scope for the project. metergraph stores +each identity once, so pushing an overlapping pull again does not double +count. By default the scope is derived from the host and public key (a +digest, never the key itself), the same on every pull of a project. If +you also run `sync langfuse` for the project, give `pull` the same +`--source-scope` so the two never store an observation twice. A later +edit of an observation in Langfuse is not re-imported by a re-pull. Full flag reference: `metergraphrelay pull langfuse --help`. @@ -577,7 +617,7 @@ same cron line is safe from several machines. metergraphrelay sync phoenix --source-scope my-project --initial-since 2026-08-01T00:00:00+00:00 --project my-project Each takes the selectors of its `pull` counterpart (`--trace-name`/`--tag`/ -`--environment`, `--project`, `--name`) plus `--route`, but **no +`--environment`/`--user-id`/`--session-id`/`--metadata`, `--project`, `--name`) plus `--route`, but **no `--since`/`--until`/`--count`**: the server chooses the window and every row in it must land before the checkpoint advances. diff --git a/pyproject.toml b/pyproject.toml index b045aef..30e0f8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "metergraphrelay" -version = "0.7.9" +version = "0.8.0" description = "Move LLM trace data between systems: pull from providers, push to metergraph." readme = "README.md" requires-python = ">=3.10" diff --git a/src/metergraphrelay/__init__.py b/src/metergraphrelay/__init__.py index fe7c60e..777f190 100644 --- a/src/metergraphrelay/__init__.py +++ b/src/metergraphrelay/__init__.py @@ -1 +1 @@ -__version__ = "0.7.9" +__version__ = "0.8.0" diff --git a/src/metergraphrelay/cli.py b/src/metergraphrelay/cli.py index 51850d3..2ff9148 100644 --- a/src/metergraphrelay/cli.py +++ b/src/metergraphrelay/cli.py @@ -63,19 +63,22 @@ def build_parser() -> argparse.ArgumentParser: pull_langfuse_parser = pull_subparsers.add_parser( "langfuse", description=( - "Pull Langfuse GENERATION observations (LLM call records) into a " - "local JSONL file shaped for metergraph's ingest API. SPAN/EVENT " - "observations and scores/evals are not imported. Requires Langfuse " - "Cloud or self-hosted v4+ (the v2 Observations API). With no " - "--trace-name/--tag/--environment/--since/--until given, imports " - "the latest --count GENERATION observations overall. WARNING: " - "generation input/output content is transferred from Langfuse " - "into the local output file, and from there into metergraph via " - "`push`, with no opt-in gate." + "Pull Langfuse observations that record an LLM call into a local " + "JSONL file shaped for metergraph's ingest API: every GENERATION, " + "and any EMBEDDING, AGENT, TOOL, CHAIN, RETRIEVER, EVALUATOR or " + "GUARDRAIL observation that names a model and carries usage or a " + "cost. Structural spans, events and scores are not imported. " + "Requires Langfuse Cloud or self-hosted v4+ (the v2 Observations " + "API). With no selector, --since or --until, imports the latest " + "--count observations overall. Rate limits (HTTP 429) and gateway " + "errors are retried after Langfuse's Retry-After. Input and output " + "content is copied into the output file by default; pass " + "--exclude-content to leave it in Langfuse." ), help=( - "Pull GENERATION call records from Langfuse (v2 Observations " - "API, Cloud/self-hosted v4+); no evals/spans/events" + "Pull LLM call records (generations, embeddings and other " + "cost-bearing observations) from Langfuse (v2 Observations API, " + "Cloud/self-hosted v4+)" ), ) pull_langfuse_parser.add_argument( @@ -84,8 +87,8 @@ def build_parser() -> argparse.ArgumentParser: type=int, default=100, help=( - "Maximum number of GENERATION observations to import (never a " - "count of distinct traces). (default: 100)" + "Maximum number of observations to import (never a count of " + "distinct traces). (default: 100)" ), ) pull_langfuse_parser.add_argument( @@ -111,7 +114,7 @@ def build_parser() -> argparse.ArgumentParser: default=None, metavar="NAME", help=( - "Only import generations whose trace name is NAME. Repeatable: " + "Only import observations whose trace name is NAME. Repeatable: " "multiple --trace-name values are OR'd together (any match). " "Combines with --tag/--environment/--since/--until using AND. " "(default: no filter, all trace names)" @@ -123,7 +126,7 @@ def build_parser() -> argparse.ArgumentParser: default=None, metavar="TAG", help=( - "Only import generations whose trace has tag TAG. Repeatable: " + "Only import observations whose trace has tag TAG. Repeatable: " "multiple --tag values require ALL given tags to be present " "(AND). Combines with --trace-name/--environment/--since/--until " "using AND. Only matches tags that already exist on the data; " @@ -136,14 +139,44 @@ def build_parser() -> argparse.ArgumentParser: default=None, help="Filter to a single Langfuse environment value. (default: no filter, all environments)", ) + _add_langfuse_attribution_selectors(pull_langfuse_parser) + pull_langfuse_parser.add_argument( + "--source-scope", + default=None, + help=( + "Import scope the rows carry, which the server deduplicates on " + "together with the observation id. Pass the --source-scope you give " + "sync langfuse so a pull and a sync of the same project never store " + "an observation twice. (default: derived from the host and public " + "key, the same on every pull of a project)" + ), + ) + pull_content = pull_langfuse_parser.add_mutually_exclusive_group() + pull_content.add_argument( + "--include-content", + dest="include_content", + action="store_true", + default=True, + help="Copy observation input and output into the output file. (default)", + ) + pull_content.add_argument( + "--exclude-content", + dest="include_content", + action="store_false", + help=( + "Leave observation input and output in Langfuse: the rows carry " + "usage, cost, timing and attribution only, marked content_opted_in " + "false." + ), + ) pull_langfuse_parser.add_argument( "--route", default=None, help=( "Override the metergraph route field for every imported row. " "(default: the Langfuse trace name, or the generation's own " - "name if the trace has none) Not a selector — see --trace-name " - "for filtering which generations are pulled." + "name if the trace has none). Not a selector: see --trace-name " + "for filtering which observations are pulled." ), ) pull_langfuse_parser.add_argument( @@ -537,7 +570,9 @@ def build_parser() -> argparse.ArgumentParser: sync_langfuse_parser = sync_subparsers.add_parser( "langfuse", description=( - "Sync Langfuse GENERATION observations to metergraph in server-" + "Sync Langfuse LLM call records (every GENERATION, and any other " + "observation that names a model and carries usage or a cost) to " + "metergraph in server-" "coordinated cron mode: pull one logical time window (at most one " "hour) from the Langfuse Observations API and push it, with " "acquire/resume/complete owned by the metergraph import-sync " @@ -546,10 +581,12 @@ def build_parser() -> argparse.ArgumentParser: "METERGRAPH_APP_TOKEN. --source-scope names this sync stream on the " "metergraph side and is required: the checkpoint is keyed on it. " "--initial-since seeds only the " - "first run. Observation content is uploaded with no opt-out." + "first run. Observation input and output are uploaded only with " + "--include-content; without it the rows carry usage, cost, timing " + "and attribution only." ), formatter_class=argparse.RawDescriptionHelpFormatter, - help="Sync Langfuse generations to metergraph (server-coordinated cron mode)", + help="Sync Langfuse LLM call records to metergraph (server-coordinated cron mode)", ) _add_sync_common(sync_langfuse_parser, scope_help=( "Name of this sync stream on the metergraph side, e.g. the Langfuse " @@ -559,16 +596,17 @@ def build_parser() -> argparse.ArgumentParser: )) sync_langfuse_parser.add_argument( "--trace-name", action="append", default=None, metavar="TRACE_NAME", - help="Only sync generations whose trace has this name. Repeatable (OR).", + help="Only sync observations whose trace has this name. Repeatable (OR).", ) sync_langfuse_parser.add_argument( "--tag", action="append", default=None, metavar="TAG", - help="Only sync generations whose trace carries this tag. Repeatable (AND).", + help="Only sync observations whose trace carries this tag. Repeatable (AND).", ) sync_langfuse_parser.add_argument( "--environment", default=None, - help="Only sync generations from this Langfuse environment.", + help="Only sync observations from this Langfuse environment.", ) + _add_langfuse_attribution_selectors(sync_langfuse_parser) sync_langfuse_parser.add_argument( "--base-url", default=None, help=( @@ -710,6 +748,37 @@ def build_parser() -> argparse.ArgumentParser: return parser +def _add_langfuse_attribution_selectors(parser: argparse.ArgumentParser) -> None: + """--user-id, --session-id and --metadata, shared by pull and sync langfuse.""" + parser.add_argument( + "--user-id", default=None, metavar="USER_ID", + help="Only import observations whose trace has this Langfuse user id.", + ) + parser.add_argument( + "--session-id", default=None, metavar="SESSION_ID", + help="Only import observations in this Langfuse session.", + ) + parser.add_argument( + "--metadata", action="append", default=None, metavar="KEY=VALUE", + help=( + "Only import observations whose metadata has KEY equal to VALUE. " + "Repeatable: every pair must match (AND)." + ), + ) + + +def _langfuse_metadata_selectors(values: list[str] | None) -> list[tuple[str, str]]: + pairs: list[tuple[str, str]] = [] + for value in values or (): + key, separator, text = value.partition("=") + if not separator or not key.strip(): + raise ConfigError( + f"--metadata expects KEY=VALUE, got {value!r}." + ) + pairs.append((key.strip(), text)) + return pairs + + def _add_sync_common(parser: argparse.ArgumentParser, *, scope_help: str) -> None: """Flags shared by the server-coordinated sync commands.""" parser.add_argument("--source-scope", default=None, help=scope_help) @@ -981,6 +1050,10 @@ def _run_pull_langfuse(args: argparse.Namespace) -> int: args.base_url or os.environ.get("LANGFUSE_BASE_URL") or DEFAULT_LANGFUSE_HOST ) until = args.until or datetime.now(timezone.utc).isoformat() + try: + metadata = _langfuse_metadata_selectors(args.metadata) + except ConfigError as exc: + return _config_error(exc) try: imported, skipped = pull_langfuse( base_url=base_url, @@ -994,11 +1067,16 @@ def _run_pull_langfuse(args: argparse.Namespace) -> int: environment=args.environment, route=args.route, output_path=args.output, + user_id=args.user_id, + session_id=args.session_id, + metadata=metadata, + include_content=args.include_content, + source_scope=(args.source_scope or "").strip() or None, ) except (LangfuseAPIError, OSError) as exc: print(f"Error: {exc}", file=sys.stderr) return 1 - print(f"Imported {imported} trace(s), skipped {skipped}, to {args.output}") + print(f"Imported {imported} observation(s), skipped {skipped}, to {args.output}") return 0 @@ -1105,6 +1183,7 @@ def _run_sync_langfuse(args: argparse.Namespace) -> int: ) try: source_scope = _require_source_scope(args) + metadata = _langfuse_metadata_selectors(args.metadata) except ConfigError as exc: return _config_error(exc) @@ -1123,6 +1202,9 @@ def pull_window(*, window_start, window_end, output_path, import_context, on_pro output_path=output_path, import_context=import_context, on_progress=on_progress, + user_id=args.user_id, + session_id=args.session_id, + metadata=metadata, ) return _run_sync_pull( diff --git a/src/metergraphrelay/providers/langfuse.py b/src/metergraphrelay/providers/langfuse.py index 7c5b238..f874649 100644 --- a/src/metergraphrelay/providers/langfuse.py +++ b/src/metergraphrelay/providers/langfuse.py @@ -1,14 +1,20 @@ from __future__ import annotations import base64 +import email.utils +import hashlib import json +import math import os +import re import sys import tempfile +import time import urllib.error import urllib.parse import urllib.request -from typing import Any, Callable +from datetime import datetime, timezone +from typing import Any, Callable, Iterable from ..reliability import reliability_fields from .. import __version__ @@ -25,18 +31,51 @@ MAX_PAGES_PER_PULL = 10_000 MAX_ITEMS_PER_PULL = 100_000 GENERATION_TYPE = "GENERATION" -# core+basic+time cover id/type/name/traceId/startTime/endTime/level/statusMessage/ -# parentObservationId/sessionId; io covers input/output; usage covers usageDetails -# and totalCost; model covers the model name (returned as `model` in -# practice, with `providedModelName` as a fallback); metadata covers explicit -# provider metadata used for provider inference in a later task; trace_context +# Langfuse's "generation-like" observation types: the ones its ingestion lets +# carry a model, usage and a cost (langfuse packages/shared/src/domain/ +# observations.ts, GenerationLikeObservationTypes, MIT). SPAN and EVENT never +# do, so they are not requested at all. +COST_BEARING_TYPES: tuple[str, ...] = ( + "GENERATION", + "EMBEDDING", + "AGENT", + "TOOL", + "CHAIN", + "RETRIEVER", + "EVALUATOR", + "GUARDRAIL", +) +# Field groups of the v2 Observations API. core+basic+time cover +# id/type/name/traceId/startTime/endTime/completionStartTime/level/ +# statusMessage/parentObservationId/sessionId/userId/version; io covers +# input/output; usage covers usageDetails, totalCost and costDetails; model +# covers the model name and modelParameters; metadata covers the explicit +# provider hints used for provider resolution; prompt covers promptName and +# promptVersion; metrics covers latency and timeToFirstToken; trace_context # denormalizes traceName/tags/environment/release onto each observation. # Requesting all of them up front avoids silently missing a field the # normalize step depends on. -RESPONSE_FIELDS = "core,basic,time,io,usage,model,metadata,trace_context" +RESPONSE_FIELDS = "core,basic,time,io,usage,model,metadata,prompt,metrics,trace_context" + +# Rate limits and gateway errors are a matter of when, not if, on a large +# pull. The policy matches the hosted importer's: honour Retry-After when +# Langfuse sends one, else double from two seconds, never wait more than two +# minutes at a time, and give up after six retries. +RETRY_STATUSES = frozenset({429, 502, 503, 504}) +MAX_RETRIES = 6 +RETRY_BASE_SECONDS = 2.0 +MAX_RETRY_SECONDS = 120.0 +REQUEST_TIMEOUT_SECONDS = 10 -def _selector_conditions(trace_names: list[str], tags: list[str]) -> list[dict[str, Any]]: +def _selector_conditions( + trace_names: list[str], + tags: list[str], + *, + user_id: str | None = None, + session_id: str | None = None, + metadata: Iterable[tuple[str, str]] = (), +) -> list[dict[str, Any]]: conditions: list[dict[str, Any]] = [] if trace_names: conditions.append( @@ -56,6 +95,24 @@ def _selector_conditions(trace_names: list[str], tags: list[str]) -> list[dict[s "value": list(tags), } ) + if user_id: + conditions.append( + {"type": "string", "column": "userId", "operator": "=", "value": user_id} + ) + if session_id: + conditions.append( + {"type": "string", "column": "sessionId", "operator": "=", "value": session_id} + ) + for key, value in metadata: + conditions.append( + { + "type": "stringObject", + "column": "metadata", + "key": key, + "operator": "=", + "value": value, + } + ) return conditions @@ -77,20 +134,38 @@ def build_base_params( trace_names: list[str], tags: list[str], environment: str | None, + observation_types: Iterable[str] = (GENERATION_TYPE,), + user_id: str | None = None, + session_id: str | None = None, + metadata: Iterable[tuple[str, str]] = (), ) -> dict[str, str]: + """Query parameters for one pull, before the page limit and cursor. + + ``observation_types`` defaults to GENERATION alone, which is what callers + written before other types were importable expect; pass + ``COST_BEARING_TYPES`` (and keep only rows that pass + ``is_importable_observation``) to import every observation that can carry + a cost. + """ + types = list(observation_types) + if not types: + raise ValueError("observation_types must name at least one type") params: dict[str, str] = {"fields": RESPONSE_FIELDS} - conditions = _selector_conditions(trace_names, tags) - if conditions: + conditions = _selector_conditions( + trace_names, tags, user_id=user_id, session_id=session_id, metadata=metadata + ) + if conditions or len(types) > 1: # Langfuse's structured `filter` param takes precedence over the - # simpler type/environment/fromStartTime/toStartTime query params — - # whenever a selector is present, those constraints must be folded - # into this same filter array, or they are silently ignored. + # simpler type/environment/fromStartTime/toStartTime query params: + # whenever a selector is present, or more than one type is wanted + # (the simple `type` param takes one), those constraints must be + # folded into this same filter array, or they are silently ignored. conditions.append( { "type": "stringOptions", "column": "type", "operator": "any of", - "value": [GENERATION_TYPE], + "value": types, } ) if since: @@ -121,7 +196,7 @@ def build_base_params( ) params["filter"] = _encode_filter(conditions) else: - params["type"] = GENERATION_TYPE + params["type"] = types[0] params["toStartTime"] = until if since: params["fromStartTime"] = since @@ -139,13 +214,46 @@ def _auth_header(public_key: str, secret_key: str) -> str: return f"Basic {token}" +def _retry_after_seconds(value: str | None, now: Callable[[], float]) -> float | None: + """Seconds named by a Retry-After header: delta-seconds or an HTTP date.""" + if not value: + return None + value = value.strip() + if value.isascii() and value.isdecimal(): + return float(value) + try: + parsed = email.utils.parsedate_to_datetime(value) + except (TypeError, ValueError, OverflowError, IndexError): + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return max(0.0, parsed.timestamp() - now()) + + +def retry_delay( + retry_after: str | None, attempt: int, *, now: Callable[[], float] = time.time +) -> float: + """Seconds to wait before retry ``attempt`` (0-based): Retry-After, else doubling.""" + seconds = _retry_after_seconds(retry_after, now) + if seconds is None: + seconds = RETRY_BASE_SECONDS * (2 ** attempt) + return min(seconds, MAX_RETRY_SECONDS) + + def fetch_observations_page( base_url: str, *, public_key: str, secret_key: str, params: dict[str, str], + sleep: Callable[[float], object] | None = time.sleep, ) -> dict[str, Any]: + """One page of observations. + + A rate limit or gateway error (``RETRY_STATUSES``) is retried up to + ``MAX_RETRIES`` times after ``retry_delay``; ``sleep=None`` disables the + retry. Any other HTTP error fails at once. + """ query = urllib.parse.urlencode(params) url = f"{base_url.rstrip('/')}{OBSERVATIONS_PATH}" if query: @@ -158,17 +266,33 @@ def fetch_observations_page( }, method="GET", ) - try: - with urllib.request.urlopen(request, timeout=10) as response: - body = read_bounded(response) - except urllib.error.HTTPError as exc: - raise LangfuseAPIError( - f"Langfuse API request failed: HTTP {exc.code} {exc.reason}" - ) from exc - except urllib.error.URLError as exc: - raise LangfuseAPIError(f"Langfuse API request failed: {exc.reason}") from exc - except ResponseTooLarge as exc: - raise LangfuseAPIError(str(exc)) from exc + attempt = 0 + while True: + try: + with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: + body = read_bounded(response) + break + except urllib.error.HTTPError as exc: + if sleep is not None and exc.code in RETRY_STATUSES and attempt < MAX_RETRIES: + headers = exc.headers + retry_after = headers.get("Retry-After") if headers is not None else None + delay = retry_delay(retry_after, attempt) + exc.close() + print( + f"Langfuse answered HTTP {exc.code}; retry {attempt + 1} of " + f"{MAX_RETRIES} in {delay:.0f} s", + file=sys.stderr, + ) + sleep(delay) + attempt += 1 + continue + raise LangfuseAPIError( + f"Langfuse API request failed: HTTP {exc.code} {exc.reason}" + ) from exc + except urllib.error.URLError as exc: + raise LangfuseAPIError(f"Langfuse API request failed: {exc.reason}") from exc + except ResponseTooLarge as exc: + raise LangfuseAPIError(str(exc)) from exc try: payload = json.loads(body) except (json.JSONDecodeError, RecursionError) as exc: @@ -177,22 +301,170 @@ def fetch_observations_page( meta = payload.get("meta") if isinstance(payload, dict) else None if not isinstance(data, list) or not isinstance(meta, dict): raise LangfuseAPIError( - "Langfuse API response missing/malformed 'data'/'meta' — unsupported " + "Langfuse API response missing/malformed 'data'/'meta': unsupported " "deployment or unexpected response shape (self-hosted v4+ with the v2 " "Observations API is required)" ) return payload -# Illustrative, not exhaustive — per the design spec's Mapping section, the -# concrete prefix table is an implementation-time task, not invented wholesale. -_PROVIDER_MODEL_PREFIXES: tuple[tuple[str, str], ...] = ( - ("gpt-", "openai"), - ("o1-", "openai"), - ("o3-", "openai"), - ("chatgpt-", "openai"), - ("claude-", "anthropic"), - ("gemini-", "google"), +# --------------------------------------------------------------------------- +# Provider resolution +# +# metergraph prices a call from its catalog, keyed on (provider, model +# spelling). Langfuse records whatever model string the caller's integration +# passed, so the relay resolves the provider, and for a gateway-style name the +# bare model, before the row leaves. Order, most to least specific: +# +# 1. an explicit provider in the observation's metadata (``provider``, +# LangChain's ``ls_provider``, OTel ``gen_ai.system`` / +# ``gen_ai.provider.name``), folded through ``_PROVIDER_SPELLINGS``; +# 2. the model string's own shape: a Bedrock ARN or model id +# (``us.anthropic.claude-...``), a Vertex resource path +# (``publishers/google/models/gemini-...``) or Anthropic-on-Vertex +# version (``claude-...@20241022``), a gateway prefix +# (``openai/gpt-4o``, LiteLLM and OpenRouter style); +# 3. a model family prefix (``gpt-``, ``o4-``, ``claude-``, ``mistral-``...). +# +# Anything else is ``unknown``, which the catalog resolves by model alone when +# the spelling is unambiguous. Approaches cross-checked against LiteLLM's +# get_llm_provider and its Bedrock cross-region prefix list +# (litellm/llms/bedrock/common_utils.py, MIT). +# --------------------------------------------------------------------------- + +# Provider spellings seen in Langfuse metadata (LangChain ls_provider, OTel +# gen_ai.system, LiteLLM custom_llm_provider) folded onto metergraph's names. +# A spelling not listed passes through lowercased. +_PROVIDER_SPELLINGS: dict[str, str] = { + "openai": "openai", + "azure": "azure", + "azure_openai": "azure", + "azure-openai": "azure", + "azure_ai": "azure", + "az.ai.openai": "azure", + "az.ai.inference": "azure", + "azure.ai.openai": "azure", + "azure.ai.inference": "azure", + "anthropic": "anthropic", + "bedrock": "bedrock", + "bedrock_converse": "bedrock", + "amazon_bedrock": "bedrock", + "amazon-bedrock": "bedrock", + "aws_bedrock": "bedrock", + "aws-bedrock": "bedrock", + "aws.bedrock": "bedrock", + "aws": "bedrock", + "google": "google", + "gemini": "google", + "google_genai": "google", + "google-genai": "google", + "google_ai_studio": "google", + "gcp.gemini": "google", + "gcp.gen_ai": "google", + "vertex": "vertex-ai", + "vertexai": "vertex-ai", + "vertex_ai": "vertex-ai", + "vertex-ai": "vertex-ai", + "google_vertexai": "vertex-ai", + "google_anthropic_vertex": "vertex-ai", + "vertex_ai_beta": "vertex-ai", + "gcp.vertex_ai": "vertex-ai", + "mistral": "mistral", + "mistralai": "mistral", + "mistral_ai": "mistral", + "meta": "meta", + "meta-llama": "meta", + "meta_llama": "meta", + "cohere": "cohere", + "cohere_chat": "cohere", + "deepseek": "deepseek", + "xai": "x-ai", + "x_ai": "x-ai", + "x-ai": "x-ai", + "grok": "x-ai", + "perplexity": "perplexity-ai", + "perplexity-ai": "perplexity-ai", + "groq": "groq", + "together": "together", + "together_ai": "together", + "togetherai": "together", + "fireworks": "fireworks", + "fireworks_ai": "fireworks", + "moonshot": "moonshotai", + "moonshotai": "moonshotai", + "alibaba": "alibaba", + "dashscope": "alibaba", + "qwen": "alibaba", + "openrouter": "openrouter", + "ollama": "ollama", +} +# Spellings that say nothing about who served the call. Resolution goes on to +# the model name instead. +_UNINFORMATIVE_PROVIDERS = frozenset( + {"", "unknown", "none", "null", "litellm", "proxy", "langfuse", "custom"} +) +# Metadata keys that carry a provider, most explicit first. Langfuse v4 +# flattens nested metadata to dotted keys; older deployments keep the nesting, +# which _metadata_value also reads. +_PROVIDER_METADATA_KEYS = ( + "provider", + "ls_provider", + "gen_ai.provider.name", + "gen_ai.system", + "custom_llm_provider", +) +# Bedrock cross-region inference prefixes and the model publishers Bedrock +# namespaces ids under (``us.anthropic.claude-...``, ``meta.llama3-...``). +_BEDROCK_MODEL_ID = re.compile( + r"^(?:(?:global|us|us-gov|eu|apac|jp|au|ca|sa)\.)?" + r"(?:anthropic|amazon|meta|mistral|cohere|ai21|deepseek|qwen|openai|writer|" + r"twelvelabs|stability|moonshotai|google|minimax|nvidia|luma)\.[a-z0-9]" +) +_VERTEX_RESOURCE = re.compile(r"(?:^|/)publishers/[^/]+/models/([^/]+)$") +# Anthropic models on Vertex are versioned with "@" (claude-3-5-sonnet-v2@20241022). +_VERTEX_ANTHROPIC = re.compile(r"^claude-[^@]+@\d{8}$") +# Gateway prefixes whose remainder is a provider's own model name. Only these +# are stripped: a prefix not listed (an org or a fine-tune path) stays part of +# the model. +_GATEWAY_PREFIXES: dict[str, str] = { + "openai": "openai", + "azure": "azure", + "anthropic": "anthropic", + "bedrock": "bedrock", + "google": "google", + "gemini": "google", + "vertex_ai": "vertex-ai", + "vertex-ai": "vertex-ai", + "mistral": "mistral", + "mistralai": "mistral", + "meta-llama": "meta", + "cohere": "cohere", + "deepseek": "deepseek", + "x-ai": "x-ai", + "xai": "x-ai", + "groq": "groq", + "together_ai": "together", + "fireworks_ai": "fireworks", + "moonshotai": "moonshotai", + "qwen": "alibaba", +} +_PROVIDER_MODEL_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = tuple( + (re.compile(pattern), provider) + for pattern, provider in ( + (r"^(?:gpt-|chatgpt-|o\d+(?:-|$)|text-embedding-(?:3|ada)|davinci-|babbage-|" + r"omni-moderation|text-moderation|whisper-|tts-|dall-e|computer-use-|codex-)", "openai"), + (r"^claude-", "anthropic"), + (r"^(?:gemini-|gemma-|text-embedding-00|text-multilingual-embedding-|" + r"imagen-|veo-)", "google"), + (r"^(?:mistral-|mixtral-|codestral-|ministral-|pixtral-|magistral-|" + r"devstral-|open-mistral-|open-mixtral-|voxtral-)", "mistral"), + (r"^(?:llama-?\d|llama-guard|meta-llama-)", "meta"), + (r"^(?:command-|command$|embed-english-|embed-multilingual-|rerank-)", "cohere"), + (r"^deepseek-", "deepseek"), + (r"^grok-", "x-ai"), + (r"^(?:qwen|qwq-)", "alibaba"), + (r"^(?:kimi-|moonshot-)", "moonshotai"), + ) ) @@ -208,19 +480,95 @@ def _resolve_model_name(observation: dict[str, Any]) -> str | None: return None -def infer_provider(observation: dict[str, Any]) -> str: +def _metadata_value(metadata: dict[str, Any], dotted_key: str) -> Any: + if dotted_key in metadata: + return metadata[dotted_key] + node: Any = metadata + for part in dotted_key.split("."): + if not isinstance(node, dict) or part not in node: + return None + node = node[part] + return node + + +def _fold_provider(spelling: str) -> str: + key = spelling.strip().lower() + return _PROVIDER_SPELLINGS.get(key, key) + + +def _explicit_provider(observation: dict[str, Any]) -> str | None: metadata = observation.get("metadata") - if isinstance(metadata, dict): - explicit = metadata.get("provider") - if isinstance(explicit, str): - explicit = explicit.strip().lower() - if explicit: - return explicit - model_name = (_resolve_model_name(observation) or "").lower() - for prefix, provider in _PROVIDER_MODEL_PREFIXES: - if model_name.startswith(prefix): - return provider - return "unknown" + if not isinstance(metadata, dict): + return None + for key in _PROVIDER_METADATA_KEYS: + value = _metadata_value(metadata, key) + if not isinstance(value, str): + continue + folded = _fold_provider(value) + if folded not in _UNINFORMATIVE_PROVIDERS: + return folded + return None + + +def _provider_from_model(model: str) -> tuple[str, str]: + """(provider, model spelling to price) from the model string alone.""" + lowered = model.strip().lower() + if lowered.startswith("arn:aws:bedrock:"): + return "bedrock", model + if _BEDROCK_MODEL_ID.match(lowered): + return "bedrock", model + vertex = _VERTEX_RESOURCE.search(model) + if vertex: + return "vertex-ai", vertex.group(1) + if _VERTEX_ANTHROPIC.match(lowered): + return "vertex-ai", model + prefix, separator, rest = model.partition("/") + if separator and rest: + gateway_provider = _GATEWAY_PREFIXES.get(prefix.strip().lower()) + if gateway_provider is not None: + if gateway_provider == "bedrock": + return "bedrock", rest + inner_provider, inner_model = _provider_from_model(rest) + if gateway_provider == "vertex-ai" or inner_provider == "unknown": + return gateway_provider, inner_model + # "openai/gpt-4o": the prefix and the family agree, or the + # family is more specific (a Bedrock id behind a prefix). + return (inner_provider if inner_provider == "bedrock" else gateway_provider), inner_model + for pattern, provider in _PROVIDER_MODEL_PATTERNS: + if pattern.match(lowered): + return provider, model + return "unknown", model + + +def resolve_provider_and_model(observation: dict[str, Any]) -> tuple[str, str | None]: + """The provider and the model spelling a row should carry. + + The model differs from Langfuse's only when a gateway prefix or a Vertex + resource path is stripped; the original is kept on the row as + ``langfuse_model``. + """ + model = _resolve_model_name(observation) + explicit = _explicit_provider(observation) + if model is None: + return explicit or "unknown", None + inferred, priced_model = _provider_from_model(model) + if explicit is None: + return inferred, priced_model + if explicit in {"openrouter", "vercel", "gateway"}: + # A router names itself; the creator prefix in the model is the + # catalog's to resolve, so the model stays as recorded. + return explicit, model + if inferred == explicit or inferred == "unknown": + return explicit, priced_model + if explicit in {"bedrock", "vertex-ai", "azure"}: + # A cloud that serves another publisher's models: the cloud is the + # channel that billed the call, the model name the publisher's. + return explicit, priced_model + return explicit, model + + +def infer_provider(observation: dict[str, Any]) -> str: + return resolve_provider_and_model(observation)[0] def _is_chat_message_list(value: Any) -> bool: @@ -396,6 +744,192 @@ def map_usage_details( } +def _positive_number(value: Any) -> bool: + return ( + isinstance(value, (int, float)) + and not isinstance(value, bool) + and math.isfinite(value) + and value > 0 + ) + + +def is_importable_observation(observation: Any) -> bool: + """Whether an observation is a call metergraph should record. + + A GENERATION always is, as it was before other types were importable. Any + other type (EMBEDDING, and the v4 AGENT/TOOL/CHAIN/RETRIEVER/EVALUATOR/ + GUARDRAIL types) is when it names a model and carries usage or a cost: + those are the ones Langfuse itself prices. Structural spans without a + model are left out. + """ + if not isinstance(observation, dict): + return False + kind = observation.get("type") + if kind == GENERATION_TYPE: + return True + if kind not in COST_BEARING_TYPES or _resolve_model_name(observation) is None: + return False + usage = observation.get("usageDetails") + # Usage units need not be whole tokens (Langfuse allows audio seconds and + # other fractional units), so any positive finite number counts. + has_usage = isinstance(usage, dict) and any( + _positive_number(value) for value in usage.values() + ) + return has_usage or _positive_number(observation.get("totalCost")) + + +def _parse_timestamp(value: Any) -> datetime | None: + if not isinstance(value, str) or not value: + return None + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) + + +def _seconds_to_ms(value: Any) -> int | None: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + if not math.isfinite(value) or value < 0: + return None + return int(round(value * 1000)) + + +def _duration_ms(observation: dict[str, Any], seconds_key: str, start_key: str, + end_key: str) -> int | None: + """Langfuse's own figure in seconds, else the gap between two timestamps.""" + reported = _seconds_to_ms(observation.get(seconds_key)) + if reported is not None: + return reported + start = _parse_timestamp(observation.get(start_key)) + end = _parse_timestamp(observation.get(end_key)) + if start is None or end is None or end < start: + return None + return int(round((end - start).total_seconds() * 1000)) + + +def _nonempty_string(value: Any) -> str | None: + return value if isinstance(value, str) and value.strip() else None + + +# metergraph keeps a call's customer metadata in ``tags``: a flat map of string +# keys to string values, at most 32 pairs, keys up to 200 and values up to +# 1000 characters. Anything outside that is dropped by the server pair by pair, +# so the relay shapes the map to fit and decides what is kept first. +MAX_TAG_PAIRS = 32 +MAX_TAG_KEY_LENGTH = 200 +MAX_TAG_VALUE_LENGTH = 1000 +LANGFUSE_TAG_PREFIX = "langfuse.tag." +LANGFUSE_TAG_VALUE = "true" +LANGFUSE_METADATA_PREFIX = "langfuse.metadata." +# The same key names the metergraph SDK's Langfuse exporter writes, so a call +# lands identically whichever path brought it in. +# Metadata the Langfuse and LangChain SDKs write themselves. It describes the +# instrumentation, not the call, and would crowd out the customer's own keys. +_SDK_METADATA_PREFIXES = ("resourceAttributes.", "scope.", "lc_versions.", "ls_") +_SDK_METADATA_KEYS = frozenset({"is_langchain_root", "resourceAttributes", "scope", + "lc_versions"}) + + +def _metadata_tag_value(value: Any) -> str | None: + if value is None: + return None + if isinstance(value, str): + return value + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float)): + return json.dumps(value) if math.isfinite(value) else None + try: + return json.dumps(value, separators=(",", ":"), sort_keys=True) + except (TypeError, ValueError): + return None + + +def _flatten_metadata(metadata: dict[str, Any], prefix: str = "") -> Iterable[tuple[str, Any]]: + for key, value in metadata.items(): + if not isinstance(key, str): + continue + dotted = f"{prefix}{key}" + if isinstance(value, dict) and value: + yield from _flatten_metadata(value, f"{dotted}.") + else: + yield dotted, value + + +def _customer_metadata(metadata: Any) -> dict[str, str]: + """Langfuse metadata as metergraph customer metadata (string to string).""" + if not isinstance(metadata, dict): + return {} + kept: dict[str, str] = {} + for key, value in _flatten_metadata(metadata): + if key in _SDK_METADATA_KEYS or key.startswith(_SDK_METADATA_PREFIXES): + continue + text = _metadata_tag_value(value) + if text is None or not key or len(key) > MAX_TAG_KEY_LENGTH: + continue + if len(text) > MAX_TAG_VALUE_LENGTH: + continue + kept[key] = text + return kept + + +def build_tags(observation: dict[str, Any], *, name: str | None = None) -> dict[str, str]: + """The row's ``tags`` map, in priority order, at most 32 pairs. + + 1. Each Langfuse tag as its own pair, ``langfuse.tag.: "true"``, so a + metadata filter or group-by on one tag works. + 2. ``name``, the trace name, when ``--route`` replaced it as the route. + 3. ``langfuse.release``, ``langfuse.version``, ``langfuse.prompt.name`` + and ``langfuse.prompt.version``. + 4. The customer's metadata as ``langfuse.metadata.``, in key order. + """ + tags: dict[str, str] = {} + langfuse_tags = observation.get("tags") + if isinstance(langfuse_tags, list): + for tag in langfuse_tags: + if not isinstance(tag, str) or not tag: + continue + key = f"{LANGFUSE_TAG_PREFIX}{tag}" + if len(key) <= MAX_TAG_KEY_LENGTH: + tags[key] = LANGFUSE_TAG_VALUE + if name: + tags["name"] = name + prompt_version = observation.get("promptVersion") + for key, value in ( + ("langfuse.release", _nonempty_string(observation.get("release"))), + ("langfuse.version", _nonempty_string(observation.get("version"))), + ("langfuse.prompt.name", _nonempty_string(observation.get("promptName"))), + ("langfuse.prompt.version", str(prompt_version) if _is_int(prompt_version) else None), + ): + if value is not None and len(value) <= MAX_TAG_VALUE_LENGTH: + tags[key] = value + for key, value in sorted(_customer_metadata(observation.get("metadata")).items()): + prefixed = f"{LANGFUSE_METADATA_PREFIX}{key}" + if len(prefixed) <= MAX_TAG_KEY_LENGTH: + tags.setdefault(prefixed, value) + if len(tags) > MAX_TAG_PAIRS: + tags = dict(list(tags.items())[:MAX_TAG_PAIRS]) + return tags + + +def _cost_details(value: Any) -> dict[str, str] | None: + """Langfuse's per-bucket cost (``costDetails``) as decimal strings.""" + if not isinstance(value, dict): + return None + details: dict[str, str] = {} + for key, amount in value.items(): + reported = reported_cost(amount, source="langfuse") + if isinstance(key, str) and reported: + details[key] = reported["reported_cost_usd"] + return details or None + + +def _model_parameters(value: Any) -> dict[str, Any] | None: + return value if isinstance(value, dict) and value else None + + def normalize_observation( observation: dict[str, Any], *, @@ -413,12 +947,9 @@ def normalize_observation( route = name_fallback or "" name_consumed = True - tags: dict[str, Any] = {} - langfuse_tags = observation.get("tags") - if isinstance(langfuse_tags, list) and langfuse_tags: - tags["langfuse_tags"] = list(langfuse_tags) - if not name_consumed and name_fallback: - tags["name"] = name_fallback + tags = build_tags( + observation, name=name_fallback if not name_consumed else None + ) error = observation.get("level") == "ERROR" raw_status_message = observation.get("statusMessage") @@ -426,13 +957,14 @@ def normalize_observation( raw_status_message if error and isinstance(raw_status_message, str) else None ) - provider = infer_provider(observation) + provider, model = resolve_provider_and_model(observation) + langfuse_model = _resolve_model_name(observation) usage = map_usage_details(observation.get("usageDetails"), provider=provider) request_json, request_text = _map_content(observation.get("input")) response_text = _response_text(observation.get("output")) - model = _resolve_model_name(observation) stop_reason = extract_stop_reason(observation) + prompt_version = observation.get("promptVersion") row = { "ts": observation["startTime"], @@ -464,6 +996,29 @@ def normalize_observation( "session_id": observation.get("sessionId"), "environment": observation.get("environment"), } + # Attribution and timing Langfuse reports for this observation. Each is + # left off the row when Langfuse has no value, as an absent field and a + # null mean the same thing to the ingest API. + optional = { + "trace_name": trace_name, + "observation_type": observation.get("type"), + "latency_ms": _duration_ms(observation, "latency", "startTime", "endTime"), + "ttft_ms": _duration_ms( + observation, "timeToFirstToken", "startTime", "completionStartTime" + ), + "user_id": _nonempty_string(observation.get("userId")), + "release": _nonempty_string(observation.get("release")), + "version": _nonempty_string(observation.get("version")), + "prompt_name": _nonempty_string(observation.get("promptName")), + "prompt_version": prompt_version if _is_int(prompt_version) else None, + "model_parameters": _model_parameters(observation.get("modelParameters")), + } + row.update({key: value for key, value in optional.items() if value is not None}) + if langfuse_model is not None and langfuse_model != model: + row["langfuse_model"] = langfuse_model + cost_details = _cost_details(observation.get("costDetails")) + if cost_details is not None and "reported_cost_usd" in row: + row["reported_cost_details"] = cost_details if stop_reason is not None: row["stop_reason"] = stop_reason if import_context is not None: @@ -478,6 +1033,33 @@ def normalize_observation( return capture_row(row) +# The fields that hold provider content on a row. A content-blind row has none +# of them and says so with content_opted_in = False. +CONTENT_FIELDS = ("request_json", "request_text", "response_text", "tool_calls") + + +def strip_content(row: dict) -> dict: + for field in CONTENT_FIELDS: + row.pop(field, None) + row["content_opted_in"] = False + return row + + +def default_import_scope(base_url: str, public_key: str) -> str: + """A stable ``import_source_scope`` for a ``pull`` of one Langfuse project. + + A Langfuse API key pair belongs to exactly one project, so the host plus + the public key names the project. Only a digest of them goes on the row: + the scope is an identity for deduplication, not a place to carry a key. + Re-pulling the same project gives the same scope, so the server's + (source, scope, observation id) claim drops a re-pulled observation + instead of storing it twice. + """ + host = base_url.strip().rstrip("/").lower() + digest = hashlib.sha256(f"{host}\n{public_key.strip()}".encode()).hexdigest() + return f"pull:{digest[:32]}" + + def _cleanup_temp_file(tmp_path: str) -> None: try: os.remove(tmp_path) @@ -500,13 +1082,31 @@ def pull_langfuse( output_path: str, import_context: ImportContext | None = None, on_progress: Callable[[], None] | None = None, + user_id: str | None = None, + session_id: str | None = None, + metadata: Iterable[tuple[str, str]] = (), + observation_types: Iterable[str] = COST_BEARING_TYPES, + include_content: bool = True, + sleep: Callable[[float], object] = time.sleep, + source_scope: str | None = None, ) -> tuple[int, int]: + if import_context is None: + # Every pulled row carries an import identity, not only sync's: without + # one, pushing an overlapping pull again stores each observation twice. + import_context = ImportContext( + source="langfuse", + source_scope=source_scope or default_import_scope(base_url, public_key), + ) base_params = build_base_params( until=until, since=since, trace_names=trace_names, tags=tags, environment=environment, + observation_types=observation_types, + user_id=user_id, + session_id=session_id, + metadata=list(metadata), ) imported = 0 skipped = 0 @@ -515,6 +1115,13 @@ def pull_langfuse( page_count = 0 item_count = 0 + def wait(seconds: float) -> None: + # A rate-limit wait is progress as far as a sync lease is concerned: + # renew after each one, so a long Retry-After cannot expire it. + sleep(seconds) + if on_progress is not None: + on_progress() + output_dir = os.path.dirname(output_path) or "." fd, tmp_path = tempfile.mkstemp( dir=output_dir, prefix=f".{os.path.basename(output_path)}.", suffix=".tmp" @@ -543,6 +1150,7 @@ def pull_langfuse( public_key=public_key, secret_key=secret_key, params=page_params, + sleep=wait, ) if on_progress is not None: on_progress() # a page fetch is progress too @@ -557,12 +1165,19 @@ def pull_langfuse( for observation in observations: if imported >= count: break + if isinstance(observation, dict) and not is_importable_observation( + observation + ): + # A span with no model and no cost: structure, not a call. + continue try: row = normalize_observation( observation, route_override=route, import_context=import_context, ) + if not include_content: + strip_content(row) line = json.dumps(row) except (KeyError, TypeError, AttributeError) as exc: skipped += 1 diff --git a/tests/e2e/langfuse_ingest.py b/tests/e2e/langfuse_ingest.py new file mode 100644 index 0000000..2dca3cb --- /dev/null +++ b/tests/e2e/langfuse_ingest.py @@ -0,0 +1,167 @@ +"""Latest relay Langfuse pull -> a running metergraph server, read back. + +Drives the real ``pull_langfuse`` loop against the recorded Langfuse fixture +(tests/fixtures/langfuse_v2, served as one stubbed page, so no Langfuse +credential is needed), pushes the JSONL to ``MG_URL`` and reads every row back +through ``/v1/calls``. What survives that round trip is the actual relay to +server contract; unit tests only prove what the relay writes to disk. + +What this is here to catch: + +* **Tags.** The server keeps only string values in ``tags``. Langfuse tags used + to travel as one list and were dropped whole; each must now land as its own + ``langfuse.tag.: "true"`` pair, next to the customer's metadata + (``langfuse.metadata.``). +* **Timing.** ``latency_ms`` and ``ttft_ms`` come from Langfuse's seconds. +* **Every cost-bearing observation lands**, embeddings included, with the + provider resolved and Langfuse's cost carried as ``reported_cost_usd``. +* **Attribution**, where the server's read returns it: ``user_id``. +* **Re-syncs do not duplicate.** The same pull is pushed twice; every + observation must be stored once, deduplicated on its import identity. + +Run it against a server whose ``/v1/calls`` returns ``tags``, ``ttft_ms``, +``user_id`` and ``reported_cost_usd``: metergraph's hosted app does; the OSS +server's read does not return them yet, so this is not part of the OSS CI job. + +Set ``MG_URL`` and ``MG_TOKEN`` (a key with ingest and read scope). ``MG_REPORT`` names a file to write the +read-back rows to (cost status and catalog price per row), for comparing a +server's pricing with Langfuse's. +""" + +from __future__ import annotations + +import json +import os +import tempfile +import time +import urllib.parse +import urllib.request +import uuid +from decimal import Decimal +from pathlib import Path +from unittest.mock import patch + +from metergraphrelay.providers import langfuse +from metergraphrelay.providers.langfuse import COST_BEARING_TYPES, pull_langfuse +from metergraphrelay.push import push_file + +FIXTURE_DIR = Path(__file__).resolve().parent.parent / "fixtures" / "langfuse_v2" +ROUTE_PREFIX = "relay.langfuse-e2e" + + +def _fixture_page(base_url, *, public_key, secret_key, params, sleep=None): + conditions = json.loads(params["filter"]) + assert conditions[0]["value"] == list(COST_BEARING_TYPES), conditions + observations = json.loads((FIXTURE_DIR / "observations.json").read_text()) + return {"data": observations["data"], "meta": {"cursor": None}} + + +def _read_rows(base_url: str, token: str, route: str) -> list[dict]: + query = urllib.parse.urlencode({"route": route, "limit": 500}) + request = urllib.request.Request( + f"{base_url}/v1/calls?{query}", + headers={"Authorization": f"Bearer {token}"}, + ) + with urllib.request.urlopen(request, timeout=10) as response: + payload = json.load(response) + return [item for item in payload["items"] if item["route"] == route] + + +def _read_back(base_url: str, token: str, route: str) -> dict[str, dict]: + return {item["request_id"]: item for item in _read_rows(base_url, token, route)} + + +def main() -> None: + base_url = os.environ["MG_URL"].rstrip("/") + token = os.environ["MG_TOKEN"] + manifest = json.loads((FIXTURE_DIR / "manifest.json").read_text()) + cost_keys = [k for k, v in manifest["observations"].items() if v.get("cost_bearing")] + route = f"{ROUTE_PREFIX}.{uuid.uuid4().hex}" + + with tempfile.TemporaryDirectory() as temporary_directory: + output = Path(temporary_directory) / "langfuse.jsonl" + with patch.object(langfuse, "fetch_observations_page", _fixture_page): + imported, skipped = pull_langfuse( + base_url="https://cloud.langfuse.com", + public_key="not-used-by-the-stub", + secret_key="not-used-by-the-stub", + count=1000, + since=None, + until="2026-01-02T00:00:00Z", + trace_names=[], + tags=[], + environment=None, + route=route, + output_path=str(output), + ) + assert (imported, skipped) == (len(cost_keys), 0), (imported, skipped) + pushed, failed = push_file(str(output), token, base_url=base_url) + assert (pushed, failed) == (imported, 0), (pushed, failed) + # A re-sync of the same window: the server must drop every row. + pushed, failed = push_file(str(output), token, base_url=base_url) + assert (pushed, failed) == (imported, 0), (pushed, failed) + + # A server with a queue (the hosted app's worker) stores rows a little + # after the push returns; wait for all of them, within a bound. + expected_ids = {manifest["observations"][key]["id"] for key in cost_keys} + deadline = time.monotonic() + float(os.environ.get("MG_WAIT_SECONDS", "90")) + stored = _read_back(base_url, token, route) + while not expected_ids <= stored.keys() and time.monotonic() < deadline: + time.sleep(2) + stored = _read_back(base_url, token, route) + # Give the second push's batch time to be processed (and dropped) too. + time.sleep(float(os.environ.get("MG_DEDUP_SETTLE_SECONDS", "10"))) + rows = _read_rows(base_url, token, route) + duplicated = sorted( + request_id for request_id in {r["request_id"] for r in rows} + if sum(r["request_id"] == request_id for r in rows) > 1 + ) + assert not duplicated, f"re-sync stored these observations twice: {duplicated}" + stored = {r["request_id"]: r for r in rows} + report = [] + for key in cost_keys: + spec = manifest["observations"][key] + readback = manifest["langfuse_readback"][key] + trace = manifest["traces"][spec["trace"]] + item = stored.get(spec["id"]) + assert item is not None, f"{key} did not land" + tags = item["tags"] or {} + for tag in trace["tags"]: + assert tags.get(f"langfuse.tag.{tag}") == "true", (key, tags) + if spec["trace"] == "main": + assert tags.get("langfuse.metadata.customer_tier") == "gold", (key, tags) + if "user_id" in item and trace.get("user_id"): + assert item["user_id"] == trace["user_id"], (key, item["user_id"]) + if readback.get("latency") is not None: + assert item["latency_ms"] == round(readback["latency"] * 1000), (key, item) + if readback.get("timeToFirstToken") is not None: + assert item["ttft_ms"] == round(readback["timeToFirstToken"] * 1000), (key, item) + assert item["provider"] in spec["expected_providers"], (key, item["provider"]) + reported = item.get("reported_cost_usd") + assert reported is not None, f"{key}: Langfuse's cost was not kept" + assert Decimal(str(reported)) == Decimal(str(readback["totalCost"])), (key, reported) + report.append({ + "key": key, + "provider": item["provider"], + "model": item["model"], + "langfuse_cost": readback["totalCost"], + "cost_usd": item.get("cost_usd"), + "reported_cost_usd": reported, + "catalog_cost_usd": item.get("catalog_cost_usd"), + "cost_status": item.get("cost_status"), + "catalog_reasons": item.get("catalog_reasons"), + "latency_ms": item["latency_ms"], + "ttft_ms": item["ttft_ms"], + "user_id": item.get("user_id"), + "tag_pairs": len(tags), + }) + if os.environ.get("MG_REPORT"): + Path(os.environ["MG_REPORT"]).write_text(json.dumps(report, indent=2) + "\n") + print( + f"langfuse e2e: {len(report)} rows round-tripped with tags, timing and cost;" + " a second push of the same rows stored none" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/fixtures/langfuse_v2/README.md b/tests/fixtures/langfuse_v2/README.md new file mode 100644 index 0000000..c4a422f --- /dev/null +++ b/tests/fixtures/langfuse_v2/README.md @@ -0,0 +1,18 @@ +# Langfuse v2 conformance fixture + +Real responses from Langfuse Cloud for one seeded conformance run (Langfuse +Python SDK 5.2.0), scrubbed before they were committed. Content is synthetic; +ids are hashes of stable labels and timestamps are shifted to start at +2026-01-01T00:00:00Z, while durations are real. + +- `observations.json`: `GET /api/public/v2/observations` with every field group + (`core,basic,time,io,metadata,model,usage,prompt,metrics,trace_context`), + all 18 observations of the run and every observation type, in the API's own + `{"data": [...], "meta": {...}}` shape so a test can serve it as one page. +- `manifest.json`: what the seeder sent (`observations.`, `traces.`) + and what Langfuse reported back (`langfuse_readback.`: `totalCost`, + `latency`, `timeToFirstToken`, `usageDetails`). Tests use it as the expected + values. + +Vendor updates unchanged. Do not hand-edit these files: a field that changes +upstream should show up as a diff here. diff --git a/tests/fixtures/langfuse_v2/manifest.json b/tests/fixtures/langfuse_v2/manifest.json new file mode 100644 index 0000000..636b375 --- /dev/null +++ b/tests/fixtures/langfuse_v2/manifest.json @@ -0,0 +1,740 @@ +{ + "dataset": { + "items": [ + { + "expected_output": { + "label": "billing" + }, + "id": "mg-conformance-item-0", + "input": { + "text": "item 0" + } + }, + { + "expected_output": { + "label": "billing" + }, + "id": "mg-conformance-item-1", + "input": { + "text": "item 1" + } + }, + { + "expected_output": { + "label": "billing" + }, + "id": "mg-conformance-item-2", + "input": { + "text": "item 2" + } + } + ], + "name": "mg-conformance-dataset" + }, + "double_count_case": false, + "environment": "conformance", + "experiment": { + "dataset_run_id": "e7b1c174f5edb86a", + "items": 3, + "name": "mg-conformance-experiment", + "run_name": "mg-conformance-experiment-mg-conformance-fixture" + }, + "langfuse_readback": { + "agent_root": { + "latency": 2.848, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "anthropic_cache_rw": { + "latency": 0.406, + "timeToFirstToken": 0.154, + "totalCost": 0.000884, + "usageDetails": { + "cache_creation_input_tokens": 300, + "cache_read_input_tokens": 800, + "input": 200, + "output": 90, + "total": 1390 + } + }, + "bedrock_claude": { + "latency": 0.407, + "timeToFirstToken": 0.152, + "totalCost": 0.00052, + "usageDetails": { + "input": 400, + "output": 50, + "total": 450 + } + }, + "delete_me": { + "latency": null, + "timeToFirstToken": null, + "totalCost": 4.5e-06, + "usageDetails": { + "input": 10, + "output": 5, + "total": 15 + } + }, + "embedding": { + "latency": null, + "timeToFirstToken": null, + "totalCost": 2.4e-05, + "usageDetails": { + "input": 1200, + "total": 1200 + } + }, + "error_call": { + "latency": 0.401, + "timeToFirstToken": 0.151, + "totalCost": 1.5e-05, + "usageDetails": { + "input": 100, + "output": 0, + "total": 100 + } + }, + "gateway_openai": { + "latency": 0.409, + "timeToFirstToken": 0.156, + "totalCost": 0.00135, + "usageDetails": { + "input": 300, + "output": 60, + "total": 360 + } + }, + "kb_retriever": { + "latency": null, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "langchain_chain": { + "latency": 0.02, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "langchain_generation": { + "latency": 0.014, + "timeToFirstToken": null, + "totalCost": 8.46e-05, + "usageDetails": { + "input": 188, + "input_cache_read": 512, + "output": 30, + "output_reasoning": 0, + "total": 730 + } + }, + "llm_step": { + "latency": 2.847, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "lookup_tool": { + "latency": null, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "o4_mini": { + "latency": 0.405, + "timeToFirstToken": 0.151, + "totalCost": 0.00275, + "usageDetails": { + "input": 500, + "output": 300, + "output_reasoning_tokens": 200, + "total": 1000 + } + }, + "observe_generation": { + "latency": 0.001, + "timeToFirstToken": null, + "totalCost": 8.46e-05, + "usageDetails": { + "input": 188, + "input_cached_tokens": 512, + "output": 30, + "output_reasoning_tokens": 0, + "total": 730 + } + }, + "observe_span": { + "latency": 0.212, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "openai_cached_reasoning": { + "latency": 0.409, + "timeToFirstToken": 0.154, + "totalCost": 0.000252, + "usageDetails": { + "input": 900, + "input_cached_tokens": 600, + "output": 120, + "output_reasoning_tokens": 40, + "total": 1660 + } + }, + "plan_chain": { + "latency": 2.847, + "timeToFirstToken": null, + "totalCost": null, + "usageDetails": {} + }, + "unknown_mistral": { + "latency": 0.407, + "timeToFirstToken": 0.152, + "totalCost": 0.00074, + "usageDetails": { + "input": 250, + "output": 40, + "total": 290 + } + } + }, + "observations": { + "agent_root": { + "depth": 0, + "id": "c4a8ba5bc88db86b", + "name": "agent-root", + "parent": null, + "trace": "main", + "type": "AGENT" + }, + "anthropic_cache_rw": { + "cost_bearing": true, + "cost_supplied": { + "cache_creation_input_tokens": 0.0003, + "cache_read_input_tokens": 6.4e-05, + "input": 0.00016, + "output": 0.00036, + "total": 0.000884 + }, + "depth": 3, + "expected_providers": [ + "anthropic" + ], + "id": "865405e64b09ea88", + "latency_ms_min": 400, + "level": "DEFAULT", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "anthropic_cache_rw" + }, + "model": "claude-3-5-haiku-20241022", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-anthropic_cache_rw", + "parent": "llm_step", + "prompt": null, + "status_message": null, + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "cache_creation_input_tokens": 300, + "cache_read_input_tokens": 800, + "input": 200, + "output": 90 + } + }, + "bedrock_claude": { + "cost_bearing": true, + "cost_supplied": null, + "depth": 3, + "expected_providers": [ + "bedrock", + "aws-bedrock", + "amazon-bedrock", + "anthropic" + ], + "id": "985dce7ccae0dda1", + "latency_ms_min": 400, + "level": "DEFAULT", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "bedrock_claude" + }, + "model": "us.anthropic.claude-3-5-haiku-20241022-v1:0", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-bedrock_claude", + "parent": "llm_step", + "prompt": null, + "status_message": null, + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "input": 400, + "output": 50 + } + }, + "delete_me": { + "cost_bearing": true, + "cost_supplied": null, + "depth": 0, + "expected_providers": [ + "openai" + ], + "id": "6f3c48d99fc9091c", + "model": "gpt-4o-mini", + "name": "gen-delete-me", + "parent": null, + "style": "manual", + "trace": "delete", + "type": "GENERATION", + "usage": { + "input": 10, + "output": 5 + } + }, + "embedding": { + "cost_bearing": true, + "cost_supplied": { + "total": 2.4e-05 + }, + "depth": 3, + "expected_providers": [ + "openai" + ], + "id": "37e3593ce5154e06", + "model": "text-embedding-3-small", + "name": "embed-query", + "parent": "kb_retriever", + "trace": "main", + "type": "EMBEDDING", + "usage": { + "input": 1200 + } + }, + "error_call": { + "cost_bearing": true, + "cost_supplied": null, + "depth": 3, + "expected_providers": [ + "openai" + ], + "id": "c91b73905cc19465", + "latency_ms_min": 400, + "level": "ERROR", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "error_call" + }, + "model": "gpt-4o-mini", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-error_call", + "parent": "llm_step", + "prompt": null, + "status_message": "RateLimitError: 429 from upstream", + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "input": 100, + "output": 0 + } + }, + "gateway_openai": { + "cost_bearing": true, + "cost_supplied": { + "total": 0.00135 + }, + "depth": 3, + "expected_providers": [ + "openai" + ], + "id": "5476ecfcd272f398", + "latency_ms_min": 400, + "level": "DEFAULT", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "gateway_openai" + }, + "model": "openai/gpt-4o", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-gateway_openai", + "parent": "llm_step", + "prompt": null, + "status_message": null, + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "input": 300, + "output": 60 + } + }, + "kb_retriever": { + "depth": 2, + "id": "930d313b5153d068", + "name": "kb-retriever", + "parent": "plan_chain", + "trace": "main", + "type": "RETRIEVER" + }, + "langchain_chain": { + "discovered": true, + "id": "127aaf08b9b8dd55", + "name": "conformance-langchain", + "parent": null, + "style": "langchain", + "trace": "langchain", + "type": "CHAIN" + }, + "langchain_generation": { + "cost_bearing": true, + "discovered": true, + "expected_providers": [ + "openai" + ], + "id": "58dd83d9847cbce7", + "model": "gpt-4o-mini-2024-07-18", + "name": "ChatOpenAI", + "parent": "langchain_chain", + "style": "langchain", + "trace": "langchain", + "type": "GENERATION", + "usage": { + "cache_read_tokens": 512, + "input_tokens": 700, + "output_tokens": 30 + } + }, + "llm_step": { + "depth": 2, + "id": "ca12db61422ad962", + "name": "llm-step", + "parent": "plan_chain", + "trace": "main", + "type": "SPAN" + }, + "lookup_tool": { + "depth": 2, + "id": "3acd634d1620dab3", + "name": "lookup-tool", + "parent": "plan_chain", + "trace": "main", + "type": "TOOL" + }, + "o4_mini": { + "cost_bearing": true, + "cost_supplied": null, + "depth": 3, + "expected_providers": [ + "openai" + ], + "id": "b60e6aecb9f84bf0", + "latency_ms_min": 400, + "level": "DEFAULT", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "o4_mini" + }, + "model": "o4-mini", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-o4_mini", + "parent": "llm_step", + "prompt": null, + "status_message": null, + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "input": 500, + "output": 300, + "output_reasoning_tokens": 200 + } + }, + "observe_generation": { + "cost_bearing": true, + "discovered": true, + "expected_providers": [ + "openai" + ], + "id": "be12f10427427b89", + "model": "gpt-4o-mini-2024-07-18", + "name": "OpenAI-generation", + "parent": "observe_span", + "style": "observe+langfuse.openai", + "trace": "observe", + "type": "GENERATION", + "usage": { + "cache_read_tokens": 512, + "input_tokens": 700, + "output_tokens": 30 + } + }, + "observe_span": { + "discovered": true, + "id": "339bfa3c4d828a55", + "name": "observe-decorated", + "parent": null, + "style": "observe+langfuse.openai", + "trace": "observe", + "type": "SPAN" + }, + "openai_cached_reasoning": { + "cost_bearing": true, + "cost_supplied": null, + "depth": 3, + "expected_providers": [ + "openai" + ], + "id": "a5f2b78f6eedc308", + "latency_ms_min": 400, + "level": "DEFAULT", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "openai_cached_reasoning" + }, + "model": "gpt-4o-mini", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-openai_cached_reasoning", + "parent": "llm_step", + "prompt": { + "name": "mg-conformance-prompt", + "version": 1 + }, + "status_message": null, + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "input": 900, + "input_cached_tokens": 600, + "output": 120, + "output_reasoning_tokens": 40 + } + }, + "plan_chain": { + "depth": 1, + "id": "80fdd884cc213178", + "name": "plan-chain", + "parent": "agent_root", + "trace": "main", + "type": "CHAIN" + }, + "unknown_mistral": { + "cost_bearing": true, + "cost_supplied": { + "input": 0.0005, + "output": 0.00024, + "total": 0.00074 + }, + "depth": 3, + "expected_providers": [ + "mistral", + "mistralai" + ], + "id": "8787d86de8cf8bac", + "latency_ms_min": 400, + "level": "DEFAULT", + "metadata": { + "nested": { + "attempt": 1, + "region": "us-west-2" + }, + "step": "unknown_mistral" + }, + "model": "mistral-large-latest", + "model_parameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-unknown_mistral", + "parent": "llm_step", + "prompt": null, + "status_message": null, + "style": "manual", + "trace": "main", + "ttft_ms_min": 150, + "type": "GENERATION", + "usage": { + "input": 250, + "output": 40 + } + } + }, + "prompt": { + "config": { + "model": "gpt-4o-mini", + "temperature": 0 + }, + "labels": [ + "production" + ], + "name": "mg-conformance-prompt", + "version": 1 + }, + "release": "rel-2026.11.22", + "schema": "mg-langfuse-conformance-manifest/1", + "scores": [ + { + "data_type": "NUMERIC", + "id": "mg-conformance-fixture-mg-helpfulness", + "name": "mg-helpfulness", + "target": "trace", + "trace_id": "23456a48a189ca76b6a9f57328c6c1f9", + "value": 0.8 + }, + { + "data_type": "BOOLEAN", + "id": "mg-conformance-fixture-mg-correct", + "name": "mg-correct", + "observation_id": "a5f2b78f6eedc308", + "target": "observation", + "trace_id": "23456a48a189ca76b6a9f57328c6c1f9", + "value": 1 + }, + { + "data_type": "CATEGORICAL", + "id": "mg-conformance-fixture-mg-category", + "name": "mg-category", + "observation_id": "a5f2b78f6eedc308", + "target": "observation", + "trace_id": "23456a48a189ca76b6a9f57328c6c1f9", + "value": "billing" + }, + { + "data_type": "TEXT", + "id": "mg-conformance-fixture-mg-note", + "name": "mg-note", + "target": "trace", + "trace_id": "23456a48a189ca76b6a9f57328c6c1f9", + "value": "looks fine" + }, + { + "data_type": "NUMERIC", + "id": "mg-conformance-fixture-mg-session-quality", + "name": "mg-session-quality", + "session_id": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "target": "session", + "value": 4 + } + ], + "scrubbed": { + "dropped": "^(scope\\.attributes\\.public_key|resourceAttributes\\.service\\.instance\\.id)$", + "epoch": "2026-01-01T00:00:00+00:00", + "ids": "sha256 of stable labels", + "tag": "mg-conformance-fixture" + }, + "sdk_versions": { + "langchain-openai": "1.8.5", + "langfuse": "5.2.0", + "metergraph": "0.6.22", + "openai": "3.57.0" + }, + "seeded_at": "2026-01-01T00:00:00+00:00", + "session_id": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "tag": "mg-conformance-fixture", + "traces": { + "delete": { + "delete_after_first_import": true, + "id": "886d3f5236bfd2e175d96530e6ea2b54", + "name": "conformance-delete", + "tags": [ + "mg-conformance-fixture", + "to-delete" + ] + }, + "langchain": { + "expected_generations": 1, + "id": "edbfab4ba39e90abb5732115c94c9388", + "mock_usage": { + "cache_read_tokens": 512, + "input_tokens": 700, + "output_tokens": 30 + }, + "name": "conformance-langchain", + "style": "langchain", + "tags": [ + "langchain", + "mg-conformance-fixture" + ] + }, + "main": { + "id": "23456a48a189ca76b6a9f57328c6c1f9", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage" + }, + "name": "conformance-workflow", + "session_id": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "style": "manual", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "user_id": "user-conf-1", + "version": "app-v1.4.2" + }, + "observe": { + "id": "e3ab5bba96a1a8ed84810bb01b0ce784", + "mock_usage": { + "cache_read_tokens": 512, + "input_tokens": 700, + "output_tokens": 30 + }, + "name": "conformance-observe", + "style": "observe+langfuse.openai", + "tags": [ + "mg-conformance-fixture", + "observe" + ], + "user_id": "user-conf-2" + } + }, + "version": "app-v1.4.2", + "with_metergraph_exporter": false +} diff --git a/tests/fixtures/langfuse_v2/observations.json b/tests/fixtures/langfuse_v2/observations.json new file mode 100644 index 0000000..647a86d --- /dev/null +++ b/tests/fixtures/langfuse_v2/observations.json @@ -0,0 +1,1267 @@ +{ + "data": [ + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": { + "input": 2.4e-05, + "total": 2.4e-05 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:00.483Z", + "environment": "conformance", + "id": "37e3593ce5154e06", + "input": "hi", + "inputCost": 2.4e-05, + "inputPrice": null, + "inputUsage": 1200, + "internalModelId": "aed0b00d40fcd65dffa571f4c", + "isRootObservation": false, + "latency": null, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "text-embedding-3-small", + "modelId": "aed0b00d40fcd65dffa571f4c", + "modelParameters": {}, + "name": "embed-query", + "output": null, + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": "930d313b5153d068", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.483Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": null, + "totalCost": 2.4e-05, + "totalPrice": "2e-8", + "totalUsage": 1200, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "EMBEDDING", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 1200, + "total": 1200 + }, + "usagePricingTierId": "2ecf9e270569745d6047425ccb2f39d3aee56c", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:00.483Z", + "environment": "conformance", + "id": "930d313b5153d068", + "input": null, + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": false, + "latency": null, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "kb-retriever", + "output": null, + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": "80fdd884cc213178", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.483Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "RETRIEVER", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:00.483Z", + "environment": "conformance", + "id": "3acd634d1620dab3", + "input": "{\"id\": 7}", + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": false, + "latency": null, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "lookup-tool", + "output": "{\"ok\": true}", + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": "80fdd884cc213178", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.483Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "TOOL", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:03.330Z", + "environment": "conformance", + "id": "ca12db61422ad962", + "input": null, + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": false, + "latency": 2.847, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "llm-step", + "output": null, + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": "80fdd884cc213178", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.483Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "SPAN", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:03.331Z", + "environment": "conformance", + "id": "c4a8ba5bc88db86b", + "input": "{\"q\": \"hi\"}", + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": true, + "latency": 2.848, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "agent-root", + "output": "{\"a\": \"done\"}", + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": null, + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.483Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "AGENT", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:03.330Z", + "environment": "conformance", + "id": "80fdd884cc213178", + "input": null, + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": false, + "latency": 2.847, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "plan-chain", + "output": null, + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": "c4a8ba5bc88db86b", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.483Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "CHAIN", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:00.638Z", + "costDetails": { + "input": 0.000135, + "input_cached_tokens": 4.5e-05, + "output": 7.2e-05, + "total": 0.000252 + }, + "createdAt": "2026-01-01T00:00:05.015Z", + "endTime": "2026-01-01T00:00:00.893Z", + "environment": "conformance", + "id": "a5f2b78f6eedc308", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case openai_cached_reasoning\"}]", + "inputCost": 0.00018, + "inputPrice": "1.5e-7", + "inputUsage": 1500, + "internalModelId": "d259773a00a5ab602a37664ab", + "isRootObservation": false, + "latency": 0.409, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "openai_cached_reasoning" + }, + "model": "gpt-4o-mini", + "modelId": "d259773a00a5ab602a37664ab", + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-openai_cached_reasoning", + "output": "ok", + "outputCost": 7.2e-05, + "outputPrice": "6e-7", + "outputUsage": 160, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "8000792d301ae2aeda09e3cd2", + "promptName": "mg-conformance-prompt", + "promptVersion": 1, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.484Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.154, + "totalCost": 0.000252, + "totalPrice": null, + "totalUsage": 1660, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.015Z", + "usageDetails": { + "input": 900, + "input_cached_tokens": 600, + "output": 120, + "output_reasoning_tokens": 40, + "total": 1660 + }, + "usagePricingTierId": "93f68bda87c2c60c5eac7dade0bd0b7b46d214", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:01.048Z", + "costDetails": { + "cache_creation_input_tokens": 0.0003, + "cache_read_input_tokens": 6.4e-05, + "input": 0.00016, + "output": 0.00036, + "total": 0.000884 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:01.300Z", + "environment": "conformance", + "id": "865405e64b09ea88", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case anthropic_cache_rw\"}]", + "inputCost": 0.0005239999999999999, + "inputPrice": "8e-7", + "inputUsage": 1300, + "internalModelId": "e8b939c35eee9ae028485f50e", + "isRootObservation": false, + "latency": 0.406, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "anthropic_cache_rw" + }, + "model": "claude-3-5-haiku-20241022", + "modelId": "e8b939c35eee9ae028485f50e", + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-anthropic_cache_rw", + "output": "ok", + "outputCost": 0.00036, + "outputPrice": "0.000004", + "outputUsage": 90, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:00.894Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.154, + "totalCost": 0.000884, + "totalPrice": null, + "totalUsage": 1390, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "cache_creation_input_tokens": 300, + "cache_read_input_tokens": 800, + "input": 200, + "output": 90, + "total": 1390 + }, + "usagePricingTierId": "f77f4e33cb9889c464e7572e94a3d543dbefff", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:01.451Z", + "costDetails": { + "input": 0.00055, + "output": 0.00132, + "output_reasoning_tokens": 0.00088, + "total": 0.00275 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:01.705Z", + "environment": "conformance", + "id": "b60e6aecb9f84bf0", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case o4_mini\"}]", + "inputCost": 0.00055, + "inputPrice": "0.0000011", + "inputUsage": 500, + "internalModelId": "59e68938fb5b8ce22c0f5655a5", + "isRootObservation": false, + "latency": 0.405, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "o4_mini" + }, + "model": "o4-mini", + "modelId": "59e68938fb5b8ce22c0f5655a5", + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-o4_mini", + "output": "ok", + "outputCost": 0.0022, + "outputPrice": "0.0000044", + "outputUsage": 500, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:01.300Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.151, + "totalCost": 0.00275, + "totalPrice": null, + "totalUsage": 1000, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 500, + "output": 300, + "output_reasoning_tokens": 200, + "total": 1000 + }, + "usagePricingTierId": "d46d99062e7a23acb8f9cea738af5b71bd2ca9a", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:01.857Z", + "costDetails": { + "input": 0.00032, + "output": 0.0002, + "total": 0.00052 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:02.112Z", + "environment": "conformance", + "id": "985dce7ccae0dda1", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case bedrock_claude\"}]", + "inputCost": 0.00032, + "inputPrice": "8e-7", + "inputUsage": 400, + "internalModelId": "e8b939c35eee9ae028485f50e", + "isRootObservation": false, + "latency": 0.407, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "bedrock_claude" + }, + "model": "us.anthropic.claude-3-5-haiku-20241022-v1:0", + "modelId": "e8b939c35eee9ae028485f50e", + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-bedrock_claude", + "output": "ok", + "outputCost": 0.0002, + "outputPrice": "0.000004", + "outputUsage": 50, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:01.705Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.152, + "totalCost": 0.00052, + "totalPrice": null, + "totalUsage": 450, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 400, + "output": 50, + "total": 450 + }, + "usagePricingTierId": "f77f4e33cb9889c464e7572e94a3d543dbefff", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:02.268Z", + "costDetails": { + "total": 0.00135 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:02.521Z", + "environment": "conformance", + "id": "5476ecfcd272f398", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case gateway_openai\"}]", + "inputCost": null, + "inputPrice": "0.0000025", + "inputUsage": 300, + "internalModelId": "4d95f20acf095195602ff74be", + "isRootObservation": false, + "latency": 0.409, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "gateway_openai" + }, + "model": "openai/gpt-4o", + "modelId": "4d95f20acf095195602ff74be", + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-gateway_openai", + "output": "ok", + "outputCost": null, + "outputPrice": "0.00001", + "outputUsage": 60, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:02.112Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.156, + "totalCost": 0.00135, + "totalPrice": null, + "totalUsage": 360, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 300, + "output": 60, + "total": 360 + }, + "usagePricingTierId": "9bf75b6cc004c7c861b2115742ade776bbeee3", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:02.674Z", + "costDetails": { + "input": 0.0005, + "output": 0.00024, + "total": 0.00074 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:02.929Z", + "environment": "conformance", + "id": "8787d86de8cf8bac", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case unknown_mistral\"}]", + "inputCost": 0.0005, + "inputPrice": null, + "inputUsage": 250, + "internalModelId": "", + "isRootObservation": false, + "latency": 0.407, + "level": "DEFAULT", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "unknown_mistral" + }, + "model": "mistral-large-latest", + "modelId": null, + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-unknown_mistral", + "output": "ok", + "outputCost": 0.00024, + "outputPrice": null, + "outputUsage": 40, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:02.522Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.152, + "totalCost": 0.00074, + "totalPrice": null, + "totalUsage": 290, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 250, + "output": 40, + "total": 290 + }, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": "2026-01-01T00:00:03.080Z", + "costDetails": { + "input": 1.5e-05, + "output": 0, + "total": 1.5e-05 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:03.330Z", + "environment": "conformance", + "id": "c91b73905cc19465", + "input": "[{\"role\": \"system\", \"content\": \"You are terse.\"}, {\"role\": \"user\", \"content\": \"case error_call\"}]", + "inputCost": 1.5e-05, + "inputPrice": "1.5e-7", + "inputUsage": 100, + "internalModelId": "d259773a00a5ab602a37664ab", + "isRootObservation": false, + "latency": 0.401, + "level": "ERROR", + "metadata": { + "customer_tier": "gold", + "feature": "support-triage", + "nested.attempt": 1, + "nested.region": "us-west-2", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0", + "step": "error_call" + }, + "model": "gpt-4o-mini", + "modelId": "d259773a00a5ab602a37664ab", + "modelParameters": { + "max_tokens": 512, + "temperature": 0.2 + }, + "name": "gen-error_call", + "output": null, + "outputCost": 0, + "outputPrice": "6e-7", + "outputUsage": 0, + "parentObservationId": "ca12db61422ad962", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "bdf1a2b5b1d0dad7a8226cdfae1731fa32", + "startTime": "2026-01-01T00:00:02.929Z", + "statusMessage": "RateLimitError: 429 from upstream", + "tags": [ + "mg-conformance-fixture", + "prod" + ], + "timeToFirstToken": 0.151, + "totalCost": 1.5e-05, + "totalPrice": null, + "totalUsage": 100, + "traceId": "23456a48a189ca76b6a9f57328c6c1f9", + "traceName": "conformance-workflow", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 100, + "output": 0, + "total": 100 + }, + "usagePricingTierId": "93f68bda87c2c60c5eac7dade0bd0b7b46d214", + "usagePricingTierName": "Standard", + "userId": "user-conf-1", + "version": "app-v1.4.2" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:04.502Z", + "environment": "conformance", + "id": "127aaf08b9b8dd55", + "input": null, + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": true, + "latency": 0.02, + "level": "DEFAULT", + "metadata": { + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "conformance-langchain", + "output": null, + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": null, + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "", + "startTime": "2026-01-01T00:00:04.482Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "langchain" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "edbfab4ba39e90abb5732115c94c9388", + "traceName": "conformance-langchain", + "type": "CHAIN", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "", + "version": "" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": { + "input": 2.82e-05, + "input_cache_read": 3.84e-05, + "output": 1.8e-05, + "total": 8.46e-05 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:04.502Z", + "environment": "conformance", + "id": "58dd83d9847cbce7", + "input": "[{\"role\": \"user\", \"content\": \"hello\"}]", + "inputCost": 6.659999999999999e-05, + "inputPrice": "1.5e-7", + "inputUsage": 700, + "internalModelId": "3fbaf8638254265697dfcf343", + "isRootObservation": false, + "latency": 0.014, + "level": "DEFAULT", + "metadata": { + "is_langchain_root": true, + "lc_versions.langchain-core": "1.8.4", + "lc_versions.langchain-openai": "1.8.5", + "ls_integration": "langchain_chat_model", + "ls_model_name": "gpt-4o-mini", + "ls_model_type": "chat", + "ls_provider": "openai", + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "gpt-4o-mini-2024-07-18", + "modelId": "3fbaf8638254265697dfcf343", + "modelParameters": {}, + "name": "ChatOpenAI", + "output": "{\"role\": \"assistant\", \"content\": \"mocked\", \"additional_kwargs\": {\"refusal\": null}}", + "outputCost": 1.8e-05, + "outputPrice": "6e-7", + "outputUsage": 30, + "parentObservationId": "127aaf08b9b8dd55", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "", + "startTime": "2026-01-01T00:00:04.488Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "langchain" + ], + "timeToFirstToken": null, + "totalCost": 8.46e-05, + "totalPrice": null, + "totalUsage": 730, + "traceId": "edbfab4ba39e90abb5732115c94c9388", + "traceName": "conformance-langchain", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 188, + "input_cache_read": 512, + "output": 30, + "output_reasoning": 0, + "total": 730 + }, + "usagePricingTierId": "6eb408e8608d1918fecb7f259b2c57d6585532", + "usagePricingTierName": "Standard", + "userId": "", + "version": "" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": {}, + "createdAt": "2026-01-01T00:00:05.012Z", + "endTime": "2026-01-01T00:00:04.714Z", + "environment": "conformance", + "id": "339bfa3c4d828a55", + "input": "{\"args\": [], \"kwargs\": {}}", + "inputCost": null, + "inputPrice": null, + "inputUsage": 0, + "internalModelId": "", + "isRootObservation": true, + "latency": 0.212, + "level": "DEFAULT", + "metadata": { + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "", + "modelId": null, + "modelParameters": {}, + "name": "observe-decorated", + "output": "ok", + "outputCost": null, + "outputPrice": null, + "outputUsage": 0, + "parentObservationId": null, + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "", + "startTime": "2026-01-01T00:00:04.502Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "observe" + ], + "timeToFirstToken": null, + "totalCost": null, + "totalPrice": null, + "totalUsage": 0, + "traceId": "e3ab5bba96a1a8ed84810bb01b0ce784", + "traceName": "conformance-observe", + "type": "SPAN", + "updatedAt": "2026-01-01T00:00:05.012Z", + "usageDetails": {}, + "usagePricingTierId": null, + "usagePricingTierName": null, + "userId": "user-conf-2", + "version": "" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": { + "input": 2.82e-05, + "input_cached_tokens": 3.84e-05, + "output": 1.8e-05, + "total": 8.46e-05 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:04.714Z", + "environment": "conformance", + "id": "be12f10427427b89", + "input": "[{\"role\": \"user\", \"content\": \"wrapped\"}]", + "inputCost": 6.659999999999999e-05, + "inputPrice": "1.5e-7", + "inputUsage": 700, + "internalModelId": "3fbaf8638254265697dfcf343", + "isRootObservation": false, + "latency": 0.001, + "level": "DEFAULT", + "metadata": { + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "gpt-4o-mini-2024-07-18", + "modelId": "3fbaf8638254265697dfcf343", + "modelParameters": { + "frequency_penalty": 0, + "max_tokens": "Infinity", + "presence_penalty": 0, + "temperature": 1, + "top_p": 1 + }, + "name": "OpenAI-generation", + "output": "{\"role\": \"assistant\", \"content\": \"mocked\"}", + "outputCost": 1.8e-05, + "outputPrice": "6e-7", + "outputUsage": 30, + "parentObservationId": "339bfa3c4d828a55", + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "", + "startTime": "2026-01-01T00:00:04.713Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "observe" + ], + "timeToFirstToken": null, + "totalCost": 8.46e-05, + "totalPrice": null, + "totalUsage": 730, + "traceId": "e3ab5bba96a1a8ed84810bb01b0ce784", + "traceName": "conformance-observe", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 188, + "input_cached_tokens": 512, + "output": 30, + "output_reasoning_tokens": 0, + "total": 730 + }, + "usagePricingTierId": "6eb408e8608d1918fecb7f259b2c57d6585532", + "usagePricingTierName": "Standard", + "userId": "user-conf-2", + "version": "" + }, + { + "bookmarked": false, + "completionStartTime": null, + "costDetails": { + "input": 1.5e-06, + "output": 3e-06, + "total": 4.5e-06 + }, + "createdAt": "2026-01-01T00:00:05.013Z", + "endTime": "2026-01-01T00:00:04.714Z", + "environment": "conformance", + "id": "6f3c48d99fc9091c", + "input": "x", + "inputCost": 1.5e-06, + "inputPrice": "1.5e-7", + "inputUsage": 10, + "internalModelId": "d259773a00a5ab602a37664ab", + "isRootObservation": true, + "latency": null, + "level": "DEFAULT", + "metadata": { + "resourceAttributes.service.name": "unknown_service:python", + "resourceAttributes.telemetry.sdk.language": "python", + "resourceAttributes.telemetry.sdk.name": "opentelemetry", + "resourceAttributes.telemetry.sdk.version": "1.45.2", + "scope.name": "langfuse-sdk", + "scope.version": "5.2.0" + }, + "model": "gpt-4o-mini", + "modelId": "d259773a00a5ab602a37664ab", + "modelParameters": {}, + "name": "gen-delete-me", + "output": "y", + "outputCost": 3e-06, + "outputPrice": "6e-7", + "outputUsage": 5, + "parentObservationId": null, + "projectId": "fixture-project", + "promptId": "", + "promptName": "", + "promptVersion": null, + "public": false, + "release": "rel-2026.11.22", + "sessionId": "", + "startTime": "2026-01-01T00:00:04.714Z", + "statusMessage": "", + "tags": [ + "mg-conformance-fixture", + "to-delete" + ], + "timeToFirstToken": null, + "totalCost": 4.5e-06, + "totalPrice": null, + "totalUsage": 15, + "traceId": "886d3f5236bfd2e175d96530e6ea2b54", + "traceName": "conformance-delete", + "type": "GENERATION", + "updatedAt": "2026-01-01T00:00:05.013Z", + "usageDetails": { + "input": 10, + "output": 5, + "total": 15 + }, + "usagePricingTierId": "93f68bda87c2c60c5eac7dade0bd0b7b46d214", + "usagePricingTierName": "Standard", + "userId": "", + "version": "" + } + ], + "meta": { + "fields": "core,basic,time,io,metadata,model,usage,prompt,metrics,trace_context" + } +} diff --git a/tests/providers/test_langfuse.py b/tests/providers/test_langfuse.py index 79f5075..71e0f85 100644 --- a/tests/providers/test_langfuse.py +++ b/tests/providers/test_langfuse.py @@ -10,6 +10,7 @@ from metergraphrelay import __version__ from metergraphrelay.import_identity import ImportContext, ImportIdentityError from metergraphrelay.providers.langfuse import ( + COST_BEARING_TYPES, PAGE_LIMIT, LangfuseAPIError, RESPONSE_FIELDS, @@ -751,7 +752,8 @@ def test_normalize_observation_full_row(): "error": False, "error_type": None, "request_id": "obs-1", - "tags": {"langfuse_tags": ["prod", "tier-1"]}, + # One pair per Langfuse tag: metergraph keeps only string values. + "tags": {"langfuse.tag.prod": "true", "langfuse.tag.tier-1": "true"}, "route": "support-bot", "content_opted_in": True, "request_json": json.dumps([{"role": "user", "content": "hi"}]), @@ -762,6 +764,8 @@ def test_normalize_observation_full_row(): "parent_span_id": None, "session_id": None, "environment": "production", + "trace_name": "support-bot", + "observation_type": "GENERATION", } @@ -1033,7 +1037,7 @@ def test_pull_langfuse_passes_selectors_into_a_single_combined_request(tmp_path) "type": "stringOptions", "column": "type", "operator": "any of", - "value": ["GENERATION"], + "value": list(COST_BEARING_TYPES), }, { "type": "datetime", diff --git a/tests/providers/test_langfuse_conformance.py b/tests/providers/test_langfuse_conformance.py new file mode 100644 index 0000000..1750838 --- /dev/null +++ b/tests/providers/test_langfuse_conformance.py @@ -0,0 +1,501 @@ +"""The Langfuse normalizer against real Langfuse Cloud responses. + +Every observation here was recorded by a live Langfuse run (see +tests/fixtures/langfuse_v2/README.md); the manifest holds what the seeder sent +and what Langfuse reported back. Nothing in these tests is hand-written JSON. +""" + +import email.message +import io +import json +import urllib.error +from decimal import Decimal +from pathlib import Path +from unittest.mock import patch + +import pytest + +from metergraphrelay.providers.langfuse import ( + COST_BEARING_TYPES, + MAX_RETRIES, + LangfuseAPIError, + build_base_params, + default_import_scope, + fetch_observations_page, + is_importable_observation, + normalize_observation, + pull_langfuse, + resolve_provider_and_model, + retry_delay, +) + +FIXTURE_DIR = Path(__file__).resolve().parent.parent / "fixtures" / "langfuse_v2" +OBSERVATIONS = json.loads((FIXTURE_DIR / "observations.json").read_text()) +MANIFEST = json.loads((FIXTURE_DIR / "manifest.json").read_text()) +BY_ID = {observation["id"]: observation for observation in OBSERVATIONS["data"]} +COST_KEYS = sorted( + key for key, spec in MANIFEST["observations"].items() if spec.get("cost_bearing") +) +STRUCTURE_KEYS = sorted( + key for key, spec in MANIFEST["observations"].items() if not spec.get("cost_bearing") +) + + +def observation(key: str) -> dict: + return BY_ID[MANIFEST["observations"][key]["id"]] + + +def row(key: str) -> dict: + return normalize_observation(observation(key), route_override=None) + + +def test_fixture_covers_every_manifest_observation(): + assert set(BY_ID) == {spec["id"] for spec in MANIFEST["observations"].values()} + + +# --- G2: which observations are imported ------------------------------------- + + +@pytest.mark.parametrize("key", COST_KEYS) +def test_every_cost_bearing_observation_is_importable(key): + assert is_importable_observation(observation(key)) + + +@pytest.mark.parametrize("key", STRUCTURE_KEYS) +def test_structural_observations_without_a_model_are_not_imported(key): + assert not is_importable_observation(observation(key)) + + +def test_embedding_is_imported_with_its_type(): + embedding = row("embedding") + assert embedding["observation_type"] == "EMBEDDING" + assert embedding["provider"] == "openai" + assert embedding["input_tokens"] == 1200 + + +def test_a_non_generation_type_needs_usage_or_cost(): + tool = dict(observation("lookup_tool"), model="gpt-4o-mini") + assert not is_importable_observation(tool) + assert is_importable_observation(dict(tool, totalCost=0.001)) + assert is_importable_observation(dict(tool, usageDetails={"input": 3})) + assert is_importable_observation(dict(tool, usageDetails={"audio_seconds": 1.5})) + assert not is_importable_observation(dict(tool, usageDetails={"input": 0, "x": True})) + assert not is_importable_observation(dict(observation("llm_step"), model="gpt-4o", totalCost=1.0)) + + +# --- G1: provider resolution and Langfuse's cost ---------------------------- + + +@pytest.mark.parametrize("key", COST_KEYS) +def test_provider_is_one_the_seeder_expected(key): + expected = MANIFEST["observations"][key]["expected_providers"] + assert row(key)["provider"] in expected + + +def test_bedrock_model_id_keeps_its_catalog_spelling(): + bedrock = row("bedrock_claude") + assert bedrock["provider"] == "bedrock" + assert bedrock["model"] == "us.anthropic.claude-3-5-haiku-20241022-v1:0" + assert "langfuse_model" not in bedrock + + +def test_gateway_prefix_is_stripped_and_the_original_kept(): + gateway = row("gateway_openai") + assert (gateway["provider"], gateway["model"]) == ("openai", "gpt-4o") + assert gateway["langfuse_model"] == "openai/gpt-4o" + + +def test_no_cost_bearing_row_is_unknown(): + assert [key for key in COST_KEYS if row(key)["provider"] == "unknown"] == [] + + +@pytest.mark.parametrize("key", COST_KEYS) +def test_langfuse_cost_is_always_carried_as_reported(key): + readback = MANIFEST["langfuse_readback"][key]["totalCost"] + normalized = row(key) + assert Decimal(normalized["reported_cost_usd"]) == Decimal(str(readback)) + assert normalized["reported_cost_source"] == "langfuse.observation.totalCost" + assert normalized["cost_usd"] == readback + + +def test_reported_cost_total_matches_langfuse(): + relay_total = sum(Decimal(row(key)["reported_cost_usd"]) for key in COST_KEYS) + langfuse_total = sum( + Decimal(str(MANIFEST["langfuse_readback"][key]["totalCost"])) for key in COST_KEYS + ) + assert relay_total == langfuse_total + + +def test_cost_details_are_carried_as_decimal_strings(): + details = row("openai_cached_reasoning")["reported_cost_details"] + assert details and all(isinstance(value, str) for value in details.values()) + assert Decimal(details["total"]) == Decimal("0.000252") + + +# --- G5: latency and time to first token ------------------------------------- + + +@pytest.mark.parametrize( + "key", [k for k in COST_KEYS if MANIFEST["observations"][k].get("latency_ms_min")] +) +def test_latency_and_ttft_match_langfuse(key): + readback = MANIFEST["langfuse_readback"][key] + spec = MANIFEST["observations"][key] + normalized = row(key) + assert normalized["latency_ms"] == round(readback["latency"] * 1000) + assert normalized["ttft_ms"] == round(readback["timeToFirstToken"] * 1000) + assert normalized["latency_ms"] >= spec["latency_ms_min"] + assert normalized["ttft_ms"] >= spec["ttft_ms_min"] + + +def test_latency_falls_back_to_timestamps_when_langfuse_omits_it(): + source = dict(observation("o4_mini"), latency=None, timeToFirstToken=None) + normalized = normalize_observation(source, route_override=None) + assert normalized["latency_ms"] == 405 + assert normalized["ttft_ms"] == 151 + + +def test_zero_length_observation_has_zero_latency_not_none(): + assert row("embedding")["latency_ms"] == 0 + assert "ttft_ms" not in row("embedding") + + +# --- G5b and G6: tags and attribution ---------------------------------------- + + +@pytest.mark.parametrize("key", COST_KEYS) +def test_every_langfuse_tag_lands_as_a_string_pair(key): + trace = MANIFEST["traces"][MANIFEST["observations"][key]["trace"]] + tags = row(key)["tags"] + for tag in trace["tags"]: + assert tags[f"langfuse.tag.{tag}"] == "true" + assert all(isinstance(value, str) for value in tags.values()) + + +def test_customer_metadata_lands_and_sdk_metadata_does_not(): + tags = row("openai_cached_reasoning")["tags"] + assert tags["langfuse.metadata.customer_tier"] == "gold" + assert tags["langfuse.metadata.feature"] == "support-triage" + assert tags["langfuse.metadata.nested.attempt"] == "1" + assert tags["langfuse.metadata.nested.region"] == "us-west-2" + sdk_written = ("resourceAttributes.", "scope.", "ls_", "lc_versions.", "is_langchain_root") + for key in (*tags, *row("langchain_generation")["tags"]): + assert not key.removeprefix("langfuse.metadata.").startswith(sdk_written), key + + +def test_release_version_and_prompt_are_filterable_tags(): + tags = row("openai_cached_reasoning")["tags"] + assert tags["langfuse.release"] == MANIFEST["release"] + assert tags["langfuse.version"] == MANIFEST["traces"]["main"]["version"] + assert tags["langfuse.prompt.name"] == "mg-conformance-prompt" + assert tags["langfuse.prompt.version"] == "1" + + +def test_attribution_fields_carry_through(): + main = MANIFEST["traces"]["main"] + normalized = row("openai_cached_reasoning") + assert normalized["user_id"] == main["user_id"] + assert normalized["session_id"] == main["session_id"] + assert normalized["release"] == MANIFEST["release"] + assert normalized["version"] == main["version"] + assert normalized["trace_name"] == main["name"] + assert normalized["prompt_name"] == "mg-conformance-prompt" + assert normalized["prompt_version"] == 1 + assert normalized["model_parameters"] == MANIFEST["observations"][ + "openai_cached_reasoning" + ]["model_parameters"] + + +def test_error_observation_keeps_its_status_message(): + spec = MANIFEST["observations"]["error_call"] + normalized = row("error_call") + assert normalized["status"] == "error" and normalized["error"] is True + assert normalized["error_type"] == spec["status_message"] + + +def test_tags_never_exceed_the_server_limit_and_langfuse_tags_come_first(): + metadata = {f"k{index:03d}": "v" for index in range(60)} + source = dict(observation("o4_mini"), metadata=metadata, tags=["zz-last", "aa"]) + tags = normalize_observation(source, route_override="r")["tags"] + assert len(tags) == 32 + assert tags["langfuse.tag.zz-last"] == "true" and tags["langfuse.tag.aa"] == "true" + assert tags["name"] == "conformance-workflow" + assert tags["langfuse.release"] == MANIFEST["release"] + assert "langfuse.metadata.k000" in tags and "langfuse.metadata.k059" not in tags + + +# --- pulling the fixture as one page ----------------------------------------- + + +def test_pull_imports_every_cost_bearing_observation_and_nothing_else(tmp_path): + output = tmp_path / "rows.jsonl" + with patch( + "metergraphrelay.providers.langfuse.fetch_observations_page", + return_value={"data": OBSERVATIONS["data"], "meta": {"cursor": None}}, + ) as fetch: + imported, skipped = pull_langfuse( + base_url="https://cloud.langfuse.com", public_key="pk", secret_key="sk", + count=1000, since=None, until="2026-01-02T00:00:00Z", trace_names=[], + tags=[], environment=None, route=None, output_path=str(output), + ) + rows = [json.loads(line) for line in output.read_text().splitlines()] + assert (imported, skipped) == (len(COST_KEYS), 0) + assert {r["request_id"] for r in rows} == { + MANIFEST["observations"][key]["id"] for key in COST_KEYS + } + sent = json.loads(fetch.call_args.kwargs["params"]["filter"]) + assert sent[0] == { + "type": "stringOptions", "column": "type", "operator": "any of", + "value": list(COST_BEARING_TYPES), + } + + +def test_pull_with_exclude_content_strips_input_and_output(tmp_path): + output = tmp_path / "rows.jsonl" + with patch( + "metergraphrelay.providers.langfuse.fetch_observations_page", + return_value={"data": OBSERVATIONS["data"], "meta": {"cursor": None}}, + ): + pull_langfuse( + base_url="https://cloud.langfuse.com", public_key="pk", secret_key="sk", + count=1000, since=None, until="2026-01-02T00:00:00Z", trace_names=[], + tags=[], environment=None, route=None, output_path=str(output), + include_content=False, + ) + for line in output.read_text().splitlines(): + normalized = json.loads(line) + assert normalized["content_opted_in"] is False + for field in ("request_json", "request_text", "response_text", "tool_calls"): + assert field not in normalized + + +def _pull_rows(tmp_path, name, data, **overrides): + output = tmp_path / f"{name}.jsonl" + kwargs = dict( + base_url="https://cloud.langfuse.com", public_key="pk", secret_key="sk", + count=1000, since=None, until="2026-01-02T00:00:00Z", trace_names=[], + tags=[], environment=None, route=None, output_path=str(output), + ) + kwargs.update(overrides) + with patch( + "metergraphrelay.providers.langfuse.fetch_observations_page", + return_value={"data": data, "meta": {"cursor": None}}, + ): + pull_langfuse(**kwargs) + return [json.loads(line) for line in output.read_text().splitlines()] + + +def _server_claims(*pushes): + """The server's dedup gate: the first row with an identity wins.""" + stored = {} + for rows in pushes: + for pushed in rows: + identity = ( + pushed["import_source"], pushed["import_source_scope"], + pushed["import_event_id"], + ) + stored.setdefault(identity, pushed) + return stored + + +def test_a_re_pull_of_the_same_window_dedups_on_the_import_identity(tmp_path): + first = _pull_rows(tmp_path, "first", OBSERVATIONS["data"]) + # The re-sync sees the same observations again, one of them edited late + # (Langfuse updated its cost), plus nothing new. + edited = [dict(obs) for obs in OBSERVATIONS["data"]] + for obs in edited: + if obs["id"] == MANIFEST["observations"]["o4_mini"]["id"]: + obs["totalCost"] = (obs.get("totalCost") or 0) + 1 + second = _pull_rows(tmp_path, "second", edited) + + for pushed in first + second: + assert pushed["import_source"] == "langfuse" + # The event id is Langfuse's observation id, the same id span_id + # and request_id carry, so scorers that match on span_id still do. + assert pushed["import_event_id"] == pushed["span_id"] == pushed["request_id"] + assert {r["import_source_scope"] for r in first + second} == { + default_import_scope("https://cloud.langfuse.com", "pk") + } + stored = _server_claims(first, second) + assert len(stored) == len(first) == len(COST_KEYS) + assert sorted(r["span_id"] for r in stored.values()) == sorted( + MANIFEST["observations"][key]["id"] for key in COST_KEYS + ) + + +def test_the_default_scope_is_per_project_and_carries_no_key(): + scope = default_import_scope("https://cloud.langfuse.com/", "pk-lf-secretish") + assert scope == default_import_scope("HTTPS://cloud.langfuse.com", " pk-lf-secretish ") + assert scope != default_import_scope("https://cloud.langfuse.com", "pk-lf-other") + assert scope != default_import_scope("https://us.cloud.langfuse.com", "pk-lf-secretish") + assert "pk-lf" not in scope and "langfuse.com" not in scope + assert 1 <= len(scope) <= 255 + + +def test_an_explicit_source_scope_matches_sync_rows(tmp_path): + rows = _pull_rows(tmp_path, "scoped", OBSERVATIONS["data"], source_scope="prod-project") + assert {r["import_source_scope"] for r in rows} == {"prod-project"} + + +def test_build_base_params_sends_attribution_selectors_in_the_filter(): + params = build_base_params( + until="2026-01-02T00:00:00Z", since=None, trace_names=[], tags=[], + environment=None, user_id="user-conf-1", session_id="s-1", + metadata=[("feature", "support-triage")], + ) + conditions = json.loads(params["filter"]) + assert {"type": "string", "column": "userId", "operator": "=", "value": "user-conf-1"} in conditions + assert {"type": "string", "column": "sessionId", "operator": "=", "value": "s-1"} in conditions + assert { + "type": "stringObject", "column": "metadata", "key": "feature", + "operator": "=", "value": "support-triage", + } in conditions + assert "type" not in params and "toStartTime" not in params + + +def test_build_base_params_default_is_unchanged_for_existing_callers(): + params = build_base_params( + until="2026-01-02T00:00:00Z", since="2026-01-01T00:00:00Z", trace_names=[], + tags=[], environment="conformance", + ) + assert params["type"] == "GENERATION" + assert params["fromStartTime"] == "2026-01-01T00:00:00Z" + assert "filter" not in params + assert "prompt" in params["fields"] and "metrics" in params["fields"] + + +# --- G11: retries ------------------------------------------------------------- + + +class _Response(io.BytesIO): + headers: dict[str, str] = {} + + def __enter__(self): + return self + + def __exit__(self, *_exc) -> None: + self.close() + + +def _http_error(code: int, retry_after: str | None = None) -> urllib.error.HTTPError: + headers = email.message.Message() + if retry_after is not None: + headers["Retry-After"] = retry_after + return urllib.error.HTTPError("https://x", code, "Too Many Requests", headers, io.BytesIO(b"")) + + +def _page() -> _Response: + return _Response(json.dumps({"data": [], "meta": {}}).encode()) + + +def test_rate_limit_is_retried_after_retry_after(): + waits: list[float] = [] + with patch( + "urllib.request.urlopen", + side_effect=[_http_error(429, "7"), _http_error(503), _page()], + ) as urlopen: + payload = fetch_observations_page( + "https://cloud.langfuse.com", public_key="pk", secret_key="sk", params={}, + sleep=waits.append, + ) + assert payload == {"data": [], "meta": {}} + assert urlopen.call_count == 3 + assert waits == [7.0, 4.0] # Retry-After, then doubling from 2 s at attempt 1 + + +def test_rate_limit_gives_up_after_max_retries(): + waits: list[float] = [] + with patch( + "urllib.request.urlopen", + side_effect=[_http_error(429) for _ in range(MAX_RETRIES + 1)], + ): + with pytest.raises(LangfuseAPIError, match="HTTP 429"): + fetch_observations_page( + "https://cloud.langfuse.com", public_key="pk", secret_key="sk", params={}, + sleep=waits.append, + ) + assert len(waits) == MAX_RETRIES + + +def test_other_errors_and_disabled_retry_fail_at_once(): + waits: list[float] = [] + with patch("urllib.request.urlopen", side_effect=[_http_error(500)]): + with pytest.raises(LangfuseAPIError, match="HTTP 500"): + fetch_observations_page( + "https://x", public_key="pk", secret_key="sk", params={}, sleep=waits.append, + ) + with patch("urllib.request.urlopen", side_effect=[_http_error(429)]): + with pytest.raises(LangfuseAPIError, match="HTTP 429"): + fetch_observations_page("https://x", public_key="pk", secret_key="sk", params={}, sleep=None) + assert waits == [] + + +def test_retry_delay_reads_http_dates_and_caps_the_wait(): + assert retry_delay("Thu, 01 Jan 2026 00:00:30 GMT", 0, now=lambda: 1767225600.0) == 30.0 + assert retry_delay("9999", 0) == 120.0 + assert retry_delay(None, 3) == 16.0 + assert retry_delay("garbage", 0) == 2.0 + + +def test_pull_renews_progress_after_a_rate_limit_wait(tmp_path): + ticks: list[str] = [] + with patch( + "urllib.request.urlopen", + side_effect=[_http_error(429, "1"), _page()], + ): + pull_langfuse( + base_url="https://x", public_key="pk", secret_key="sk", count=10, since=None, + until="2026-01-02T00:00:00Z", trace_names=[], tags=[], environment=None, + route=None, output_path=str(tmp_path / "o.jsonl"), + on_progress=lambda: ticks.append("tick"), sleep=lambda _seconds: ticks.append("sleep"), + ) + assert ticks[:2] == ["sleep", "tick"] + + +# --- provider spellings beyond the fixture ------------------------------------ + + +@pytest.mark.parametrize( + ("model", "metadata", "expected"), + [ + ("o4-mini", None, ("openai", "o4-mini")), + ("o3", None, ("openai", "o3")), + ("text-embedding-3-large", None, ("openai", "text-embedding-3-large")), + ("eu.anthropic.claude-sonnet-4-20250514-v1:0", None, + ("bedrock", "eu.anthropic.claude-sonnet-4-20250514-v1:0")), + ("meta.llama3-1-70b-instruct-v1:0", None, ("bedrock", "meta.llama3-1-70b-instruct-v1:0")), + ("arn:aws:bedrock:us-east-1:111111111111:inference-profile/us.anthropic.claude-3-5-haiku", + None, ("bedrock", + "arn:aws:bedrock:us-east-1:111111111111:inference-profile/us.anthropic.claude-3-5-haiku")), + ("bedrock/us.anthropic.claude-3-5-haiku-20241022-v1:0", None, + ("bedrock", "us.anthropic.claude-3-5-haiku-20241022-v1:0")), + ("anthropic/claude-3-5-haiku-20241022", None, ("anthropic", "claude-3-5-haiku-20241022")), + ("vertex_ai/gemini-2.0-flash", None, ("vertex-ai", "gemini-2.0-flash")), + ("projects/p/locations/us-central1/publishers/google/models/gemini-2.5-pro", None, + ("vertex-ai", "gemini-2.5-pro")), + ("claude-3-5-sonnet-v2@20241022", None, ("vertex-ai", "claude-3-5-sonnet-v2@20241022")), + ("gemini-2.5-flash", None, ("google", "gemini-2.5-flash")), + ("codestral-latest", None, ("mistral", "codestral-latest")), + ("mistral/mistral-large-latest", None, ("mistral", "mistral-large-latest")), + ("llama-3.1-8b-instant", None, ("meta", "llama-3.1-8b-instant")), + ("meta-llama/Llama-3.3-70B-Instruct", None, ("meta", "Llama-3.3-70B-Instruct")), + ("command-r-plus", None, ("cohere", "command-r-plus")), + ("grok-3", None, ("x-ai", "grok-3")), + ("my-finetune", None, ("unknown", "my-finetune")), + ("acme/my-finetune", None, ("unknown", "acme/my-finetune")), + # Explicit metadata wins, in any of the spellings integrations write. + ("claude-3-5-haiku-20241022", {"ls_provider": "amazon_bedrock"}, + ("bedrock", "claude-3-5-haiku-20241022")), + ("gpt-4o", {"gen_ai.system": "az.ai.openai"}, ("azure", "gpt-4o")), + ("gpt-4o", {"gen_ai": {"system": "openai"}}, ("openai", "gpt-4o")), + ("llama-3.1-8b-instant", {"ls_provider": "groq"}, ("groq", "llama-3.1-8b-instant")), + ("gemini-2.0-flash", {"ls_provider": "google_vertexai"}, ("vertex-ai", "gemini-2.0-flash")), + ("openai/gpt-4o", {"provider": "openrouter"}, ("openrouter", "openai/gpt-4o")), + ("gpt-4o", {"ls_provider": "litellm"}, ("openai", "gpt-4o")), + ], +) +def test_provider_resolution(model, metadata, expected): + source = {"model": model} + if metadata is not None: + source["metadata"] = metadata + assert resolve_provider_and_model(source) == expected diff --git a/tests/test_cli.py b/tests/test_cli.py index f063b96..e745cee 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -149,9 +149,92 @@ def test_main_pull_langfuse_dispatches_to_pull_langfuse(tmp_path): environment=None, route=None, output_path=str(output_path), + user_id=None, + session_id=None, + metadata=[], + include_content=True, + source_scope=None, ) +def _pull_langfuse_args(env_file, output_path, *extra): + return [ + "pull", "langfuse", "--env-file", str(env_file), "--output", str(output_path), + "--until", "2026-08-07T00:00:00+00:00", *extra, + ] + + +def test_main_pull_langfuse_passes_attribution_selectors_and_content_opt_out(tmp_path): + env_file = tmp_path / ".env" + env_file.write_text("LANGFUSE_PUBLIC_KEY=pk-1\nLANGFUSE_SECRET_KEY=sk-1\n") + output_path = tmp_path / "out.jsonl" + + with patch("metergraphrelay.cli.pull_langfuse", return_value=(0, 0)) as mock_pull: + exit_code = main(_pull_langfuse_args( + env_file, output_path, + "--user-id", "user-1", "--session-id", "sess-1", + "--metadata", "feature=support-triage", "--metadata", "tier=a=b", + "--exclude-content", + )) + + assert exit_code == 0 + kwargs = mock_pull.call_args.kwargs + assert kwargs["user_id"] == "user-1" + assert kwargs["session_id"] == "sess-1" + # Only the first "=" splits, so a value may itself contain "=". + assert kwargs["metadata"] == [("feature", "support-triage"), ("tier", "a=b")] + assert kwargs["include_content"] is False + + +def test_main_pull_langfuse_passes_an_explicit_source_scope(tmp_path): + env_file = tmp_path / ".env" + env_file.write_text("LANGFUSE_PUBLIC_KEY=pk-1\nLANGFUSE_SECRET_KEY=sk-1\n") + + with patch("metergraphrelay.cli.pull_langfuse", return_value=(0, 0)) as mock_pull: + exit_code = main(_pull_langfuse_args( + env_file, tmp_path / "out.jsonl", "--source-scope", " prod-project ", + )) + + assert exit_code == 0 + assert mock_pull.call_args.kwargs["source_scope"] == "prod-project" + + +def test_main_pull_langfuse_rejects_metadata_selector_without_equals(tmp_path, capsys): + env_file = tmp_path / ".env" + env_file.write_text("LANGFUSE_PUBLIC_KEY=pk-1\nLANGFUSE_SECRET_KEY=sk-1\n") + + with patch("metergraphrelay.cli.pull_langfuse") as mock_pull: + exit_code = main(_pull_langfuse_args(env_file, tmp_path / "o.jsonl", "--metadata", "feature")) + + assert exit_code != 0 + mock_pull.assert_not_called() + assert "--metadata expects KEY=VALUE" in capsys.readouterr().err + + +def test_main_pull_langfuse_content_flags_are_mutually_exclusive(tmp_path): + env_file = tmp_path / ".env" + with pytest.raises(SystemExit): + main(_pull_langfuse_args(env_file, tmp_path / "o.jsonl", "--include-content", "--exclude-content")) + + +def test_sync_langfuse_help_no_longer_claims_content_has_no_opt_out(capsys): + with pytest.raises(SystemExit): + main(["sync", "langfuse", "--help"]) + text = " ".join(capsys.readouterr().out.split()) + assert "no opt-out" not in text + assert "uploaded only with --include-content" in text + assert "--user-id" in text and "--session-id" in text and "--metadata" in text + assert "\u2014" not in text # no em dashes in user-facing copy + + +def test_pull_langfuse_help_has_no_em_dashes_and_names_content_flags(capsys): + with pytest.raises(SystemExit): + main(["pull", "langfuse", "--help"]) + text = " ".join(capsys.readouterr().out.split()) + assert "\u2014" not in text + assert "--exclude-content" in text and "EMBEDDING" in text + + def test_main_pull_langfuse_credentials_are_loaded_from_env(tmp_path): env_file = tmp_path / ".env" env_file.write_text("LANGFUSE_PUBLIC_KEY=pk-env\nLANGFUSE_SECRET_KEY=sk-env\n") @@ -1490,6 +1573,8 @@ def test_sync_langfuse_dispatches_with_an_explicit_scope(tmp_path, capsys): "--initial-since", "2026-08-01T00:00:00Z", "--max-window-seconds", "1800", "--trace-name", "support-desk/triage", "--tag", "prod", + "--user-id", "user-1", "--session-id", "sess-1", + "--metadata", "feature=support-triage", ] ) @@ -1515,6 +1600,9 @@ def test_sync_langfuse_dispatches_with_an_explicit_scope(tmp_path, capsys): assert kwargs["provider_errors"] == (LangfuseAPIError,) assert kwargs["allow_skipped"] is False assert pulled["since"] == "2026-08-19T00:00:00+00:00" + assert pulled["user_id"] == "user-1" + assert pulled["session_id"] == "sess-1" + assert pulled["metadata"] == [("feature", "support-triage")] assert pulled["until"] == "2026-08-19T01:00:00+00:00" assert pulled["count"] >= 1_000_000 assert pulled["trace_names"] == ["support-desk/triage"] diff --git a/uv.lock b/uv.lock index 26155ad..f277919 100644 --- a/uv.lock +++ b/uv.lock @@ -244,7 +244,7 @@ wheels = [ [[package]] name = "metergraphrelay" -version = "0.7.9" +version = "0.8.0" source = { editable = "." } dependencies = [ { name = "openai" },