Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
feat: add generation-issue chips on traces for every data source (#1491)
Aman Agarwal26251ba2619b
diff --git a/docs/docs.json b/docs/docs.jsonindex 6a64101a..041da143 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -80,6 +80,17 @@{"group": "Observability","pages": [+ {+ "group": "Telemetry",+ "icon": "wave-pulse",+ "pages": [+ "latest/openlit/observability/telemetry/overview",+ "latest/openlit/observability/telemetry/traces",+ "latest/openlit/observability/telemetry/ai-analysis",+ "latest/openlit/observability/telemetry/metrics",+ "latest/openlit/observability/telemetry/logs"+ ]+ },"latest/openlit/observability/tracing","latest/openlit/observability/metrics","latest/openlit/observability/error",diff --git a/docs/images/traces-generation-issue-detail.png b/docs/images/traces-generation-issue-detail.pngnew file mode 100644index 00000000..03503c10Binary files /dev/null and b/docs/images/traces-generation-issue-detail.png differdiff --git a/docs/images/traces-generation-issues-filtered.png b/docs/images/traces-generation-issues-filtered.pngnew file mode 100644index 00000000..f69bbfe0Binary files /dev/null and b/docs/images/traces-generation-issues-filtered.png differdiff --git a/docs/images/traces-generation-issues-tooltip.png b/docs/images/traces-generation-issues-tooltip.pngnew file mode 100644index 00000000..f4224833Binary files /dev/null and b/docs/images/traces-generation-issues-tooltip.png differdiff --git a/docs/images/traces-generation-issues.png b/docs/images/traces-generation-issues.pngnew file mode 100644index 00000000..ad43f56eBinary files /dev/null and b/docs/images/traces-generation-issues.png differdiff --git a/docs/latest/openlit/observability/telemetry/overview.mdx b/docs/latest/openlit/observability/telemetry/overview.mdxindex b5ca8cc2..2c481e05 100644--- a/docs/latest/openlit/observability/telemetry/overview.mdx+++ b/docs/latest/openlit/observability/telemetry/overview.mdx@@ -18,7 +18,7 @@ The **Telemetry** page is the single home for every OpenTelemetry signal OpenLIT<CardGroup cols={2}><Card title="Traces" href="/latest/openlit/observability/telemetry/traces" icon="diagram-project">- Distributed traces with grouping, a five-view trace detail explorer, and span/resource attributes+ Distributed traces with generation-issue chips, grouping, a five-view detail explorer, and span/resource attributes</Card><Card title="AI Analysis" href="/latest/openlit/observability/telemetry/ai-analysis" icon="sparkles">AI-generated review of a trace or span across strengths, improvements, cost, and token efficiencydiff --git a/docs/latest/openlit/observability/telemetry/traces.mdx b/docs/latest/openlit/observability/telemetry/traces.mdxindex 06ebb0db..a0f03d59 100644--- a/docs/latest/openlit/observability/telemetry/traces.mdx+++ b/docs/latest/openlit/observability/telemetry/traces.mdx@@ -1,15 +1,52 @@---title: "Traces & Exceptions"-description: "Filter and group traces, then drill into a five-view trace detail explorer with span attributes, chat view, timeline, and DAG"+description: "Filter and group traces, spot generation issues, then drill into a five-view trace detail explorer with span attributes, chat view, timeline, and DAG"---Navigate to **Telemetry > Traces** (`/telemetry`) to view all distributed traces from your AI applications with detailed span analysis and execution flow. You can also create custom trace widgets in your dashboards to monitor specific trace metrics, latency trends, and performance insights alongside other observability data.## Filtering-The Traces list supports filtering by Models, Providers, Max Cost, Span Names, Environments, and Services, plus a time range and result limit. You can also filter on custom attributes - Span Attributes, Resource Attributes, or any top-level trace Field.+The Traces list supports filtering by Models, Providers, Max Cost, Span Names, Environments, Services, and **Generation issues**, plus a time range and result limit. You can also filter on custom attributes - Span Attributes, Resource Attributes, or any top-level trace Field.-The trace table shows, per row: Span/Trace ID, Time, Span Name, Duration, Service Name, Application Name, Cost, Total Tokens, Model, Provider, and Vector Count. Clicking a row opens the trace detail view in a resizable side sheet, with a **Full Screen** button that opens the same view at `/telemetry/traces/<id>`.+The trace table shows, per row: Span/Trace ID, Time, Span Name, Duration, Service Name, Application Name, Cost, Total Tokens, Model, Provider, and Vector Count. Rows with a generation issue also show a **Truncated**, **Filtered**, **Empty**, or **Model swapped** badge. Clicking a row opens the trace detail view in a resizable side sheet, with a **Full Screen** button that opens the same view at `/telemetry/traces/<id>`.++## Generation issues++The **Generation issues** bar sits under the traces volume chart. Each chip is `{count}/{eligible}` for the current time window — unique traces, not individual spans — so retries and nested generations do not inflate the totals.++<Frame>+ <img src="/images/traces-generation-issues.png" alt="Generation issues chips on the Traces page: Truncated, Filtered, Empty, and Model swapped" />+</Frame>++| Chip | Meaning |+| --- | --- |+| **Truncated** | The reply stopped because the model hit its token limit (`length`, `max_tokens`, or `max_length`). |+| **Filtered** | A content or safety filter blocked the reply (`content_filter`, `content_filtered`, or `safety`). |+| **Empty** | The model returned no completion tokens. Tool-call finishes are not counted as empty. |+| **Model swapped** | The provider served a different model than the one requested (`gen_ai.request.model` vs `gen_ai.response.model`). Provider prefixes such as `openai/` are ignored. |++Percentages use the **eligible** set: traces that recorded the attributes needed for that check (finish reason, output tokens, or both model names). Hover a chip for the meaning, the count in this window, and whether clicking will filter or clear.++<Frame>+ <img src="/images/traces-generation-issues-tooltip.png" alt="Tooltip on the Truncated chip explaining token-limit stops and that clicking filters the list" />+</Frame>++Click a chip to show only matching traces. The chip turns amber, the list updates, and matching rows keep the issue badge. Click the same chip again to show all traces.++<Frame>+ <img src="/images/traces-generation-issues-filtered.png" alt="Traces list filtered to Truncated generations, with Truncated badges on openai.chat.completions rows" />+</Frame>++Open a matching trace to see a warning on the detail header — for example, truncated generations suggest raising `max_tokens` or shortening the prompt.++<Frame>+ <img src="/images/traces-generation-issue-detail.png" alt="Trace detail warning that generation stopped because the model hit max tokens" />+</Frame>++<Info>+Generation issues work on every traces connector OpenLIT can list — built-in ClickHouse plus Tempo, Jaeger, and other OpenPlait adapters. ClickHouse counts the full window. External backends sample traces in the window, so chip totals there describe the sample rather than every trace in storage.+</Info>## Group tracesdiff --git a/src/client/src/__tests__/app/api/metrics/llm/generation-health/route.test.ts b/src/client/src/__tests__/app/api/metrics/llm/generation-health/route.test.tsnew file mode 100644index 00000000..19fad673--- /dev/null+++ b/src/client/src/__tests__/app/api/metrics/llm/generation-health/route.test.ts@@ -0,0 +1,104 @@+jest.mock("@/lib/platform/llm/generation-health", () => ({+ getGenerationHealth: jest.fn(),+}));++jest.mock("@/helpers/server/platform", () => ({+ validateMetricsRequest: jest.fn(),+ validateMetricsRequestType: {+ GENERATION_HEALTH: "GENERATION_HEALTH",+ },+}));++jest.mock("@/lib/session", () => ({+ getCurrentUser: jest.fn(async () => ({ id: "user-1" })),+}));++jest.mock("@/lib/organisation", () => ({+ getCurrentOrganisation: jest.fn(async () => null),+ getCurrentProjectForOrganisation: jest.fn(async () => null),+}));++class TestResponse {+ status: number;+ private body: unknown;++ constructor(body?: unknown, init?: { status?: number }) {+ this.body = body;+ this.status = init?.status ?? 200;+ }++ static json(body: unknown, init?: { status?: number }) {+ return new TestResponse(body, init);+ }++ async json() {+ return this.body;+ }+}++(global as any).Response = TestResponse;++import { POST } from "@/app/api/metrics/llm/generation-health/route";+import { getGenerationHealth } from "@/lib/platform/llm/generation-health";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";+import getMessage from "@/constants/messages";++function makeRequest(body: unknown) {+ return {+ json: async () => body,+ headers: { get: () => null },+ } as any;+}++describe("POST /api/metrics/llm/generation-health", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("returns 400 for invalid JSON", async () => {+ const request = {+ json: async () => {+ throw new Error("bad json");+ },+ headers: { get: () => null },+ } as any;++ const res = await POST(request);+ expect(res.status).toBe(400);+ expect(await res.json()).toBe(getMessage().TELEMETRY_SOURCE_INVALID_JSON);+ });++ it("returns 400 when timeLimit is missing", async () => {+ (validateMetricsRequest as jest.Mock).mockReturnValue({+ success: false,+ err: "Start date or End date missing!",+ });++ const res = await POST(makeRequest({}));+ expect(res.status).toBe(400);+ expect(validateMetricsRequest).toHaveBeenCalledWith(+ expect.objectContaining({ timeLimit: undefined }),+ validateMetricsRequestType.GENERATION_HEALTH+ );+ });++ it("returns generation health on success", async () => {+ (validateMetricsRequest as jest.Mock).mockReturnValue({ success: true });+ (getGenerationHealth as jest.Mock).mockResolvedValue({+ data: [{ truncated_pct: 12, truncated: 3, truncated_eligible: 25 }],+ });++ const res = await POST(+ makeRequest({+ timeLimit: { start: "2024-01-01", end: "2024-01-02" },+ })+ );+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({+ data: [{ truncated_pct: 12, truncated: 3, truncated_eligible: 25 }],+ });+ });+});diff --git a/src/client/src/__tests__/constants/messages.test.ts b/src/client/src/__tests__/constants/messages.test.tsindex 20e6ccc6..9cc5db91 100644--- a/src/client/src/__tests__/constants/messages.test.ts+++ b/src/client/src/__tests__/constants/messages.test.ts@@ -43,6 +43,17 @@ describe("getMessage()", () => {expect(msgs.SECRET_DELETED).toBe("Secret deleted successfully!");});+ it("has generation-health messages with count/eligible placeholders", () => {+ const msgs = getMessage();+ expect(msgs.GENERATION_HEALTH_STAT_OF_ELIGIBLE).toContain("{count}");+ expect(msgs.GENERATION_HEALTH_STAT_OF_ELIGIBLE).toContain("{eligible}");+ expect(msgs.GENERATION_HEALTH_STAT_SKIPPED).toContain("{skipped}");+ expect(msgs.GENERATION_HEALTH_STAT_SKIPPED).toContain("{total}");+ expect(msgs.GENERATION_HEALTH_TIP_TRUNCATED).toBeTruthy();+ expect(msgs.GENERATION_HEALTH_TIP_SWAPPED).toBeTruthy();+ expect(msgs.GENERATION_HEALTH_CLICK_TO_FILTER).toBeTruthy();+ });+it("has evaluation-related messages", () => {const msgs = getMessage();expect(msgs.EVALUATION_CONFIG_NOT_FOUND).toBeDefined();diff --git a/src/client/src/__tests__/helpers/client/filter-persistence.test.ts b/src/client/src/__tests__/helpers/client/filter-persistence.test.tsindex d82f7a60..ac11dce6 100644--- a/src/client/src/__tests__/helpers/client/filter-persistence.test.ts+++ b/src/client/src/__tests__/helpers/client/filter-persistence.test.ts@@ -25,6 +25,7 @@ describe("filter persistence helpers", () => {services: "api",tr: "7D",gb: "serviceName",+ gh: "truncated",limit: "50",});@@ -36,6 +37,7 @@ describe("filter persistence helpers", () => {expect(params.has("services")).toBe(false);expect(params.has("tr")).toBe(false);expect(params.has("gb")).toBe(false);+ expect(params.has("gh")).toBe(false);expect(params.has("limit")).toBe(false);});});diff --git a/src/client/src/__tests__/helpers/client/trace.test.ts b/src/client/src/__tests__/helpers/client/trace.test.tsindex a145b055..3859bf07 100644--- a/src/client/src/__tests__/helpers/client/trace.test.ts+++ b/src/client/src/__tests__/helpers/client/trace.test.ts@@ -264,6 +264,7 @@ describe('normalizeTrace', () => {expect(result).toHaveProperty('model');expect(result.provider).toBe('openai');expect(result.model).toBe('gpt-4');+ expect((result as any).SpanAttributes['gen_ai.request.model']).toBe('gpt-4');});it('fills in defaultValues for missing attributes', () => {diff --git a/src/client/src/__tests__/helpers/server/platform.test.ts b/src/client/src/__tests__/helpers/server/platform.test.tsindex e1b466f2..b20ad393 100644--- a/src/client/src/__tests__/helpers/server/platform.test.ts+++ b/src/client/src/__tests__/helpers/server/platform.test.ts@@ -45,6 +45,7 @@ describe('validateMetricsRequest', () => {'GENERATION_BY_APPLICATION','GET_TOTAL_EVALUATION_DETECTED','GET_EVALUATION_ANALYTICS',+ 'GENERATION_HEALTH',] as const;timeLimitTypes.forEach((type) => {@@ -360,6 +361,18 @@ describe('getFilterWhereCondition', () => {expect(result).toContain("= 'it\\'s'");});+ it('adds generation health predicates for truncated and swapped chips', () => {+ const result = getFilterWhereCondition(+ { timeLimit, selectedConfig: { generationHealth: ['truncated', 'swapped'] } } as any,+ true+ );+ expect(result).toContain('gen_ai.response.finish_reasons');+ expect(result).toContain('length');+ expect(result).toContain('gen_ai.request.model');+ expect(result).toContain('gen_ai.response.model');+ expect(result).toContain(' OR ');+ });+it('adds notOrEmpty conditions', () => {const result = getFilterWhereCondition({notOrEmpty: [{ key: 'SpanAttributes' }, { key: 'ServiceName' }],diff --git a/src/client/src/__tests__/lib/platform/datasource/query-map.test.ts b/src/client/src/__tests__/lib/platform/datasource/query-map.test.tsindex 02b1a834..0d9f6709 100644--- a/src/client/src/__tests__/lib/platform/datasource/query-map.test.ts+++ b/src/client/src/__tests__/lib/platform/datasource/query-map.test.ts@@ -278,6 +278,28 @@ describe("metricParamsToOpenLITQuery", () => {expect(back.timeLimit.start).toBe("2026-07-01T00:00:00.000Z");expect(back.timeLimit.end).toBe("2026-07-01T01:00:00.000Z");});++ it("round-trips generationHealth on the ClickHouse path without vendor filters", () => {+ const query = metricParamsToOpenLITQuery({+ timeLimit: {+ start: new Date("2026-07-01T00:00:00.000Z"),+ end: new Date("2026-07-01T01:00:00.000Z"),+ type: "CUSTOM",+ },+ selectedConfig: { generationHealth: ["truncated", "swapped"] },+ } as any);+ expect(query.generationHealth).toEqual(["truncated", "swapped"]);+ expect(query.filters || []).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({ key: "openlit.generation.health" }),+ ])+ );+ const back = toMetricParams(query);+ expect(back.selectedConfig.generationHealth).toEqual([+ "truncated",+ "swapped",+ ]);+ });});describe("denormalizeSpanToTraceRow", () => {diff --git a/src/client/src/__tests__/lib/platform/generation-health/classify.test.ts b/src/client/src/__tests__/lib/platform/generation-health/classify.test.tsnew file mode 100644index 00000000..02bcc1be--- /dev/null+++ b/src/client/src/__tests__/lib/platform/generation-health/classify.test.ts@@ -0,0 +1,245 @@+import {+ classifyFromNormalizedTrace,+ classifyGenerationHealth,+ isGenerationHealthChip,+ matchesGenerationHealthChip,+ normalizeModelName,+ parseGenerationHealthChips,+ percentOfEligible,+ listedSpansMatchingGenerationHealth,+ spanMatchesAnyGenerationHealthChip,+ hasGenerationHealthFilter,+ uniqueTraceCount,+} from "@/lib/platform/generation-health/classify";+import { generationHealthWhereSql } from "@/lib/platform/generation-health/sql";++describe("classifyGenerationHealth", () => {+ it("maps OpenAI length to truncated", () => {+ const health = classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "length",+ "gen_ai.usage.output_tokens": "12",+ });+ expect(health.finishCategory).toBe("truncated");+ expect(health.hasFinishReason).toBe(true);+ expect(matchesGenerationHealthChip(health, "truncated")).toBe(true);+ });++ it("maps array-encoded and Anthropic/Google aliases", () => {+ expect(+ classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "['max_tokens']",+ }).finishCategory+ ).toBe("truncated");+ expect(+ classifyGenerationHealth({+ "gen_ai.response.finish_reason": "MAX_TOKENS",+ }).finishCategory+ ).toBe("truncated");+ expect(+ classifyGenerationHealth({+ "gen_ai.response.finish_reasons": '["content_filter"]',+ }).finishCategory+ ).toBe("filtered");+ expect(+ classifyGenerationHealth({+ "gen_ai.response.finish_reason": "SAFETY",+ }).finishCategory+ ).toBe("filtered");+ });++ it("does not treat tool_call as empty even with 0 output tokens", () => {+ const health = classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "tool_calls",+ "gen_ai.usage.output_tokens": "0",+ });+ expect(health.finishCategory).toBe("tool_call");+ expect(matchesGenerationHealthChip(health, "empty")).toBe(false);+ });++ it("treats zero output tokens as empty when the field is present", () => {+ const health = classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "stop",+ "gen_ai.usage.output_tokens": "0",+ });+ expect(health.finishCategory).toBe("empty");+ expect(health.hasOutputTokens).toBe(true);+ expect(matchesGenerationHealthChip(health, "empty")).toBe(true);+ });++ it("skips empty when output tokens are missing", () => {+ const health = classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "stop",+ });+ expect(health.finishCategory).toBe("ok");+ expect(health.hasOutputTokens).toBe(false);+ expect(matchesGenerationHealthChip(health, "empty")).toBe(false);+ });++ it("flags a model swap and ignores gateway prefixes", () => {+ const health = classifyGenerationHealth({+ "gen_ai.request.model": "openai/gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ });+ expect(health.modelSwap).toBe(true);+ expect(health.hasBothModels).toBe(true);+ expect(matchesGenerationHealthChip(health, "swapped")).toBe(true);+ });++ it("does not flag a swap when only the prefix differs", () => {+ const health = classifyGenerationHealth({+ "gen_ai.request.model": "openai/gpt-4o",+ "gen_ai.response.model": "gpt-4o",+ });+ expect(health.modelSwap).toBe(false);+ });++ it("does not treat a missing served model as a swap", () => {+ const health = classifyGenerationHealth({+ "gen_ai.request.model": "gpt-4o",+ });+ expect(health.modelSwap).toBe(false);+ expect(health.hasBothModels).toBe(false);+ expect(matchesGenerationHealthChip(health, "swapped")).toBe(false);+ });++ it("treats date-suffixed served models as a swap", () => {+ const health = classifyGenerationHealth({+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-2024-08-06",+ });+ expect(health.modelSwap).toBe(true);+ });++ it("still matches empty when a truncated call has 0 output tokens", () => {+ const health = classifyGenerationHealth({+ "gen_ai.response.finish_reasons": "length",+ "gen_ai.usage.output_tokens": "0",+ });+ expect(health.finishCategory).toBe("truncated");+ expect(matchesGenerationHealthChip(health, "truncated")).toBe(true);+ expect(matchesGenerationHealthChip(health, "empty")).toBe(true);+ });+});++describe("classifyFromNormalizedTrace", () => {+ it("reads mapped row fields", () => {+ const health = classifyFromNormalizedTrace({+ finishReason: "length",+ model: "gpt-4o",+ responseModel: "gpt-4o-mini",+ completionTokens: "8",+ });+ expect(health.finishCategory).toBe("truncated");+ expect(health.modelSwap).toBe(true);+ });++ it("prefers SpanAttributes when mapped fields are placeholders", () => {+ const health = classifyFromNormalizedTrace({+ model: "-",+ responseModel: undefined,+ SpanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ });+ expect(health.modelSwap).toBe(true);+ });+});++describe("helpers", () => {+ it("normalizes model names", () => {+ expect(normalizeModelName(" OpenAI/GPT-4o ")).toBe("gpt-4o");+ });++ it("parses chip lists", () => {+ expect(isGenerationHealthChip("truncated")).toBe(true);+ expect(isGenerationHealthChip("loop")).toBe(false);+ expect(parseGenerationHealthChips(["truncated", "nope", "swapped"])).toEqual(+ ["truncated", "swapped"]+ );+ expect(hasGenerationHealthFilter(["truncated"])).toBe(true);+ expect(hasGenerationHealthFilter(["nope"])).toBe(false);+ expect(hasGenerationHealthFilter(undefined)).toBe(false);+ });++ it("matches any selected chip against span attributes", () => {+ expect(+ spanMatchesAnyGenerationHealthChip(+ { "gen_ai.response.finish_reasons": "length" },+ ["truncated"]+ )+ ).toBe(true);+ expect(+ spanMatchesAnyGenerationHealthChip(+ { "gen_ai.response.finish_reasons": "stop" },+ ["truncated", "filtered"]+ )+ ).toBe(false);+ expect(+ spanMatchesAnyGenerationHealthChip(+ { "gen_ai.response.finish_reasons": "length" },+ []+ )+ ).toBe(true);+ });++ it("lists one matching span per trace", () => {+ const listed = listedSpansMatchingGenerationHealth(+ [+ {+ traceId: "t-1",+ spanAttributes: { "http.method": "GET" },+ },+ {+ traceId: "t-1",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ },+ {+ traceId: "t-2",+ spanAttributes: { "gen_ai.request.model": "gpt-4o" },+ },+ ],+ ["swapped"]+ );+ expect(listed).toHaveLength(1);+ expect(listed[0]?.traceId).toBe("t-1");+ expect(listed[0]?.spanAttributes?.["gen_ai.response.model"]).toBe(+ "gpt-4o-mini"+ );+ });++ it("counts distinct traces", () => {+ expect(+ uniqueTraceCount([+ { traceId: "t-1" },+ { traceId: "t-1" },+ { traceId: "t-2" },+ ])+ ).toBe(2);+ });++ it("returns 0% when the eligible set is empty", () => {+ expect(percentOfEligible(4, 0)).toBe(0);+ expect(percentOfEligible(4, 8)).toBe(50);+ });+});++describe("generationHealthWhereSql", () => {+ it("returns empty when no chips are selected", () => {+ expect(generationHealthWhereSql([])).toBe("");+ expect(generationHealthWhereSql(undefined)).toBe("");+ });++ it("ORs selected chip predicates", () => {+ const sql = generationHealthWhereSql(["truncated", "swapped"]);+ expect(sql).toContain("OR");+ expect(sql).toContain("gen_ai.response.finish_reasons");+ expect(sql).toContain("gen_ai.request.model");+ expect(sql).toContain("gen_ai.response.model");+ expect(sql).toContain("length");+ expect(sql).toContain("replaceRegexpOne");+ });+});diff --git a/src/client/src/__tests__/lib/platform/generation-health/format.test.ts b/src/client/src/__tests__/lib/platform/generation-health/format.test.tsnew file mode 100644index 00000000..75e7747e--- /dev/null+++ b/src/client/src/__tests__/lib/platform/generation-health/format.test.ts@@ -0,0 +1,33 @@+import {+ fillTemplate,+ generationHealthCountLine,+ generationHealthSkippedLine,+ generationHealthTipMeaning,+} from "@/lib/platform/generation-health/format";++describe("generation health copy", () => {+ it("explains each chip in plain language", () => {+ expect(generationHealthTipMeaning("truncated")).toMatch(/token limit/i);+ expect(generationHealthTipMeaning("filtered")).toMatch(/safety filter/i);+ expect(generationHealthTipMeaning("empty")).toMatch(/no completion tokens/i);+ expect(generationHealthTipMeaning("swapped")).toMatch(/different model/i);+ });++ it("shows count over eligible on the face of the UI", () => {+ expect(+ fillTemplate("{count}/{eligible}", { count: 24, eligible: 193 })+ ).toBe("24/193");+ expect(generationHealthCountLine(24, 193)).toBe(+ "24 of 193 traces in this window"+ );+ expect(generationHealthCountLine(0, 20)).toBe(+ "None of 20 traces in this window"+ );+ expect(generationHealthCountLine(0, 0)).toMatch(/attributes needed/i);+ });++ it("explains skipped spans only when some were ineligible", () => {+ expect(generationHealthSkippedLine(0, 100)).toBeNull();+ expect(generationHealthSkippedLine(60, 100)).toContain("60 of 100");+ });+});diff --git a/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts b/src/client/src/__tests__/lib/platform/llm/generation-health.test.tsnew file mode 100644index 00000000..8d06a762--- /dev/null+++ b/src/client/src/__tests__/lib/platform/llm/generation-health.test.ts@@ -0,0 +1,197 @@+jest.mock("@/lib/platform/common", () => ({+ dataCollector: jest.fn(),+ OTEL_TRACES_TABLE_NAME: "otel_traces",+}));++jest.mock("@/helpers/server/platform", () => ({+ getFilterPreviousParams: jest.fn((params) => params),+ getFilterWhereCondition: jest.fn(() => "1 = 1"),+}));++jest.mock("@/lib/telemetry-source", () => ({+ resolveTelemetrySourceDescriptor: jest.fn(async () => ({+ isBuiltIn: true,+ type: "clickhouse",+ })),+}));++jest.mock("@/lib/platform/connectors/datasource/facade", () => ({+ resolveSignalReadContext: jest.fn(),+}));++jest.mock("@/lib/platform/connectors/datasource/clickhouse/query-map", () => ({+ metricParamsToOpenLITQuery: jest.fn(() => ({+ signal: "traces",+ timeRange: { start: new Date(), end: new Date() },+ })),+}));++import { dataCollector } from "@/lib/platform/common";+import {+ getGenerationHealth,+ summarizeGenerationHealthFromSpans,+} from "@/lib/platform/llm/generation-health";+import { resolveTelemetrySourceDescriptor } from "@/lib/telemetry-source";++const mockedDataCollector = dataCollector as jest.MockedFunction<+ typeof dataCollector+>;+const mockedResolve = resolveTelemetrySourceDescriptor as jest.MockedFunction<+ typeof resolveTelemetrySourceDescriptor+>;++const params = {+ timeLimit: {+ start: new Date("2024-01-01"),+ end: new Date("2024-01-02"),+ type: "custom",+ },+};++describe("getGenerationHealth", () => {+ beforeEach(() => {+ mockedDataCollector.mockReset();+ mockedResolve.mockResolvedValue({+ isBuiltIn: true,+ type: "clickhouse",+ } as any);+ });++ it("computes percents against the eligible set, not all LLM spans", async () => {+ mockedDataCollector.mockResolvedValue({+ data: [+ {+ llm_spans: 100,+ finish_eligible: 40,+ truncated: 10,+ filtered: 2,+ empty_eligible: 80,+ empty: 4,+ swap_eligible: 20,+ swapped: 5,+ previous_llm_spans: 100,+ previous_finish_eligible: 40,+ previous_truncated: 8,+ previous_filtered: 2,+ previous_empty_eligible: 80,+ previous_empty: 4,+ previous_swap_eligible: 20,+ previous_swapped: 5,+ },+ ],+ });++ const result = await getGenerationHealth(params);+ const row = result.data?.[0];+ expect(row?.llm_spans).toBe(100);+ expect(row?.truncated).toBe(10);+ expect(row?.truncated_eligible).toBe(40);+ expect(row?.truncated_pct).toBe(25);+ expect(row?.swapped_pct).toBe(25);+ expect(row?.empty_pct).toBe(5);+ const query = mockedDataCollector.mock.calls[0][0].query as string;+ expect(query).toContain("finish_eligible");+ expect(query).toContain("swap_eligible");+ expect(query).toContain("empty_eligible");+ expect(query).toContain("uniqExactIf");+ expect(query).toContain("TraceId");+ expect(query).not.toContain("countIf");+ expect(query).not.toContain("operationType");+ });++ it("returns unsupported when the source cannot sample traces", async () => {+ mockedResolve.mockResolvedValue({+ isBuiltIn: false,+ type: "tempo",+ } as any);+ const { resolveSignalReadContext } = await import(+ "@/lib/platform/connectors/datasource/facade"+ );+ (resolveSignalReadContext as jest.Mock).mockResolvedValue({+ adapter: {},+ descriptor: { type: "tempo" },+ });+ const result = await getGenerationHealth(params);+ expect(result.data?.[0]?.unsupported).toBe(true);+ expect(mockedDataCollector).not.toHaveBeenCalled();+ });++ it("classifies sampled spans for any traces adapter with sampleTracesForGraph", async () => {+ mockedResolve.mockResolvedValue({+ isBuiltIn: false,+ type: "tempo",+ } as any);+ const { resolveSignalReadContext } = await import(+ "@/lib/platform/connectors/datasource/facade"+ );+ const { metricParamsToOpenLITQuery } = await import(+ "@/lib/platform/connectors/datasource/clickhouse/query-map"+ );+ const sampleTracesForGraph = jest.fn(async () => [+ {+ traceId: "t-trunc",+ spanAttributes: {+ "gen_ai.response.finish_reasons": "length",+ "gen_ai.usage.output_tokens": "12",+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o",+ },+ },+ {+ traceId: "t-swap",+ spanAttributes: {+ "gen_ai.response.finish_reasons": "stop",+ "gen_ai.usage.output_tokens": "8",+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ },+ ]);+ (resolveSignalReadContext as jest.Mock).mockResolvedValue({+ adapter: { sampleTracesForGraph },+ descriptor: { type: "tempo" },+ });+ const result = await getGenerationHealth(params);+ const row = result.data?.[0];+ expect(row?.unsupported).toBeFalsy();+ expect(row?.llm_spans).toBe(2);+ expect(row?.truncated).toBe(1);+ expect(row?.swapped).toBe(1);+ expect(mockedDataCollector).not.toHaveBeenCalled();+ expect(sampleTracesForGraph).toHaveBeenCalledWith(expect.anything(), 200);+ expect(metricParamsToOpenLITQuery).toHaveBeenCalledWith(+ expect.anything(),+ "traces"+ );+ });+});++describe("summarizeGenerationHealthFromSpans", () => {+ it("counts one row per trace so child LLM spans do not inflate chips", () => {+ const row = summarizeGenerationHealthFromSpans([+ {+ traceId: "t-1",+ spanAttributes: { "http.method": "GET" },+ },+ {+ traceId: "t-1",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ },+ {+ traceId: "t-1",+ spanAttributes: {+ "gen_ai.response.finish_reasons": "length",+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o",+ },+ },+ ]);+ expect(row.llm_spans).toBe(1);+ expect(row.swapped).toBe(1);+ expect(row.truncated).toBe(1);+ expect(row.swapped_eligible).toBe(1);+ });+});diff --git a/src/client/src/__tests__/lib/platform/request/request.test.ts b/src/client/src/__tests__/lib/platform/request/request.test.tsindex a85aec22..43d71cdc 100644--- a/src/client/src/__tests__/lib/platform/request/request.test.ts+++ b/src/client/src/__tests__/lib/platform/request/request.test.ts@@ -177,6 +177,36 @@ describe('getRequests', () => {const { query } = (dataCollector as jest.Mock).mock.calls[1][0];expect(query).toContain('toInt32OrZero(gen_ai.usage.prompt_tokens)');});++ it('lists one matching span per trace when generation-health chips are on', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ total: 3 }], err: null })+ .mockResolvedValueOnce({ data: [], err: null });++ await getRequests({+ ...baseParams,+ selectedConfig: { generationHealth: ['truncated'] },+ } as typeof baseParams & { selectedConfig: { generationHealth: string[] } });++ const countQuery = (dataCollector as jest.Mock).mock.calls[0][0].query as string;+ const listQuery = (dataCollector as jest.Mock).mock.calls[1][0].query as string;+ expect(countQuery).toContain('uniqExact(TraceId)');+ expect(countQuery).not.toContain('COUNT(*)');+ expect(listQuery).toContain('LIMIT 1 BY TraceId');+ });++ it('keeps span-level counts when generation-health chips are off', async () => {+ (dataCollector as jest.Mock)+ .mockResolvedValueOnce({ data: [{ total: 3 }], err: null })+ .mockResolvedValueOnce({ data: [], err: null });++ await getRequests(baseParams);++ const countQuery = (dataCollector as jest.Mock).mock.calls[0][0].query as string;+ const listQuery = (dataCollector as jest.Mock).mock.calls[1][0].query as string;+ expect(countQuery).toContain('COUNT(*)');+ expect(listQuery).not.toContain('LIMIT 1 BY TraceId');+ });});describe('getRequestViaSpanId', () => {diff --git a/src/client/src/__tests__/lib/platform/traces/read.test.ts b/src/client/src/__tests__/lib/platform/traces/read.test.tsindex da1b16e2..5cbb02bb 100644--- a/src/client/src/__tests__/lib/platform/traces/read.test.ts+++ b/src/client/src/__tests__/lib/platform/traces/read.test.ts@@ -179,6 +179,157 @@ describe("listTraceRecords", () => {expect(mockGetRequests).not.toHaveBeenCalled();});+ it("filters Tempo traces by generation-health chips from a full-trace sample", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const sampleTracesForGraph = jest.fn().mockResolvedValue([+ {+ traceId: "t-http",+ spanId: "root",+ parentSpanId: "",+ name: "GET /health",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: { "http.method": "GET" },+ resourceAttributes: {},+ },+ {+ traceId: "t-swap",+ spanId: "child",+ parentSpanId: "root",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:01.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ },+ ]);+ const listSpans = jest.fn();+ mockGetAdapter.mockResolvedValue({ sampleTracesForGraph, listSpans });++ const res = await listTraceRecords({+ ...params,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(sampleTracesForGraph).toHaveBeenCalled();+ expect(listSpans).not.toHaveBeenCalled();+ expect(res).toMatchObject({+ err: null,+ total: 1,+ freshness: "sampled",+ records: [+ expect.objectContaining({+ TraceId: "t-swap",+ SpanId: "child",+ }),+ ],+ });+ });++ it("expands the sample until a later generation-health page can be filled", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const swappedSpan = (index: number) => ({+ traceId: `t-${index}`,+ spanId: `s-${index}`,+ parentSpanId: "",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ });+ const sampleTracesForGraph = jest+ .fn()+ .mockImplementation(async (_query: unknown, maxTraces: number) =>+ Array.from({ length: maxTraces }, (_, index) => swappedSpan(index))+ );+ mockGetAdapter.mockResolvedValue({ sampleTracesForGraph, listSpans: jest.fn() });++ const res = await listTraceRecords({+ ...params,+ limit: 10,+ offset: 200,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(sampleTracesForGraph.mock.calls.map((call) => call[1])).toEqual([+ 210,+ ]);+ const records = (res as { records?: Array<Record<string, unknown>> }).records;+ expect(res).toMatchObject({ err: null, freshness: "sampled" });+ expect(records).toHaveLength(10);+ expect(records?.[0]).toMatchObject({ TraceId: "t-200", SpanId: "s-200" });+ expect(records?.[9]).toMatchObject({ TraceId: "t-209" });+ });++ it("keeps sampling when the first budget cannot fill the requested health page", async () => {+ mockResolveDescriptor.mockResolvedValue(tempo);+ const swappedSpan = (index: number) => ({+ traceId: `t-swap-${index}`,+ spanId: `s-${index}`,+ parentSpanId: "",+ name: "openai.chat.completions",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: {+ "gen_ai.request.model": "gpt-4o",+ "gen_ai.response.model": "gpt-4o-mini",+ },+ resourceAttributes: {},+ });+ const httpSpan = (index: number) => ({+ traceId: `t-http-${index}`,+ spanId: `h-${index}`,+ parentSpanId: "",+ name: "GET /health",+ serviceName: "api",+ timestamp: "2026-07-01T00:00:00.000Z",+ durationNs: 1,+ statusCode: "OK",+ spanAttributes: { "http.method": "GET" },+ resourceAttributes: {},+ });+ const sampleTracesForGraph = jest+ .fn()+ .mockImplementation(async (_query: unknown, maxTraces: number) => {+ const swapped = maxTraces >= 400 ? 50 : 10;+ return [+ ...Array.from({ length: swapped }, (_, index) => swappedSpan(index)),+ ...Array.from({ length: maxTraces - swapped }, (_, index) =>+ httpSpan(index)+ ),+ ];+ });+ mockGetAdapter.mockResolvedValue({ sampleTracesForGraph, listSpans: jest.fn() });++ const res = await listTraceRecords({+ ...params,+ limit: 50,+ offset: 0,+ selectedConfig: { generationHealth: ["swapped"] },+ } as never);++ expect(sampleTracesForGraph.mock.calls.map((call) => call[1])).toEqual([+ 200, 400,+ ]);+ expect((res as { records?: unknown[] }).records).toHaveLength(50);+ expect(res).toMatchObject({ freshness: "sampled" });+ });+it("uses the backend trace count so pagination total does not grow with offset", async () => {mockResolveDescriptor.mockResolvedValue(tempo);let releaseCount!: () => void;diff --git a/src/client/src/app/api/metrics/llm/generation-health/route.ts b/src/client/src/app/api/metrics/llm/generation-health/route.tsnew file mode 100644index 00000000..6e93f740--- /dev/null+++ b/src/client/src/app/api/metrics/llm/generation-health/route.ts@@ -0,0 +1,49 @@+import { withRouteAccess } from "@/lib/access/route-access";+import { MetricParams, TimeLimit } from "@/lib/platform/common";+import { getGenerationHealth } from "@/lib/platform/llm/generation-health";+import {+ validateMetricsRequest,+ validateMetricsRequestType,+} from "@/helpers/server/platform";+import { getRequestEnvironment } from "@/constants/openlit-context";+import getMessage from "@/constants/messages";++async function POSTHandler(request: Request) {+ let formData: Record<string, unknown>;+ try {+ formData = await request.json();+ } catch {+ return Response.json(getMessage().TELEMETRY_SOURCE_INVALID_JSON, {+ status: 400,+ });+ }++ const timeLimit = formData.timeLimit as TimeLimit;+ const params: MetricParams = {+ timeLimit,+ selectedConfig: formData.selectedConfig,+ ...(typeof formData.sourceId === "string" ? { sourceId: formData.sourceId } : {}),+ environment:+ typeof formData.environment === "string"+ ? formData.environment+ : getRequestEnvironment(request),+ };++ const validationParam = validateMetricsRequest(+ params,+ validateMetricsRequestType.GENERATION_HEALTH+ );++ if (!validationParam.success) {+ return Response.json(validationParam.err, {+ status: 400,+ });+ }++ const res = await getGenerationHealth(params);+ return Response.json(res);+}++export const POST = withRouteAccess("metrics.read", POSTHandler, {+ requireDbConfig: true,+});diff --git a/src/client/src/app/api/telemetry/[...segments]/route.ts b/src/client/src/app/api/telemetry/[...segments]/route.tsindex 3438f222..4be59cd9 100644--- a/src/client/src/app/api/telemetry/[...segments]/route.ts+++ b/src/client/src/app/api/telemetry/[...segments]/route.ts@@ -26,6 +26,7 @@ async function post(request: Request, context: RouteContext, path: string): Prom"llm/model/top": () => import("@/app/api/metrics/llm/model/top/route"),"llm/token/time": () => import("@/app/api/metrics/llm/token/time/route"),"llm/token/request/average": () => import("@/app/api/metrics/llm/token/request/average/route"),+ "llm/generation-health": () => import("@/app/api/metrics/llm/generation-health/route"),"vector/application": () => import("@/app/api/metrics/vector/application/route"),"vector/environment": () => import("@/app/api/metrics/vector/environment/route"),"vector/operation": () => import("@/app/api/metrics/vector/operation/route"),diff --git a/src/client/src/components/(playground)/filter/traces-filter.tsx b/src/client/src/components/(playground)/filter/traces-filter.tsxindex cfd1bd48..23c54595 100644--- a/src/client/src/components/(playground)/filter/traces-filter.tsx+++ b/src/client/src/components/(playground)/filter/traces-filter.tsx@@ -42,6 +42,8 @@ import {getFilterStorageKey,} from "@/helpers/client/filter-persistence";import type { Signal } from "@/utils/hooks/useSignalCapabilities";+import { GENERATION_HEALTH_CHIPS, parseGenerationHealthChips } from "@/lib/platform/generation-health/classify";+import { generationHealthChipLabel } from "@/lib/platform/generation-health/format";const m = getMessage();@@ -166,6 +168,7 @@ function configToParams(config: Partial<FilterConfig>, params: URLSearchParams)params.delete("metricTypes");// remove all existing cf entriesparams.delete("cf");+ params.delete("gh");if (config.models?.length) params.set("models", config.models.join(","));if (config.providers?.length) params.set("providers", config.providers.join(","));@@ -183,6 +186,9 @@ function configToParams(config: Partial<FilterConfig>, params: URLSearchParams)params.append("cf", [attributeType, key, value].join(CF_SEP));}});+ if (config.generationHealth?.length) {+ params.set("gh", config.generationHealth.join(","));+ }}function paramsToConfig(params: URLSearchParams): Partial<FilterConfig> {@@ -220,6 +226,10 @@ function paramsToConfig(params: URLSearchParams): Partial<FilterConfig> {};}).filter((f) => f.key && f.value);}+ const gh = params.get("gh");+ if (gh) {+ config.generationHealth = parseGenerationHealthChips(gh.split(","));+ }return config;}@@ -293,6 +303,7 @@ const DynamicFilters = ({case "severities":case "metricNames":case "metricTypes":+ case "generationHealth":if (operationType === "add") {setSelectedFilterValues((s) => {const typeArray = s[type] || [];@@ -518,6 +529,19 @@ const DynamicFilters = ({clearItem={clearFilter}/>) : null}+ {pageName === "request" ? (+ <ComboDropdown+ options={GENERATION_HEALTH_CHIPS.map((chip) => ({+ label: generationHealthChipLabel(chip),+ value: chip,+ }))}+ title={m.GENERATION_HEALTH_CHIP_GROUP}+ type="generationHealth"+ updateSelectedValues={updateSelectedValues}+ selectedValues={selectedFilterValues.generationHealth}+ clearItem={clearFilter}+ />+ ) : null}{filterConfig?.maxCost ? (<SlideWithValuelabel={m.OBSERVABILITY_MAX_COST}diff --git a/src/client/src/components/(playground)/observability/generation-health-bar.tsx b/src/client/src/components/(playground)/observability/generation-health-bar.tsxnew file mode 100644index 00000000..91c0e7db--- /dev/null+++ b/src/client/src/components/(playground)/observability/generation-health-bar.tsx@@ -0,0 +1,161 @@+"use client";++import { useCallback, useEffect } from "react";+import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";+import { getPingStatus } from "@/selectors/database-config";+import { getCurrentProjectEnvironment } from "@/selectors/project";+import { useRootStore } from "@/store";+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";+import { getFilterParamsForDashboard } from "@/helpers/client/filter";+import getMessage from "@/constants/messages";+import type { GenerationHealthChip } from "@/lib/platform/generation-health/classify";+import type { GenerationHealthRow } from "@/lib/platform/llm/generation-health";+import {+ fillTemplate,+ generationHealthChipLabel,+ generationHealthCountLine,+ generationHealthSkippedLine,+ generationHealthTipMeaning,+} from "@/lib/platform/generation-health/format";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/components/ui/tooltip";++const METRICS: Array<{+ chip: GenerationHealthChip;+ countKey: keyof GenerationHealthRow;+ eligibleKey: keyof GenerationHealthRow;+}> = [+ { chip: "truncated", countKey: "truncated", eligibleKey: "truncated_eligible" },+ { chip: "filtered", countKey: "filtered", eligibleKey: "filtered_eligible" },+ { chip: "empty", countKey: "empty", eligibleKey: "empty_eligible" },+ { chip: "swapped", countKey: "swapped", eligibleKey: "swapped_eligible" },+];++export default function GenerationHealthBar() {+ const m = getMessage();+ const filter = useRootStore(getFilterDetails);+ const pingStatus = useRootStore(getPingStatus);+ const environment = useRootStore(getCurrentProjectEnvironment);+ const updateFilter = useRootStore(getUpdateFilter);+ const { data, isFetched, isLoading, fireRequest } = useFetchWrapper();+ const selected = filter.selectedConfig.generationHealth || [];++ const fetchData = useCallback(async () => {+ fireRequest({+ body: JSON.stringify({+ ...getFilterParamsForDashboard(filter),+ ...(environment ? { environment } : {}),+ }),+ requestType: "POST",+ url: "/api/telemetry/llm/generation-health",+ responseDataKey: "data[0]",+ });+ }, [environment, filter, fireRequest]);++ useEffect(() => {+ if (+ filter.timeLimit.start &&+ filter.timeLimit.end &&+ pingStatus === "success"+ ) {+ fetchData();+ }+ }, [filter, fetchData, pingStatus]);++ const row = (data || {}) as GenerationHealthRow;+ if (row.unsupported) return null;++ const isLoadingData = isLoading || !isFetched || pingStatus === "pending";++ const toggle = (chip: GenerationHealthChip) => {+ const isOn = selected.length === 1 && selected[0] === chip;+ updateFilter("selectedConfig", {+ generationHealth: isOn ? [] : [chip],+ });+ };++ return (+ <div+ className="mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1.5 border-t border-stone-200 pt-2 dark:border-stone-800"+ aria-label={m.GENERATION_HEALTH_CHIP_GROUP}+ >+ <p className="text-[11px] font-medium text-stone-500 dark:text-stone-400">+ {m.GENERATION_HEALTH_CHIP_GROUP}+ </p>+ <TooltipProvider delayDuration={200}>+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ {METRICS.map((metric) => {+ const count = Number(row[metric.countKey] || 0);+ const eligible = Number(row[metric.eligibleKey] || 0);+ const isActive = selected.includes(metric.chip);+ const ratio = fillTemplate(m.GENERATION_HEALTH_STAT_OF_ELIGIBLE, {+ count: isLoadingData ? "—" : count,+ eligible: isLoadingData ? "—" : eligible,+ });+ const hasHits = !isLoadingData && count > 0;+ const skippedLine = generationHealthSkippedLine(+ Math.max(row.llm_spans - eligible, 0),+ row.llm_spans+ );+ const label = generationHealthChipLabel(metric.chip);+ const meaning = generationHealthTipMeaning(metric.chip);+ const clickHint = isActive+ ? m.GENERATION_HEALTH_CLICK_TO_CLEAR+ : m.GENERATION_HEALTH_CLICK_TO_FILTER;+ return (+ <Tooltip key={metric.chip}>+ <TooltipTrigger asChild>+ <button+ type="button"+ aria-pressed={isActive}+ aria-label={`${label}. ${meaning} ${ratio}. ${clickHint}`}+ onClick={() => toggle(metric.chip)}+ className={`inline-flex cursor-pointer items-center gap-1.5 rounded-md border px-2 py-1 text-[11px] tabular-nums transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-400/70 ${+ isActive+ ? "border-amber-700 bg-amber-700 text-white shadow-sm dark:border-amber-500 dark:bg-amber-600"+ : hasHits+ ? "border-amber-300 bg-amber-50 font-medium text-amber-950 hover:border-amber-400 hover:bg-amber-100 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-100 dark:hover:bg-amber-900/50"+ : "border-stone-300 bg-white text-stone-700 hover:border-stone-400 hover:bg-stone-50 dark:border-stone-600 dark:bg-stone-950 dark:text-stone-200 dark:hover:border-stone-400"+ }`}+ >+ <span>{label}</span>+ <span className="font-medium">{ratio}</span>+ </button>+ </TooltipTrigger>+ <TooltipContent+ side="bottom"+ className="max-w-[260px] px-3 py-2 text-xs leading-relaxed"+ >+ {isLoadingData ? (+ m.LOADING+ ) : (+ <div className="flex flex-col gap-1.5">+ <p className="font-medium text-stone-950 dark:text-stone-50">+ {meaning}+ </p>+ <p>+ {generationHealthCountLine(count, eligible)}+ </p>+ {skippedLine ? (+ <p className="text-stone-500 dark:text-stone-400">+ {skippedLine}+ </p>+ ) : null}+ <p className="text-stone-500 dark:text-stone-400">+ {clickHint}+ </p>+ </div>+ )}+ </TooltipContent>+ </Tooltip>+ );+ })}+ </div>+ </TooltipProvider>+ </div>+ );+}diff --git a/src/client/src/components/(playground)/observability/signal-list.tsx b/src/client/src/components/(playground)/observability/signal-list.tsxindex 8341d3cf..c1903be6 100644--- a/src/client/src/components/(playground)/observability/signal-list.tsx+++ b/src/client/src/components/(playground)/observability/signal-list.tsx@@ -21,6 +21,7 @@ import { toast } from "sonner";import { ObservabilitySignalConfig } from "./registry";import SignalSummary from "./signal-summary";import SignalRecords from "./signal-records";+import GenerationHealthBar from "./generation-health-bar";import { TraceDetailView } from "./trace-detail-page";import { MetricDetailView } from "./metric-detail-page";import { LogDetailView } from "./log-detail-page";@@ -291,6 +292,25 @@ export default function ObservabilitySignalList({if (!isTraceSignal && !isSessionSignal) setPreviewSpanId(null);}, [isTraceSignal, isSessionSignal, previewSpanId, selectedParam]);+ useEffect(() => {+ if (!isTraceSignal || isLoading || !isFetched || !selectedParam) return;+ const visible = rows.some(+ (row: any) => config.getRowId(row) === selectedParam+ );+ if (visible) return;+ skipSelectedHydrationRef.current = true;+ setPreviewSpanId(null);+ setSelectedInUrl(null);+ }, [+ config,+ isFetched,+ isLoading,+ isTraceSignal,+ rows,+ selectedParam,+ setSelectedInUrl,+ ]);+const selectedMetricRow = useMemo(() => {if (!isMetricSignal || !selectedParam) return null;return (@@ -409,12 +429,13 @@ export default function ObservabilitySignalList({return (<>- <div className="mb-3">+ <div className="mb-3 flex flex-col gap-2"><SignalSummarykey={`summary-${config.key}`}config={config}data={summaryData as any}isLoading={isSummaryLoading || pingStatus === "pending"}+ footer={config.key === "traces" ? <GenerationHealthBar /> : null}/></div><TracesFilterdiff --git a/src/client/src/components/(playground)/observability/signal-records.tsx b/src/client/src/components/(playground)/observability/signal-records.tsxindex be56c7b8..078c6e38 100644--- a/src/client/src/components/(playground)/observability/signal-records.tsx+++ b/src/client/src/components/(playground)/observability/signal-records.tsx@@ -19,6 +19,15 @@ import {hasCodingAgentVendorIcon,} from "@/components/svg/coding-agents";import getMessage from "@/constants/messages";+import {+ classifyFromNormalizedTrace,+ matchesGenerationHealthChip,+ type GenerationHealthChip,+} from "@/lib/platform/generation-health/classify";+import {+ fillTemplate,+ generationHealthChipLabel,+} from "@/lib/platform/generation-health/format";const m = getMessage();@@ -109,6 +118,29 @@ function MiniMeta({);}+function HealthBadge({+ chip,+ title,+}: {+ chip: GenerationHealthChip;+ title?: string;+}) {+ const tone =+ chip === "swapped"+ ? "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-200"+ : chip === "filtered"+ ? "border-rose-200 bg-rose-50 text-rose-800 dark:border-rose-900/50 dark:bg-rose-950/40 dark:text-rose-200"+ : "border-orange-200 bg-orange-50 text-orange-800 dark:border-orange-900/50 dark:bg-orange-950/40 dark:text-orange-200";+ return (+ <span+ title={title || generationHealthChipLabel(chip)}+ className={`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium ${tone}`}+ >+ {generationHealthChipLabel(chip)}+ </span>+ );+}+function TraceRecord({row,config,@@ -123,6 +155,16 @@ function TraceRecord({onOpen: (row: any) => void;}) {const show = (key: string) => visibilityColumns[key] !== false;+ const health = classifyFromNormalizedTrace(row);+ const healthChips: GenerationHealthChip[] = (+ ["truncated", "filtered", "empty", "swapped"] as GenerationHealthChip[]+ ).filter((chip) => matchesGenerationHealthChip(health, chip));+ const swapTitle = health.modelSwap+ ? fillTemplate(m.GENERATION_HEALTH_BADGE_SWAPPED_TITLE, {+ requested: health.requestedModel,+ served: health.servedModel,+ })+ : undefined;return (<buttontype="button"@@ -136,10 +178,21 @@ function TraceRecord({<div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between"><div className="min-w-0"><div className="flex min-w-0 items-center gap-2">- <span className={`h-2 w-2 rounded-full ${config.key === "exceptions" ? "bg-rose-500" : "bg-sky-500"}`} />- <h3 className="truncate text-sm font-semibold text-stone-950 dark:text-stone-50">+ <span className={`h-2 w-2 shrink-0 rounded-full ${config.key === "exceptions" ? "bg-rose-500" : "bg-sky-500"}`} />+ <h3 className="min-w-0 truncate text-sm font-semibold text-stone-950 dark:text-stone-50">{show("spanName") ? row.spanName || row.id : row.id}</h3>+ {healthChips.length ? (+ <span className="flex shrink-0 flex-wrap items-center gap-1">+ {healthChips.map((chip) => (+ <HealthBadge+ key={chip}+ chip={chip}+ title={chip === "swapped" ? swapTitle : undefined}+ />+ ))}+ </span>+ ) : null}</div><div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-stone-500 dark:text-stone-400">{show("time") && <span>{row.time}</span>}@@ -778,7 +831,7 @@ export default function SignalRecords({row={row}config={config}visibilityColumns={visibilityColumns}- isSelected={selectedId === row.spanId}+ isSelected={selectedId === config.getRowId(row)}onOpen={onOpen}/>)diff --git a/src/client/src/components/(playground)/observability/signal-summary.tsx b/src/client/src/components/(playground)/observability/signal-summary.tsxindex 99ab239d..45a04875 100644--- a/src/client/src/components/(playground)/observability/signal-summary.tsx+++ b/src/client/src/components/(playground)/observability/signal-summary.tsx@@ -9,6 +9,7 @@ import {XAxis,YAxis,} from "recharts";+import type { ReactNode } from "react";import { ObservabilitySignalConfig } from "./registry";import getMessage from "@/constants/messages";@@ -45,10 +46,12 @@ export default function SignalSummary({config,data,isLoading,+ footer,}: {config: ObservabilitySignalConfig;data?: SummaryData;isLoading?: boolean;+ footer?: ReactNode;}) {const buckets = data?.buckets || [];const metricLabel =@@ -103,6 +106,7 @@ export default function SignalSummary({</ResponsiveContainer></div></div>+ {footer}</section>);}diff --git a/src/client/src/components/(playground)/observability/trace-detail-page.tsx b/src/client/src/components/(playground)/observability/trace-detail-page.tsxindex 4873eacb..61c1c04d 100644--- a/src/client/src/components/(playground)/observability/trace-detail-page.tsx+++ b/src/client/src/components/(playground)/observability/trace-detail-page.tsx@@ -17,6 +17,11 @@ import { AlertTriangle, ArrowLeft, ChevronLeft, ChevronRight, Clock, Copy, Cpu,import SpanHierarchyExplorer from "./span-hierarchy-explorer";import { Button } from "@/components/ui/button";import getMessage from "@/constants/messages";+import {+ classifyGenerationHealth,+ matchesGenerationHealthChip,+} from "@/lib/platform/generation-health/classify";+import { fillTemplate } from "@/lib/platform/generation-health/format";import Evaluations from "@/components/(playground)/request/components/evaluations";import { RequestProvider } from "@/components/(playground)/request/request-context";import TraceAiAnalysisPanel from "@/components/(playground)/request/components/trace-ai-analysis-panel";@@ -54,6 +59,44 @@ function formatSessionDurationMs(ms: number): string {// non-`full` content-capture mode (CLI flag OPENLIT_CODING_CONTENT_CAPTURE).// We surface the one command that flips it on; everything else (modes,// scope, scrubbing guarantees) lives in the docs to keep this terse.+function GenerationHealthNote({+ spanAttributes,+}: {+ spanAttributes: Record<string, unknown>;+}) {+ const m = getMessage();+ const health = classifyGenerationHealth(spanAttributes);+ const notes: string[] = [];+ if (matchesGenerationHealthChip(health, "truncated")) {+ notes.push(m.GENERATION_HEALTH_DETAIL_TRUNCATED);+ }+ if (matchesGenerationHealthChip(health, "filtered")) {+ notes.push(m.GENERATION_HEALTH_DETAIL_FILTERED);+ }+ if (matchesGenerationHealthChip(health, "empty")) {+ notes.push(m.GENERATION_HEALTH_DETAIL_EMPTY);+ }+ if (health.modelSwap) {+ notes.push(+ fillTemplate(m.GENERATION_HEALTH_DETAIL_SWAPPED, {+ requested: health.requestedModel,+ served: health.servedModel,+ })+ );+ }+ if (!notes.length) return null;+ return (+ <div className="flex flex-col gap-1 rounded-md border border-amber-200 bg-amber-50 px-2 py-1.5 text-[11px] text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/40 dark:text-amber-200">+ {notes.map((note) => (+ <div key={note} className="flex items-start gap-2">+ <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />+ <span>{note}</span>+ </div>+ ))}+ </div>+ );+}+function ContentCaptureNote() {const m = getMessage();const command = m.CODING_AGENT_CONTENT_CAPTURE_NOTE_COMMAND;@@ -947,6 +990,7 @@ export function TraceDetailView({{showContentCaptureNote && (<ContentCaptureNote />)}+ <GenerationHealthNote spanAttributes={spanAttributes} /><div className="hidden h-[min(860px,calc(100vh-12rem))] min-h-[620px] overflow-hidden rounded-md border border-stone-200 bg-white dark:border-stone-800 dark:bg-stone-950 lg:block"><ResizablePanelGroup direction="horizontal" className="h-full"><ResizablePanel defaultSize={48} minSize={32} maxSize={68}>diff --git a/src/client/src/constants/messages/en.ts b/src/client/src/constants/messages/en.tsindex f1690fa5..79fa9ea2 100644--- a/src/client/src/constants/messages/en.ts+++ b/src/client/src/constants/messages/en.ts@@ -275,6 +275,42 @@ export const OBSERVABILITY_COPY_UNSUPPORTED =export const OBSERVABILITY_LINK_COPIED = "Link copied to clipboard";export const OBSERVABILITY_LINK_COPY_FAILED = "Could not copy link";export const OBSERVABILITY_COPY_SHARE_LINK = "Copy shareable link";+export const GENERATION_HEALTH_TRUNCATED = "Truncated";+export const GENERATION_HEALTH_FILTERED = "Filtered";+export const GENERATION_HEALTH_EMPTY = "Empty";+export const GENERATION_HEALTH_SWAPPED = "Model swapped";+export const GENERATION_HEALTH_CHIP_GROUP = "Generation issues";+export const GENERATION_HEALTH_CLICK_TO_FILTER =+ "Click to show only these traces";+export const GENERATION_HEALTH_CLICK_TO_CLEAR =+ "Showing these traces — click to show all";+export const GENERATION_HEALTH_STAT_OF_ELIGIBLE = "{count}/{eligible}";+export const GENERATION_HEALTH_TIP_TRUNCATED =+ "The reply stopped because the model hit its token limit.";+export const GENERATION_HEALTH_TIP_FILTERED =+ "A content or safety filter blocked the reply.";+export const GENERATION_HEALTH_TIP_EMPTY =+ "The model returned no completion tokens.";+export const GENERATION_HEALTH_TIP_SWAPPED =+ "The provider served a different model than the one requested.";+export const GENERATION_HEALTH_TIP_COUNT =+ "{count} of {eligible} traces in this window";+export const GENERATION_HEALTH_TIP_NONE =+ "None of {eligible} traces in this window";+export const GENERATION_HEALTH_TIP_NO_ELIGIBLE =+ "No traces in this window recorded the attributes needed for this check.";+export const GENERATION_HEALTH_STAT_SKIPPED =+ "{skipped} of {total} generations couldn't be checked — missing attributes.";+export const GENERATION_HEALTH_DETAIL_TRUNCATED =+ "Generation stopped because the model hit max tokens. Raise max_tokens or shorten the prompt.";+export const GENERATION_HEALTH_DETAIL_FILTERED =+ "Generation was blocked by a content filter or safety system.";+export const GENERATION_HEALTH_DETAIL_EMPTY =+ "The model returned no completion tokens.";+export const GENERATION_HEALTH_DETAIL_SWAPPED =+ "Requested {requested} but the provider served {served}.";+export const GENERATION_HEALTH_BADGE_SWAPPED_TITLE =+ "Requested {requested} → served {served}";export const OBSERVABILITY_TIME = "Time";export const OBSERVABILITY_SEVERITY = "Severity";export const OBSERVABILITY_BODY = "Body";diff --git a/src/client/src/constants/traces.ts b/src/client/src/constants/traces.tsindex ab10c632..ce6cafa8 100644--- a/src/client/src/constants/traces.ts+++ b/src/client/src/constants/traces.ts@@ -306,6 +306,7 @@ export const TraceMapping: Record<TraceMappingKeyType, TraceMappingValueType> =label: "Finish Reason",type: "string",path: "response.finish_reasons",+ paths: ["response.finish_reasons", "response.finish_reason"],prefix: SpanAttributesGenAIPrefix,},response: {diff --git a/src/client/src/helpers/client/filter-persistence.ts b/src/client/src/helpers/client/filter-persistence.tsindex 8d9f1a51..b5b80de1 100644--- a/src/client/src/helpers/client/filter-persistence.ts+++ b/src/client/src/helpers/client/filter-persistence.ts@@ -18,6 +18,7 @@ export const FILTER_PARAM_KEYS = ["metricNames","metricTypes","cf",+ "gh","gb","gbv",];diff --git a/src/client/src/helpers/client/trace.ts b/src/client/src/helpers/client/trace.tsindex 27d01654..b57cd727 100644--- a/src/client/src/helpers/client/trace.ts+++ b/src/client/src/helpers/client/trace.ts@@ -146,7 +146,7 @@ export const normalizeTrace = (item: TraceRow): TransformedTraceRow => {}}- return normalizedTrace;+ return Object.assign(normalizedTrace, { SpanAttributes: spanAttrs });};function normalizeMappingPath(pathConfig: TraceMappingPathType) {diff --git a/src/client/src/helpers/server/platform.ts b/src/client/src/helpers/server/platform.tsindex 051dd0ae..4895df0d 100644--- a/src/client/src/helpers/server/platform.ts+++ b/src/client/src/helpers/server/platform.ts@@ -12,6 +12,8 @@ import {} from "../server/trace";import { FilterWhereConditionType } from "@/types/platform";import { buildVersionWhereClause } from "@/lib/platform/agents/version-where";+import { parseGenerationHealthChips } from "@/lib/platform/generation-health/classify";+import { generationHealthWhereSql } from "@/lib/platform/generation-health/sql";function escapeClickHouseString(value: string) {return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");@@ -89,6 +91,7 @@ export const validateMetricsRequestType = {// evaluationGET_TOTAL_EVALUATION_DETECTED: "GET_TOTAL_EVALUATION_DETECTED",GET_EVALUATION_ANALYTICS: "GET_EVALUATION_ANALYTICS",+ GENERATION_HEALTH: "GENERATION_HEALTH",};export const validateMetricsRequest = (@@ -142,6 +145,7 @@ export const validateMetricsRequest = (// Evaluationcase validateMetricsRequestType.GET_TOTAL_EVALUATION_DETECTED:case validateMetricsRequestType.GET_EVALUATION_ANALYTICS:+ case validateMetricsRequestType.GENERATION_HEALTH:if (!params.timeLimit?.start || !params.timeLimit?.end) {return {success: false,@@ -326,6 +330,14 @@ export const getFilterWhereCondition = ();}+ const generationHealth = parseGenerationHealthChips(+ filter.selectedConfig.generationHealth+ );+ if (generationHealth.length) {+ const healthClause = generationHealthWhereSql(generationHealth);+ if (healthClause) whereArray.push(healthClause);+ }+if (filter.selectedConfig.customFilters?.length) {filter.selectedConfig.customFilters.forEach(({ attributeType, key, value }) => {if (key && value) {diff --git a/src/client/src/lib/platform/connectors/datasource/clickhouse/query-map.ts b/src/client/src/lib/platform/connectors/datasource/clickhouse/query-map.tsindex 06cf4333..db19d4dd 100644--- a/src/client/src/lib/platform/connectors/datasource/clickhouse/query-map.ts+++ b/src/client/src/lib/platform/connectors/datasource/clickhouse/query-map.ts@@ -10,6 +10,7 @@ import type {QuerySort,Signal,} from "../types";+import { parseGenerationHealthChips } from "@/lib/platform/generation-health/classify";/** Build a `TimeLimit` from an OpenLITQuery time range. */export function toTimeLimit(query: OpenLITQuery): TimeLimit {@@ -91,6 +92,9 @@ export function toMetricParams(});}if (customFilters.length) selectedConfig.customFilters = customFilters;+ if (query.generationHealth?.length) {+ selectedConfig.generationHealth = query.generationHealth;+ }return {timeLimit: toTimeLimit(query),limit: query.limit,@@ -468,5 +472,6 @@ export function metricParamsToOpenLITQuery(aiSelector: opts.aiSelector ?? signal === "traces",interval: opts.interval,maxDataPoints: opts.maxDataPoints,+ generationHealth: parseGenerationHealthChips(cfg.generationHealth),};}diff --git a/src/client/src/lib/platform/connectors/datasource/grafana/tempo.ts b/src/client/src/lib/platform/connectors/datasource/grafana/tempo.tsindex c3261de9..94d2b237 100644--- a/src/client/src/lib/platform/connectors/datasource/grafana/tempo.ts+++ b/src/client/src/lib/platform/connectors/datasource/grafana/tempo.ts@@ -59,6 +59,7 @@ import {} from "../l1-compute";import { bucketSpansByInterval } from "../graph/sample-aggregate";import { clampQueryToSource } from "../http/limits";+import { GENERATION_HEALTH_SAMPLE_MAX } from "@/lib/platform/generation-health/classify";const TTL_MS = 30_000;const MAX_TRACE_FETCH = 200;@@ -1091,8 +1092,8 @@ export class TempoAdapter extends BaseExternalAdapter {// collapse the list. Grafana Cloud can return a valid search hit whose// full OTLP payload exceeds its per-trace response limit (HTTP 422).const candidateLimit = Math.min(- MAX_TRACE_FETCH,- Math.max(maxTraces, maxTraces * 2)+ Math.max(MAX_TRACE_FETCH, maxTraces * 2),+ GENERATION_HEALTH_SAMPLE_MAX);const ids = await this.searchTraceIds(query, candidateLimit);const perTrace = await mapPool(@@ -1155,7 +1156,10 @@ export class TempoAdapter extends BaseExternalAdapter {// Stratification (multi-service fan-out) lives in shared// `fetchSpansForAggregation` so all L1 backends benefit. Per-service// calls land here with a single service.name filter.- return this.fetchSampledSpans(query, Math.min(maxTraces, MAX_TRACE_FETCH));+ return this.fetchSampledSpans(+ query,+ Math.min(maxTraces, GENERATION_HEALTH_SAMPLE_MAX)+ );}/**diff --git a/src/client/src/lib/platform/connectors/datasource/jaeger/adapter.ts b/src/client/src/lib/platform/connectors/datasource/jaeger/adapter.tsindex 054d581b..3ec95e73 100644--- a/src/client/src/lib/platform/connectors/datasource/jaeger/adapter.ts+++ b/src/client/src/lib/platform/connectors/datasource/jaeger/adapter.ts@@ -46,6 +46,11 @@ import {} from "../l1-compute";import { spanFieldValue } from "../graph/sample-aggregate";import { mapPool } from "../graph/map-pool";+import {+ firstSpanMatchingGenerationHealth,+ GENERATION_HEALTH_SAMPLE_MAX,+ spanMatchesAnyGenerationHealthChip,+} from "@/lib/platform/generation-health/classify";const TTL_MS = 30_000;const MAX_SERVICES = 50;@@ -53,6 +58,8 @@ const MAX_QUERY_SERVICES = 24;const SERVICE_TRACE_TIMEOUT_MS = 15_000;const SERVICE_TRACE_CONCURRENCY = 8;const SPAN_INDEX_MAX = 5_000;+/** Same budget as `countTraces` / list pagination so health counts see the traces the user can page to. */+const TRACE_SEARCH_BUDGET = 200;const ZERO_PARENT = new Set(["", "0".repeat(16), "0".repeat(32)]);const spanIndexBySource = new Map<string, Map<string, NormalizedSpan>>();@@ -494,6 +501,18 @@ export class JaegerAdapter extends BaseExternalAdapter {);if (!anyMatch) continue;}+ if (query.generationHealth?.length) {+ const anyMatch = spans.some((span) =>+ spanMatchesAnyGenerationHealthChip(+ {+ ...span.resourceAttributes,+ ...span.spanAttributes,+ },+ query.generationHealth+ )+ );+ if (!anyMatch) continue;+ }const root = pickRootSpan(spans);const startMs = root?.timestamp? new Date(root.timestamp).getTime()@@ -537,18 +556,31 @@ export class JaegerAdapter extends BaseExternalAdapter {const start = Date.now();const pageSize = Math.min(query.limit || 25, 200);const offset = Math.max(0, query.offset || 0);- const traces = await this.collectTraces(query, offset + pageSize);- const roots = traces- .map((trace) => pickRootSpan(flattenJaegerTraces([trace]).map(toNormalizedSpan)))+ const budget = query.generationHealth?.length+ ? Math.max(offset + pageSize, 200)+ : offset + pageSize;+ const traces = await this.collectTraces(query, budget);+ const rows = traces+ .map((trace) => {+ const spans = flattenJaegerTraces([trace]).map(toNormalizedSpan);+ if (query.generationHealth?.length) {+ const hit = firstSpanMatchingGenerationHealth(+ spans,+ query.generationHealth+ );+ if (hit) return hit;+ }+ return pickRootSpan(spans);+ }).filter((span): span is NormalizedSpan => !!span);rememberSpans(this.descriptor.id, this.spansFromTraces(traces));- const rows = roots.slice(offset, offset + pageSize);+ const page = rows.slice(offset, offset + pageSize);return {fields: [],- rows,+ rows: page,meta: {latencyMs: Date.now() - start,- truncated: roots.length >= offset + pageSize,+ truncated: rows.length >= offset + pageSize,degraded: ["serverAggregation"],},};@@ -557,8 +589,11 @@ export class JaegerAdapter extends BaseExternalAdapter {async countTraces(query: OpenLITQuery): Promise<{ total: number; truncated: boolean }> {- const traces = await this.collectTraces(query, 200);- return { total: traces.length, truncated: traces.length >= 200 };+ const traces = await this.collectTraces(query, TRACE_SEARCH_BUDGET);+ return {+ total: traces.length,+ truncated: traces.length >= TRACE_SEARCH_BUDGET,+ };}/**@@ -624,7 +659,7 @@ export class JaegerAdapter extends BaseExternalAdapter {): Promise<NormalizedSpan[]> {const traces = await this.collectTraces(query,- Math.min(maxTraces || 100, 100)+ Math.min(Math.max(1, maxTraces || 100), GENERATION_HEALTH_SAMPLE_MAX));// Cap flattened spans so one Cursor session cannot explode L1 memory.return this.spansFromTraces(traces).slice(0, 5_000);diff --git a/src/client/src/lib/platform/connectors/datasource/types.ts b/src/client/src/lib/platform/connectors/datasource/types.tsindex 27e7d6eb..f7b5b310 100644--- a/src/client/src/lib/platform/connectors/datasource/types.ts+++ b/src/client/src/lib/platform/connectors/datasource/types.ts@@ -154,6 +154,12 @@ export interface OpenLITQuery {* intelligence surfaces.*/aiSelector?: boolean;+ /**+ * In-process filter on listed spans (truncation, refusal, empty completion,+ * silent model swap). ClickHouse evaluates this in SQL; other trace+ * adapters sample full traces and apply the same classifier.+ */+ generationHealth?: import("@/lib/platform/generation-health/classify").GenerationHealthChip[];/*** Optional time-bucket size for time-series requests, e.g. "1m", "1h".* Adapters map this to their native bucketing.diff --git a/src/client/src/lib/platform/generation-health/classify.ts b/src/client/src/lib/platform/generation-health/classify.tsnew file mode 100644index 00000000..da086932--- /dev/null+++ b/src/client/src/lib/platform/generation-health/classify.ts@@ -0,0 +1,268 @@+export const GENERATION_HEALTH_CHIPS = [+ "truncated",+ "filtered",+ "empty",+ "swapped",+] as const;++export type GenerationHealthChip = (typeof GENERATION_HEALTH_CHIPS)[number];++export type FinishCategory =+ | "truncated"+ | "filtered"+ | "empty"+ | "tool_call"+ | "ok"+ | "unknown";++export type GenerationHealth = {+ finishCategory: FinishCategory;+ finishReasonRaw: string;+ modelSwap: boolean;+ requestedModel: string;+ servedModel: string;+ hasFinishReason: boolean;+ hasBothModels: boolean;+ hasOutputTokens: boolean;+ outputTokens: number | null;+};++const TRUNCATED_ALIASES = new Set(["length", "max_tokens", "max_length"]);+const FILTERED_ALIASES = new Set([+ "content_filter",+ "content_filtered",+ "safety",+]);+const TOOL_CALL_ALIASES = new Set(["tool_calls", "tool_use", "tool_call"]);+const OK_ALIASES = new Set(["stop", "end_turn", "stop_sequence"]);++const FINISH_REASON_KEYS = [+ "gen_ai.response.finish_reasons",+ "gen_ai.response.finish_reason",+];+const REQUEST_MODEL_KEYS = ["gen_ai.request.model"];+const RESPONSE_MODEL_KEYS = ["gen_ai.response.model"];+const OUTPUT_TOKEN_KEYS = [+ "gen_ai.usage.output_tokens",+ "gen_ai.client.token.usage.output",+ "gen_ai.usage.completion_tokens",+ "output_tokens",+ "completion_tokens",+];++export function isGenerationHealthChip(+ value: unknown+): value is GenerationHealthChip {+ return (+ typeof value === "string" &&+ (GENERATION_HEALTH_CHIPS as readonly string[]).includes(value)+ );+}++export function parseGenerationHealthChips(+ values: unknown+): GenerationHealthChip[] {+ if (!Array.isArray(values)) return [];+ return values.filter(isGenerationHealthChip);+}++export function hasGenerationHealthFilter(values: unknown): boolean {+ return parseGenerationHealthChips(values).length > 0;+}++function firstAttr(+ attrs: Record<string, unknown> | undefined,+ keys: string[]+): string {+ if (!attrs) return "";+ for (const key of keys) {+ const value = attrs[key];+ if (value === undefined || value === null) continue;+ const text = String(value).trim();+ if (text && text !== "-") return text;+ }+ return "";+}++export function finishReasonTokens(raw: string): string[] {+ if (!raw) return [];+ return raw.toLowerCase().match(/[a-z0-9_]+/g) ?? [];+}++export function normalizeModelName(raw: string): string {+ const trimmed = raw.trim().toLowerCase();+ if (!trimmed) return "";+ const slash = trimmed.lastIndexOf("/");+ return slash >= 0 ? trimmed.slice(slash + 1) : trimmed;+}++function finishCategoryFromTokens(+ tokens: string[],+ outputTokens: number | null+): FinishCategory {+ if (tokens.some((token) => TOOL_CALL_ALIASES.has(token))) return "tool_call";+ if (tokens.some((token) => TRUNCATED_ALIASES.has(token))) return "truncated";+ if (tokens.some((token) => FILTERED_ALIASES.has(token))) return "filtered";+ if (outputTokens === 0) return "empty";+ if (tokens.some((token) => OK_ALIASES.has(token))) return "ok";+ if (tokens.length === 0) {+ return outputTokens === 0 ? "empty" : "unknown";+ }+ return "ok";+}++function parseOutputTokens(+ attrs: Record<string, unknown> | undefined+): { value: number | null; present: boolean } {+ const raw = firstAttr(attrs, OUTPUT_TOKEN_KEYS);+ if (!raw) return { value: null, present: false };+ const numeric = Number(raw);+ if (!Number.isFinite(numeric)) return { value: null, present: false };+ return { value: numeric, present: true };+}++export function classifyGenerationHealth(+ attrs: Record<string, unknown> | undefined+): GenerationHealth {+ const finishReasonRaw = firstAttr(attrs, FINISH_REASON_KEYS);+ const requestedModel = firstAttr(attrs, REQUEST_MODEL_KEYS);+ const servedModel = firstAttr(attrs, RESPONSE_MODEL_KEYS);+ const tokens = parseOutputTokens(attrs);+ const finishTokens = finishReasonTokens(finishReasonRaw);+ const finishCategory = finishCategoryFromTokens(finishTokens, tokens.value);+ const requestedNorm = normalizeModelName(requestedModel);+ const servedNorm = normalizeModelName(servedModel);+ const hasBothModels = Boolean(requestedNorm && servedNorm);++ return {+ finishCategory,+ finishReasonRaw,+ modelSwap: hasBothModels && requestedNorm !== servedNorm,+ requestedModel,+ servedModel,+ hasFinishReason: finishTokens.length > 0,+ hasBothModels,+ hasOutputTokens: tokens.present,+ outputTokens: tokens.value,+ };+}++export function classifyFromNormalizedTrace(row: {+ finishReason?: unknown;+ model?: unknown;+ responseModel?: unknown;+ completionTokens?: unknown;+ SpanAttributes?: Record<string, unknown>;+}): GenerationHealth {+ const attrs = { ...(row.SpanAttributes || {}) };+ if (row.finishReason != null && String(row.finishReason).trim() !== "-") {+ attrs["gen_ai.response.finish_reasons"] = row.finishReason;+ }+ if (row.model != null && String(row.model).trim() !== "-") {+ attrs["gen_ai.request.model"] = row.model;+ }+ if (row.responseModel != null && String(row.responseModel).trim() !== "-") {+ attrs["gen_ai.response.model"] = row.responseModel;+ }+ if (+ row.completionTokens != null &&+ String(row.completionTokens).trim() !== "-"+ ) {+ attrs["gen_ai.usage.output_tokens"] = row.completionTokens;+ }+ return classifyGenerationHealth(attrs);+}++export function matchesGenerationHealthChip(+ health: GenerationHealth,+ chip: GenerationHealthChip+): boolean {+ if (chip === "truncated") {+ return health.hasFinishReason && health.finishCategory === "truncated";+ }+ if (chip === "filtered") {+ return health.hasFinishReason && health.finishCategory === "filtered";+ }+ if (chip === "empty") {+ return (+ health.hasOutputTokens &&+ health.outputTokens === 0 &&+ health.finishCategory !== "tool_call"+ );+ }+ return health.modelSwap;+}++export function spanMatchesAnyGenerationHealthChip(+ attrs: Record<string, unknown> | undefined,+ chips: GenerationHealthChip[] | undefined+): boolean {+ if (!chips?.length) return true;+ const health = classifyGenerationHealth(attrs);+ return chips.some((chip) => matchesGenerationHealthChip(health, chip));+}++export function spanGenerationHealthAttrs(span: {+ spanAttributes?: Record<string, unknown>;+ resourceAttributes?: Record<string, unknown>;+}): Record<string, unknown> {+ return {+ ...(span.resourceAttributes || {}),+ ...(span.spanAttributes || {}),+ };+}++export function firstSpanMatchingGenerationHealth<+ T extends {+ spanAttributes?: Record<string, unknown>;+ resourceAttributes?: Record<string, unknown>;+ },+>(spans: T[], chips: GenerationHealthChip[] | undefined): T | undefined {+ if (!chips?.length) return undefined;+ return spans.find((span) =>+ spanMatchesAnyGenerationHealthChip(spanGenerationHealthAttrs(span), chips)+ );+}++/** One listed row per matching trace (the span that actually has the issue). */+export function listedSpansMatchingGenerationHealth<+ T extends {+ traceId?: string;+ spanAttributes?: Record<string, unknown>;+ resourceAttributes?: Record<string, unknown>;+ },+>(spans: T[], chips: GenerationHealthChip[] | undefined): T[] {+ if (!chips?.length) return spans;+ const grouped = new Map<string, T[]>();+ spans.forEach((span, index) => {+ const key = String(span.traceId || "").trim() || `span:${index}`;+ const group = grouped.get(key);+ if (group) group.push(span);+ else grouped.set(key, [span]);+ });+ const listed: T[] = [];+ for (const group of Array.from(grouped.values())) {+ const hit = firstSpanMatchingGenerationHealth(group, chips);+ if (hit) listed.push(hit);+ }+ return listed;+}++/** Same budget as Jaeger/Tempo list sampling so chip filters can fill a page. */+export const GENERATION_HEALTH_SAMPLE_TRACES = 200;+/** Hard ceiling when expanding the sample to fill a later filtered page. */+export const GENERATION_HEALTH_SAMPLE_MAX = 1000;++export function uniqueTraceCount(spans: Array<{ traceId?: string }>): number {+ const ids = new Set<string>();+ for (const span of spans) {+ const id = String(span.traceId || "").trim();+ if (id) ids.add(id);+ }+ return ids.size || spans.length;+}++export function percentOfEligible(count: number, eligible: number): number {+ if (!eligible || eligible <= 0) return 0;+ return (count / eligible) * 100;+}diff --git a/src/client/src/lib/platform/generation-health/format.ts b/src/client/src/lib/platform/generation-health/format.tsnew file mode 100644index 00000000..e7769a6c--- /dev/null+++ b/src/client/src/lib/platform/generation-health/format.ts@@ -0,0 +1,51 @@+import getMessage from "@/constants/messages";+import type { GenerationHealthChip } from "./classify";++export function fillTemplate(+ template: string,+ values: Record<string, string | number>+): string {+ return Object.entries(values).reduce(+ (text, [key, value]) => text.split(`{${key}}`).join(String(value)),+ template+ );+}++export function generationHealthChipLabel(chip: GenerationHealthChip): string {+ const m = getMessage();+ if (chip === "truncated") return m.GENERATION_HEALTH_TRUNCATED;+ if (chip === "filtered") return m.GENERATION_HEALTH_FILTERED;+ if (chip === "empty") return m.GENERATION_HEALTH_EMPTY;+ return m.GENERATION_HEALTH_SWAPPED;+}++export function generationHealthTipMeaning(chip: GenerationHealthChip): string {+ const m = getMessage();+ if (chip === "truncated") return m.GENERATION_HEALTH_TIP_TRUNCATED;+ if (chip === "filtered") return m.GENERATION_HEALTH_TIP_FILTERED;+ if (chip === "empty") return m.GENERATION_HEALTH_TIP_EMPTY;+ return m.GENERATION_HEALTH_TIP_SWAPPED;+}++export function generationHealthCountLine(+ count: number,+ eligible: number+): string {+ const m = getMessage();+ if (eligible <= 0) return m.GENERATION_HEALTH_TIP_NO_ELIGIBLE;+ if (count <= 0) {+ return fillTemplate(m.GENERATION_HEALTH_TIP_NONE, { eligible });+ }+ return fillTemplate(m.GENERATION_HEALTH_TIP_COUNT, { count, eligible });+}++export function generationHealthSkippedLine(+ skipped: number,+ total: number+): string | null {+ if (skipped <= 0 || total <= 0) return null;+ return fillTemplate(getMessage().GENERATION_HEALTH_STAT_SKIPPED, {+ skipped,+ total,+ });+}diff --git a/src/client/src/lib/platform/generation-health/sql.ts b/src/client/src/lib/platform/generation-health/sql.tsnew file mode 100644index 00000000..82c1c0cc--- /dev/null+++ b/src/client/src/lib/platform/generation-health/sql.ts@@ -0,0 +1,81 @@+import type { GenerationHealthChip } from "./classify";++const FINISH_REASONS_KEY = "gen_ai.response.finish_reasons";+const FINISH_REASON_KEY = "gen_ai.response.finish_reason";+const REQUEST_MODEL_KEY = "gen_ai.request.model";+const RESPONSE_MODEL_KEY = "gen_ai.response.model";+const OUTPUT_TOKEN_KEYS = [+ "gen_ai.usage.output_tokens",+ "gen_ai.client.token.usage.output",+ "gen_ai.usage.completion_tokens",+];++export const FINISH_REASON_RAW_SQL = `if(notEmpty(SpanAttributes['${FINISH_REASONS_KEY}']), SpanAttributes['${FINISH_REASONS_KEY}'], SpanAttributes['${FINISH_REASON_KEY}'])`;++export const FINISH_REASON_NORM_SQL = `replaceRegexpAll(lowerUTF8(${FINISH_REASON_RAW_SQL}), '[^a-z0-9_,]', '')`;++export const HAS_FINISH_REASON_SQL = `notEmpty(${FINISH_REASON_RAW_SQL})`;++function matchAliases(aliases: string[]): string {+ return `match(${FINISH_REASON_NORM_SQL}, '(^|,)(${aliases.join("|")})(,|$)')`;+}++export const IS_TRUNCATED_SQL = matchAliases([+ "length",+ "max_tokens",+ "max_length",+]);+export const IS_FILTERED_SQL = matchAliases([+ "content_filter",+ "content_filtered",+ "safety",+]);+export const IS_TOOL_CALL_SQL = matchAliases([+ "tool_calls",+ "tool_use",+ "tool_call",+]);++export const HAS_OUTPUT_TOKENS_SQL = `(${OUTPUT_TOKEN_KEYS.map(+ (key) => `notEmpty(SpanAttributes['${key}'])`+).join(" OR ")})`;++export const OUTPUT_TOKENS_SQL = `toFloat64OrZero(if(notEmpty(SpanAttributes['${OUTPUT_TOKEN_KEYS[0]}']), SpanAttributes['${OUTPUT_TOKEN_KEYS[0]}'], if(notEmpty(SpanAttributes['${OUTPUT_TOKEN_KEYS[1]}']), SpanAttributes['${OUTPUT_TOKEN_KEYS[1]}'], SpanAttributes['${OUTPUT_TOKEN_KEYS[2]}'])))`;++export const IS_EMPTY_SQL = `(${HAS_OUTPUT_TOKENS_SQL} AND ${OUTPUT_TOKENS_SQL} = 0 AND NOT (${IS_TOOL_CALL_SQL}))`;++function modelRawSql(key: string): string {+ return `trim(BOTH ' ' FROM SpanAttributes['${key}'])`;+}++/** Last path segment after `/`, else the whole name. `openai/gpt-4o` → `gpt-4o`. */+function normalizeModelSql(key: string): string {+ const raw = modelRawSql(key);+ return `lowerUTF8(replaceRegexpOne(${raw}, '^[^/]+/', ''))`;+}++export const HAS_BOTH_MODELS_SQL = `(notEmpty(${modelRawSql(REQUEST_MODEL_KEY)}) AND notEmpty(${modelRawSql(RESPONSE_MODEL_KEY)}))`;++export const IS_MODEL_SWAP_SQL = `(${HAS_BOTH_MODELS_SQL} AND ${normalizeModelSql(REQUEST_MODEL_KEY)} != ${normalizeModelSql(RESPONSE_MODEL_KEY)})`;++export const HAS_LLM_SPAN_SQL = `(notEmpty(SpanAttributes['${REQUEST_MODEL_KEY}']) OR notEmpty(SpanAttributes['gen_ai.operation.name']) OR ${HAS_FINISH_REASON_SQL} OR notEmpty(${modelRawSql(RESPONSE_MODEL_KEY)}))`;++/** Count traces, not spans, so chip totals match the traces list. */+export function uniqTraceIfSql(predicate: string): string {+ return `uniqExactIf(TraceId, ${predicate})`;+}++const CHIP_PREDICATE: Record<GenerationHealthChip, string> = {+ truncated: `(${HAS_FINISH_REASON_SQL} AND ${IS_TRUNCATED_SQL})`,+ filtered: `(${HAS_FINISH_REASON_SQL} AND ${IS_FILTERED_SQL})`,+ empty: IS_EMPTY_SQL,+ swapped: IS_MODEL_SWAP_SQL,+};++export function generationHealthWhereSql(+ chips: GenerationHealthChip[] | undefined+): string {+ const unique = Array.from(new Set(chips || []));+ if (!unique.length) return "";+ return `(${unique.map((chip) => CHIP_PREDICATE[chip]).join(" OR ")})`;+}diff --git a/src/client/src/lib/platform/llm/generation-health.ts b/src/client/src/lib/platform/llm/generation-health.tsnew file mode 100644index 00000000..2b285d6f--- /dev/null+++ b/src/client/src/lib/platform/llm/generation-health.ts@@ -0,0 +1,376 @@+import {+ getFilterPreviousParams,+ getFilterWhereCondition,+} from "@/helpers/server/platform";+import { MetricParams, dataCollector, OTEL_TRACES_TABLE_NAME } from "../common";+import {+ HAS_BOTH_MODELS_SQL,+ HAS_FINISH_REASON_SQL,+ HAS_LLM_SPAN_SQL,+ HAS_OUTPUT_TOKENS_SQL,+ IS_EMPTY_SQL,+ IS_FILTERED_SQL,+ IS_MODEL_SWAP_SQL,+ IS_TRUNCATED_SQL,+ uniqTraceIfSql,+} from "@/lib/platform/generation-health/sql";+import {+ classifyGenerationHealth,+ GENERATION_HEALTH_SAMPLE_TRACES,+ matchesGenerationHealthChip,+ percentOfEligible,+} from "@/lib/platform/generation-health/classify";+import { UnsupportedCapabilityError } from "@/lib/platform/connectors/datasource/types";++export type GenerationHealthRow = {+ unsupported?: boolean;+ llm_spans: number;+ truncated: number;+ truncated_eligible: number;+ truncated_pct: number;+ filtered: number;+ filtered_eligible: number;+ filtered_pct: number;+ empty: number;+ empty_eligible: number;+ empty_pct: number;+ swapped: number;+ swapped_eligible: number;+ swapped_pct: number;+ previous_truncated: number;+ previous_truncated_eligible: number;+ previous_truncated_pct: number;+ previous_filtered: number;+ previous_filtered_eligible: number;+ previous_filtered_pct: number;+ previous_empty: number;+ previous_empty_eligible: number;+ previous_empty_pct: number;+ previous_swapped: number;+ previous_swapped_eligible: number;+ previous_swapped_pct: number;+};++function asCount(value: unknown): number {+ const numeric = Number(value);+ return Number.isFinite(numeric) ? numeric : 0;+}++function metric(count: unknown, eligible: unknown, total: number) {+ const c = asCount(count);+ const e = asCount(eligible);+ return {+ count: c,+ eligible: e,+ skipped: Math.max(total - e, 0),+ pct: percentOfEligible(c, e),+ };+}++function emptyRow(unsupported = false): GenerationHealthRow {+ return {+ unsupported,+ llm_spans: 0,+ truncated: 0,+ truncated_eligible: 0,+ truncated_pct: 0,+ filtered: 0,+ filtered_eligible: 0,+ filtered_pct: 0,+ empty: 0,+ empty_eligible: 0,+ empty_pct: 0,+ swapped: 0,+ swapped_eligible: 0,+ swapped_pct: 0,+ previous_truncated: 0,+ previous_truncated_eligible: 0,+ previous_truncated_pct: 0,+ previous_filtered: 0,+ previous_filtered_eligible: 0,+ previous_filtered_pct: 0,+ previous_empty: 0,+ previous_empty_eligible: 0,+ previous_empty_pct: 0,+ previous_swapped: 0,+ previous_swapped_eligible: 0,+ previous_swapped_pct: 0,+ };+}++function fromQueryRow(+ current: Record<string, unknown> | undefined,+ previous: Record<string, unknown> | undefined+): GenerationHealthRow {+ const llmSpans = asCount(current?.llm_spans);+ const previousSpans = asCount(previous?.llm_spans);+ const truncated = metric(+ current?.truncated,+ current?.finish_eligible,+ llmSpans+ );+ const filtered = metric(+ current?.filtered,+ current?.finish_eligible,+ llmSpans+ );+ const empty = metric(current?.empty, current?.empty_eligible, llmSpans);+ const swapped = metric(current?.swapped, current?.swap_eligible, llmSpans);+ const previousTruncated = metric(+ previous?.truncated,+ previous?.finish_eligible,+ previousSpans+ );+ const previousFiltered = metric(+ previous?.filtered,+ previous?.finish_eligible,+ previousSpans+ );+ const previousEmpty = metric(+ previous?.empty,+ previous?.empty_eligible,+ previousSpans+ );+ const previousSwapped = metric(+ previous?.swapped,+ previous?.swap_eligible,+ previousSpans+ );++ return {+ llm_spans: llmSpans,+ truncated: truncated.count,+ truncated_eligible: truncated.eligible,+ truncated_pct: truncated.pct,+ filtered: filtered.count,+ filtered_eligible: filtered.eligible,+ filtered_pct: filtered.pct,+ empty: empty.count,+ empty_eligible: empty.eligible,+ empty_pct: empty.pct,+ swapped: swapped.count,+ swapped_eligible: swapped.eligible,+ swapped_pct: swapped.pct,+ previous_truncated: previousTruncated.count,+ previous_truncated_eligible: previousTruncated.eligible,+ previous_truncated_pct: previousTruncated.pct,+ previous_filtered: previousFiltered.count,+ previous_filtered_eligible: previousFiltered.eligible,+ previous_filtered_pct: previousFiltered.pct,+ previous_empty: previousEmpty.count,+ previous_empty_eligible: previousEmpty.eligible,+ previous_empty_pct: previousEmpty.pct,+ previous_swapped: previousSwapped.count,+ previous_swapped_eligible: previousSwapped.eligible,+ previous_swapped_pct: previousSwapped.pct,+ };+}++function healthAttrs(span: {+ spanAttributes?: Record<string, unknown>;+ resourceAttributes?: Record<string, unknown>;+}): Record<string, unknown> {+ return {+ ...(span.resourceAttributes || {}),+ ...(span.spanAttributes || {}),+ };+}++function isLlmSpan(attrs: Record<string, unknown> | undefined): boolean {+ if (!attrs) return false;+ const health = classifyGenerationHealth(attrs);+ return (+ health.hasFinishReason ||+ health.hasBothModels ||+ health.hasOutputTokens ||+ Boolean(attrs["gen_ai.request.model"]) ||+ Boolean(attrs["gen_ai.operation.name"])+ );+}++function traceGroupKey(+ span: { traceId?: string },+ index: number+): string {+ const id = String(span.traceId || "").trim();+ return id || `span:${index}`;+}++export function summarizeGenerationHealthFromSpans(+ spans: Array<{+ traceId?: string;+ spanAttributes?: Record<string, unknown>;+ resourceAttributes?: Record<string, unknown>;+ }>+): GenerationHealthRow {+ const grouped = new Map<string, typeof spans>();+ spans.forEach((span, index) => {+ const key = traceGroupKey(span, index);+ const group = grouped.get(key);+ if (group) group.push(span);+ else grouped.set(key, [span]);+ });++ let truncated = 0;+ let filtered = 0;+ let empty = 0;+ let swapped = 0;+ let finishEligible = 0;+ let emptyEligible = 0;+ let swapEligible = 0;+ let llmTraces = 0;+ for (const group of Array.from(grouped.values())) {+ const llm = group.filter((span) => isLlmSpan(healthAttrs(span)));+ if (!llm.length) continue;+ llmTraces += 1;+ const healths = llm.map((span) =>+ classifyGenerationHealth(healthAttrs(span))+ );+ if (healths.some((health) => health.hasFinishReason)) finishEligible += 1;+ if (healths.some((health) => health.hasOutputTokens)) emptyEligible += 1;+ if (healths.some((health) => health.hasBothModels)) swapEligible += 1;+ if (healths.some((health) => matchesGenerationHealthChip(health, "truncated"))) {+ truncated += 1;+ }+ if (healths.some((health) => matchesGenerationHealthChip(health, "filtered"))) {+ filtered += 1;+ }+ if (healths.some((health) => matchesGenerationHealthChip(health, "empty"))) {+ empty += 1;+ }+ if (healths.some((health) => matchesGenerationHealthChip(health, "swapped"))) {+ swapped += 1;+ }+ }+ return fromQueryRow(+ {+ llm_spans: llmTraces,+ finish_eligible: finishEligible,+ truncated,+ filtered,+ empty_eligible: emptyEligible,+ empty,+ swap_eligible: swapEligible,+ swapped,+ },+ {}+ );+}++async function fromExternalSample(params: MetricParams): Promise<GenerationHealthRow> {+ const { resolveSignalReadContext } =+ await import("@/lib/platform/connectors/datasource/facade");+ const { metricParamsToOpenLITQuery } =+ await import("@/lib/platform/connectors/datasource/clickhouse/query-map");+ const context = await resolveSignalReadContext("traces", {+ sourceId: params.sourceId,+ environment: params.environment,+ });+ const adapter = context?.adapter;+ if (typeof adapter?.sampleTracesForGraph !== "function") {+ return emptyRow(true);+ }+ const query = metricParamsToOpenLITQuery(+ paramsWithoutHealthChips(params),+ "traces"+ );+ try {+ const spans = await adapter.sampleTracesForGraph(+ query,+ GENERATION_HEALTH_SAMPLE_TRACES+ );+ return summarizeGenerationHealthFromSpans(spans);+ } catch (err) {+ if (err instanceof UnsupportedCapabilityError) return emptyRow(true);+ throw err;+ }+}++async function resolveExternalTraces(params: MetricParams) {+ const { resolveTelemetrySourceDescriptor } =+ await import("@/lib/telemetry-source");+ const descriptor = await resolveTelemetrySourceDescriptor({+ signal: "traces",+ sourceId: params.sourceId,+ environment: params.environment,+ });+ if (descriptor.isBuiltIn || descriptor.type === "clickhouse") {+ return null;+ }+ return { descriptor };+}++function paramsWithoutHealthChips(params: MetricParams): MetricParams {+ const selectedConfig = { ...(params.selectedConfig || {}) };+ delete selectedConfig.generationHealth;+ return { ...params, selectedConfig };+}++function windowQuery(params: MetricParams) {+ const scoped = paramsWithoutHealthChips(params);+ return `+ SELECT+ ${uniqTraceIfSql(HAS_LLM_SPAN_SQL)} AS llm_spans,+ ${uniqTraceIfSql(HAS_FINISH_REASON_SQL)} AS finish_eligible,+ ${uniqTraceIfSql(`${HAS_FINISH_REASON_SQL} AND ${IS_TRUNCATED_SQL}`)} AS truncated,+ ${uniqTraceIfSql(`${HAS_FINISH_REASON_SQL} AND ${IS_FILTERED_SQL}`)} AS filtered,+ ${uniqTraceIfSql(HAS_OUTPUT_TOKENS_SQL)} AS empty_eligible,+ ${uniqTraceIfSql(IS_EMPTY_SQL)} AS empty,+ ${uniqTraceIfSql(HAS_BOTH_MODELS_SQL)} AS swap_eligible,+ ${uniqTraceIfSql(IS_MODEL_SWAP_SQL)} AS swapped+ FROM ${OTEL_TRACES_TABLE_NAME}+ WHERE ${getFilterWhereCondition(scoped, true)}+ `;+}++export async function getGenerationHealth(+ params: MetricParams+): Promise<{ err?: unknown; data?: GenerationHealthRow[] }> {+ const external = await resolveExternalTraces(params);+ if (external) {+ try {+ return { data: [await fromExternalSample(params)] };+ } catch (err) {+ return { err, data: [] };+ }+ }++ const previousParams = getFilterPreviousParams(params);+ const query = `+ SELECT+ current_data.llm_spans AS llm_spans,+ current_data.finish_eligible AS finish_eligible,+ current_data.truncated AS truncated,+ current_data.filtered AS filtered,+ current_data.empty_eligible AS empty_eligible,+ current_data.empty AS empty,+ current_data.swap_eligible AS swap_eligible,+ current_data.swapped AS swapped,+ previous_data.llm_spans AS previous_llm_spans,+ previous_data.finish_eligible AS previous_finish_eligible,+ previous_data.truncated AS previous_truncated,+ previous_data.filtered AS previous_filtered,+ previous_data.empty_eligible AS previous_empty_eligible,+ previous_data.empty AS previous_empty,+ previous_data.swap_eligible AS previous_swap_eligible,+ previous_data.swapped AS previous_swapped+ FROM (${windowQuery(params)}) AS current_data+ CROSS JOIN (${windowQuery(previousParams)}) AS previous_data+ `;++ const result = await dataCollector({ query });+ if (result.err) return { err: result.err, data: [] };+ const rows = (result.data as Record<string, unknown>[]) || [];+ const current = rows[0] || {};+ const previous = {+ llm_spans: current.previous_llm_spans,+ finish_eligible: current.previous_finish_eligible,+ truncated: current.previous_truncated,+ filtered: current.previous_filtered,+ empty_eligible: current.previous_empty_eligible,+ empty: current.previous_empty,+ swap_eligible: current.previous_swap_eligible,+ swapped: current.previous_swapped,+ };+ return { data: [fromQueryRow(current, previous)] };+}diff --git a/src/client/src/lib/platform/request/index.ts b/src/client/src/lib/platform/request/index.tsindex be1969f1..c93ec739 100644--- a/src/client/src/lib/platform/request/index.ts+++ b/src/client/src/lib/platform/request/index.ts@@ -11,6 +11,7 @@ import {getFilterPreviousParams,getFilterWhereCondition,} from "@/helpers/server/platform";+import { hasGenerationHealthFilter } from "@/lib/platform/generation-health/classify";const PREDEFINED_GROUP_BY: Record<string, string> = {model: `SpanAttributes['gen_ai.request.model']`,@@ -232,8 +233,14 @@ export async function getRequestsConfig(params: MetricParams) {export async function getRequests(params: MetricParams) {const { limit = 10, offset = 0 } = params;+ const oneRowPerTrace = hasGenerationHealthFilter(+ params.selectedConfig?.generationHealth+ );+ const totalExpr = oneRowPerTrace+ ? "CAST(uniqExact(TraceId) AS INTEGER)"+ : "CAST(COUNT(*) AS INTEGER)";- const countQuery = `SELECT CAST(COUNT(*) AS INTEGER) AS total FROM ${OTEL_TRACES_TABLE_NAME}+ const countQuery = `SELECT ${totalExpr} AS total FROM ${OTEL_TRACES_TABLE_NAME}WHERE ${getFilterWhereCondition(params, true)}`;const { data: dataTotal, err: errTotal } = await dataCollector(@@ -257,6 +264,7 @@ export async function getRequests(params: MetricParams) {: `ORDER BY ${params.sorting.type} ${params.sorting.direction} `: `ORDER BY Timestamp desc `}+ ${oneRowPerTrace ? "LIMIT 1 BY TraceId" : ""}LIMIT ${limit}OFFSET ${offset}`;diff --git a/src/client/src/lib/platform/traces/read.ts b/src/client/src/lib/platform/traces/read.tsindex 5765fffb..07931496 100644--- a/src/client/src/lib/platform/traces/read.ts+++ b/src/client/src/lib/platform/traces/read.ts@@ -12,6 +12,7 @@ import { getFilterPreviousParams } from "@/helpers/server/platform";import { metricParamsToOpenLITQuery } from "@/lib/platform/connectors/datasource/clickhouse/query-map";import { denormalizeSpanToTraceRow } from "@/lib/platform/connectors/datasource/clickhouse/normalize";import type {+ DataSourceAdapter,NormalizedSpan,OpenLITQuery,} from "@/lib/platform/connectors/datasource/types";@@ -30,6 +31,12 @@ import { consoleLog } from "@/utils/log";import { AdapterError } from "@openplait/adapter-sdk";import { pickRootSpan } from "@/lib/platform/connectors/datasource/graph/sample-fetch";import { normalizeOtlpId } from "@/lib/platform/connectors/datasource/otlp-json";+import {+ GENERATION_HEALTH_SAMPLE_MAX,+ GENERATION_HEALTH_SAMPLE_TRACES,+ listedSpansMatchingGenerationHealth,+ uniqueTraceCount,+} from "@/lib/platform/generation-health/classify";async function resolveTracesAdapter(sourceId?: string, environment?: string) {const { adapter, descriptor } = await resolveSignalReadContext("traces", {@@ -59,6 +66,109 @@ function externalTraceQuery(params: MetricParams, opts?: { aiSelector?: booleanreturn { ...query, filters: filters?.length ? filters : undefined };}+function usesSqlGenerationHealth(descriptor: { isBuiltIn: boolean; type: string }) {+ return descriptor.isBuiltIn || descriptor.type === "clickhouse";+}++async function listedSpansForHealthSample(+ adapter: DataSourceAdapter,+ listed: NormalizedSpan[],+ chips: NonNullable<OpenLITQuery["generationHealth"]>+): Promise<NormalizedSpan[]> {+ if (!listed.length) return [];+ if (listedSpansMatchingGenerationHealth(listed, chips).length) return listed;+ if (typeof adapter.getTraceSpans !== "function") return listed;+ const seen = new Set<string>();+ const trees: NormalizedSpan[] = [];+ for (const row of listed) {+ const traceId = String(row.traceId || "").trim();+ if (!traceId || seen.has(traceId)) continue;+ seen.add(traceId);+ const tree = await adapter.getTraceSpans(traceId);+ if (tree.length) trees.push(...tree);+ else trees.push(row);+ }+ return trees;+}++async function collectMatchingGenerationHealthRows(+ fetchSpans: (budget: number) => Promise<NormalizedSpan[]>,+ chips: NonNullable<OpenLITQuery["generationHealth"]>,+ needed: number+): Promise<{ matched: NormalizedSpan[]; truncated: boolean }> {+ let budget = Math.max(GENERATION_HEALTH_SAMPLE_TRACES, needed);+ let matched: NormalizedSpan[] = [];+ let truncated = false;+ while (budget <= GENERATION_HEALTH_SAMPLE_MAX) {+ const spans = await fetchSpans(budget);+ matched = listedSpansMatchingGenerationHealth(spans, chips);+ const unique = uniqueTraceCount(spans);+ truncated = unique >= budget;+ if (matched.length >= needed || !truncated) break;+ const next = Math.min(budget * 2, GENERATION_HEALTH_SAMPLE_MAX);+ if (next <= budget) break;+ budget = next;+ }+ return { matched, truncated };+}++function sampledHealthListResult(+ matched: NormalizedSpan[],+ offset: number,+ pageSize: number,+ truncated: boolean+) {+ const page = matched.slice(offset, offset + pageSize);+ const total = truncated+ ? Math.max(+ matched.length,+ offset + page.length + (page.length === pageSize ? 1 : 0)+ )+ : matched.length;+ return {+ err: null,+ records: page.map((row) => denormalizeSpanToTraceRow(row)),+ total,+ freshness: "sampled" as const,+ };+}++async function listGenerationHealthRecords(+ adapter: DataSourceAdapter,+ query: OpenLITQuery,+ params: MetricParams+) {+ const chips = query.generationHealth || [];+ const pageSize = Math.min(params.limit || 25, GENERATION_HEALTH_SAMPLE_MAX);+ const offset = Math.max(0, params.offset || 0);+ const needed = offset + pageSize;+ if (typeof adapter.sampleTracesForGraph === "function") {+ try {+ const { matched, truncated } = await collectMatchingGenerationHealthRows(+ (budget) => adapter.sampleTracesForGraph!(query, budget),+ chips,+ needed+ );+ return sampledHealthListResult(matched, offset, pageSize, truncated);+ } catch (err) {+ if (!(err instanceof UnsupportedCapabilityError)) throw err;+ }+ }+ const { matched, truncated } = await collectMatchingGenerationHealthRows(+ async (budget) => {+ const frame = await adapter.listSpans({+ ...query,+ limit: budget,+ offset: 0,+ });+ return listedSpansForHealthSample(adapter, frame.rows || [], chips);+ },+ chips,+ needed+ );+ return sampledHealthListResult(matched, offset, pageSize, truncated);+}+function asErrorMessage(err: unknown): string {if (err instanceof UnsupportedCapabilityError) return err.message;if (err instanceof AdapterError) {@@ -79,6 +189,12 @@ export async function listTraceRecords(params: MetricParams) {try {const query = externalTraceQuery(params, { aiSelector: false });+ if (+ query.generationHealth?.length &&+ !usesSqlGenerationHealth(descriptor)+ ) {+ return await listGenerationHealthRecords(adapter, query, params);+ }// Interactive lists always query the selected adapter directly. Sampling// caches are reserved for aggregate/intelligence computation.// Run list + count in parallel: Tempo/Jaeger count paths are oftendiff --git a/src/client/src/types/platform.ts b/src/client/src/types/platform.tsindex d44a6bbf..1a84b4ec 100644--- a/src/client/src/types/platform.ts+++ b/src/client/src/types/platform.ts@@ -1,3 +1,5 @@+import type { GenerationHealthChip } from "@/lib/platform/generation-health/classify";+export type OPERATION_TYPE = "llm" | "vectordb";/**@@ -34,6 +36,12 @@ export type FilterWhereConditionType = {spanNames: string[];environments: string[];customFilters: { attributeType: string; key: string; value: string }[];+ /**+ * Truncation / refusal / empty-completion / silent-model-swap chips.+ * ClickHouse evaluates this in SQL; other trace adapters sample full+ * traces and apply the same classifier.+ */+ generationHealth: GenerationHealthChip[];/*** Version filter for agent-scoped views. When set, queries are scoped* to spans matching the version's hash attribute and/or the version'sdiff --git a/src/client/src/types/store/filter.ts b/src/client/src/types/store/filter.tsindex 8595c5d8..5124fab0 100644--- a/src/client/src/types/store/filter.ts+++ b/src/client/src/types/store/filter.ts@@ -50,6 +50,7 @@ export type CustomFilter = {* `VersionFilter` from either path now points at the same interface.*/import type { VersionFilter } from "@/types/platform";+import type { GenerationHealthChip } from "@/lib/platform/generation-health/classify";export type { VersionFilter };export interface FilterConfig {@@ -68,6 +69,8 @@ export interface FilterConfig {metricNames: string[];metricTypes: string[];customFilters?: CustomFilter[];+ /** Truncated / filtered / empty / model-swapped chips on traces. */+ generationHealth?: GenerationHealthChip[];/** Locked agent version scope used by the agent detail page. */versionFilter?: VersionFilter;}