From 278506aa5c404b5a2aa1a941653eaf7a0eea7252 Mon Sep 17 00:00:00 2001 From: Arathy Kumar <49025521+ArathyKumar@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:44:10 +0530 Subject: [PATCH 1/8] chore: initialize fullsend per-repo installation --- .fullsend/config.yaml | 21 +++++ .github/workflows/fullsend.yaml | 150 +++++++++++++++++++++++++++++++ .github/workflows/prioritize.yml | 59 ++++++++++++ 3 files changed, 230 insertions(+) create mode 100644 .fullsend/config.yaml create mode 100644 .github/workflows/fullsend.yaml create mode 100644 .github/workflows/prioritize.yml diff --git a/.fullsend/config.yaml b/.fullsend/config.yaml new file mode 100644 index 0000000000..13a247e43c --- /dev/null +++ b/.fullsend/config.yaml @@ -0,0 +1,21 @@ +# fullsend per-repo configuration +# https://github.com/fullsend-ai/fullsend +# +# This file configures fullsend for per-repo installation mode. +# See https://fullsend.sh/docs/guides/infrastructure/layered-config-reference +version: "1" +tracker: + github: + allowed_targets: + repos: + - fullsend-ai/fullsend + - fullsend-ai/agents +runtime: pi +roles: + - review +allowed_remote_resources: + - https://raw.githubusercontent.com/fullsend-ai/fullsend/ + - https://raw.githubusercontent.com/fullsend-ai/agents/ +inference: + project: firefly-868139 + wif_provider: projects/275116376890/locations/global/workloadIdentityPools/uie-github-fullsend-inference/providers/gh-repo-116304230 diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml new file mode 100644 index 0000000000..5f35bd5e82 --- /dev/null +++ b/.github/workflows/fullsend.yaml @@ -0,0 +1,150 @@ +# This file is managed by fullsend. Do not edit it directly. +# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/fullsend.yaml +--- +# fullsend shim workflow (per-repo installation mode) +# Routes events to agent workflows via reusable-dispatch.yml. +# All agent execution happens in this repository's context. +# +# Security: pull request events use pull_request, not pull_request_target +# (GitHub blocks pull_request_target by default in public repositories; +# ADR 0164). On pull_request this workflow runs from the PR's own +# copy and forwards the repository secrets, so the dispatch job runs only for +# same-repo PRs, whose authors already have write access. Fork PRs are skipped +# here and again in reusable-dispatch.yml (a fork cannot edit the upstream +# copy; a vendored copy runs from the PR); a maintainer comments /fs-review +# to review one. In private repositories keep "Send secrets to workflows +# from pull requests" and "Send write tokens to workflows from pull +# requests" (Settings > Actions > General) turned off. +# reusable-dispatch.yml checks out the base side for pull request events. +# +# Routing: this shim forwards the raw event context to reusable-dispatch.yml, +# which determines the stage and runs the agent inline (ADR 62). +# Adding a new stage requires only a job in reusable-dispatch.yml — zero changes to this repo. +# +# Concurrency: per-role cancel-in-progress groups live in reusable-dispatch.yml +# stage jobs with -agent- suffix. Roles operate independently (#2452). +name: fullsend + +on: + issues: + types: [opened, edited, labeled] + issue_comment: + types: [created] + pull_request: + types: [opened, synchronize, ready_for_review, closed, labeled, unlabeled] + pull_request_review: + types: [submitted] + +permissions: {} + +jobs: + dispatch: + if: >- + (github.event_name != 'pull_request' && github.event_name != 'pull_request_review' + || github.event.pull_request.head.ref != 'fullsend/scaffold-install') + && (github.event_name != 'pull_request' + || github.event.pull_request.head.repo.id == github.repository_id) + && (github.event_name != 'issue_comment' + || startsWith(github.event.comment.body, '/fs-')) + permissions: + actions: write + id-token: write + contents: write + issues: write + packages: read + pull-requests: write + uses: fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml@d11de3ea0dde5aa652110b6716c19e000c426df7 # v0.57.1 + with: + event_action: ${{ github.event.action }} + mint_url: ${{ vars.FULLSEND_MINT_URL }} + gcp_region: ${{ vars.FULLSEND_GCP_REGION }} + project_number: ${{ vars.FULLSEND_PROJECT_NUMBER }} + runner_image: ubuntu-24.04 + secrets: + FULLSEND_GCP_WIF_PROVIDER: ${{ secrets.FULLSEND_GCP_WIF_PROVIDER }} + FULLSEND_GCP_PROJECT_ID: ${{ secrets.FULLSEND_GCP_PROJECT_ID }} + FULLSEND_OPENAI_API_KEY: ${{ secrets.FULLSEND_OPENAI_API_KEY }} + FULLSEND_INFERENCE_GATEWAY_API_KEY: ${{ secrets.FULLSEND_INFERENCE_GATEWAY_API_KEY }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }} + FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} + FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} + FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} + FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + FULLSEND_GITHUB_RUNNER_SECRETS: ${{ secrets.FULLSEND_GITHUB_RUNNER_SECRETS }} + + stop-fix: + # Job-level if: is intentionally coarse — it only screens for the + # /fs-fix-stop command on a PR from a non-bot. The authoritative + # authorization decision (collaborator permission API + PR-author escape + # hatch) is made in the step below, so a maintainer whose author_association + # is not MEMBER (e.g. private org membership) is not filtered out (ADR 0054). + if: >- + github.event_name == 'issue_comment' + && github.event.issue.pull_request + && github.event.comment.user.type != 'Bot' + && github.event.comment.body == '/fs-fix-stop' + runs-on: ubuntu-24.04 + permissions: + contents: read + issues: write + pull-requests: write + steps: + - name: Add fullsend-no-fix label and notify + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.issue.number }} + REPO: ${{ github.repository }} + COMMENT_USER_LOGIN: ${{ github.event.comment.user.login }} + ISSUE_USER_LOGIN: ${{ github.event.issue.user.login }} + run: | + set -euo pipefail + # ADR 0054: authorize via the collaborator permission API + # (admin|maintain|write), not author_association — the latter grants + # contributor status to anyone with a single merged PR (issue #5421). + # Mirrors has_repo_permission() in reusable-dispatch.yml, including the + # custom-role --jq resolution; keep the two in sync. + # The PR author may always stop the fix agent on their own PR. + authorized=false + if [[ -n "$COMMENT_USER_LOGIN" && "$COMMENT_USER_LOGIN" == "$ISSUE_USER_LOGIN" ]]; then + authorized=true + else + if api_err=$(mktemp); then + # $p is a jq variable; the single quotes are intentional. + # shellcheck disable=SC2016 + if role=$(gh api "repos/$REPO/collaborators/$COMMENT_USER_LOGIN/permission" \ + --jq '.user.permissions as $p + | if (.role_name | type) != "string" or .role_name == "" then "none" + elif (.role_name | IN("admin", "maintain", "write", "triage", "read")) then .role_name + elif $p == null then + if (.permission | IN("admin", "write", "read")) then .permission else "none" end + elif ($p | type) == "object" then + if $p.admin == true then "admin" + elif $p.maintain == true then "maintain" + elif $p.push == true then "write" + elif $p.triage == true then "triage" + elif $p.pull == true then "read" + else "none" end + else "none" end' 2>"$api_err"); then + case "$role" in + admin|maintain|write) authorized=true ;; + esac + else + echo "::warning::Permission API call failed for $COMMENT_USER_LOGIN: $(cat "$api_err")" + fi + rm -f "$api_err" + else + echo "::warning::Failed to create temp file for permission check of $COMMENT_USER_LOGIN" + fi + fi + if [[ "$authorized" != "true" ]]; then + echo "::notice::User $COMMENT_USER_LOGIN is not authorized to stop the fix agent (requires write access or PR authorship)" + exit 0 + fi + gh label create "fullsend-no-fix" --repo "$REPO" \ + --description "Skip bot-triggered fix agent runs" --color "FBCA04" \ + 2>/dev/null || true + gh pr edit "$PR_NUMBER" --repo "$REPO" \ + --add-label "fullsend-no-fix" + gh pr comment "$PR_NUMBER" --repo "$REPO" \ + --body "Fix agent disabled for this PR. Remove the \`fullsend-no-fix\` label or use \`/fs-fix\` to re-engage." diff --git a/.github/workflows/prioritize.yml b/.github/workflows/prioritize.yml new file mode 100644 index 0000000000..51f19af074 --- /dev/null +++ b/.github/workflows/prioritize.yml @@ -0,0 +1,59 @@ +# This file is managed by fullsend. Do not edit it directly. +# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/prioritize.yml +--- +# fullsend-stage: prioritize +name: Prioritize + +permissions: + actions: write + contents: read + id-token: write + issues: write + +on: + workflow_dispatch: + inputs: + event_type: + description: Event type that triggered prioritization + required: true + type: string + source_repo: + description: Repository the event came from (owner/repo) + required: true + type: string + event_payload: + description: JSON-encoded payload of the triggering event + required: true + type: string + project_number: + description: GitHub Projects V2 project number for RICE scoring + required: false + type: string + +concurrency: + group: fullsend-prioritize-${{ inputs.source_repo }}-${{ fromJSON(inputs.event_payload).issue.number || fromJSON(inputs.event_payload).pull_request.number }} + cancel-in-progress: true + +jobs: + prioritize: + uses: fullsend-ai/fullsend/.github/workflows/reusable-prioritize.yml@d11de3ea0dde5aa652110b6716c19e000c426df7 # v0.57.1 + with: + event_type: ${{ inputs.event_type }} + source_repo: ${{ inputs.source_repo }} + event_payload: ${{ inputs.event_payload }} + mint_url: ${{ vars.FULLSEND_MINT_URL }} + gcp_region: ${{ vars.FULLSEND_GCP_REGION }} + project_number: ${{ inputs.project_number || vars.FULLSEND_PROJECT_NUMBER }} + runner_image: ubuntu-24.04 + secrets: + FULLSEND_GCP_WIF_PROVIDER: ${{ secrets.FULLSEND_GCP_WIF_PROVIDER }} + FULLSEND_GCP_PROJECT_ID: ${{ secrets.FULLSEND_GCP_PROJECT_ID }} + FULLSEND_OPENAI_API_KEY: ${{ secrets.FULLSEND_OPENAI_API_KEY }} + FULLSEND_INFERENCE_GATEWAY_API_KEY: ${{ secrets.FULLSEND_INFERENCE_GATEWAY_API_KEY }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }} + FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} + FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} + FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} + FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + FULLSEND_GITHUB_RUNNER_SECRETS: ${{ secrets.FULLSEND_GITHUB_RUNNER_SECRETS }} From db0cb0d7ef4d5ba4d0953879aca98b113e19ed0c Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Tue, 1 Dec 2026 17:51:56 +0530 Subject: [PATCH 2/8] chore: configure review agent model and disable out-of-rollout agents --- .fullsend/config.yaml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.fullsend/config.yaml b/.fullsend/config.yaml index 13a247e43c..597c237a65 100644 --- a/.fullsend/config.yaml +++ b/.fullsend/config.yaml @@ -13,6 +13,13 @@ tracker: runtime: pi roles: - review +agents: + - name: review + model: google-vertex/gemini-3.8-flash + - name: retro + enabled: false + - name: prioritize + enabled: false allowed_remote_resources: - https://raw.githubusercontent.com/fullsend-ai/fullsend/ - https://raw.githubusercontent.com/fullsend-ai/agents/ From 5422e43f76e48ceb37dc5d7772deccb691549d7a Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Tue, 1 Dec 2026 18:02:12 +0530 Subject: [PATCH 3/8] chore: ignore fullsend local resource cache Co-authored-by: Cursor --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 6f6ad9dc21..f8e64ce33f 100644 --- a/.gitignore +++ b/.gitignore @@ -133,3 +133,6 @@ browserstack.err # Local Netlify folder .netlify + +# fullsend local resource cache +.fullsend/.fullsend-cache/ From d149dd0aa5151b4679c2d4060a9e42caa7efe557 Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Tue, 1 Dec 2026 18:40:41 +0530 Subject: [PATCH 4/8] chore: export Fullsend run telemetry to Langfuse Co-authored-by: Cursor --- .fullsend/scripts/langfuse-post-run.py | 460 +++++++++++++++++++++++ .github/workflows/fullsend-langfuse.yaml | 36 ++ .github/workflows/fullsend.yaml | 50 +++ 3 files changed, 546 insertions(+) create mode 100644 .fullsend/scripts/langfuse-post-run.py create mode 100644 .github/workflows/fullsend-langfuse.yaml diff --git a/.fullsend/scripts/langfuse-post-run.py b/.fullsend/scripts/langfuse-post-run.py new file mode 100644 index 0000000000..3fb1baa4bd --- /dev/null +++ b/.fullsend/scripts/langfuse-post-run.py @@ -0,0 +1,460 @@ +# Generated by uie-fullsend langfuse-setup. Uses trusted default-branch code. +"""Add generation observations to native Fullsend traces; Python standard library. + +Derived from fullsend-component/scripts/lib/langfuse.sh's generation bridge. +Only model/usage and CI metadata are exported; artifacts never supply code, +credentials, an endpoint, or prompt/response content. +""" +import argparse +import base64 +import hashlib +import json +import math +import os +from pathlib import Path +import re +import secrets +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +def attributes(entries): + if isinstance(entries, dict): + return dict(entries) + result = {} + for entry in entries or []: + value = entry.get("value", {}) + for kind in ("stringValue", "intValue", "doubleValue", "boolValue"): + if kind in value: + result[entry["key"]] = value[kind] + break + return result + + +def otlp_attributes(values): + result = [] + for key, value in values.items(): + if value is None: + continue + if isinstance(value, bool): + encoded = {"boolValue": value} + elif isinstance(value, int): + encoded = {"intValue": str(value)} + elif isinstance(value, float): + encoded = {"doubleValue": value} + elif isinstance(value, list): + encoded = {"arrayValue": {"values": [{"stringValue": str(item)} for item in value]}} + else: + encoded = {"stringValue": str(value)} + result.append({"key": key, "value": encoded}) + return result + + +def extract_team_value(value): + if value is None: + return None + if isinstance(value, dict): + raw = value.get("title") or value.get("name") or value.get("team") + if raw is None: + return None + team = str(raw).strip() + else: + team = str(value).strip() + if not team or team.lower() in ("unassigned", "none", "null"): + return None + return team + + +def hydrate_jira_team_from_api(issue_key, env, team_field=None): + if not issue_key or not env: + return None + if not re.fullmatch(r"[A-Za-z0-9_]+-\d+", str(issue_key)): + return None + team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" + if not re.fullmatch(r"[\w.-]+", str(team_field)): + return None + base_url = env.get("JIRA_BASE_URL") or env.get("FULLSEND_JIRA_URL") or "https://redhat.atlassian.net" + user_email = env.get("JIRA_USER_EMAIL") or env.get("FULLSEND_JIRA_EMAIL") + token = env.get("JIRA_TOKEN") or env.get("FULLSEND_JIRA_API_TOKEN") + if not (base_url and user_email and token): + return None + endpoint = f"{base_url.rstrip('/')}/rest/api/3/issue/{issue_key}?fields={urllib.parse.quote(str(team_field))}" + auth = base64.b64encode(f"{user_email}:{token}".encode("utf-8")).decode("ascii") + headers = {"Authorization": f"Basic {auth}", "Accept": "application/json"} + req = urllib.request.Request(endpoint, headers=headers, method="GET") + + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + try: + with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as resp: + data = json.loads(resp.read() or b"{}") + fields = data.get("fields", {}) if isinstance(data, dict) else {} + return extract_team_value(fields.get(team_field)) + except urllib.error.HTTPError as error: + print( + f"Jira Team hydration failed for {issue_key} (HTTP {error.code}); " + "using repository team fallback.", + file=sys.stderr, + ) + return None + except Exception as error: + # Do not expose URLs, credentials, or upstream error bodies in workflow logs. + print( + f"Jira Team hydration failed for {issue_key} ({type(error).__name__}); " + "using repository team fallback.", + file=sys.stderr, + ) + return None + + +def resolve_jira_runtime_team(event=None, env=None, context=None, team_field=None, issue_key=None, span_team=None): + if env is None: + env = os.environ + team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" + + # Precedence: native Jira ticket Team > normalized event payload team > JIRA_ISSUE_TEAM > JIRA_TEAM > FULLSEND_TEAM / repo fallback > omitted. + + # 1. Native Jira ticket Team + if span_team is not None: + team = extract_team_value(span_team) + if team is not None: + return team + + if isinstance(event, dict): + issue = ( + event.get("issue") + or (event.get("data", {}).get("issue") if isinstance(event.get("data"), dict) else None) + or (event.get("entity") if isinstance(event.get("entity"), dict) and ("fields" in event["entity"] or team_field in event["entity"]) else None) + or (event.get("raw") if isinstance(event.get("raw"), dict) and ("fields" in event["raw"] or team_field in event["raw"]) else None) + or (event if "fields" in event or team_field in event else None) + ) + if isinstance(issue, dict): + fields = issue.get("fields") if isinstance(issue.get("fields"), dict) else issue + team = extract_team_value(fields.get(team_field)) + if team is not None: + return team + + eff_issue_key = ( + issue_key + or event.get("issue_key") + or (event.get("entity", {}).get("key") if isinstance(event.get("entity"), dict) else None) + or (event.get("issue", {}).get("key") if isinstance(event.get("issue"), dict) else None) + or env.get("JIRA_ISSUE_KEY") + or env.get("ISSUE_KEY") + or env.get("FULLSEND_TICKET") + ) + if eff_issue_key: + hydrated = hydrate_jira_team_from_api(eff_issue_key, env, team_field=team_field) + if hydrated is not None: + return hydrated + else: + eff_issue_key = ( + issue_key + or env.get("JIRA_ISSUE_KEY") + or env.get("ISSUE_KEY") + or env.get("FULLSEND_TICKET") + ) + if eff_issue_key: + hydrated = hydrate_jira_team_from_api(eff_issue_key, env, team_field=team_field) + if hydrated is not None: + return hydrated + + # 2. Normalized event payload team + if isinstance(event, dict): + event_team = ( + event.get("team") + or (event.get("entity", {}).get("team") if isinstance(event.get("entity"), dict) else None) + or (event.get("state", {}).get("team") if isinstance(event.get("state"), dict) else None) + or (event.get("data", {}).get("team") if isinstance(event.get("data"), dict) else None) + ) + team = extract_team_value(event_team) + if team is not None: + return team + + # 3. JIRA_ISSUE_TEAM + team = extract_team_value(env.get("JIRA_ISSUE_TEAM")) + if team is not None: + return team + + # 4. JIRA_TEAM + team = extract_team_value(env.get("JIRA_TEAM")) + if team is not None: + return team + + # 5. FULLSEND_TEAM / the FRFLY-864 setup fallback + team = extract_team_value(env.get("FULLSEND_TEAM")) + if team is not None: + return team + + if context and context.get("team"): + team = extract_team_value(context["team"]) + if team is not None: + return team + + otel_attrs = env.get("OTEL_RESOURCE_ATTRIBUTES") or "" + for item in otel_attrs.split(","): + if "=" in item: + k, v = item.split("=", 1) + if k.strip() == "team": + team = extract_team_value(urllib.parse.unquote(v.strip())) + if team is not None: + return team + + return None + + +def add_filterable_context(values): + for key in ("project_key", "cost_center", "team", "github.repository", "github.run_id"): + if values.get(key): + name = key.replace(".", "_") + for level in ("trace", "observation"): + values[f"langfuse.{level}.metadata.{name}"] = values[key] + tags = [f"{label}:{values[key]}" for key, label in ( + ("gen_ai.agent.name", "stage"), + ("project_key", "project_key"), ("cost_center", "cost_center"), + ("team", "team"), + ("github.repository", "repo"), + ) if values.get(key)] + if tags: + values["langfuse.trace.tags"] = tags + + +def number(value, integer=False): + if value is None: + return None + parsed = float(value) + if not math.isfinite(parsed) or parsed < 0: + raise ValueError("Invalid usage value") + return int(parsed) if integer else parsed + + +def read_spans(path): + # The exporter writes one OTLP resourceSpans envelope per JSONL line. + if path.stat().st_size > 32 * 1024 * 1024: + raise ValueError("Telemetry exceeds size limit") + spans = {} + with path.open(encoding="utf-8") as stream: + for line in stream: + if not line.strip(): + continue + record = json.loads(line) + for resource in record.get("resourceSpans", []): + for scope in resource.get("scopeSpans", []): + for span in scope.get("spans", []): + spans[(span.get("traceId"), span.get("spanId"))] = span + return list(spans.values()) + + +def build_payload(path, context): + spans = read_spans(path) + agents = [span for span in spans if attributes(span.get("attributes")).get("gen_ai.operation.name") == "invoke_agent"] + # Fullsend emits a root "run" span and a child "agent" span, both tagged invoke_agent. + # Only the innermost belongs to a generation; counting both also suppresses the metrics + # fallback below, costing cost precision (FRFLY-755). Keyed on (traceId, spanId) so a + # child in one trace cannot suppress an agent in another. + parents = {(span.get("traceId"), span.get("parentSpanId")) for span in agents if span.get("parentSpanId")} + model_bearing = [span for span in agents if attributes(span.get("attributes")).get("gen_ai.request.model")] + agents = [span for span in agents if (span.get("traceId"), span.get("spanId")) not in parents] + metrics = {} + metrics_path = path.with_name("metrics.json") + if metrics_path.is_file() and metrics_path.stat().st_size < 1024 * 1024: + metrics = json.loads(metrics_path.read_text(encoding="utf-8")) + if not isinstance(metrics, dict): + metrics = {} + # Use metrics only for a single agent; don't multiply whole-run totals across agents. + # A genuine multi-agent run can collapse to one nested target, so also refuse when more + # than one agent span carries its own model (FRFLY-755). + if len(agents) != 1 or len(model_bearing) > 1: + metrics = {} + output = [] + for agent in agents: + source = attributes(agent.get("attributes")) + if any(span.get("parentSpanId") == agent.get("spanId") and + attributes(span.get("attributes")).get("langfuse.observation.type") == "generation" for span in spans): + continue + model = source.get("gen_ai.request.model") or metrics.get("model") + if not model: + continue # Never invent a model (the GitLab reference has a Gemini fallback). + trace_id, parent_id = agent.get("traceId") or "", agent.get("spanId") or "" + if not re.fullmatch(r"[0-9a-fA-F]{32}", trace_id) or not re.fullmatch(r"[0-9a-fA-F]{16}", parent_id): + raise ValueError("Invalid trace identity") + start, end = int(agent["startTimeUnixNano"]), int(agent["endTimeUnixNano"]) + if start < 0 or end < start: + raise ValueError("Invalid span timestamps") + model = str(model).removeprefix("google-vertex/") + values = dict(context) + values.update({"langfuse.observation.type": "generation", "gen_ai.operation.name": "generate_content", + "gen_ai.request.model": model, "langfuse.observation.model.name": model, + "gen_ai.system": source.get("gen_ai.system")}) + usage = metrics.get("token_usage") or {} + for attr, fallback in (("gen_ai.usage.input_tokens", "input"), ("gen_ai.usage.output_tokens", "output"), + ("gen_ai.usage.cache_read.input_tokens", "cache_read"), + ("gen_ai.usage.reasoning.output_tokens", "reasoning")): + value = source.get(attr) + if value is None and attr.endswith("reasoning.output_tokens"): + value = source.get("gen_ai.usage.reasoning_tokens") + if value is None: + value = usage.get(fallback) + if value is not None: + values[attr] = number(value, integer=True) + # fullsend.cost_usd on the span is rounded to 2dp; metrics.json beside the telemetry + # carries full precision for the same run, so prefer it (FRFLY-755). + cost = metrics.get("total_cost_usd") + if cost is None: + cost = source.get("fullsend.cost_usd") + if cost is not None: + values["gen_ai.usage.cost"] = number(cost) + values["langfuse.observation.cost_details"] = json.dumps({"total": number(cost)}) + for attr, fallback in (("fullsend.num_turns", "iterations"), ("fullsend.tool_calls", None)): + value = source.get(attr) + if value is None and fallback is not None: + value = metrics.get(fallback) + if value is not None: + values[attr] = number(value, integer=True) + stage = source.get("gen_ai.agent.name") or next( + (parent.name.removeprefix("fullsend-") for parent in path.parents + if parent.name.startswith("fullsend-")), "run") + values["gen_ai.agent.name"] = stage + trace_name = f"{stage}: {context.get('github.repository', 'fullsend')}" + if context.get("github.run_id"): + trace_name += f"#{context['github.run_id']}" + values["langfuse.trace.name"] = trace_name + span_id = hashlib.sha256(f"fullsend-langfuse-generation-v1:{trace_id}:{parent_id}".encode()).hexdigest()[:16] + + # Resolve authoritative team attribute for the agent span + event = None + for candidate in ("event.json", "normalized-event.json", "input.json"): + ef = path.with_name(candidate) + if ef.is_file(): + try: + event = json.loads(ef.read_text(encoding="utf-8")) + break + except Exception: + pass + span_team = source.get("team") + issue_key = source.get("jira.issue_key") or source.get("jira.key") or source.get("work_item.key") or source.get("issue_key") + runtime_team = resolve_jira_runtime_team(event=event, env=os.environ, context=context, issue_key=issue_key, span_team=span_team) + if runtime_team is not None: + values["team"] = runtime_team + else: + values.pop("team", None) + + add_filterable_context(values) + output.append({"traceId": trace_id, "spanId": span_id, "parentSpanId": parent_id, + "name": f"{stage.capitalize()} Generation: {model}", "kind": 1, + "startTimeUnixNano": str(start), "endTimeUnixNano": str(end), + "attributes": otlp_attributes(values), "status": {"code": (agent.get("status") or {}).get("code", 1)}}) + return {"resourceSpans": [{"resource": {"attributes": otlp_attributes(context)}, + "scopeSpans": [{"scope": {"name": "fullsend-generation-bridge", "version": "1.0.0"}, "spans": output}]}]} + + +def verification_payload(trace_id, context): + if not re.fullmatch(r"[0-9a-fA-F]{32}", trace_id): + raise ValueError("Invalid verification trace ID") + if not context.get("cost_center") or context["cost_center"].lower() == "unassigned": + raise ValueError("Missing configured cost_center resource attribute") + now = time.time_ns() + values = dict(context) + values["langfuse.trace.name"] = "Fullsend Langfuse verification" + add_filterable_context(values) + span = {"traceId": trace_id.lower(), "spanId": secrets.token_hex(8), + "name": "Fullsend Langfuse verification", "kind": 1, + "startTimeUnixNano": str(now), "endTimeUnixNano": str(now + 1_000_000), + "attributes": otlp_attributes(values), "status": {"code": 1}} + return {"resourceSpans": [{"resource": {"attributes": otlp_attributes(context)}, + "scopeSpans": [{"scope": {"name": "fullsend-generation-bridge", "version": "1.0.0"}, + "spans": [span]}]}]} + + +def export(payload, env): + endpoint = env.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "") + url = urllib.parse.urlsplit(endpoint) + is_loopback_http = url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1", "::1") + if (url.scheme != "https" and not is_loopback_http) or not url.hostname or url.username or url.password or url.query or url.fragment: + raise ValueError("Invalid configured export endpoint") + headers = {"Content-Type": "application/json", "x-langfuse-ingestion-version": "4"} + for item in env.get("OTEL_EXPORTER_OTLP_TRACES_HEADERS", "").split(","): + if "=" in item: + key, value = item.split("=", 1) + headers[key.strip()] = urllib.parse.unquote(value.strip()) + if not any(key.lower() == "authorization" for key in headers): + raise ValueError("Missing configured export authorization") + request = urllib.request.Request(endpoint, data=json.dumps(payload).encode(), headers=headers, method="POST") + # Don't forward authentication to an unexpected redirect destination. + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response: + result = json.loads(response.read() or b"{}") + if int((result.get("partialSuccess") or {}).get("rejectedSpans", 0)): + raise ValueError("Backend rejected generation spans") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("artifacts", nargs="?", type=Path) + parser.add_argument("--dry-run", action="store_true", help="Build and count spans without contacting Langfuse") + parser.add_argument("--verify-trace-id", help="Export one diagnostic trace with this 32-character hex ID") + args = parser.parse_args(argv) + if args.artifacts is None and args.verify_trace_id is None: + parser.error("artifacts or --verify-trace-id is required") + if args.artifacts is not None and args.verify_trace_id is not None: + parser.error("artifacts and --verify-trace-id cannot be combined") + context = {} + for item in (os.environ.get("OTEL_RESOURCE_ATTRIBUTES") or "").split(","): + if "=" in item: + key, value = item.split("=", 1) + context[key.strip()] = urllib.parse.unquote(value.strip()) + context["github.repository"] = os.environ.get("GITHUB_REPOSITORY", context.get("github.repository", "fullsend")) + for env_key, attr in (("SOURCE_RUN_ID", "github.run_id"), ("SOURCE_RUN_ATTEMPT", "github.run_attempt"), + ("SOURCE_ACTOR", "user.id")): + if os.environ.get(env_key): + context[attr] = os.environ[env_key] + runtime_team = resolve_jira_runtime_team(env=os.environ, context=context) + if runtime_team is not None: + context["team"] = runtime_team + else: + context.pop("team", None) + if context.get("github.run_id"): + context["session.id"] = context["langfuse.session.id"] = context["github.run_id"] + if context.get("user.id"): + context["langfuse.user.id"] = context["user.id"] + if args.verify_trace_id is not None: + try: + payload = verification_payload(args.verify_trace_id, context) + if not args.dry_run: + export(payload, os.environ) + print(f"{'Prepared' if args.dry_run else 'Exported'} verification trace {args.verify_trace_id.lower()}.") + return 0 + except Exception as error: + status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" + print(f"Langfuse verification failed: {type(error).__name__}{status}", file=sys.stderr) + return 1 + files = sorted(args.artifacts.rglob("run-telemetry.jsonl")) + if not files: + print("No Fullsend telemetry artifacts found; nothing to export.") + failed = False + for path in files: + try: + payload = build_payload(path, context) + count = len(payload["resourceSpans"][0]["scopeSpans"][0]["spans"]) + if count and not args.dry_run: + export(payload, os.environ) + print(f"{'Prepared' if args.dry_run else 'Exported'} {count} generation spans.") + if not count: + print("No agent spans with known models need generation export.") + except Exception as error: + # Never print URLs, headers, artifact content, or upstream error bodies. + status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" + print(f"Langfuse generation export failed: {type(error).__name__}{status}", file=sys.stderr) + failed = True + return int(failed) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/fullsend-langfuse.yaml b/.github/workflows/fullsend-langfuse.yaml new file mode 100644 index 0000000000..b632daa3aa --- /dev/null +++ b/.github/workflows/fullsend-langfuse.yaml @@ -0,0 +1,36 @@ +# Generated by uie-fullsend langfuse-setup. Uses trusted default-branch code. +name: Fullsend Langfuse +on: + workflow_dispatch: + inputs: + trace_id: + description: OTLP trace ID for verification (32 hexadecimal characters) + required: true + type: string +# Least privilege: checks out trusted default-branch Langfuse script without write credentials. +permissions: + contents: read +jobs: + generation: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Export Langfuse trace + env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_RESOURCE_ATTRIBUTES: ${{ vars.OTEL_RESOURCE_ATTRIBUTES }} + JIRA_BASE_URL: ${{ vars.JIRA_BASE_URL }} + JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }} + JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} + FULLSEND_JIRA_TEAM_FIELD: ${{ vars.FULLSEND_JIRA_TEAM_FIELD }} + SOURCE_RUN_ID: ${{ github.run_id }} + SOURCE_RUN_ATTEMPT: ${{ github.run_attempt }} + SOURCE_ACTOR: ${{ github.actor }} + VERIFY_TRACE_ID: ${{ inputs.trace_id }} + run: | + python3 .fullsend/scripts/langfuse-post-run.py --verify-trace-id "$VERIFY_TRACE_ID" diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 5f35bd5e82..9db522d445 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -148,3 +148,53 @@ jobs: --add-label "fullsend-no-fix" gh pr comment "$PR_NUMBER" --repo "$REPO" \ --body "Fix agent disabled for this PR. Remove the \`fullsend-no-fix\` label or use \`/fs-fix\` to re-engage." + + # >>> uie-fullsend langfuse-export (managed block: re-run `uie-fullsend langfuse setup` to refresh) + # Exports Fullsend telemetry directly to Langfuse when this run has published + # fullsend-* telemetry artifacts. Runs after the upstream Fullsend dispatch job. + langfuse-export: + needs: dispatch + if: always() && !cancelled() + runs-on: ubuntu-24.04 + permissions: + actions: read # download artifacts from this run + contents: read # checkout trusted default-branch script + steps: + - name: Detect Fullsend telemetry artifacts + id: telemetry + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_ID: ${{ github.run_id }} + run: | + artifacts="$(gh api --paginate "repos/$GH_REPO/actions/runs/$RUN_ID/artifacts?per_page=100" --jq '.artifacts[].name | select(startswith("fullsend-"))')" + [ -n "$artifacts" ] && echo "found=true" >> "$GITHUB_OUTPUT" || exit 0 + + - name: Checkout Langfuse script + if: steps.telemetry.outputs.found == 'true' + uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Download Fullsend artifacts + if: steps.telemetry.outputs.found == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: gh run download "${{ github.run_id }}" --pattern 'fullsend-*' --dir "$RUNNER_TEMP/langfuse-artifacts" + + - name: Export Langfuse trace + if: steps.telemetry.outputs.found == 'true' + env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_RESOURCE_ATTRIBUTES: ${{ vars.OTEL_RESOURCE_ATTRIBUTES }} + JIRA_BASE_URL: ${{ vars.JIRA_BASE_URL }} + JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }} + JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} + FULLSEND_JIRA_TEAM_FIELD: ${{ vars.FULLSEND_JIRA_TEAM_FIELD }} + SOURCE_RUN_ID: ${{ github.run_id }} + SOURCE_RUN_ATTEMPT: ${{ github.run_attempt }} + SOURCE_ACTOR: ${{ github.actor }} + run: python3 .fullsend/scripts/langfuse-post-run.py "$RUNNER_TEMP/langfuse-artifacts" + # <<< uie-fullsend langfuse-export From 151f0e37504ce559be11377dc1794b30e4ed3d02 Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Tue, 1 Dec 2026 18:42:14 +0530 Subject: [PATCH 5/8] Revert "chore: export Fullsend run telemetry to Langfuse" This reverts commit d149dd0aa5151b4679c2d4060a9e42caa7efe557. --- .fullsend/scripts/langfuse-post-run.py | 460 ----------------------- .github/workflows/fullsend-langfuse.yaml | 36 -- .github/workflows/fullsend.yaml | 50 --- 3 files changed, 546 deletions(-) delete mode 100644 .fullsend/scripts/langfuse-post-run.py delete mode 100644 .github/workflows/fullsend-langfuse.yaml diff --git a/.fullsend/scripts/langfuse-post-run.py b/.fullsend/scripts/langfuse-post-run.py deleted file mode 100644 index 3fb1baa4bd..0000000000 --- a/.fullsend/scripts/langfuse-post-run.py +++ /dev/null @@ -1,460 +0,0 @@ -# Generated by uie-fullsend langfuse-setup. Uses trusted default-branch code. -"""Add generation observations to native Fullsend traces; Python standard library. - -Derived from fullsend-component/scripts/lib/langfuse.sh's generation bridge. -Only model/usage and CI metadata are exported; artifacts never supply code, -credentials, an endpoint, or prompt/response content. -""" -import argparse -import base64 -import hashlib -import json -import math -import os -from pathlib import Path -import re -import secrets -import sys -import time -import urllib.error -import urllib.parse -import urllib.request - - -def attributes(entries): - if isinstance(entries, dict): - return dict(entries) - result = {} - for entry in entries or []: - value = entry.get("value", {}) - for kind in ("stringValue", "intValue", "doubleValue", "boolValue"): - if kind in value: - result[entry["key"]] = value[kind] - break - return result - - -def otlp_attributes(values): - result = [] - for key, value in values.items(): - if value is None: - continue - if isinstance(value, bool): - encoded = {"boolValue": value} - elif isinstance(value, int): - encoded = {"intValue": str(value)} - elif isinstance(value, float): - encoded = {"doubleValue": value} - elif isinstance(value, list): - encoded = {"arrayValue": {"values": [{"stringValue": str(item)} for item in value]}} - else: - encoded = {"stringValue": str(value)} - result.append({"key": key, "value": encoded}) - return result - - -def extract_team_value(value): - if value is None: - return None - if isinstance(value, dict): - raw = value.get("title") or value.get("name") or value.get("team") - if raw is None: - return None - team = str(raw).strip() - else: - team = str(value).strip() - if not team or team.lower() in ("unassigned", "none", "null"): - return None - return team - - -def hydrate_jira_team_from_api(issue_key, env, team_field=None): - if not issue_key or not env: - return None - if not re.fullmatch(r"[A-Za-z0-9_]+-\d+", str(issue_key)): - return None - team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" - if not re.fullmatch(r"[\w.-]+", str(team_field)): - return None - base_url = env.get("JIRA_BASE_URL") or env.get("FULLSEND_JIRA_URL") or "https://redhat.atlassian.net" - user_email = env.get("JIRA_USER_EMAIL") or env.get("FULLSEND_JIRA_EMAIL") - token = env.get("JIRA_TOKEN") or env.get("FULLSEND_JIRA_API_TOKEN") - if not (base_url and user_email and token): - return None - endpoint = f"{base_url.rstrip('/')}/rest/api/3/issue/{issue_key}?fields={urllib.parse.quote(str(team_field))}" - auth = base64.b64encode(f"{user_email}:{token}".encode("utf-8")).decode("ascii") - headers = {"Authorization": f"Basic {auth}", "Accept": "application/json"} - req = urllib.request.Request(endpoint, headers=headers, method="GET") - - class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, *args, **kwargs): - return None - - try: - with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as resp: - data = json.loads(resp.read() or b"{}") - fields = data.get("fields", {}) if isinstance(data, dict) else {} - return extract_team_value(fields.get(team_field)) - except urllib.error.HTTPError as error: - print( - f"Jira Team hydration failed for {issue_key} (HTTP {error.code}); " - "using repository team fallback.", - file=sys.stderr, - ) - return None - except Exception as error: - # Do not expose URLs, credentials, or upstream error bodies in workflow logs. - print( - f"Jira Team hydration failed for {issue_key} ({type(error).__name__}); " - "using repository team fallback.", - file=sys.stderr, - ) - return None - - -def resolve_jira_runtime_team(event=None, env=None, context=None, team_field=None, issue_key=None, span_team=None): - if env is None: - env = os.environ - team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" - - # Precedence: native Jira ticket Team > normalized event payload team > JIRA_ISSUE_TEAM > JIRA_TEAM > FULLSEND_TEAM / repo fallback > omitted. - - # 1. Native Jira ticket Team - if span_team is not None: - team = extract_team_value(span_team) - if team is not None: - return team - - if isinstance(event, dict): - issue = ( - event.get("issue") - or (event.get("data", {}).get("issue") if isinstance(event.get("data"), dict) else None) - or (event.get("entity") if isinstance(event.get("entity"), dict) and ("fields" in event["entity"] or team_field in event["entity"]) else None) - or (event.get("raw") if isinstance(event.get("raw"), dict) and ("fields" in event["raw"] or team_field in event["raw"]) else None) - or (event if "fields" in event or team_field in event else None) - ) - if isinstance(issue, dict): - fields = issue.get("fields") if isinstance(issue.get("fields"), dict) else issue - team = extract_team_value(fields.get(team_field)) - if team is not None: - return team - - eff_issue_key = ( - issue_key - or event.get("issue_key") - or (event.get("entity", {}).get("key") if isinstance(event.get("entity"), dict) else None) - or (event.get("issue", {}).get("key") if isinstance(event.get("issue"), dict) else None) - or env.get("JIRA_ISSUE_KEY") - or env.get("ISSUE_KEY") - or env.get("FULLSEND_TICKET") - ) - if eff_issue_key: - hydrated = hydrate_jira_team_from_api(eff_issue_key, env, team_field=team_field) - if hydrated is not None: - return hydrated - else: - eff_issue_key = ( - issue_key - or env.get("JIRA_ISSUE_KEY") - or env.get("ISSUE_KEY") - or env.get("FULLSEND_TICKET") - ) - if eff_issue_key: - hydrated = hydrate_jira_team_from_api(eff_issue_key, env, team_field=team_field) - if hydrated is not None: - return hydrated - - # 2. Normalized event payload team - if isinstance(event, dict): - event_team = ( - event.get("team") - or (event.get("entity", {}).get("team") if isinstance(event.get("entity"), dict) else None) - or (event.get("state", {}).get("team") if isinstance(event.get("state"), dict) else None) - or (event.get("data", {}).get("team") if isinstance(event.get("data"), dict) else None) - ) - team = extract_team_value(event_team) - if team is not None: - return team - - # 3. JIRA_ISSUE_TEAM - team = extract_team_value(env.get("JIRA_ISSUE_TEAM")) - if team is not None: - return team - - # 4. JIRA_TEAM - team = extract_team_value(env.get("JIRA_TEAM")) - if team is not None: - return team - - # 5. FULLSEND_TEAM / the FRFLY-864 setup fallback - team = extract_team_value(env.get("FULLSEND_TEAM")) - if team is not None: - return team - - if context and context.get("team"): - team = extract_team_value(context["team"]) - if team is not None: - return team - - otel_attrs = env.get("OTEL_RESOURCE_ATTRIBUTES") or "" - for item in otel_attrs.split(","): - if "=" in item: - k, v = item.split("=", 1) - if k.strip() == "team": - team = extract_team_value(urllib.parse.unquote(v.strip())) - if team is not None: - return team - - return None - - -def add_filterable_context(values): - for key in ("project_key", "cost_center", "team", "github.repository", "github.run_id"): - if values.get(key): - name = key.replace(".", "_") - for level in ("trace", "observation"): - values[f"langfuse.{level}.metadata.{name}"] = values[key] - tags = [f"{label}:{values[key]}" for key, label in ( - ("gen_ai.agent.name", "stage"), - ("project_key", "project_key"), ("cost_center", "cost_center"), - ("team", "team"), - ("github.repository", "repo"), - ) if values.get(key)] - if tags: - values["langfuse.trace.tags"] = tags - - -def number(value, integer=False): - if value is None: - return None - parsed = float(value) - if not math.isfinite(parsed) or parsed < 0: - raise ValueError("Invalid usage value") - return int(parsed) if integer else parsed - - -def read_spans(path): - # The exporter writes one OTLP resourceSpans envelope per JSONL line. - if path.stat().st_size > 32 * 1024 * 1024: - raise ValueError("Telemetry exceeds size limit") - spans = {} - with path.open(encoding="utf-8") as stream: - for line in stream: - if not line.strip(): - continue - record = json.loads(line) - for resource in record.get("resourceSpans", []): - for scope in resource.get("scopeSpans", []): - for span in scope.get("spans", []): - spans[(span.get("traceId"), span.get("spanId"))] = span - return list(spans.values()) - - -def build_payload(path, context): - spans = read_spans(path) - agents = [span for span in spans if attributes(span.get("attributes")).get("gen_ai.operation.name") == "invoke_agent"] - # Fullsend emits a root "run" span and a child "agent" span, both tagged invoke_agent. - # Only the innermost belongs to a generation; counting both also suppresses the metrics - # fallback below, costing cost precision (FRFLY-755). Keyed on (traceId, spanId) so a - # child in one trace cannot suppress an agent in another. - parents = {(span.get("traceId"), span.get("parentSpanId")) for span in agents if span.get("parentSpanId")} - model_bearing = [span for span in agents if attributes(span.get("attributes")).get("gen_ai.request.model")] - agents = [span for span in agents if (span.get("traceId"), span.get("spanId")) not in parents] - metrics = {} - metrics_path = path.with_name("metrics.json") - if metrics_path.is_file() and metrics_path.stat().st_size < 1024 * 1024: - metrics = json.loads(metrics_path.read_text(encoding="utf-8")) - if not isinstance(metrics, dict): - metrics = {} - # Use metrics only for a single agent; don't multiply whole-run totals across agents. - # A genuine multi-agent run can collapse to one nested target, so also refuse when more - # than one agent span carries its own model (FRFLY-755). - if len(agents) != 1 or len(model_bearing) > 1: - metrics = {} - output = [] - for agent in agents: - source = attributes(agent.get("attributes")) - if any(span.get("parentSpanId") == agent.get("spanId") and - attributes(span.get("attributes")).get("langfuse.observation.type") == "generation" for span in spans): - continue - model = source.get("gen_ai.request.model") or metrics.get("model") - if not model: - continue # Never invent a model (the GitLab reference has a Gemini fallback). - trace_id, parent_id = agent.get("traceId") or "", agent.get("spanId") or "" - if not re.fullmatch(r"[0-9a-fA-F]{32}", trace_id) or not re.fullmatch(r"[0-9a-fA-F]{16}", parent_id): - raise ValueError("Invalid trace identity") - start, end = int(agent["startTimeUnixNano"]), int(agent["endTimeUnixNano"]) - if start < 0 or end < start: - raise ValueError("Invalid span timestamps") - model = str(model).removeprefix("google-vertex/") - values = dict(context) - values.update({"langfuse.observation.type": "generation", "gen_ai.operation.name": "generate_content", - "gen_ai.request.model": model, "langfuse.observation.model.name": model, - "gen_ai.system": source.get("gen_ai.system")}) - usage = metrics.get("token_usage") or {} - for attr, fallback in (("gen_ai.usage.input_tokens", "input"), ("gen_ai.usage.output_tokens", "output"), - ("gen_ai.usage.cache_read.input_tokens", "cache_read"), - ("gen_ai.usage.reasoning.output_tokens", "reasoning")): - value = source.get(attr) - if value is None and attr.endswith("reasoning.output_tokens"): - value = source.get("gen_ai.usage.reasoning_tokens") - if value is None: - value = usage.get(fallback) - if value is not None: - values[attr] = number(value, integer=True) - # fullsend.cost_usd on the span is rounded to 2dp; metrics.json beside the telemetry - # carries full precision for the same run, so prefer it (FRFLY-755). - cost = metrics.get("total_cost_usd") - if cost is None: - cost = source.get("fullsend.cost_usd") - if cost is not None: - values["gen_ai.usage.cost"] = number(cost) - values["langfuse.observation.cost_details"] = json.dumps({"total": number(cost)}) - for attr, fallback in (("fullsend.num_turns", "iterations"), ("fullsend.tool_calls", None)): - value = source.get(attr) - if value is None and fallback is not None: - value = metrics.get(fallback) - if value is not None: - values[attr] = number(value, integer=True) - stage = source.get("gen_ai.agent.name") or next( - (parent.name.removeprefix("fullsend-") for parent in path.parents - if parent.name.startswith("fullsend-")), "run") - values["gen_ai.agent.name"] = stage - trace_name = f"{stage}: {context.get('github.repository', 'fullsend')}" - if context.get("github.run_id"): - trace_name += f"#{context['github.run_id']}" - values["langfuse.trace.name"] = trace_name - span_id = hashlib.sha256(f"fullsend-langfuse-generation-v1:{trace_id}:{parent_id}".encode()).hexdigest()[:16] - - # Resolve authoritative team attribute for the agent span - event = None - for candidate in ("event.json", "normalized-event.json", "input.json"): - ef = path.with_name(candidate) - if ef.is_file(): - try: - event = json.loads(ef.read_text(encoding="utf-8")) - break - except Exception: - pass - span_team = source.get("team") - issue_key = source.get("jira.issue_key") or source.get("jira.key") or source.get("work_item.key") or source.get("issue_key") - runtime_team = resolve_jira_runtime_team(event=event, env=os.environ, context=context, issue_key=issue_key, span_team=span_team) - if runtime_team is not None: - values["team"] = runtime_team - else: - values.pop("team", None) - - add_filterable_context(values) - output.append({"traceId": trace_id, "spanId": span_id, "parentSpanId": parent_id, - "name": f"{stage.capitalize()} Generation: {model}", "kind": 1, - "startTimeUnixNano": str(start), "endTimeUnixNano": str(end), - "attributes": otlp_attributes(values), "status": {"code": (agent.get("status") or {}).get("code", 1)}}) - return {"resourceSpans": [{"resource": {"attributes": otlp_attributes(context)}, - "scopeSpans": [{"scope": {"name": "fullsend-generation-bridge", "version": "1.0.0"}, "spans": output}]}]} - - -def verification_payload(trace_id, context): - if not re.fullmatch(r"[0-9a-fA-F]{32}", trace_id): - raise ValueError("Invalid verification trace ID") - if not context.get("cost_center") or context["cost_center"].lower() == "unassigned": - raise ValueError("Missing configured cost_center resource attribute") - now = time.time_ns() - values = dict(context) - values["langfuse.trace.name"] = "Fullsend Langfuse verification" - add_filterable_context(values) - span = {"traceId": trace_id.lower(), "spanId": secrets.token_hex(8), - "name": "Fullsend Langfuse verification", "kind": 1, - "startTimeUnixNano": str(now), "endTimeUnixNano": str(now + 1_000_000), - "attributes": otlp_attributes(values), "status": {"code": 1}} - return {"resourceSpans": [{"resource": {"attributes": otlp_attributes(context)}, - "scopeSpans": [{"scope": {"name": "fullsend-generation-bridge", "version": "1.0.0"}, - "spans": [span]}]}]} - - -def export(payload, env): - endpoint = env.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "") - url = urllib.parse.urlsplit(endpoint) - is_loopback_http = url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1", "::1") - if (url.scheme != "https" and not is_loopback_http) or not url.hostname or url.username or url.password or url.query or url.fragment: - raise ValueError("Invalid configured export endpoint") - headers = {"Content-Type": "application/json", "x-langfuse-ingestion-version": "4"} - for item in env.get("OTEL_EXPORTER_OTLP_TRACES_HEADERS", "").split(","): - if "=" in item: - key, value = item.split("=", 1) - headers[key.strip()] = urllib.parse.unquote(value.strip()) - if not any(key.lower() == "authorization" for key in headers): - raise ValueError("Missing configured export authorization") - request = urllib.request.Request(endpoint, data=json.dumps(payload).encode(), headers=headers, method="POST") - # Don't forward authentication to an unexpected redirect destination. - class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, *args, **kwargs): - return None - with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response: - result = json.loads(response.read() or b"{}") - if int((result.get("partialSuccess") or {}).get("rejectedSpans", 0)): - raise ValueError("Backend rejected generation spans") - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("artifacts", nargs="?", type=Path) - parser.add_argument("--dry-run", action="store_true", help="Build and count spans without contacting Langfuse") - parser.add_argument("--verify-trace-id", help="Export one diagnostic trace with this 32-character hex ID") - args = parser.parse_args(argv) - if args.artifacts is None and args.verify_trace_id is None: - parser.error("artifacts or --verify-trace-id is required") - if args.artifacts is not None and args.verify_trace_id is not None: - parser.error("artifacts and --verify-trace-id cannot be combined") - context = {} - for item in (os.environ.get("OTEL_RESOURCE_ATTRIBUTES") or "").split(","): - if "=" in item: - key, value = item.split("=", 1) - context[key.strip()] = urllib.parse.unquote(value.strip()) - context["github.repository"] = os.environ.get("GITHUB_REPOSITORY", context.get("github.repository", "fullsend")) - for env_key, attr in (("SOURCE_RUN_ID", "github.run_id"), ("SOURCE_RUN_ATTEMPT", "github.run_attempt"), - ("SOURCE_ACTOR", "user.id")): - if os.environ.get(env_key): - context[attr] = os.environ[env_key] - runtime_team = resolve_jira_runtime_team(env=os.environ, context=context) - if runtime_team is not None: - context["team"] = runtime_team - else: - context.pop("team", None) - if context.get("github.run_id"): - context["session.id"] = context["langfuse.session.id"] = context["github.run_id"] - if context.get("user.id"): - context["langfuse.user.id"] = context["user.id"] - if args.verify_trace_id is not None: - try: - payload = verification_payload(args.verify_trace_id, context) - if not args.dry_run: - export(payload, os.environ) - print(f"{'Prepared' if args.dry_run else 'Exported'} verification trace {args.verify_trace_id.lower()}.") - return 0 - except Exception as error: - status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" - print(f"Langfuse verification failed: {type(error).__name__}{status}", file=sys.stderr) - return 1 - files = sorted(args.artifacts.rglob("run-telemetry.jsonl")) - if not files: - print("No Fullsend telemetry artifacts found; nothing to export.") - failed = False - for path in files: - try: - payload = build_payload(path, context) - count = len(payload["resourceSpans"][0]["scopeSpans"][0]["spans"]) - if count and not args.dry_run: - export(payload, os.environ) - print(f"{'Prepared' if args.dry_run else 'Exported'} {count} generation spans.") - if not count: - print("No agent spans with known models need generation export.") - except Exception as error: - # Never print URLs, headers, artifact content, or upstream error bodies. - status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" - print(f"Langfuse generation export failed: {type(error).__name__}{status}", file=sys.stderr) - failed = True - return int(failed) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/.github/workflows/fullsend-langfuse.yaml b/.github/workflows/fullsend-langfuse.yaml deleted file mode 100644 index b632daa3aa..0000000000 --- a/.github/workflows/fullsend-langfuse.yaml +++ /dev/null @@ -1,36 +0,0 @@ -# Generated by uie-fullsend langfuse-setup. Uses trusted default-branch code. -name: Fullsend Langfuse -on: - workflow_dispatch: - inputs: - trace_id: - description: OTLP trace ID for verification (32 hexadecimal characters) - required: true - type: string -# Least privilege: checks out trusted default-branch Langfuse script without write credentials. -permissions: - contents: read -jobs: - generation: - runs-on: ubuntu-24.04 - timeout-minutes: 10 - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.repository.default_branch }} - persist-credentials: false - - name: Export Langfuse trace - env: - OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} - OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} - OTEL_RESOURCE_ATTRIBUTES: ${{ vars.OTEL_RESOURCE_ATTRIBUTES }} - JIRA_BASE_URL: ${{ vars.JIRA_BASE_URL }} - JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }} - JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} - FULLSEND_JIRA_TEAM_FIELD: ${{ vars.FULLSEND_JIRA_TEAM_FIELD }} - SOURCE_RUN_ID: ${{ github.run_id }} - SOURCE_RUN_ATTEMPT: ${{ github.run_attempt }} - SOURCE_ACTOR: ${{ github.actor }} - VERIFY_TRACE_ID: ${{ inputs.trace_id }} - run: | - python3 .fullsend/scripts/langfuse-post-run.py --verify-trace-id "$VERIFY_TRACE_ID" diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 9db522d445..5f35bd5e82 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -148,53 +148,3 @@ jobs: --add-label "fullsend-no-fix" gh pr comment "$PR_NUMBER" --repo "$REPO" \ --body "Fix agent disabled for this PR. Remove the \`fullsend-no-fix\` label or use \`/fs-fix\` to re-engage." - - # >>> uie-fullsend langfuse-export (managed block: re-run `uie-fullsend langfuse setup` to refresh) - # Exports Fullsend telemetry directly to Langfuse when this run has published - # fullsend-* telemetry artifacts. Runs after the upstream Fullsend dispatch job. - langfuse-export: - needs: dispatch - if: always() && !cancelled() - runs-on: ubuntu-24.04 - permissions: - actions: read # download artifacts from this run - contents: read # checkout trusted default-branch script - steps: - - name: Detect Fullsend telemetry artifacts - id: telemetry - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - RUN_ID: ${{ github.run_id }} - run: | - artifacts="$(gh api --paginate "repos/$GH_REPO/actions/runs/$RUN_ID/artifacts?per_page=100" --jq '.artifacts[].name | select(startswith("fullsend-"))')" - [ -n "$artifacts" ] && echo "found=true" >> "$GITHUB_OUTPUT" || exit 0 - - - name: Checkout Langfuse script - if: steps.telemetry.outputs.found == 'true' - uses: actions/checkout@v4 - with: - ref: ${{ github.event.repository.default_branch }} - persist-credentials: false - - - name: Download Fullsend artifacts - if: steps.telemetry.outputs.found == 'true' - env: - GH_TOKEN: ${{ github.token }} - run: gh run download "${{ github.run_id }}" --pattern 'fullsend-*' --dir "$RUNNER_TEMP/langfuse-artifacts" - - - name: Export Langfuse trace - if: steps.telemetry.outputs.found == 'true' - env: - OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} - OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} - OTEL_RESOURCE_ATTRIBUTES: ${{ vars.OTEL_RESOURCE_ATTRIBUTES }} - JIRA_BASE_URL: ${{ vars.JIRA_BASE_URL }} - JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }} - JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} - FULLSEND_JIRA_TEAM_FIELD: ${{ vars.FULLSEND_JIRA_TEAM_FIELD }} - SOURCE_RUN_ID: ${{ github.run_id }} - SOURCE_RUN_ATTEMPT: ${{ github.run_attempt }} - SOURCE_ACTOR: ${{ github.actor }} - run: python3 .fullsend/scripts/langfuse-post-run.py "$RUNNER_TEMP/langfuse-artifacts" - # <<< uie-fullsend langfuse-export From 310320292657b273beaa8a5dfd9ce07fa490a1a6 Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Tue, 1 Dec 2026 18:45:23 +0530 Subject: [PATCH 6/8] chore: export Fullsend run telemetry to Langfuse Co-authored-by: Cursor --- .fullsend/scripts/langfuse-post-run.py | 460 +++++++++++++++++++++++ .github/workflows/fullsend-langfuse.yaml | 36 ++ .github/workflows/fullsend.yaml | 50 +++ 3 files changed, 546 insertions(+) create mode 100644 .fullsend/scripts/langfuse-post-run.py create mode 100644 .github/workflows/fullsend-langfuse.yaml diff --git a/.fullsend/scripts/langfuse-post-run.py b/.fullsend/scripts/langfuse-post-run.py new file mode 100644 index 0000000000..3fb1baa4bd --- /dev/null +++ b/.fullsend/scripts/langfuse-post-run.py @@ -0,0 +1,460 @@ +# Generated by uie-fullsend langfuse-setup. Uses trusted default-branch code. +"""Add generation observations to native Fullsend traces; Python standard library. + +Derived from fullsend-component/scripts/lib/langfuse.sh's generation bridge. +Only model/usage and CI metadata are exported; artifacts never supply code, +credentials, an endpoint, or prompt/response content. +""" +import argparse +import base64 +import hashlib +import json +import math +import os +from pathlib import Path +import re +import secrets +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + + +def attributes(entries): + if isinstance(entries, dict): + return dict(entries) + result = {} + for entry in entries or []: + value = entry.get("value", {}) + for kind in ("stringValue", "intValue", "doubleValue", "boolValue"): + if kind in value: + result[entry["key"]] = value[kind] + break + return result + + +def otlp_attributes(values): + result = [] + for key, value in values.items(): + if value is None: + continue + if isinstance(value, bool): + encoded = {"boolValue": value} + elif isinstance(value, int): + encoded = {"intValue": str(value)} + elif isinstance(value, float): + encoded = {"doubleValue": value} + elif isinstance(value, list): + encoded = {"arrayValue": {"values": [{"stringValue": str(item)} for item in value]}} + else: + encoded = {"stringValue": str(value)} + result.append({"key": key, "value": encoded}) + return result + + +def extract_team_value(value): + if value is None: + return None + if isinstance(value, dict): + raw = value.get("title") or value.get("name") or value.get("team") + if raw is None: + return None + team = str(raw).strip() + else: + team = str(value).strip() + if not team or team.lower() in ("unassigned", "none", "null"): + return None + return team + + +def hydrate_jira_team_from_api(issue_key, env, team_field=None): + if not issue_key or not env: + return None + if not re.fullmatch(r"[A-Za-z0-9_]+-\d+", str(issue_key)): + return None + team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" + if not re.fullmatch(r"[\w.-]+", str(team_field)): + return None + base_url = env.get("JIRA_BASE_URL") or env.get("FULLSEND_JIRA_URL") or "https://redhat.atlassian.net" + user_email = env.get("JIRA_USER_EMAIL") or env.get("FULLSEND_JIRA_EMAIL") + token = env.get("JIRA_TOKEN") or env.get("FULLSEND_JIRA_API_TOKEN") + if not (base_url and user_email and token): + return None + endpoint = f"{base_url.rstrip('/')}/rest/api/3/issue/{issue_key}?fields={urllib.parse.quote(str(team_field))}" + auth = base64.b64encode(f"{user_email}:{token}".encode("utf-8")).decode("ascii") + headers = {"Authorization": f"Basic {auth}", "Accept": "application/json"} + req = urllib.request.Request(endpoint, headers=headers, method="GET") + + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + try: + with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as resp: + data = json.loads(resp.read() or b"{}") + fields = data.get("fields", {}) if isinstance(data, dict) else {} + return extract_team_value(fields.get(team_field)) + except urllib.error.HTTPError as error: + print( + f"Jira Team hydration failed for {issue_key} (HTTP {error.code}); " + "using repository team fallback.", + file=sys.stderr, + ) + return None + except Exception as error: + # Do not expose URLs, credentials, or upstream error bodies in workflow logs. + print( + f"Jira Team hydration failed for {issue_key} ({type(error).__name__}); " + "using repository team fallback.", + file=sys.stderr, + ) + return None + + +def resolve_jira_runtime_team(event=None, env=None, context=None, team_field=None, issue_key=None, span_team=None): + if env is None: + env = os.environ + team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" + + # Precedence: native Jira ticket Team > normalized event payload team > JIRA_ISSUE_TEAM > JIRA_TEAM > FULLSEND_TEAM / repo fallback > omitted. + + # 1. Native Jira ticket Team + if span_team is not None: + team = extract_team_value(span_team) + if team is not None: + return team + + if isinstance(event, dict): + issue = ( + event.get("issue") + or (event.get("data", {}).get("issue") if isinstance(event.get("data"), dict) else None) + or (event.get("entity") if isinstance(event.get("entity"), dict) and ("fields" in event["entity"] or team_field in event["entity"]) else None) + or (event.get("raw") if isinstance(event.get("raw"), dict) and ("fields" in event["raw"] or team_field in event["raw"]) else None) + or (event if "fields" in event or team_field in event else None) + ) + if isinstance(issue, dict): + fields = issue.get("fields") if isinstance(issue.get("fields"), dict) else issue + team = extract_team_value(fields.get(team_field)) + if team is not None: + return team + + eff_issue_key = ( + issue_key + or event.get("issue_key") + or (event.get("entity", {}).get("key") if isinstance(event.get("entity"), dict) else None) + or (event.get("issue", {}).get("key") if isinstance(event.get("issue"), dict) else None) + or env.get("JIRA_ISSUE_KEY") + or env.get("ISSUE_KEY") + or env.get("FULLSEND_TICKET") + ) + if eff_issue_key: + hydrated = hydrate_jira_team_from_api(eff_issue_key, env, team_field=team_field) + if hydrated is not None: + return hydrated + else: + eff_issue_key = ( + issue_key + or env.get("JIRA_ISSUE_KEY") + or env.get("ISSUE_KEY") + or env.get("FULLSEND_TICKET") + ) + if eff_issue_key: + hydrated = hydrate_jira_team_from_api(eff_issue_key, env, team_field=team_field) + if hydrated is not None: + return hydrated + + # 2. Normalized event payload team + if isinstance(event, dict): + event_team = ( + event.get("team") + or (event.get("entity", {}).get("team") if isinstance(event.get("entity"), dict) else None) + or (event.get("state", {}).get("team") if isinstance(event.get("state"), dict) else None) + or (event.get("data", {}).get("team") if isinstance(event.get("data"), dict) else None) + ) + team = extract_team_value(event_team) + if team is not None: + return team + + # 3. JIRA_ISSUE_TEAM + team = extract_team_value(env.get("JIRA_ISSUE_TEAM")) + if team is not None: + return team + + # 4. JIRA_TEAM + team = extract_team_value(env.get("JIRA_TEAM")) + if team is not None: + return team + + # 5. FULLSEND_TEAM / the FRFLY-864 setup fallback + team = extract_team_value(env.get("FULLSEND_TEAM")) + if team is not None: + return team + + if context and context.get("team"): + team = extract_team_value(context["team"]) + if team is not None: + return team + + otel_attrs = env.get("OTEL_RESOURCE_ATTRIBUTES") or "" + for item in otel_attrs.split(","): + if "=" in item: + k, v = item.split("=", 1) + if k.strip() == "team": + team = extract_team_value(urllib.parse.unquote(v.strip())) + if team is not None: + return team + + return None + + +def add_filterable_context(values): + for key in ("project_key", "cost_center", "team", "github.repository", "github.run_id"): + if values.get(key): + name = key.replace(".", "_") + for level in ("trace", "observation"): + values[f"langfuse.{level}.metadata.{name}"] = values[key] + tags = [f"{label}:{values[key]}" for key, label in ( + ("gen_ai.agent.name", "stage"), + ("project_key", "project_key"), ("cost_center", "cost_center"), + ("team", "team"), + ("github.repository", "repo"), + ) if values.get(key)] + if tags: + values["langfuse.trace.tags"] = tags + + +def number(value, integer=False): + if value is None: + return None + parsed = float(value) + if not math.isfinite(parsed) or parsed < 0: + raise ValueError("Invalid usage value") + return int(parsed) if integer else parsed + + +def read_spans(path): + # The exporter writes one OTLP resourceSpans envelope per JSONL line. + if path.stat().st_size > 32 * 1024 * 1024: + raise ValueError("Telemetry exceeds size limit") + spans = {} + with path.open(encoding="utf-8") as stream: + for line in stream: + if not line.strip(): + continue + record = json.loads(line) + for resource in record.get("resourceSpans", []): + for scope in resource.get("scopeSpans", []): + for span in scope.get("spans", []): + spans[(span.get("traceId"), span.get("spanId"))] = span + return list(spans.values()) + + +def build_payload(path, context): + spans = read_spans(path) + agents = [span for span in spans if attributes(span.get("attributes")).get("gen_ai.operation.name") == "invoke_agent"] + # Fullsend emits a root "run" span and a child "agent" span, both tagged invoke_agent. + # Only the innermost belongs to a generation; counting both also suppresses the metrics + # fallback below, costing cost precision (FRFLY-755). Keyed on (traceId, spanId) so a + # child in one trace cannot suppress an agent in another. + parents = {(span.get("traceId"), span.get("parentSpanId")) for span in agents if span.get("parentSpanId")} + model_bearing = [span for span in agents if attributes(span.get("attributes")).get("gen_ai.request.model")] + agents = [span for span in agents if (span.get("traceId"), span.get("spanId")) not in parents] + metrics = {} + metrics_path = path.with_name("metrics.json") + if metrics_path.is_file() and metrics_path.stat().st_size < 1024 * 1024: + metrics = json.loads(metrics_path.read_text(encoding="utf-8")) + if not isinstance(metrics, dict): + metrics = {} + # Use metrics only for a single agent; don't multiply whole-run totals across agents. + # A genuine multi-agent run can collapse to one nested target, so also refuse when more + # than one agent span carries its own model (FRFLY-755). + if len(agents) != 1 or len(model_bearing) > 1: + metrics = {} + output = [] + for agent in agents: + source = attributes(agent.get("attributes")) + if any(span.get("parentSpanId") == agent.get("spanId") and + attributes(span.get("attributes")).get("langfuse.observation.type") == "generation" for span in spans): + continue + model = source.get("gen_ai.request.model") or metrics.get("model") + if not model: + continue # Never invent a model (the GitLab reference has a Gemini fallback). + trace_id, parent_id = agent.get("traceId") or "", agent.get("spanId") or "" + if not re.fullmatch(r"[0-9a-fA-F]{32}", trace_id) or not re.fullmatch(r"[0-9a-fA-F]{16}", parent_id): + raise ValueError("Invalid trace identity") + start, end = int(agent["startTimeUnixNano"]), int(agent["endTimeUnixNano"]) + if start < 0 or end < start: + raise ValueError("Invalid span timestamps") + model = str(model).removeprefix("google-vertex/") + values = dict(context) + values.update({"langfuse.observation.type": "generation", "gen_ai.operation.name": "generate_content", + "gen_ai.request.model": model, "langfuse.observation.model.name": model, + "gen_ai.system": source.get("gen_ai.system")}) + usage = metrics.get("token_usage") or {} + for attr, fallback in (("gen_ai.usage.input_tokens", "input"), ("gen_ai.usage.output_tokens", "output"), + ("gen_ai.usage.cache_read.input_tokens", "cache_read"), + ("gen_ai.usage.reasoning.output_tokens", "reasoning")): + value = source.get(attr) + if value is None and attr.endswith("reasoning.output_tokens"): + value = source.get("gen_ai.usage.reasoning_tokens") + if value is None: + value = usage.get(fallback) + if value is not None: + values[attr] = number(value, integer=True) + # fullsend.cost_usd on the span is rounded to 2dp; metrics.json beside the telemetry + # carries full precision for the same run, so prefer it (FRFLY-755). + cost = metrics.get("total_cost_usd") + if cost is None: + cost = source.get("fullsend.cost_usd") + if cost is not None: + values["gen_ai.usage.cost"] = number(cost) + values["langfuse.observation.cost_details"] = json.dumps({"total": number(cost)}) + for attr, fallback in (("fullsend.num_turns", "iterations"), ("fullsend.tool_calls", None)): + value = source.get(attr) + if value is None and fallback is not None: + value = metrics.get(fallback) + if value is not None: + values[attr] = number(value, integer=True) + stage = source.get("gen_ai.agent.name") or next( + (parent.name.removeprefix("fullsend-") for parent in path.parents + if parent.name.startswith("fullsend-")), "run") + values["gen_ai.agent.name"] = stage + trace_name = f"{stage}: {context.get('github.repository', 'fullsend')}" + if context.get("github.run_id"): + trace_name += f"#{context['github.run_id']}" + values["langfuse.trace.name"] = trace_name + span_id = hashlib.sha256(f"fullsend-langfuse-generation-v1:{trace_id}:{parent_id}".encode()).hexdigest()[:16] + + # Resolve authoritative team attribute for the agent span + event = None + for candidate in ("event.json", "normalized-event.json", "input.json"): + ef = path.with_name(candidate) + if ef.is_file(): + try: + event = json.loads(ef.read_text(encoding="utf-8")) + break + except Exception: + pass + span_team = source.get("team") + issue_key = source.get("jira.issue_key") or source.get("jira.key") or source.get("work_item.key") or source.get("issue_key") + runtime_team = resolve_jira_runtime_team(event=event, env=os.environ, context=context, issue_key=issue_key, span_team=span_team) + if runtime_team is not None: + values["team"] = runtime_team + else: + values.pop("team", None) + + add_filterable_context(values) + output.append({"traceId": trace_id, "spanId": span_id, "parentSpanId": parent_id, + "name": f"{stage.capitalize()} Generation: {model}", "kind": 1, + "startTimeUnixNano": str(start), "endTimeUnixNano": str(end), + "attributes": otlp_attributes(values), "status": {"code": (agent.get("status") or {}).get("code", 1)}}) + return {"resourceSpans": [{"resource": {"attributes": otlp_attributes(context)}, + "scopeSpans": [{"scope": {"name": "fullsend-generation-bridge", "version": "1.0.0"}, "spans": output}]}]} + + +def verification_payload(trace_id, context): + if not re.fullmatch(r"[0-9a-fA-F]{32}", trace_id): + raise ValueError("Invalid verification trace ID") + if not context.get("cost_center") or context["cost_center"].lower() == "unassigned": + raise ValueError("Missing configured cost_center resource attribute") + now = time.time_ns() + values = dict(context) + values["langfuse.trace.name"] = "Fullsend Langfuse verification" + add_filterable_context(values) + span = {"traceId": trace_id.lower(), "spanId": secrets.token_hex(8), + "name": "Fullsend Langfuse verification", "kind": 1, + "startTimeUnixNano": str(now), "endTimeUnixNano": str(now + 1_000_000), + "attributes": otlp_attributes(values), "status": {"code": 1}} + return {"resourceSpans": [{"resource": {"attributes": otlp_attributes(context)}, + "scopeSpans": [{"scope": {"name": "fullsend-generation-bridge", "version": "1.0.0"}, + "spans": [span]}]}]} + + +def export(payload, env): + endpoint = env.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "") + url = urllib.parse.urlsplit(endpoint) + is_loopback_http = url.scheme == "http" and url.hostname in ("localhost", "127.0.0.1", "::1") + if (url.scheme != "https" and not is_loopback_http) or not url.hostname or url.username or url.password or url.query or url.fragment: + raise ValueError("Invalid configured export endpoint") + headers = {"Content-Type": "application/json", "x-langfuse-ingestion-version": "4"} + for item in env.get("OTEL_EXPORTER_OTLP_TRACES_HEADERS", "").split(","): + if "=" in item: + key, value = item.split("=", 1) + headers[key.strip()] = urllib.parse.unquote(value.strip()) + if not any(key.lower() == "authorization" for key in headers): + raise ValueError("Missing configured export authorization") + request = urllib.request.Request(endpoint, data=json.dumps(payload).encode(), headers=headers, method="POST") + # Don't forward authentication to an unexpected redirect destination. + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response: + result = json.loads(response.read() or b"{}") + if int((result.get("partialSuccess") or {}).get("rejectedSpans", 0)): + raise ValueError("Backend rejected generation spans") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("artifacts", nargs="?", type=Path) + parser.add_argument("--dry-run", action="store_true", help="Build and count spans without contacting Langfuse") + parser.add_argument("--verify-trace-id", help="Export one diagnostic trace with this 32-character hex ID") + args = parser.parse_args(argv) + if args.artifacts is None and args.verify_trace_id is None: + parser.error("artifacts or --verify-trace-id is required") + if args.artifacts is not None and args.verify_trace_id is not None: + parser.error("artifacts and --verify-trace-id cannot be combined") + context = {} + for item in (os.environ.get("OTEL_RESOURCE_ATTRIBUTES") or "").split(","): + if "=" in item: + key, value = item.split("=", 1) + context[key.strip()] = urllib.parse.unquote(value.strip()) + context["github.repository"] = os.environ.get("GITHUB_REPOSITORY", context.get("github.repository", "fullsend")) + for env_key, attr in (("SOURCE_RUN_ID", "github.run_id"), ("SOURCE_RUN_ATTEMPT", "github.run_attempt"), + ("SOURCE_ACTOR", "user.id")): + if os.environ.get(env_key): + context[attr] = os.environ[env_key] + runtime_team = resolve_jira_runtime_team(env=os.environ, context=context) + if runtime_team is not None: + context["team"] = runtime_team + else: + context.pop("team", None) + if context.get("github.run_id"): + context["session.id"] = context["langfuse.session.id"] = context["github.run_id"] + if context.get("user.id"): + context["langfuse.user.id"] = context["user.id"] + if args.verify_trace_id is not None: + try: + payload = verification_payload(args.verify_trace_id, context) + if not args.dry_run: + export(payload, os.environ) + print(f"{'Prepared' if args.dry_run else 'Exported'} verification trace {args.verify_trace_id.lower()}.") + return 0 + except Exception as error: + status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" + print(f"Langfuse verification failed: {type(error).__name__}{status}", file=sys.stderr) + return 1 + files = sorted(args.artifacts.rglob("run-telemetry.jsonl")) + if not files: + print("No Fullsend telemetry artifacts found; nothing to export.") + failed = False + for path in files: + try: + payload = build_payload(path, context) + count = len(payload["resourceSpans"][0]["scopeSpans"][0]["spans"]) + if count and not args.dry_run: + export(payload, os.environ) + print(f"{'Prepared' if args.dry_run else 'Exported'} {count} generation spans.") + if not count: + print("No agent spans with known models need generation export.") + except Exception as error: + # Never print URLs, headers, artifact content, or upstream error bodies. + status = f" (HTTP {error.code})" if isinstance(error, urllib.error.HTTPError) else "" + print(f"Langfuse generation export failed: {type(error).__name__}{status}", file=sys.stderr) + failed = True + return int(failed) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/fullsend-langfuse.yaml b/.github/workflows/fullsend-langfuse.yaml new file mode 100644 index 0000000000..b632daa3aa --- /dev/null +++ b/.github/workflows/fullsend-langfuse.yaml @@ -0,0 +1,36 @@ +# Generated by uie-fullsend langfuse-setup. Uses trusted default-branch code. +name: Fullsend Langfuse +on: + workflow_dispatch: + inputs: + trace_id: + description: OTLP trace ID for verification (32 hexadecimal characters) + required: true + type: string +# Least privilege: checks out trusted default-branch Langfuse script without write credentials. +permissions: + contents: read +jobs: + generation: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Export Langfuse trace + env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_RESOURCE_ATTRIBUTES: ${{ vars.OTEL_RESOURCE_ATTRIBUTES }} + JIRA_BASE_URL: ${{ vars.JIRA_BASE_URL }} + JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }} + JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} + FULLSEND_JIRA_TEAM_FIELD: ${{ vars.FULLSEND_JIRA_TEAM_FIELD }} + SOURCE_RUN_ID: ${{ github.run_id }} + SOURCE_RUN_ATTEMPT: ${{ github.run_attempt }} + SOURCE_ACTOR: ${{ github.actor }} + VERIFY_TRACE_ID: ${{ inputs.trace_id }} + run: | + python3 .fullsend/scripts/langfuse-post-run.py --verify-trace-id "$VERIFY_TRACE_ID" diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 5f35bd5e82..9db522d445 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -148,3 +148,53 @@ jobs: --add-label "fullsend-no-fix" gh pr comment "$PR_NUMBER" --repo "$REPO" \ --body "Fix agent disabled for this PR. Remove the \`fullsend-no-fix\` label or use \`/fs-fix\` to re-engage." + + # >>> uie-fullsend langfuse-export (managed block: re-run `uie-fullsend langfuse setup` to refresh) + # Exports Fullsend telemetry directly to Langfuse when this run has published + # fullsend-* telemetry artifacts. Runs after the upstream Fullsend dispatch job. + langfuse-export: + needs: dispatch + if: always() && !cancelled() + runs-on: ubuntu-24.04 + permissions: + actions: read # download artifacts from this run + contents: read # checkout trusted default-branch script + steps: + - name: Detect Fullsend telemetry artifacts + id: telemetry + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_ID: ${{ github.run_id }} + run: | + artifacts="$(gh api --paginate "repos/$GH_REPO/actions/runs/$RUN_ID/artifacts?per_page=100" --jq '.artifacts[].name | select(startswith("fullsend-"))')" + [ -n "$artifacts" ] && echo "found=true" >> "$GITHUB_OUTPUT" || exit 0 + + - name: Checkout Langfuse script + if: steps.telemetry.outputs.found == 'true' + uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Download Fullsend artifacts + if: steps.telemetry.outputs.found == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: gh run download "${{ github.run_id }}" --pattern 'fullsend-*' --dir "$RUNNER_TEMP/langfuse-artifacts" + + - name: Export Langfuse trace + if: steps.telemetry.outputs.found == 'true' + env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: ${{ vars.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT }} + OTEL_EXPORTER_OTLP_TRACES_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_TRACES_HEADERS }} + OTEL_RESOURCE_ATTRIBUTES: ${{ vars.OTEL_RESOURCE_ATTRIBUTES }} + JIRA_BASE_URL: ${{ vars.JIRA_BASE_URL }} + JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }} + JIRA_USER_EMAIL: ${{ secrets.JIRA_USER_EMAIL }} + FULLSEND_JIRA_TEAM_FIELD: ${{ vars.FULLSEND_JIRA_TEAM_FIELD }} + SOURCE_RUN_ID: ${{ github.run_id }} + SOURCE_RUN_ATTEMPT: ${{ github.run_attempt }} + SOURCE_ACTOR: ${{ github.actor }} + run: python3 .fullsend/scripts/langfuse-post-run.py "$RUNNER_TEMP/langfuse-artifacts" + # <<< uie-fullsend langfuse-export From f9655a9005a9d8fded502ba0f25edf9f63107716 Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Tue, 1 Dec 2026 19:23:35 +0530 Subject: [PATCH 7/8] fix(ci): pin Playwright jobs to Ubuntu 24.04 Co-authored-by: Cursor --- .github/workflows/tests.yml | 3 ++- .github/workflows/visual-regression.yml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 76ae344537..82e40bb7cf 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -67,7 +67,8 @@ jobs: test: name: Unit Tests (Web Test Runner) - runs-on: ubuntu-latest + # Playwright 1.57 cannot install Chromium on ubuntu-latest (Ubuntu 26.04). + runs-on: ubuntu-24.04 steps: - name: Checkout repository uses: actions/checkout@v4 diff --git a/.github/workflows/visual-regression.yml b/.github/workflows/visual-regression.yml index 54cd070c2b..e73e5118f0 100644 --- a/.github/workflows/visual-regression.yml +++ b/.github/workflows/visual-regression.yml @@ -24,7 +24,8 @@ on: jobs: e2e: - runs-on: ubuntu-latest + # Playwright 1.57 cannot install Chromium on ubuntu-latest (Ubuntu 26.04). + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 From 2c4b557fed353fabaf2fca49b7c67fd28f0b931f Mon Sep 17 00:00:00 2001 From: ArathyKumar Date: Wed, 2 Dec 2026 18:05:45 +0530 Subject: [PATCH 8/8] fix: require HTTPS before sending Jira credentials Co-authored-by: Cursor --- .fullsend/scripts/langfuse-post-run.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.fullsend/scripts/langfuse-post-run.py b/.fullsend/scripts/langfuse-post-run.py index 3fb1baa4bd..eb17f150c4 100644 --- a/.fullsend/scripts/langfuse-post-run.py +++ b/.fullsend/scripts/langfuse-post-run.py @@ -76,10 +76,18 @@ def hydrate_jira_team_from_api(issue_key, env, team_field=None): team_field = team_field or env.get("FULLSEND_JIRA_TEAM_FIELD") or "customfield_10001" if not re.fullmatch(r"[\w.-]+", str(team_field)): return None - base_url = env.get("JIRA_BASE_URL") or env.get("FULLSEND_JIRA_URL") or "https://redhat.atlassian.net" + base_url = (env.get("JIRA_BASE_URL") or env.get("FULLSEND_JIRA_URL") or "https://redhat.atlassian.net").strip() + parsed = urllib.parse.urlsplit(base_url) + # Never send Jira credentials to a non-HTTPS URL. Callers fall back to the repository team. + if parsed.scheme.lower() != "https" or not parsed.hostname: + print( + f"Jira Team hydration skipped for {issue_key}; using repository team fallback.", + file=sys.stderr, + ) + return None user_email = env.get("JIRA_USER_EMAIL") or env.get("FULLSEND_JIRA_EMAIL") token = env.get("JIRA_TOKEN") or env.get("FULLSEND_JIRA_API_TOKEN") - if not (base_url and user_email and token): + if not (user_email and token): return None endpoint = f"{base_url.rstrip('/')}/rest/api/3/issue/{issue_key}?fields={urllib.parse.quote(str(team_field))}" auth = base64.b64encode(f"{user_email}:{token}".encode("utf-8")).decode("ascii")