πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(events): outlier chart strip above the trace table (LFE-14451) (#15486)
Nikita Kabardin70ec9083f854
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex 0ecdad7dec..9ff6bada8f 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -41,6 +41,7 @@ this.| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` || Diverse v4 session shapes (chat / coding-agent / mixed) for the session-detail view | `pnpm run seed -- session-shapes --shape all` (the `agent` shape has I/O on AGENT/TOOL with no GENERATION β pre-LFE-10520 the "first generation" default rendered empty cards for it; the current "All observations with I/O" default renders it correctly; v4 on by default) || Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |+| Long-window v4 traffic with cost/latency/token OUTLIERS (outlier chart strip, LFE-14451) | `pnpm run seed -- outlier-traffic --days 90` (diurnal base load + deterministic spikes + hour-long Γ8-latency incidents; root AGENT + GENERATION carrying cost + TOOL per trace; v4 on by default) || Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` || Lots of scores on every node (dense score badges, tree-row overflow testing) | add `--scores-per-node 12` to `trace-tree` (N distinct scores per observation; try `--depth 2 --breadth 44` for many tall sibling rows) || Varied human-annotation queues (annotate UI / keyboard testing) | `pnpm run seed -- annotation-queue --core-items 12` (creates a "core types" queue covering every score-field render path + an "edge cases" queue with archived/stale/partial scores and observation/session/deleted/completed items) |diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.mdindex 64fa6c383d..819d890d1c 100644--- a/packages/shared/scripts/seeder/AGENTS.md+++ b/packages/shared/scripts/seeder/AGENTS.md@@ -16,6 +16,7 @@ pnpm run seed -- support-agent --v4 --id-prefix <hex> # demo-grade handcraftedpnpm run seed -- long-session --traces 300 --observations-per-trace 8pnpm run seed -- session-shapes --shape all # chat / coding-agent / mixed v4 sessionspnpm run seed -- many-traces --count 100000 --days 14+pnpm run seed -- outlier-traffic --days 90 # diurnal v4 traffic w/ cost/latency/token outliers (outlier chart strip)pnpm run seed -- scored-traces --traces 24 --v4 # scores w/ spaces in the name```diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.tsindex e238c64ac8..3f082ad820 100644--- a/packages/shared/scripts/seeder/scenarios/index.ts+++ b/packages/shared/scripts/seeder/scenarios/index.ts@@ -3,6 +3,7 @@ import { annotationQueueScenario } from "./annotation-queue";import { deepChainScenario } from "./deep-chain";import { longSessionScenario } from "./long-session";import { manyTracesScenario } from "./many-traces";+import { outlierTrafficScenario } from "./outlier-traffic";import { scoredTracesScenario } from "./scored-traces";import { sessionShapesScenario } from "./session-shapes";import { supportAgentScenario } from "./support-agent";@@ -18,6 +19,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {"deep-chain": deepChainScenario,"long-session": longSessionScenario,"many-traces": manyTracesScenario,+ "outlier-traffic": outlierTrafficScenario,"scored-traces": scoredTracesScenario,"session-shapes": sessionShapesScenario,"annotation-queue": annotationQueueScenario,diff --git a/packages/shared/scripts/seeder/scenarios/outlier-traffic.ts b/packages/shared/scripts/seeder/scenarios/outlier-traffic.tsnew file mode 100644index 0000000000..be5b5472ca--- /dev/null+++ b/packages/shared/scripts/seeder/scenarios/outlier-traffic.ts@@ -0,0 +1,453 @@+import {+ createTrace,+ createObservation,+ createTracesCh,+ createObservationsCh,+ createEventsCh,+ EventRecordInsertType,+ ObservationRecordInsertType,+ TraceRecordInsertType,+} from "../../../src/server";+import { observationToEvent, traceToEvent } from "./event-mirror";+import { GEN_INPUT_PRICE, GEN_OUTPUT_PRICE } from "./payload";+import { jitter, utcDayStartMs } from "./rng";+import {+ chunk,+ ScenarioContext,+ ScenarioDefinition,+ SeedError,+ SeedSummary,+} from "./types";+import { countRows, escapeLike, tracesListLink } from "./verify";++/**+ * Long-window traffic with deliberate outliers, built for the outlier chart+ * strip above the trace table (LFE-14451): a diurnal base load spread over+ * the past N days, with deterministic cost / latency / token spikes and a few+ * hour-long latency "incidents" that read as plateaus on the strip.+ *+ * Per trace: root AGENT (its latency spans the trace) + one GENERATION child+ * carrying usage/cost + one TOOL child. Cost lives on the generation, not the+ * root β the shape the strip's root-filter-agnostic aggregation exists for.+ *+ * The outlier recipe is a pure function of the global trace index, so re-runs+ * with the same seed and flags rewrite identical data:+ * - cost spike (idx % 89 === 0): usage Γ30 on a premium-rate model+ * - mega cost (idx % 979 === 0): additionally rate Γ12 (rare, dominates)+ * - latency spike(idx % 71 === 3): generation duration Γ35+ * - token spike (idx % 113 === 7): usage Γ25 at a discount rate β tokens+ * without a matching cost spike+ * - incidents: K deterministic (day, hour) windows where every trace runs+ * Γ8 slower and every 3rd one ERRORs+ */++const TRACE_NAMES = [+ "checkout-assistant",+ "support-copilot",+ "search-agent",+ "summarize-doc",+ "classify-ticket",+];++const MODELS = ["gpt-4o", "gpt-4o-mini", "claude-sonnet-4", "gemini-2.5-flash"];++const INCIDENT_HOURS = [14, 9, 19];++const usageCost = (+ usageInput: number,+ usageOutput: number,+ rateMultiplier: number,+) => {+ const inputCost = usageInput * GEN_INPUT_PRICE * rateMultiplier;+ const outputCost = usageOutput * GEN_OUTPUT_PRICE * rateMultiplier;+ const usage = {+ input: usageInput,+ output: usageOutput,+ total: usageInput + usageOutput,+ };+ const cost = {+ input: inputCost,+ output: outputCost,+ total: inputCost + outputCost,+ };+ return {+ provided_usage_details: usage,+ usage_details: usage,+ provided_cost_details: cost,+ cost_details: cost,+ total_cost: cost.total,+ };+};++/** Diurnal hour pick: ~15% land in the night hours, the rest in 07:00β22:00. */+const diurnalHour = (seed: number, salt: number): number => {+ const v = jitter(seed, salt, 100);+ return v < 15 ? v % 7 : 7 + (v % 16);+};++const run = async (+ ctx: ScenarioContext,+ params: Record<string, string | number | boolean>,+): Promise<SeedSummary> => {+ const startedAt = Date.now();+ const days = params["days"] as number;+ const tracesPerDay = params["traces-per-day"] as number;+ const incidents = params["incidents"] as number;+ const withV4 = params["v4"] as boolean;++ if (days < 1 || days > 366) {+ throw new SeedError(+ `--days must be between 1 and 366, got ${days}`,+ "pass the window the chart should cover, e.g. --days 90",+ );+ }+ if (tracesPerDay < 1) {+ throw new SeedError(+ `--traces-per-day must be >= 1, got ${tracesPerDay}`,+ "pass a positive base density, e.g. --traces-per-day 120",+ );+ }+ if (incidents < 0) {+ throw new SeedError(+ `--incidents must be >= 0, got ${incidents}`,+ "pass 0 to seed without incident windows",+ );+ }++ const traceCount = days * tracesPerDay;+ const counts: Record<string, number> = {+ traces: traceCount,+ observations: traceCount * 3,+ events: withV4 ? traceCount * 4 : 0, // synthetic trace span + 3 observations+ };+ const links = [tracesListLink(ctx)];++ if (ctx.dryRun) {+ return {+ scenario: "outlier-traffic",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: Array.from(+ { length: Math.min(traceCount, 5) },+ (_, i) => `${ctx.idPrefix}-d1-t${i}`,+ ),+ sessionIds: [],+ counts,+ verified: {},+ links,+ dryRun: true,+ durationMs: Date.now() - startedAt,+ };+ }++ // Incident windows: deterministic (day, hour) slots spread over the range.+ const incidentSlots = new Set<string>();+ for (let k = 0; k < incidents; k++) {+ const day = 1 + ((5 + k * 11) % days);+ incidentSlots.add(`${day}:${INCIDENT_HOURS[k % INCIDENT_HOURS.length]}`);+ }++ ctx.log(+ `building ${traceCount} traces over ${days} day(s) (${incidentSlots.size} incident window(s))`,+ );++ const users = Array.from(+ { length: 20 },+ (_, i) => `user-${ctx.idPrefix}-${i}`,+ );+ const dayStartToday = utcDayStartMs();++ const traces: TraceRecordInsertType[] = [];+ const observations: ObservationRecordInsertType[] = [];+ const events: EventRecordInsertType[] = [];++ // Start at yesterday (d = 1): today's partial day would place events in the+ // future, hidden by the UI's "past N days" windows.+ for (let d = 1; d <= days; d++) {+ const dayStart = dayStartToday - d * 86_400_000;+ for (let i = 0; i < tracesPerDay; i++) {+ const g = (d - 1) * tracesPerDay + i; // global index drives the recipe+ const traceId = `${ctx.idPrefix}-d${d}-t${i}`;++ const hour = diurnalHour(ctx.seed, g * 7 + 1);+ // jitter() not rng: these land in ClickHouse ORDER BY keys (start_time);+ // see the seeder rules on stream-position randomness.+ const timestamp =+ dayStart + hour * 3_600_000 + jitter(ctx.seed, g * 13 + 2, 3_599_000);++ const isIncident = incidentSlots.has(`${d}:${hour}`);+ const costOutlier = g % 89 === 0;+ const megaCost = g % 979 === 0;+ const latencyOutlier = g % 71 === 3;+ const tokenOutlier = g % 113 === 7;++ const usageScale = costOutlier || megaCost ? 30 : tokenOutlier ? 25 : 1;+ const rateMultiplier = megaCost+ ? 12 * 4+ : costOutlier+ ? 4+ : tokenOutlier+ ? 0.05+ : 1;+ const durationScale = latencyOutlier ? 35 : isIncident ? 8 : 1;++ const usageInput =+ (200 + jitter(ctx.seed, g * 17 + 3, 5000)) * usageScale;+ const usageOutput =+ (100 + jitter(ctx.seed, g * 19 + 4, 2200)) * usageScale;+ const model = costOutlier || megaCost ? "gpt-4o" : MODELS[g % 4];+ const hasError = isIncident && g % 3 === 0;++ const genStart = timestamp + 40 + jitter(ctx.seed, g * 23 + 5, 200);+ const genDuration =+ (600 + jitter(ctx.seed, g * 29 + 6, 3200)) * durationScale;+ const genEnd = genStart + genDuration;+ const toolStart = genEnd + 20 + jitter(ctx.seed, g * 31 + 7, 100);+ const toolEnd = toolStart + 80 + jitter(ctx.seed, g * 37 + 8, 800);+ const name = TRACE_NAMES[g % TRACE_NAMES.length];++ const trace = createTrace({+ id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ session_id: null,+ timestamp,+ name,+ user_id: users[jitter(ctx.seed, g * 41 + 9, users.length - 1)],+ release: "v2.0.1",+ version: "v2.0.1",+ tags: ["seed", "outlier-traffic"],+ public: false,+ bookmarked: false,+ metadata: { scenario: "outlier-traffic", day: String(d) },+ input: `User request handled by ${name} (#${g})`,+ output: hasError ? "" : `Resolved by ${name} (#${g})`,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });+ traces.push(trace);++ const emptyUsageCost = {+ provided_usage_details: {},+ usage_details: {},+ provided_cost_details: {},+ cost_details: {},+ total_cost: null,+ };++ const root = createObservation({+ id: `${traceId}-o0`,+ trace_id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ type: "AGENT",+ parent_observation_id: null,+ name: "handle-request",+ start_time: timestamp,+ end_time: toolEnd,+ completion_start_time: null,+ level: hasError ? "ERROR" : "DEFAULT",+ status_message: hasError ? "Upstream model timeout" : null,+ version: null,+ input: null,+ output: null,+ metadata: { scenario: "outlier-traffic" },+ provided_model_name: null,+ internal_model_id: null,+ model_parameters: "{}",+ ...emptyUsageCost,+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });++ const generation = createObservation({+ id: `${traceId}-o1`,+ trace_id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ type: "GENERATION",+ parent_observation_id: `${traceId}-o0`,+ name: "llm-completion",+ start_time: genStart,+ end_time: genEnd,+ completion_start_time:+ genStart + Math.min(300, Math.round(genDuration / 4)),+ level: hasError ? "ERROR" : "DEFAULT",+ status_message: hasError ? "Upstream model timeout" : null,+ version: null,+ input: JSON.stringify({+ messages: [{ role: "user", content: `Request #${g} for ${name}` }],+ }),+ output: hasError ? "" : `Completion for request #${g}`,+ metadata: { scenario: "outlier-traffic" },+ provided_model_name: model,+ internal_model_id: null,+ model_parameters: JSON.stringify({ temperature: 0.2 }),+ ...usageCost(usageInput, usageOutput, rateMultiplier),+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });++ const tool = createObservation({+ id: `${traceId}-o2`,+ trace_id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ type: "TOOL",+ parent_observation_id: `${traceId}-o0`,+ name: "persist-result",+ start_time: toolStart,+ end_time: toolEnd,+ completion_start_time: null,+ level: "DEFAULT",+ status_message: null,+ version: null,+ input: null,+ output: null,+ metadata: { scenario: "outlier-traffic" },+ provided_model_name: null,+ internal_model_id: null,+ model_parameters: "{}",+ ...emptyUsageCost,+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });++ observations.push(root, generation, tool);++ if (withV4) {+ events.push(+ traceToEvent(trace),+ observationToEvent(root, trace),+ observationToEvent(generation, trace),+ observationToEvent(tool, trace),+ );+ }+ }+ }++ ctx.log(+ `inserting ${traces.length} traces, ${observations.length} observations${withV4 ? `, ${events.length} events` : ""}`,+ );+ for (const batch of chunk(traces, 1000)) {+ await createTracesCh(batch);+ }+ for (const batch of chunk(observations, 1000)) {+ await createObservationsCh(batch);+ }+ for (const batch of chunk(events, 500)) {+ await createEventsCh(batch);+ }++ const prefix = `${escapeLike(ctx.idPrefix)}-d%`;+ const verified: Record<string, number> = {+ traces: await countRows(+ "traces",+ `project_id = {projectId: String} AND id LIKE {prefix: String}`,+ { projectId: ctx.projectId, prefix },+ "uniqExact(id)",+ ),+ observations: await countRows(+ "observations",+ `project_id = {projectId: String} AND id LIKE {prefix: String}`,+ { projectId: ctx.projectId, prefix },+ "uniqExact(id)",+ ),+ ...(withV4+ ? {+ events: await countRows(+ "events_core",+ `project_id = {projectId: String} AND trace_id LIKE {prefix: String} AND is_deleted = 0`,+ { projectId: ctx.projectId, prefix },+ "uniqExact(span_id)",+ ),+ }+ : {}),+ };++ if (verified.traces < counts.traces) {+ throw new SeedError(+ `Readback mismatch: expected ${counts.traces} traces, found ${verified.traces}`,+ );+ }+ if (verified.observations < counts.observations) {+ throw new SeedError(+ `Readback mismatch: expected ${counts.observations} observations, found ${verified.observations}`,+ );+ }+ if (withV4 && (verified.events ?? 0) < counts.events) {+ throw new SeedError(+ `Readback mismatch: expected ${counts.events} events, found ${verified.events}`,+ );+ }++ return {+ scenario: "outlier-traffic",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ // Day 1 only ever holds tracesPerDay traces β never list ids that were+ // not written (a deep link built from one would 404).+ traceIds: Array.from(+ { length: Math.min(tracesPerDay, 5) },+ (_, i) => `${ctx.idPrefix}-d1-t${i}`,+ ),+ sessionIds: [],+ counts,+ verified,+ links,+ dryRun: false,+ durationMs: Date.now() - startedAt,+ };+};++export const outlierTrafficScenario: ScenarioDefinition = {+ name: "outlier-traffic",+ description:+ "Diurnal base traffic over the past N days with deterministic cost/latency/token outliers and hour-long latency incidents β built for the outlier chart strip above the trace table (LFE-14451). Root AGENT + GENERATION (carries cost) + TOOL per trace.",+ supportsV4: true,+ flags: [+ {+ flag: "days",+ type: "number",+ default: 90,+ description: "spread traffic over the past N days (starting yesterday)",+ },+ {+ flag: "traces-per-day",+ type: "number",+ default: 120,+ description: "base traces per day (3 observations each)",+ },+ {+ flag: "incidents",+ type: "number",+ default: 3,+ description: "hour-long Γ8-latency incident windows across the range",+ },+ {+ flag: "v4",+ type: "boolean",+ default: true,+ description:+ "mirror into v4 events tables (on by default: the outlier strip reads events)",+ },+ ],+ run,+};diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsxindex 8cd609761c..42e36e6fb0 100644--- a/web/src/components/table/data-table-toolbar.tsx+++ b/web/src/components/table/data-table-toolbar.tsx@@ -125,6 +125,9 @@ interface DataTableToolbarProps<TData, TValue> {* query β not the toolbar's stale local mirror β is captured. */currentSearchQuery?: string;actionButtons?: React.ReactNode;+ /** Rendered at the start of the right-aligned control cluster (left of the+ * Columns toggle) β e.g. the events table's "Pulse" reopen button. */+ preColumnsSlot?: React.ReactNode;filterState?: FilterState;setFilterState?:| Dispatch<SetStateAction<FilterState>>@@ -206,6 +209,7 @@ export function DataTableToolbar<TData, TValue>({searchConfig,currentSearchQuery,actionButtons,+ preColumnsSlot,filterState,setFilterState,columnVisibility,@@ -491,6 +495,7 @@ export function DataTableToolbar<TData, TValue>({)}<div className="flex flex-row flex-wrap gap-2 pr-0.5 @3xl:ml-auto">+ {preColumnsSlot}{!!columnVisibility && !!setColumnVisibility && (<DataTableColumnVisibilityFiltercolumns={columns}diff --git a/web/src/components/trace/components/_layout/TraceLayoutMobile.tsx b/web/src/components/trace/components/_layout/TraceLayoutMobile.tsxindex 6c912e19db..9d014dad3a 100644--- a/web/src/components/trace/components/_layout/TraceLayoutMobile.tsx+++ b/web/src/components/trace/components/_layout/TraceLayoutMobile.tsx@@ -132,7 +132,7 @@ export function TraceLayoutMobile({<TabsBarTrigger value="tree">Tree</TabsBarTrigger><TabsBarTrigger value="timeline">Timeline</TabsBarTrigger>{showGraph && <TabsBarTrigger value="graph">Graph</TabsBarTrigger>}- <TabsBarTrigger value="info">Info</TabsBarTrigger>+ <TabsBarTrigger value="info">Data</TabsBarTrigger></TabsBarList>{/* Inactive tabs unmount (Radix default). On memory-constrained mobilediff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex a9ab08c7d4..b0a3816ac4 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -65,7 +65,7 @@ import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTablimport useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";import { BreakdownTooltip } from "@/src/components/trace/components/_shared/BreakdownToolTip";-import { InfoIcon, LightbulbIcon } from "lucide-react";+import { ChartNoAxesColumn, InfoIcon, LightbulbIcon } from "lucide-react";import { ProvidedModelNameCell } from "@/src/features/models/components/ProvidedModelNameCell";import { LocalIsoDate } from "@/src/components/LocalIsoDate";import { Badge } from "@/src/components/ui/badge";@@ -130,6 +130,9 @@ import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presetimport { EventsChartView } from "@/src/features/chart-view/EventsChartView";import { ViewModeToggle } from "@/src/features/chart-view/components/ViewModeToggle";import { useChartViewState } from "@/src/features/chart-view/lib/useChartViewState";+import { EventsOutlierStrip } from "@/src/features/events/components/outlier-strip/EventsOutlierStrip";+import useLocalStorage from "@/src/components/useLocalStorage";+import { Button } from "@/src/components/ui/button";import {chartFilterExclusionReason,chartSearchFieldReason,@@ -479,6 +482,21 @@ export default function ObservationsEventsTable({[dateRange],);+ // Pulse strip open/closed β per-user persisted; null = no explicit choice+ // yet (open on desktop, closed on mobile β resolved below once isMobile is+ // known).+ const [pulseClosedStored, setPulseClosed] = useLocalStorage<boolean | null>(+ "events-outlier-strip-closed",+ null,+ );+ // Drill-in writes the clicked bucket as an absolute range. URL-only+ // (pushIn β browser Back restores the outer window) and deliberately NOT+ // persisted as the project's default range β a transient zoom must not+ // become tomorrow's baseline.+ const { setTimeRange: setTimeRangeTransient } = useTableDateRange(projectId, {+ persistAsDefault: false,+ });+const dateRangeFilter: FilterState = toStartTimeFilterState(dateRange);const appRootDefault = useAppRootDefault({@@ -750,6 +768,21 @@ export default function ObservationsEventsTable({// rest as "not applied" (see chartFilterExclusions below).const chartEnabled = !hideControls && !userId && !sessionId;+ // The outlier strip additionally hides on prompt-version-scoped tables:+ // `promptVersion` is a page-scope prop the aggregate query cannot express+ // (number filter, not a forwardable dimension), and unlike sidebar facets it+ // has no "not applied" affordance β the strip would silently aggregate+ // across ALL versions while the table shows one. (`promptName` forwards.)+ // External state pins also disqualify it: the strip's drill-in writes the+ // URL range, which a table on externalDateRange would ignore β chart and+ // table would silently diverge. (No current surface combines these with+ // chartEnabled; this encodes the invariant for future mounts.)+ const outlierStripEnabled =+ chartEnabled &&+ promptVersion === undefined &&+ !externalDateRange &&+ !externalFilterState;+// The chart is actually on screen (not just enabled). Only then do we mark// the filters it can't honour as "not applied", so table mode stays untouched.// Both surfaces use the stateless per-column / per-field reason resolvers@@ -1059,6 +1092,22 @@ export default function ObservationsEventsTable({// checkboxes would do nothing. Omit the select column on mobile until a// dedicated mobile action affordance exists.const isMobile = useIsMobile();+ const pulseClosed = pulseClosedStored ?? isMobile;+ // One reopen affordance for both surfaces: the desktop toolbar slot (left of+ // Columns) and the mobile header band β mobile defaults to closed, so+ // without this the strip would be unreachable there.+ const pulseReopenButton =+ outlierStripEnabled && chartViewMode !== "chart" && pulseClosed ? (+ <Button+ variant="outline"+ size="sm"+ onClick={() => setPulseClosed(false)}+ className="h-8 gap-1.5 text-xs"+ >+ <ChartNoAxesColumn className="h-3.5 w-3.5" />+ Pulse+ </Button>+ ) : null;const enableSorting = !hideControls;const columns: LangfuseColumnDef<EventsTableRow>[] = [@@ -1962,6 +2011,7 @@ export default function ObservationsEventsTable({onModeChange={setChartViewMode}/>)}+ {pulseReopenButton}</div>)}{!hideControls && !isMobile && (@@ -2044,6 +2094,7 @@ export default function ObservationsEventsTable({setRowHeight={setRowHeight}timeRange={showControlsInPageHeader ? undefined : timeRange}setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}+ preColumnsSlot={pulseReopenButton ?? undefined}viewModeToggle={chartEnabled ? (<ViewModeToggle@@ -2175,6 +2226,21 @@ export default function ObservationsEventsTable({)}<div className="flex flex-1 flex-col overflow-hidden">+ {/* Pulse strip (LFE-14451): table-width, so the facet sidebar keeps+ its full height (design feedback); hidden in full chart mode. */}+ {outlierStripEnabled &&+ chartViewMode !== "chart" &&+ !pulseClosed && (+ <EventsOutlierStrip+ projectId={projectId}+ filterState={filterState}+ fromTimestamp={chartTimeWindow.from}+ toTimestamp={chartTimeWindow.to}+ searchIgnored={Boolean(searchQuery)}+ onSelectRange={setTimeRangeTransient}+ onClose={() => setPulseClosed(true)}+ />+ )}{chartEnabled && chartViewMode === "chart" ? (<EventsChartViewprojectId={projectId}diff --git a/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsx b/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsxnew file mode 100644index 0000000000..5f482c7dbf--- /dev/null+++ b/web/src/features/events/components/outlier-strip/EventsOutlierStrip.tsx@@ -0,0 +1,478 @@+import { useMemo, useRef, useState } from "react";+import { ChevronDown, X } from "lucide-react";+import { type FilterState, type QueryType } from "@langfuse/shared";+import { api } from "@/src/utils/api";+import { cn } from "@/src/utils/tailwind";+import { useElementSize } from "@/src/hooks/useElementSize";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { Button } from "@/src/components/ui/button";+import {+ chartFilterExclusionReason,+ toChartFilters,+} from "@/src/features/chart-view/lib/chartFilterCompatibility";+import { OutlierBarStrip } from "./OutlierBarStrip";+import {+ OUTLIER_STRIP_METRICS,+ outlierStripQueryMetrics,+ pickChartGranularity,+ prepareOutlierSeries,+ rowsToOutlierBins,+ type OutlierQueryRow,+ type OutlierStripAggKey,+ type OutlierStripMetricKey,+} from "./lib/binning";+import {+ useOutlierStripSettings,+ type OutlierStripSettings,+} from "./lib/useOutlierStripSettings";++/**+ * Production container for the outlier strip ("Pulse") above the events table+ * (LFE-14451). Open by default; the X hands control back to the caller, which+ * re-opens it via a toolbar "Pulse" button. One `dashboard.executeQuery` call+ * fetches count + every registered aggregate per time bucket (see the metric+ * registry in lib/binning.ts), so switching metrics, aggregations, or the+ * multi-chart layout never refetches. Bucket width adapts to the measured+ * width (space calculator β granularity preset). Clicking a bar narrows the+ * table's time range to that bucket; the browser Back button restores the+ * outer view.+ *+ * Filters forward exactly like the in-view chart (`toChartFilters`); filters+ * the aggregate query can't express are disclosed by a small "not applied"+ * hint on the strip (unlike chart mode's sidebar dimming: here the TABLE+ * still honors those filters, only the strip doesn't).+ */++/** Target horizontal pixels per bar for granularity picking. */+const BAR_SLOT_TARGET_PX = 5;+/** Each chart needs this much width for Split (all three) to be offered. */+const CHART_MIN_WIDTH_PX = 400;+const CHART_GAP_PX = 24;++const SPLIT_METRICS: OutlierStripMetricKey[] = ["cost", "latency", "tokens"];++type StripMode = OutlierStripSettings["mode"];++const modeLabel = (mode: StripMode): string =>+ mode === "split" ? "Split" : OUTLIER_STRIP_METRICS[mode].shortLabel;++/**+ * Prevent Radix's close-refocus ONLY after a pointer-driven selection β the+ * programmatic refocus renders as a keyboard-style outline on the trigger.+ * Escape / click-outside / keyboard selection keep the default focus return+ * so keyboard users aren't dropped onto <body> (mirrors ChatMessages,+ * LFE-6864).+ */+const usePointerSelectionFocusGuard = () => {+ const selectedViaPointerRef = useRef(false);+ return {+ markPointerSelection: (event: { detail: number }) => {+ // Keyboard-synthesized clicks carry detail 0; real pointer clicks β₯ 1.+ if (event.detail > 0) selectedViaPointerRef.current = true;+ },+ onCloseAutoFocus: (event: Event) => {+ if (selectedViaPointerRef.current) {+ event.preventDefault();+ selectedViaPointerRef.current = false;+ }+ },+ };+};++const AggDropdown = ({+ metricLabel,+ value,+ options,+ onChange,+}: {+ metricLabel: string;+ value: OutlierStripAggKey;+ options: readonly OutlierStripAggKey[];+ onChange: (agg: OutlierStripAggKey) => void;+}) => {+ const focusGuard = usePointerSelectionFocusGuard();+ return (+ <span className="flex items-baseline gap-1">+ {/* The separator dot stays outside the trigger so hover styling+ (underline) applies to the value only. */}+ <span className="text-muted-foreground font-mono text-[11px] leading-none">+ Β·+ </span>+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={`${metricLabel} aggregation: ${value}`}+ className="text-muted-foreground hover:text-foreground flex items-center gap-0.5 font-mono text-[11px] leading-none underline-offset-2 hover:underline"+ >+ {value}+ <ChevronDown className="h-2.5 w-2.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ onCloseAutoFocus={focusGuard.onCloseAutoFocus}+ >+ {options.map((agg) => (+ <DropdownMenuItem+ key={agg}+ onClick={(event) => {+ focusGuard.markPointerSelection(event);+ onChange(agg);+ }}+ className="font-mono text-xs"+ >+ {agg}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </span>+ );+};++const ModeDropdown = ({+ value,+ options,+ onChange,+}: {+ value: StripMode;+ options: StripMode[];+ onChange: (mode: StripMode) => void;+}) => {+ const focusGuard = usePointerSelectionFocusGuard();+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={`Chart mode: ${modeLabel(value)}`}+ className="text-foreground hover:text-muted-foreground flex items-center gap-0.5 font-mono text-[11px] leading-none font-bold"+ >+ {modeLabel(value)}+ <ChevronDown className="h-2.5 w-2.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ onCloseAutoFocus={focusGuard.onCloseAutoFocus}+ >+ {options.map((mode) => (+ <DropdownMenuItem+ key={mode}+ onClick={(event) => {+ focusGuard.markPointerSelection(event);+ onChange(mode);+ }}+ className="font-mono text-xs"+ >+ {modeLabel(mode)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};++/** Filters the strip's aggregate query cannot express β excluding the ones+ * whose dropping is by design (the explicit from/to carries startTime; root+ * scoping is deliberately ignored per the LFE-14451 product call).+ * `has:`/`-has:` presence filters (type "null") are dropped by toChartFilters+ * even on forwardable columns, so they count regardless of column. */+const countIgnoredFilters = (filterState: FilterState): number =>+ filterState.filter(+ (f) =>+ !(f.type === "datetime" && f.column === "startTime") &&+ f.column !== "isRootObservation" &&+ f.column !== "hasParentObservation" &&+ (f.type === "null" || chartFilterExclusionReason(f.column) !== null),+ ).length;++export function EventsOutlierStrip({+ projectId,+ filterState,+ fromTimestamp,+ toTimestamp,+ searchIgnored = false,+ onSelectRange,+ onClose,+}: {+ projectId: string;+ filterState: FilterState;+ fromTimestamp: Date;+ toTimestamp: Date;+ /** The table has an active free-text search the strip cannot apply. */+ searchIgnored?: boolean;+ onSelectRange: (range: { from: Date; to: Date }) => void;+ onClose: () => void;+}) {+ const [wrapperRef, size] = useElementSize<HTMLDivElement>();+ // Transient drag selection, shared across the sibling charts so a drag on+ // one strip highlights the same time span on all (LFE-14532, Grafana-style).+ // Window-keyed: a range/granularity change (drill, browser back/forward)+ // invalidates a lingering band by derivation.+ const [dragSelection, setDragSelection] = useState<{+ fromMs: number;+ toMs: number;+ windowKey: string;+ } | null>(null);+ const { settings, update } = useOutlierStripSettings();++ const fromMs = fromTimestamp.getTime();+ const toMs = toTimestamp.getTime();+ const validRange = fromMs < toMs;+ // getBoundingClientRect includes the wrapper's px-2 padding (border-box).+ const width = Math.max((size?.width ?? 0) - 16, 0);++ // Split adapts: 3 charts when they fit, 2 (Cost + Latency) on smaller+ // widths, and only below the 2-chart threshold does Split leave the menu.+ // A stored Split preference degrades to Cost WITHOUT being overwritten.+ const splitChartCount = Math.min(+ SPLIT_METRICS.length,+ Math.floor((width + CHART_GAP_PX) / (CHART_MIN_WIDTH_PX + CHART_GAP_PX)),+ );+ const splitFits = splitChartCount >= 2;+ const mode: StripMode =+ settings.mode === "split" && !splitFits ? "cost" : settings.mode;+ const modeOptions: StripMode[] = splitFits+ ? [...SPLIT_METRICS, "split"]+ : [...SPLIT_METRICS];++ const visibleMetrics: OutlierStripMetricKey[] =+ mode === "split" ? SPLIT_METRICS.slice(0, splitChartCount) : [mode];+ const chartCount = visibleMetrics.length;+ const chartWidth = (width - CHART_GAP_PX * (chartCount - 1)) / chartCount;++ const granularity = pickChartGranularity({+ rangeMs: toMs - fromMs,+ widthPx: Math.max(chartWidth, 1),+ barSlotPx: BAR_SLOT_TARGET_PX,+ });++ const filters = useMemo(() => toChartFilters(filterState), [filterState]);+ const ignoredFilterCount =+ countIgnoredFilters(filterState) + (searchIgnored ? 1 : 0);++ const query: QueryType = useMemo(+ () => ({+ view: "observations",+ dimensions: [],+ // Every registered aggregate in one scan (registry-derived), so metric+ // and aggregation switching never refetch.+ metrics: outlierStripQueryMetrics(),+ filters,+ timeDimension: { granularity: granularity.granularity },+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ // Must stay null: an orderBy disables the WITH FILL densification.+ orderBy: null,+ }),+ [filters, granularity.granularity, fromTimestamp, toTimestamp],+ );++ const queryResult = api.dashboard.executeQuery.useQuery(+ { projectId, query, version: "v2" },+ {+ // Wait for the first width measurement β it decides the bucket size.+ enabled: validRange && width > 0,+ // Keep the previous bins on refetch (auto-refresh ticks re-key the query+ // via the re-evaluated relative window) β a persistent band must not+ // flash to a skeleton every interval.+ placeholderData: (prev) => prev,+ meta: { silentHttpCodes: [422] },+ trpc: { context: { skipBatch: true } },+ },+ );++ const bins = useMemo(+ () =>+ queryResult.data+ ? rowsToOutlierBins(queryResult.data as OutlierQueryRow[])+ : [],+ [queryResult.data],+ );++ const aggregationFor = (metric: OutlierStripMetricKey): OutlierStripAggKey =>+ metric === "latency"+ ? settings.latencyAgg+ : metric === "cost"+ ? settings.costAgg+ : "max";++ const series = useMemo(+ () =>+ (mode === "split" ? SPLIT_METRICS.slice(0, splitChartCount) : [mode]).map(+ (metric) =>+ prepareOutlierSeries({+ bins,+ metric,+ aggregation:+ metric === "latency"+ ? settings.latencyAgg+ : metric === "cost"+ ? settings.costAgg+ : "max",+ fromMs,+ toMs,+ stepSeconds: granularity.stepSeconds,+ widthPx: chartWidth,+ }),+ ),+ [+ bins,+ fromMs,+ toMs,+ granularity.stepSeconds,+ mode,+ splitChartCount,+ settings.latencyAgg,+ settings.costAgg,+ chartWidth,+ ],+ );++ const handleSelectBucket = (range: { fromMs: number; toMs: number }) => {+ onSelectRange({ from: new Date(range.fromMs), to: new Date(range.toMs) });+ };++ const setAggregation = (+ metric: OutlierStripMetricKey,+ agg: OutlierStripAggKey,+ ) => {+ if (metric === "latency") {+ update({ latencyAgg: agg as OutlierStripSettings["latencyAgg"] });+ } else if (metric === "cost") {+ update({ costAgg: agg as OutlierStripSettings["costAgg"] });+ }+ };++ const stepMs = granularity.stepSeconds * 1000;+ const selectionWindowKey = `${fromMs}:${toMs}:${stepMs}`;+ const activeSelection =+ dragSelection && dragSelection.windowKey === selectionWindowKey+ ? dragSelection+ : null;+ const handleSelectionChange = (+ range: { fromMs: number; toMs: number } | null,+ ) =>+ setDragSelection(+ range ? { ...range, windowKey: selectionWindowKey } : null,+ );+ // Held-over bins from a different window can miss the new grid entirely;+ // that must render as "loading", never as a false "No events in range".+ const placeholderMissesGrid =+ queryResult.isPlaceholderData &&+ series.every(+ (s) => s.maxValue === 0 && s.dense.every((bin) => bin.count === 0),+ );+ const isLoading =+ validRange &&+ width > 0 &&+ ((queryResult.isPending && !queryResult.isError) || placeholderMissesGrid);++ // First paint renders nothing inside the measuring wrapper: the bucket size+ // needs the width, so painting before the first measurement would flash a+ // skeleton sized for nothing.+ return (+ <div ref={wrapperRef} className="shrink-0 border-b">+ {size === undefined ? null : (+ <div className="relative px-2 pt-1 pb-1">+ <Button+ variant="ghost"+ size="icon"+ aria-label="Close Pulse chart"+ onClick={onClose}+ className="text-muted-foreground absolute top-0.5 right-1 z-[1] h-6 w-6"+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ {isLoading || width === 0 ? (+ <div className="bg-muted h-[76px] animate-pulse rounded" />+ ) : queryResult.isError ? (+ <div className="text-muted-foreground flex h-[76px] items-center justify-center text-[11px]">+ Could not load the outlier chart for the current view.+ </div>+ ) : (+ <div+ // Dim held-over bins during a refetch (filter change, saved-view+ // switch, drill-in) β stale data must not read as current.+ className={cn(+ "flex transition-opacity",+ queryResult.isPlaceholderData &&+ queryResult.isFetching &&+ "opacity-60",+ )}+ style={{ gap: CHART_GAP_PX }}+ >+ {visibleMetrics.map((metric, slot) => {+ const def = OUTLIER_STRIP_METRICS[metric];+ const aggOptions = def.aggregations.map((agg) => agg.key);+ return (+ <div key={slot} className="min-w-0">+ <div className="flex items-baseline gap-1.5">+ {slot === 0 ? (+ <>+ <ModeDropdown+ value={mode}+ options={modeOptions}+ onChange={(next) => update({ mode: next })}+ />+ {mode === "split" && (+ <span className="text-muted-foreground font-mono text-[11px] leading-none">+ {def.shortLabel}+ </span>+ )}+ </>+ ) : (+ <span className="text-muted-foreground font-mono text-[11px] leading-none">+ {def.shortLabel}+ </span>+ )}+ {/* The bar's aggregate must be legible (max vs p95, β¦);+ single-option metrics render it statically. */}+ {aggOptions.length > 1 ? (+ <AggDropdown+ metricLabel={def.shortLabel}+ value={aggregationFor(metric)}+ options={aggOptions}+ onChange={(agg) => setAggregation(metric, agg)}+ />+ ) : (+ <span className="text-muted-foreground/70 font-mono text-[11px] leading-none">+ Β· {aggOptions[0]}+ </span>+ )}+ {/* Unlike full chart mode (which dims sidebar facets),+ the TABLE still honors these filters β only the strip+ can't express them, so the disclosure lives here. */}+ {slot === 0 && ignoredFilterCount > 0 && (+ <span+ className="text-muted-foreground/70 font-mono text-[11px] leading-none"+ title="Some active filters (measures, scores, comments, metadata, free-text search) cannot be applied to this chart's aggregate query. The table still honors them; the chart shows the unfiltered distribution for those."+ >+ Β· {ignoredFilterCount} filter+ {ignoredFilterCount > 1 ? "s" : ""} not applied+ </span>+ )}+ </div>+ <OutlierBarStrip+ className="mt-1"+ dense={series[slot].dense}+ maxValue={series[slot].maxValue}+ ticks={series[slot].ticks}+ stepMs={stepMs}+ metric={metric}+ widthPx={chartWidth}+ onSelectBucket={handleSelectBucket}+ selection={activeSelection}+ onSelectionChange={handleSelectionChange}+ />+ </div>+ );+ })}+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/web/src/features/events/components/outlier-strip/OutlierBarStrip.stories.tsx b/web/src/features/events/components/outlier-strip/OutlierBarStrip.stories.tsxnew file mode 100644index 0000000000..d36692d6fb--- /dev/null+++ b/web/src/features/events/components/outlier-strip/OutlierBarStrip.stories.tsx@@ -0,0 +1,140 @@+import { fn } from "storybook/test";+import preview from "../../../../../.storybook/preview";+import { OutlierBarStrip } from "./OutlierBarStrip";+import { makeFixtureSeries } from "./lib/fixtures";++/**+ * Design surface for the outlier strip above the trace table (LFE-14451).+ * Every bar is the WORST single event in its time bucket (max cost / latency+ * / tokens) β the strip exists to click into spikes, so the visual must read+ * at a glance: compact, Firefox-devtools-inspired, values on hover only,+ * sparse gridline ticks, a baseline that keeps the plot boundary visible+ * where data is absent.+ *+ * Locked defaults (design review 2026-07-27): sqrt scale, 40px height.+ */++const spikyCost = makeFixtureSeries({+ rangeMs: 24 * 3600 * 1000,+ stepSeconds: 600,+ profile: "spiky",+ metric: "cost",+ widthPx: 720,+});++const meta = preview.meta({+ component: OutlierBarStrip,+ args: {+ onSelectBucket: fn(),+ },+});++export const Default = meta.story({+ args: {+ ...spikyCost,+ metric: "cost",+ },+});++/** Real outliers are 10β40x the base load: linear scale crushes the base into+ * a barely-visible baseline; sqrt (the locked default) keeps the base+ * readable while spikes still dominate. */+export const ScaleMatrix = meta.story({+ render: () => (+ <div className="flex flex-col gap-5 p-2">+ {(["linear", "sqrt"] as const).map((scale) => (+ <div key={scale}>+ <div className="text-muted-foreground mb-1 font-mono text-[10px]">+ scale: {scale}+ </div>+ <OutlierBarStrip {...spikyCost} metric="cost" scale={scale} />+ </div>+ ))}+ </div>+ ),+});++export const HeightMatrix = meta.story({+ render: () => (+ <div className="flex flex-col gap-5 p-2">+ {[40, 56, 72].map((height) => (+ <div key={height}>+ <div className="text-muted-foreground mb-1 font-mono text-[10px]">+ height {height}px+ </div>+ <OutlierBarStrip {...spikyCost} metric="cost" heightPx={height} />+ </div>+ ))}+ </div>+ ),+});++/** The β₯1200px layout: three 400px charts side by side. */+export const ThreeUp = meta.story({+ render: () => {+ const fixture = (metric: "cost" | "latency" | "tokens") =>+ makeFixtureSeries({+ rangeMs: 24 * 3600 * 1000,+ stepSeconds: 1800,+ profile: "spiky",+ metric,+ widthPx: 400,+ });+ return (+ <div className="flex gap-6 p-2">+ <OutlierBarStrip {...fixture("cost")} metric="cost" />+ <OutlierBarStrip {...fixture("latency")} metric="latency" />+ <OutlierBarStrip {...fixture("tokens")} metric="tokens" />+ </div>+ );+ },+});++export const BurstyWeek = meta.story({+ args: {+ ...makeFixtureSeries({+ rangeMs: 7 * 24 * 3600 * 1000,+ stepSeconds: 3600,+ profile: "bursty",+ metric: "latency",+ widthPx: 900,+ }),+ metric: "latency",+ },+});++export const SparseData = meta.story({+ args: {+ ...makeFixtureSeries({+ rangeMs: 24 * 3600 * 1000,+ stepSeconds: 600,+ profile: "sparse",+ metric: "tokens",+ widthPx: 720,+ }),+ metric: "tokens",+ },+});++/** Events exist but carry no cost data (e.g. root-only shapes) β the strip+ * shows activity ticks + an honest hint instead of a fake-zero skyline. */+export const NoMetricData = meta.story({+ args: {+ ...makeFixtureSeries({+ rangeMs: 24 * 3600 * 1000,+ stepSeconds: 600,+ profile: "noMetricData",+ metric: "cost",+ widthPx: 720,+ }),+ metric: "cost",+ },+});++export const MinimalNoLabels = meta.story({+ args: {+ ...spikyCost,+ metric: "cost",+ showTimeLabels: false,+ },+});diff --git a/web/src/features/events/components/outlier-strip/OutlierBarStrip.tsx b/web/src/features/events/components/outlier-strip/OutlierBarStrip.tsxnew file mode 100644index 0000000000..47a28c13b6--- /dev/null+++ b/web/src/features/events/components/outlier-strip/OutlierBarStrip.tsx@@ -0,0 +1,528 @@+import { useMemo, useRef, useState } from "react";+import { cn } from "@/src/utils/tailwind";+import { X } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Layer } from "@/src/components/ui/layer";+import {+ formatBucketRange,+ OUTLIER_STRIP_METRICS,+ type OutlierStripDenseBin,+ type OutlierStripMetricKey,+ type OutlierStripTick,+} from "./lib/binning";++/**+ * OutlierBarStrip β compact, Firefox-devtools-inspired bar strip (LFE-14451).+ * Pure visualiser: renders the dense series `prepareOutlierSeries` produced+ * and decides nothing about data. Every bar is the worst single event in its+ * time bucket; clicking a bar reports the bucket's range so the caller can+ * narrow the table's time window.+ *+ * The strip always spans the full `widthPx` (fractional bar slots), with a+ * baseline and sparse vertical gridline ticks so the chart's boundaries stay+ * visible even where the range holds no data.+ */++const METRIC_COLOR: Record<OutlierStripMetricKey, string> = {+ cost: "hsl(var(--chart-1))",+ latency: "hsl(var(--chart-2))",+ tokens: "hsl(var(--chart-4))",+};++/** Pointer travel before a press becomes a range-drag instead of a click. */+const DRAG_THRESHOLD_PX = 5;++export type OutlierBarStripProps = {+ dense: OutlierStripDenseBin[];+ /** Max metric value across buckets (0 = no data anywhere). */+ maxValue: number;+ stepMs: number;+ metric: OutlierStripMetricKey;+ /** Full plot width; bars stretch/shrink to span it exactly. */+ widthPx: number;+ /** Prepared gridline ticks ({@link prepareOutlierSeries}). */+ ticks: OutlierStripTick[];+ /** Height of the bar canvas, labels excluded. */+ heightPx?: number;+ /**+ * Bar-height scale. Real cost/latency outliers are 10β40x the base load β+ * linear renders the base nearly invisible; sqrt (default) keeps it+ * readable while outliers still dominate.+ */+ scale?: "linear" | "sqrt";+ /** 1px baseline tick where events exist but carry no metric data. */+ showActivityTicks?: boolean;+ /** Sparse time labels under the gridline ticks. */+ showTimeLabels?: boolean;+ onSelectBucket?: (range: { fromMs: number; toMs: number }) => void;+ /** Transient drag selection (ms range), shared across sibling charts so a+ * drag on one strip highlights on all (LF-34, Grafana-style). */+ selection?: { fromMs: number; toMs: number } | null;+ onSelectionChange?: (range: { fromMs: number; toMs: number } | null) => void;+ className?: string;+};++export function OutlierBarStrip({+ dense,+ maxValue,+ stepMs,+ metric,+ widthPx,+ ticks,+ // Defaults locked by design review: sqrt scale keeps the base load+ // readable under 10-40x outliers; 50px height tuned 2026-07-28.+ heightPx = 50,+ scale = "sqrt",+ showActivityTicks = true,+ showTimeLabels = true,+ onSelectBucket,+ selection = null,+ onSelectionChange,+ className,+}: OutlierBarStripProps) {+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);+ const [mouse, setMouse] = useState<{ x: number; y: number } | null>(null);+ // Touch model: taps and drags PREVIEW (pinned tooltip with an explicit+ // Explore action) instead of navigating β accidental touches must never+ // change the table's range. A tap previews one bucket, a drag previews the+ // selected span. Anchor is captured in viewport coords at the gesture;+ // `windowKey` pins the preview to the bucket grid it was captured on, so+ // any range/granularity change (drill-in, browser back/forward) invalidates+ // it by derivation β no effects.+ const [touchPreview, setTouchPreview] = useState<{+ fromMs: number;+ toMs: number;+ anchorX: number;+ anchorY: number;+ windowKey: string;+ } | null>(null);+ // Drag gesture bookkeeping lives in a ref: pointermove during a drag only+ // updates the SHARED selection via onSelectionChange, never local state.+ const dragRef = useRef<{ startX: number; dragging: boolean } | null>(null);++ const metricSpec = OUTLIER_STRIP_METRICS[metric];+ const color = METRIC_COLOR[metric];+ const binCount = Math.max(dense.length, 1);+ // Fractional slots: the plot always spans the full width, so empty regions+ // read as "chart with no data here" instead of trailing whitespace.+ const slotPx = widthPx / binCount;+ // Exactly 1px between bars, square corners (design review 2026-07-27).+ const barWidth = Math.max(slotPx - 1, 0.5);+ // Bars sit ON the 1px baseline, never across it.+ const plotHeight = heightPx - 1;+ const labelHeight = showTimeLabels ? 13 : 0;+ const hasData = maxValue > 0;+ const hasActivity = dense.some((bin) => bin.count > 0);++ // Maps a dragged pixel span to a bucket-snapped ms range.+ const spanToRange = (x1: number, x2: number) => {+ const clamp = (x: number) =>+ Math.min(Math.max(x, 0), Math.max(widthPx - 1, 0));+ const startIdx = Math.min(+ Math.floor(clamp(Math.min(x1, x2)) / slotPx),+ binCount - 1,+ );+ const endIdx = Math.min(+ Math.floor(clamp(Math.max(x1, x2)) / slotPx),+ binCount - 1,+ );+ const startMs = dense[startIdx]?.bucketStartMs ?? 0;+ const endMs = (dense[endIdx]?.bucketStartMs ?? 0) + stepMs;+ return { fromMs: startMs, toMs: endMs };+ };++ // The static plot (ticks, baseline, bars, labels) reconciles hundreds of+ // SVG nodes; memoized so cursor-follow tooltip renders (every mousemove)+ // only touch the crosshair + tooltip.+ const staticLayers = useMemo(() => {+ const barHeight = (value: number) => {+ // Corrupt data (e.g. end_time < start_time) must not NaN the height.+ const fraction = Math.max(value, 0) / maxValue;+ const scaled = scale === "sqrt" ? Math.sqrt(fraction) : fraction;+ return Math.max(1.5, scaled * plotHeight);+ };+ return (+ <>+ {/* Sparse vertical gridline ticks (Firefox-devtools style) */}+ {ticks.map((tick) => (+ <line+ key={`tick-${tick.index}`}+ x1={tick.index * slotPx}+ y1={0}+ x2={tick.index * slotPx}+ y2={plotHeight}+ className="stroke-foreground"+ strokeWidth={1}+ opacity={0.07}+ />+ ))}++ {/* Plot baseline: the chart's boundary stays visible without data */}+ <line+ x1={0}+ y1={heightPx - 0.5}+ x2={widthPx}+ y2={heightPx - 0.5}+ className="stroke-border"+ strokeWidth={1}+ />++ {/* Bars */}+ {dense.map((bin, i) => {+ if (bin.value === null) {+ // Events without metric data get a subtle activity tick so the+ // strip never reads "nothing happened" when data is merely absent.+ return showActivityTicks && bin.count > 0 ? (+ <rect+ key={i}+ x={i * slotPx}+ y={plotHeight - 1.5}+ width={barWidth}+ height={1.5}+ className="fill-muted-foreground"+ opacity={0.6}+ />+ ) : null;+ }+ const h = hasData ? barHeight(bin.value) : 0;+ return (+ <rect+ key={i}+ x={i * slotPx}+ y={plotHeight - h}+ width={barWidth}+ height={h}+ fill={color}+ opacity={0.8}+ />+ );+ })}++ {/* Sparse time labels on the tick grid */}+ {showTimeLabels &&+ ticks.map((tick) => (+ <text+ key={`label-${tick.index}`}+ x={tick.index * slotPx + 3}+ y={heightPx + 9}+ className="fill-muted-foreground/80 font-mono"+ fontSize={9}+ >+ {tick.label}+ </text>+ ))}+ </>+ );+ }, [+ dense,+ slotPx,+ barWidth,+ heightPx,+ plotHeight,+ widthPx,+ color,+ ticks,+ maxValue,+ scale,+ hasData,+ showActivityTicks,+ showTimeLabels,+ ]);++ // ?? null: a stale hoverIndex can outlive a shrinking dense array (data or+ // granularity change mid-hover), and undefined slips past a !== null check.+ const hovered = hoverIndex !== null ? (dense[hoverIndex] ?? null) : null;+ const hoveredHasData =+ hovered !== null && (hovered.count > 0 || hovered.value !== null);+ const windowKey = `${stepMs}:${dense[0]?.bucketStartMs ?? 0}:${dense.length}`;+ const activePreview =+ touchPreview && touchPreview.windowKey === windowKey ? touchPreview : null;+ // Aggregate stats over the previewed span (a tap's span is one bucket).+ const previewStats = activePreview+ ? dense.reduce(+ (acc, bin) => {+ if (+ bin.bucketStartMs >= activePreview.fromMs &&+ bin.bucketStartMs < activePreview.toMs+ ) {+ acc.count += bin.count;+ if (bin.value !== null) {+ acc.value =+ acc.value === null ? bin.value : Math.max(acc.value, bin.value);+ }+ }+ return acc;+ },+ { count: 0, value: null as number | null },+ )+ : null;+ const previewHasData =+ previewStats !== null &&+ (previewStats.count > 0 || previewStats.value !== null);++ return (+ <div className={cn("relative", className)} style={{ width: widthPx }}>+ <svg+ width={widthPx}+ height={heightPx + labelHeight}+ role="img"+ aria-label={`${metricSpec.shortLabel} (max / bucket)`}+ className={cn(+ // pan-y: horizontal touch drags select a range; vertical stays with+ // the page scroll (LF-34 mobile gesture requirement). select-none ++ // the pointerdown preventDefault keep a range-drag from ALSO+ // starting a native text selection over the tick labels.+ "block touch-pan-y select-none",+ hoveredHasData || selection ? "cursor-pointer" : "cursor-default",+ )}+ onPointerLeave={(event) => {+ if (event.pointerType !== "mouse") return;+ setHoverIndex(null);+ setMouse(null);+ }}+ onPointerDown={(event) => {+ if (event.button !== 0 && event.pointerType === "mouse") return;+ // A drag must not double as a native text-selection drag.+ event.preventDefault();+ const rect = event.currentTarget.getBoundingClientRect();+ dragRef.current = {+ startX: event.clientX - rect.left,+ dragging: false,+ };+ event.currentTarget.setPointerCapture(event.pointerId);+ }}+ onPointerMove={(event) => {+ const rect = event.currentTarget.getBoundingClientRect();+ const x = event.clientX - rect.left;+ if (event.pointerType === "mouse") {+ // Cursor hover: crosshair + follow-tooltip (touch never hovers β+ // its compat mouse events would pin a stale tooltip after taps).+ const index = Math.floor(x / slotPx);+ setHoverIndex(index >= 0 && index < dense.length ? index : null);+ setMouse({ x: event.clientX, y: event.clientY });+ }+ const drag = dragRef.current;+ if (!drag) return;+ if (!drag.dragging && Math.abs(x - drag.startX) < DRAG_THRESHOLD_PX) {+ return;+ }+ if (!drag.dragging) setTouchPreview(null);+ drag.dragging = true;+ onSelectionChange?.(spanToRange(drag.startX, x));+ }}+ onPointerUp={(event) => {+ const drag = dragRef.current;+ dragRef.current = null;+ if (!drag) return;+ const rect = event.currentTarget.getBoundingClientRect();+ const x = event.clientX - rect.left;+ if (drag.dragging) {+ const range = spanToRange(drag.startX, x);+ if (event.pointerType !== "mouse") {+ // Touch: keep the selection band and offer an explicit Explore+ // instead of applying on release.+ setTouchPreview({+ ...range,+ anchorX: rect.left + (drag.startX + x) / 2,+ anchorY: rect.top,+ windowKey,+ });+ return;+ }+ // Mouse, Grafana-style: apply the dragged span to the range.+ onSelectionChange?.(null);+ setTouchPreview(null);+ onSelectBucket?.(range);+ return;+ }+ const index = Math.floor(x / slotPx);+ const bin = dense[index];+ if (!bin) return;+ if (event.pointerType !== "mouse") {+ // Touch tap = PREVIEW: pin the tooltip over the bucket; the+ // tooltip's Explore action performs the navigation.+ setTouchPreview({+ fromMs: bin.bucketStartMs,+ toMs: bin.bucketStartMs + stepMs,+ anchorX: rect.left + (index + 0.5) * slotPx,+ anchorY: rect.top,+ windowKey,+ });+ setHoverIndex(index);+ setMouse(null);+ return;+ }+ // Mouse click without movement drills into the bucket. Mirror the+ // tooltip's guard β a truly empty bucket would just drill the table+ // into a zero-row window.+ if ((bin.count > 0 || bin.value !== null) && onSelectBucket) {+ onSelectBucket({+ fromMs: bin.bucketStartMs,+ toMs: bin.bucketStartMs + stepMs,+ });+ }+ }}+ onPointerCancel={() => {+ dragRef.current = null;+ onSelectionChange?.(null);+ }}+ >+ {staticLayers}++ {/* Shared drag-selection overlay (LF-34) */}+ {selection &&+ (() => {+ const first = dense[0]?.bucketStartMs;+ if (first === undefined) return null;+ const startX = ((selection.fromMs - first) / stepMs) * slotPx;+ const endX = ((selection.toMs - first) / stepMs) * slotPx;+ const x = Math.max(startX, 0);+ const w = Math.min(endX, widthPx) - x;+ if (w <= 0) return null;+ return (+ <rect+ x={x}+ y={0}+ width={w}+ height={plotHeight}+ className="fill-foreground"+ opacity={0.12}+ />+ );+ })()}++ {/* Hover crosshair column */}+ {hoverIndex !== null && (+ <rect+ x={hoverIndex * slotPx}+ y={0}+ width={slotPx}+ height={heightPx}+ className="fill-foreground"+ opacity={0.08}+ />+ )}+ </svg>++ {!hasData && (+ <span className="text-muted-foreground/70 pointer-events-none absolute inset-0 flex items-center justify-center text-[10px]">+ {hasActivity+ ? `No ${metricSpec.shortLabel.toLowerCase()} data in range`+ : "No events in range"}+ </span>+ )}++ {/* Tooltip β portals to the overlay tooltip layer so it can escape the+ band's ancestors (overflow clipping, sticky-toolbar stacking) and+ float freely at the cursor's top-right. */}+ {hovered && mouse && !activePreview && (+ <Layer name="tooltip">+ <div+ className="bg-popover text-popover-foreground pointer-events-none fixed rounded border px-1.5 py-1 font-mono text-[11px] leading-tight whitespace-nowrap shadow-sm"+ style={+ // Top-right of the cursor; flips to top-left near the viewport's+ // right edge so it never runs off screen.+ mouse.x + 200 > window.innerWidth+ ? {+ left: mouse.x - 10,+ top: mouse.y - 8,+ transform: "translate(-100%, -100%)",+ }+ : {+ left: mouse.x + 10,+ top: mouse.y - 8,+ transform: "translateY(-100%)",+ }+ }+ >+ <div className="text-muted-foreground">+ {formatBucketRange(hovered.bucketStartMs, stepMs)}+ </div>+ <div className="font-bold">+ {hovered.value !== null+ ? metricSpec.format(hovered.value)+ : hovered.count > 0+ ? "no data"+ : metricSpec.format(0)}+ <span className="text-muted-foreground ml-1.5 font-normal">+ Β· {hovered.count} events+ </span>+ </div>+ </div>+ </Layer>+ )}++ {/* Touch preview β pinned above the tapped bucket or dragged span, with+ an explicit Explore action so an accidental touch never changes the+ range. */}+ {activePreview && previewStats && (+ <Layer name="tooltip">+ <div+ className="bg-popover text-popover-foreground fixed rounded border px-2 py-1.5 font-mono text-[11px] leading-tight whitespace-nowrap shadow-md"+ style={{+ left: Math.min(+ Math.max(activePreview.anchorX, 90),+ typeof window !== "undefined"+ ? window.innerWidth - 90+ : activePreview.anchorX,+ ),+ top: activePreview.anchorY - 6,+ transform: "translate(-50%, -100%)",+ }}+ >+ <div className="flex items-start justify-between gap-3">+ <div>+ <div className="text-muted-foreground">+ {formatBucketRange(+ activePreview.fromMs,+ activePreview.toMs - activePreview.fromMs,+ )}+ </div>+ <div className="font-bold">+ {previewStats.value !== null+ ? metricSpec.format(previewStats.value)+ : previewStats.count > 0+ ? "no data"+ : metricSpec.format(0)}+ <span className="text-muted-foreground ml-1.5 font-normal">+ Β· {previewStats.count} events+ </span>+ </div>+ </div>+ <button+ type="button"+ aria-label="Dismiss preview"+ className="text-muted-foreground -mt-0.5 -mr-0.5 p-0.5"+ onClick={() => {+ setTouchPreview(null);+ setHoverIndex(null);+ onSelectionChange?.(null);+ }}+ >+ <X className="h-3 w-3" />+ </button>+ </div>+ {previewHasData && (+ <Button+ size="sm"+ className="mt-1.5 h-6 w-full text-[10px]"+ onClick={() => {+ const range = {+ fromMs: activePreview.fromMs,+ toMs: activePreview.toMs,+ };+ setTouchPreview(null);+ setHoverIndex(null);+ onSelectionChange?.(null);+ onSelectBucket?.(range);+ }}+ >+ Explore this window+ </Button>+ )}+ </div>+ </Layer>+ )}+ </div>+ );+}diff --git a/web/src/features/events/components/outlier-strip/lib/binning.clienttest.ts b/web/src/features/events/components/outlier-strip/lib/binning.clienttest.tsnew file mode 100644index 0000000000..aba77fe82d--- /dev/null+++ b/web/src/features/events/components/outlier-strip/lib/binning.clienttest.ts@@ -0,0 +1,252 @@+import { describe, it, expect } from "vitest";+import {+ OUTLIER_STRIP_METRICS,+ outlierStripQueryMetrics,+ outlierStripResultColumn,+ pickChartGranularity,+ prepareOutlierSeries,+ rowsToOutlierBins,+ type OutlierStripBin,+} from "./binning";++describe("pickChartGranularity", () => {+ it("picks the finest preset that fits the width", () => {+ // 24h into 200 slots (1000px / 5px): 10m (144 bars) fits, 5m (288) not.+ expect(+ pickChartGranularity({+ rangeMs: 24 * 3600 * 1000,+ widthPx: 1000,+ barSlotPx: 5,+ }),+ ).toEqual({ granularity: "10m", stepSeconds: 600 });+ });++ it("adapts to narrower widths with coarser presets", () => {+ // 24h into 60 slots: 30m (48 bars) fits, 15m (96) not.+ expect(+ pickChartGranularity({+ rangeMs: 24 * 3600 * 1000,+ widthPx: 300,+ barSlotPx: 5,+ }).granularity,+ ).toBe("30m");+ });++ it("falls back to the coarsest preset for extreme ranges", () => {+ // 2 years into 100 slots: even 1w gives 105 bars β accept the overflow.+ expect(+ pickChartGranularity({+ rangeMs: 730 * 86400 * 1000,+ widthPx: 500,+ barSlotPx: 5,+ }).granularity,+ ).toBe("1w");+ });++ it("caps requested buckets even on huge widths", () => {+ const { stepSeconds } = pickChartGranularity({+ rangeMs: 90 * 86400 * 1000,+ widthPx: 100_000,+ barSlotPx: 1,+ });+ expect((90 * 86400) / stepSeconds).toBeLessThanOrEqual(2000);+ });+});++describe("metric registry", () => {+ it("derives the query metrics from every registered aggregation", () => {+ const metrics = outlierStripQueryMetrics();+ expect(metrics).toContainEqual({ measure: "count", aggregation: "count" });+ // Every registry option maps to exactly one query metric β a new+ // aggregation option cannot exist without being fetched.+ for (const def of Object.values(OUTLIER_STRIP_METRICS)) {+ for (const agg of def.aggregations) {+ expect(metrics).toContainEqual({+ measure: def.measure,+ aggregation: agg.queryAggregation,+ });+ }+ }+ // count + 2 cost + 3 latency + 1 tokens+ expect(metrics).toHaveLength(7);+ });+});++describe("rowsToOutlierBins", () => {+ it("drops WITH FILL rows so non-nullable zero-fills never become phantom bars", () => {+ const bins = rowsToOutlierBins([+ {+ time_dimension: "2025-03-10 10:00:00",+ count_count: "2",+ max_totalCost: "0.5",+ sum_totalCost: "2.5",+ max_latency: "1500",+ p95_latency: "1000",+ avg_latency: "800",+ max_totalTokens: "300",+ },+ // ClickHouse WITH FILL filler: count 0, nullable measures null, but the+ // non-nullable tokens measure fills with its type default 0.+ {+ time_dimension: "2025-03-10 10:01:00",+ count_count: "0",+ max_totalCost: null,+ max_latency: null,+ max_totalTokens: "0",+ },+ ]);++ expect(bins).toHaveLength(1);+ expect(bins[0].count).toBe(2);+ expect(bins[0].values).toEqual({+ max_totalCost: 0.5,+ sum_totalCost: 2.5,+ max_latency: 1500,+ p95_latency: 1000,+ avg_latency: 800,+ max_totalTokens: 300,+ });+ });+});++describe("prepareOutlierSeries", () => {+ // Raw query units (latency in ms); derived values scale off `value`.+ const bin = (+ bucketStartMs: number,+ value: number | null,+ ): OutlierStripBin => ({+ bucketStart: new Date(bucketStartMs),+ count: value === null ? 0 : 1,+ values: {+ max_totalCost: value,+ sum_totalCost: value === null ? null : value * 10,+ max_latency: value === null ? null : value * 1000,+ p95_latency: value === null ? null : value * 500,+ avg_latency: value === null ? null : value * 250,+ max_totalTokens: value,+ },+ });++ it("densifies onto the epoch grid with nulls for empty buckets", () => {+ const step = 60;+ const t0 = Math.floor(Date.UTC(2025, 2, 10, 10, 0, 0) / 60000) * 60000;+ const { dense, maxValue } = prepareOutlierSeries({+ bins: [bin(t0, 3), bin(t0 + 120_000, 7)],+ metric: "cost",+ fromMs: t0,+ toMs: t0 + 179_000, // covers three buckets+ stepSeconds: step,+ });++ expect(dense.map((d) => d.value)).toEqual([3, null, 7]);+ expect(maxValue).toBe(7);+ });++ it("snaps the grid phase to the server's buckets (non-UTC ClickHouse)", () => {+ const step = 86400; // 1d buckets aligned to a +02:00 server timezone+ const utcMidnight = Date.UTC(2025, 2, 10);+ const offset = 2 * 3600 * 1000;+ const serverBucket = utcMidnight - offset;+ const { dense } = prepareOutlierSeries({+ bins: [bin(serverBucket, 4)],+ metric: "cost",+ fromMs: utcMidnight,+ toMs: utcMidnight + 86400_000,+ stepSeconds: step,+ });++ // A phase-0 UTC grid would miss the bucket entirely and blank the chart.+ expect(dense.some((d) => d.value === 4)).toBe(true);+ expect(+ dense.every(+ (d) => d.bucketStartMs % 86400_000 === serverBucket % 86400_000,+ ),+ ).toBe(true);+ });++ it("excludes a zero-width trailing bucket when `to` sits on a boundary", () => {+ const step = 60;+ const t0 = Math.floor(Date.UTC(2025, 2, 10, 10, 0, 0) / 60000) * 60000;+ const { dense } = prepareOutlierSeries({+ bins: [bin(t0, 1)],+ metric: "cost",+ fromMs: t0,+ toMs: t0 + 120_000, // exactly two buckets+ stepSeconds: step,+ });++ expect(dense).toHaveLength(2);+ });++ it("selects the aggregation's result column via the registry", () => {+ const step = 60;+ const t0 = Math.floor(Date.UTC(2025, 2, 10, 10, 0, 0) / 60000) * 60000;+ const run = (metric: "cost" | "latency", aggregation: string) =>+ prepareOutlierSeries({+ bins: [bin(t0, 8)],+ metric,+ aggregation,+ fromMs: t0,+ toMs: t0 + 60_000,+ stepSeconds: step,+ }).dense[0].value;++ expect(run("latency", "max")).toBe(8); // 8000ms β 8s+ expect(run("latency", "p95")).toBe(4); // 4000ms β 4s+ expect(run("latency", "avg")).toBe(2); // 2000ms β 2s+ expect(run("cost", "max")).toBe(8);+ expect(run("cost", "sum")).toBe(80); // sum = 10 Γ max in the helper+ // Unknown option falls back to the metric's default (max) β a stored+ // legacy value can never plot the wrong column.+ expect(run("cost", "median")).toBe(8);+ });++ it("places phase-aware ticks with presentation-ready labels", () => {+ const step = 86400;+ const utcMidnight = Date.UTC(2025, 2, 10);+ const offset = 2 * 3600 * 1000; // +02:00 server: phase-shifted buckets+ const bins = Array.from({ length: 30 }, (_, i) =>+ bin(utcMidnight - offset + i * 86400_000, 1 + i),+ );+ const { dense, ticks } = prepareOutlierSeries({+ bins,+ metric: "cost",+ fromMs: utcMidnight,+ toMs: utcMidnight + 30 * 86400_000,+ stepSeconds: step,+ widthPx: 600, // 20px slots β ticks every β₯110px+ });++ expect(dense.length).toBeGreaterThan(0);+ // The old epoch-modulo predicate produced ZERO ticks on shifted grids.+ expect(ticks.length).toBeGreaterThan(1);+ for (const tick of ticks) {+ expect(tick.index).toBeGreaterThan(0);+ expect(tick.index).toBeLessThan(dense.length);+ expect(tick.label).toMatch(/^[A-Z][a-z]{2} \d{1,2}$/); // "MMM d"+ }+ });++ it("aligns the grid to the epoch, not to `from`", () => {+ const step = 60;+ const t0 = Math.floor(Date.UTC(2025, 2, 10, 10, 0, 0) / 60000) * 60000;+ const { dense } = prepareOutlierSeries({+ bins: [bin(t0, 5)],+ metric: "cost",+ fromMs: t0 + 30_000, // mid-bucket start+ toMs: t0 + 90_000,+ stepSeconds: step,+ });++ // First grid bucket is the epoch-aligned one containing `from`.+ expect(dense[0].bucketStartMs).toBe(t0);+ expect(dense[0].value).toBe(5);+ });+});++describe("outlierStripResultColumn", () => {+ it("matches executeQuery's `${aggregation}_${measure}` naming", () => {+ expect(outlierStripResultColumn("totalCost", "sum")).toBe("sum_totalCost");+ expect(outlierStripResultColumn("latency", "p95")).toBe("p95_latency");+ });+});diff --git a/web/src/features/events/components/outlier-strip/lib/binning.ts b/web/src/features/events/components/outlier-strip/lib/binning.tsnew file mode 100644index 0000000000..a009031a5a--- /dev/null+++ b/web/src/features/events/components/outlier-strip/lib/binning.ts@@ -0,0 +1,379 @@+import { format } from "date-fns";+import {+ compactNumberFormatter,+ latencyFormatter,+ usdFormatter,+} from "@/src/utils/numbers";+import { parseChartTimestamp } from "@/src/features/widgets/chart-library/prepareTimeAxis";++/**+ * Preparer layer for the outlier strip (LFE-14451), following the charts+ * manifesto: every decision (step choice, densification, metric extraction,+ * tick placement, formatting, scale inputs) happens here in pure functions;+ * the SVG visualiser only renders the prepared model.+ *+ * The METRIC REGISTRY is the single source of truth for what the strip can+ * plot: each aggregation option declares its executeQuery aggregation once,+ * and the query metrics, result-column extraction, dropdown options, and+ * labels are all DERIVED from it β a new option is one line, and cannot be+ * half-wired (the class of bug where a switch changed the label but not the+ * data).+ */++/**+ * Grid steps for the strip's sparse gridline ticks, in seconds. Purely+ * presentational; the data granularity comes from {@link pickChartGranularity}.+ */+export const OUTLIER_STRIP_STEP_LADDER_SECONDS = [+ 1,+ 2,+ 5,+ 10,+ 15,+ 30, // seconds+ 60,+ 120,+ 300,+ 600,+ 900,+ 1800, // minutes+ 3600,+ 7200,+ 10800,+ 21600,+ 43200, // hours+ 86400,+ 172800, // days+] as const;++/**+ * The fixed-width `dashboard.executeQuery` granularity presets the strip may+ * request, finest first. All are epoch-aligned in ClickHouse+ * (toStartOfMinute / toStartOfInterval), so client grid math matches the+ * server's buckets. Variable-length tokens (month, toMonday weeks) are+ * excluded on purpose. Finer sub-minute steps need a backend addition β+ * tracked as a follow-up to LFE-14451.+ */+export const OUTLIER_STRIP_GRANULARITIES = [+ { granularity: "minute", stepSeconds: 60 },+ { granularity: "5m", stepSeconds: 300 },+ { granularity: "10m", stepSeconds: 600 },+ { granularity: "15m", stepSeconds: 900 },+ { granularity: "30m", stepSeconds: 1800 },+ { granularity: "1h", stepSeconds: 3600 },+ { granularity: "2h", stepSeconds: 7200 },+ { granularity: "4h", stepSeconds: 14400 },+ { granularity: "1d", stepSeconds: 86400 },+ { granularity: "2d", stepSeconds: 172800 },+ { granularity: "1w", stepSeconds: 604800 },+] as const;++export type OutlierStripGranularity =+ (typeof OUTLIER_STRIP_GRANULARITIES)[number];++/** Never ask the backend for more buckets than this, whatever the width. */+const MAX_STRIP_BUCKETS = 2000;+/** Densification guard: even the coarsest preset on an URL-injected absurd+ * custom range must not build an unbounded client-side array. */+const MAX_DENSE_BINS = 4000;+/** Minimum horizontal pixels between gridline ticks / labels. */+const TICK_MIN_SPACING_PX = 110;++/**+ * Picks the finest granularity preset that fits the range into the available+ * bar slots ("fit as many bars as possible in the current width"). Falls back+ * to the coarsest preset for extreme rangeΓwidth combinations β the strip+ * then renders more bars than ideally fit rather than failing.+ */+export function pickChartGranularity(params: {+ rangeMs: number;+ widthPx: number;+ /** Horizontal pixels one bar occupies, gap included. */+ barSlotPx: number;+}): OutlierStripGranularity {+ const rangeSeconds = Math.max(1, params.rangeMs / 1000);+ const maxBars = Math.max(+ 1,+ Math.min(Math.floor(params.widthPx / params.barSlotPx), MAX_STRIP_BUCKETS),+ );++ for (const entry of OUTLIER_STRIP_GRANULARITIES) {+ if (Math.ceil(rangeSeconds / entry.stepSeconds) <= maxBars) return entry;+ }++ return OUTLIER_STRIP_GRANULARITIES[OUTLIER_STRIP_GRANULARITIES.length - 1];+}++// ---------------------------------------------------------------------------+// Metric registry+// ---------------------------------------------------------------------------++export type OutlierStripMetricKey = "cost" | "latency" | "tokens";+export type OutlierStripLatencyAgg = "max" | "p95" | "avg";+export type OutlierStripCostAgg = "max" | "sum";+export type OutlierStripAggKey = OutlierStripLatencyAgg | OutlierStripCostAgg;++type AggregationDef = {+ /** The user-facing option key (currently 1:1 with the query aggregation). */+ key: OutlierStripAggKey;+ /** The executeQuery aggregation this option lowers to. */+ queryAggregation: "max" | "sum" | "p95" | "avg";+};++export type OutlierStripMetricDef = {+ shortLabel: string;+ /** First entry is the default (the outlier semantics: max). */+ aggregations: readonly AggregationDef[];+ /** The executeQuery measure name on the v2 observations view. */+ measure: string;+ /** Raw result value β plotted unit (e.g. latency ms β s). */+ fromRaw: (raw: number) => number;+ format: (value: number) => string;+};++export const OUTLIER_STRIP_METRICS: Record<+ OutlierStripMetricKey,+ OutlierStripMetricDef+> = {+ cost: {+ shortLabel: "Cost",+ measure: "totalCost",+ aggregations: [+ { key: "max", queryAggregation: "max" },+ { key: "sum", queryAggregation: "sum" },+ ],+ fromRaw: (raw) => raw,+ format: (value) =>+ usdFormatter(value, 2, value < 0.001 ? 6 : value < 0.1 ? 4 : 2),+ },+ latency: {+ shortLabel: "Latency",+ measure: "latency",+ aggregations: [+ { key: "max", queryAggregation: "max" },+ { key: "p95", queryAggregation: "p95" },+ { key: "avg", queryAggregation: "avg" },+ ],+ fromRaw: (raw) => raw / 1000, // executeQuery latency is in ms+ format: (value) => latencyFormatter(value * 1000),+ },+ tokens: {+ shortLabel: "Tokens",+ measure: "totalTokens",+ aggregations: [{ key: "max", queryAggregation: "max" }],+ fromRaw: (raw) => raw,+ format: (value) => compactNumberFormatter(value),+ },+};++/** executeQuery result column for a (measure, aggregation) pair. */+export const outlierStripResultColumn = (+ measure: string,+ queryAggregation: string,+): string => `${queryAggregation}_${measure}`;++/**+ * The executeQuery `metrics` array β derived from the registry so every+ * registered aggregation option is fetched in the one shared scan.+ */+export const outlierStripQueryMetrics = (): {+ measure: string;+ aggregation: "count" | AggregationDef["queryAggregation"];+}[] => [+ { measure: "count", aggregation: "count" },+ ...Object.values(OUTLIER_STRIP_METRICS).flatMap((def) =>+ def.aggregations.map((agg) => ({+ measure: def.measure,+ aggregation: agg.queryAggregation,+ })),+ ),+];++/** Resolves an aggregation option, falling back to the metric's default. */+export const resolveAggregation = (+ metric: OutlierStripMetricKey,+ aggregation: string | undefined,+): AggregationDef => {+ const def = OUTLIER_STRIP_METRICS[metric];+ return (+ def.aggregations.find((agg) => agg.key === aggregation) ??+ def.aggregations[0]+ );+};++// ---------------------------------------------------------------------------+// Row β bin mapping+// ---------------------------------------------------------------------------++/** One executeQuery row; metric columns are looked up via the registry. */+export type OutlierQueryRow = Record<string, unknown> & {+ time_dimension?: string;+ count_count?: unknown;+};++/**+ * One bucket of aggregates. `values` is keyed by result column+ * ({@link outlierStripResultColumn}), holding RAW query values (unit mapping+ * happens at extraction via the registry's `fromRaw`).+ */+export type OutlierStripBin = {+ bucketStart: Date;+ count: number;+ values: Record<string, number | null>;+};++const toNumberOrNull = (raw: unknown): number | null =>+ raw === null || raw === undefined ? null : Number(raw);++/**+ * Maps executeQuery rows to strip bins.+ *+ * WITH FILL rows (count 0) are dropped rather than mapped: ClickHouse fills+ * non-nullable measures with type DEFAULTS (e.g. tokens UInt64 β 0) while+ * nullable ones fill as null β mapping those rows would draw a phantom+ * baseline across every empty bucket. The client densifies empty buckets to+ * honest nulls anyway.+ */+export const rowsToOutlierBins = (rows: OutlierQueryRow[]): OutlierStripBin[] =>+ rows.flatMap((row) => {+ const bucketStart = parseChartTimestamp(row.time_dimension);+ const count = Number(row.count_count ?? 0);+ if (!bucketStart || count === 0) return [];+ const values: Record<string, number | null> = {};+ for (const def of Object.values(OUTLIER_STRIP_METRICS)) {+ for (const agg of def.aggregations) {+ const column = outlierStripResultColumn(+ def.measure,+ agg.queryAggregation,+ );+ values[column] = toNumberOrNull(row[column]);+ }+ }+ return [{ bucketStart, count, values }];+ });++// ---------------------------------------------------------------------------+// Series preparation (densify + ticks)+// ---------------------------------------------------------------------------++/** One bucket on the dense grid; `value` null = no data in this bucket. */+export type OutlierStripDenseBin = {+ bucketStartMs: number;+ count: number;+ value: number | null;+};++/** A prepared gridline tick: dense-bin index + presentation-ready label. */+export type OutlierStripTick = { index: number; label: string };++/** A bucket's tooltip time range, day-scale buckets without the time part. */+export const formatBucketRange = (fromMs: number, stepMs: number): string => {+ const from = new Date(fromMs);+ const to = new Date(fromMs + stepMs);+ const dayPattern = stepMs >= 86_400_000 ? "MMM d" : "MMM d, HH:mm:ss";+ return `${format(from, dayPattern)} β ${format(to, stepMs >= 86_400_000 ? "MMM d" : "HH:mm:ss")}`;+};++/**+ * Smallest "nice" tick step at least `minPx` wide at the current bar slot.+ * Ticks must be MULTIPLES of the bucket step β placement subtracts the grid+ * phase and tests a modulo, and a non-multiple would place ticks irregularly.+ */+const pickTickStepMs = (+ stepMs: number,+ slotPx: number,+ minPx: number,+): number => {+ for (const step of OUTLIER_STRIP_STEP_LADDER_SECONDS) {+ const tickMs = step * 1000;+ if (tickMs % stepMs === 0 && (tickMs / stepMs) * slotPx >= minPx) {+ return tickMs;+ }+ }+ // Every k-th bucket, k sized to the pixel budget β aligned by construction.+ return Math.max(1, Math.ceil(minPx / slotPx)) * stepMs;+};++/**+ * Densifies server buckets onto the bucket grid covering [fromMs, toMs),+ * extracts one metric/aggregation via the registry, and places gridline+ * ticks. Grid math uses the same epoch arithmetic as ClickHouse's+ * toStartOfInterval β never date-library startOfDay/week β and snaps its+ * PHASE to the server's returned buckets, so a self-hosted non-UTC ClickHouse+ * yields a shifted-but-correct chart instead of a blank one.+ */+export function prepareOutlierSeries(params: {+ bins: OutlierStripBin[];+ metric: OutlierStripMetricKey;+ /** Aggregation option key; invalid values fall back to the metric default. */+ aggregation?: string;+ fromMs: number;+ toMs: number;+ stepSeconds: number;+ /** Plot width; drives tick spacing. 0/absent = no ticks (tests). */+ widthPx?: number;+}): {+ dense: OutlierStripDenseBin[];+ /** Max metric value across buckets; 0 when the range has no data. */+ maxValue: number;+ ticks: OutlierStripTick[];+} {+ const stepMs = params.stepSeconds * 1000;+ const def = OUTLIER_STRIP_METRICS[params.metric];+ const agg = resolveAggregation(params.metric, params.aggregation);+ const column = outlierStripResultColumn(def.measure, agg.queryAggregation);++ const byBucketMs = new Map<number, OutlierStripBin>();+ for (const bin of params.bins) {+ byBucketMs.set(bin.bucketStart.getTime(), bin);+ }++ // Snap the grid's phase to the server's buckets (non-UTC ClickHouse aligns+ // day+ buckets to its own timezone; a phase-0 grid would miss every bucket).+ const phase =+ params.bins.length > 0+ ? ((params.bins[0].bucketStart.getTime() % stepMs) + stepMs) % stepMs+ : 0;+ const firstBucketMs =+ Math.floor((params.fromMs - phase) / stepMs) * stepMs + phase;+ const dense: OutlierStripDenseBin[] = [];+ let maxValue = 0;++ for (+ let bucketMs = firstBucketMs;+ // Exclusive: a `to` exactly on a boundary must not add a trailing bucket+ // that covers zero time. MAX_DENSE_BINS guards URL-injected absurd ranges.+ bucketMs < params.toMs && dense.length < MAX_DENSE_BINS;+ bucketMs += stepMs+ ) {+ const bin = byBucketMs.get(bucketMs);+ const raw = bin ? (bin.values[column] ?? null) : null;+ const value = raw === null ? null : def.fromRaw(raw);+ if (value !== null && value > maxValue) maxValue = value;+ dense.push({+ bucketStartMs: bucketMs,+ count: bin?.count ?? 0,+ value,+ });+ }++ // Gridline ticks β phase-aware, presentation-ready labels.+ const ticks: OutlierStripTick[] = [];+ if (params.widthPx && params.widthPx > 0 && dense.length > 0) {+ const slotPx = params.widthPx / dense.length;+ const tickStepMs = pickTickStepMs(stepMs, slotPx, TICK_MIN_SPACING_PX);+ for (let i = 1; i < dense.length; i++) {+ if ((dense[i].bucketStartMs - phase) % tickStepMs === 0) {+ ticks.push({+ index: i,+ label: format(+ new Date(dense[i].bucketStartMs),+ tickStepMs >= 86_400_000 ? "MMM d" : "HH:mm",+ ),+ });+ }+ }+ }++ return { dense, maxValue, ticks };+}diff --git a/web/src/features/events/components/outlier-strip/lib/fixtures.ts b/web/src/features/events/components/outlier-strip/lib/fixtures.tsnew file mode 100644index 0000000000..9a2a531c30--- /dev/null+++ b/web/src/features/events/components/outlier-strip/lib/fixtures.ts@@ -0,0 +1,106 @@+import {+ prepareOutlierSeries,+ type OutlierStripBin,+ type OutlierStripMetricKey,+} from "./binning";++/**+ * Deterministic fake data for the outlier-strip design stories. Seeded PRNG so+ * every Storybook render (and screenshot) is identical.+ */++const mulberry32 = (seed: number) => {+ let a = seed;+ return () => {+ a |= 0;+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+};++export type FixtureProfile =+ /** Base load with occasional 10β40x outliers β the target hunting ground. */+ | "spiky"+ /** Quiet nights, dense bursts β tests band scanability. */+ | "bursty"+ /** Many empty buckets β tests gap semantics. */+ | "sparse"+ /** Events exist but carry no metric data (root-only cost shape). */+ | "noMetricData";++export const FIXTURE_BASE_MS = Date.UTC(2026, 6, 26, 0, 0, 0); // fixed: 2026-07-26++export function makeFixtureBins(params: {+ rangeMs: number;+ stepSeconds: number;+ profile: FixtureProfile;+ seed?: number;+}): { bins: OutlierStripBin[]; fromMs: number; toMs: number } {+ const rand = mulberry32(params.seed ?? 42);+ const stepMs = params.stepSeconds * 1000;+ const fromMs = FIXTURE_BASE_MS;+ const toMs = fromMs + params.rangeMs;++ const bins: OutlierStripBin[] = [];+ for (let t = fromMs; t < toMs; t += stepMs) {+ const hourOfDay = new Date(t).getUTCHours();+ const daytime = hourOfDay >= 7 && hourOfDay <= 22;++ let present = true;+ if (params.profile === "sparse") present = rand() < 0.3;+ if (params.profile === "bursty")+ present = daytime ? rand() < 0.9 : rand() < 0.15;+ if (!present) continue;++ const outlier =+ params.profile === "spiky" || params.profile === "bursty"+ ? rand() < 0.04+ ? 10 + rand() * 30+ : 1+ : 1;+ const base = 0.5 + rand() * 0.8;+ const count = Math.max(1, Math.round(rand() * 40 * (daytime ? 1 : 0.3)));++ const noData = params.profile === "noMetricData";+ // Raw query units: latency in ms (the registry's fromRaw divides by 1000).+ bins.push({+ bucketStart: new Date(t),+ count,+ values: {+ max_totalCost: noData ? null : 0.02 * base * outlier,+ sum_totalCost: noData ? null : 0.02 * base * outlier * 5,+ max_latency: noData ? null : 2000 * base * outlier,+ p95_latency: noData ? null : 2000 * base * outlier * 0.6,+ avg_latency: noData ? null : 2000 * base * outlier * 0.35,+ max_totalTokens: noData ? null : Math.round(1500 * base * outlier),+ },+ });+ }++ return { bins, fromMs, toMs };+}++export function makeFixtureSeries(params: {+ rangeMs: number;+ stepSeconds: number;+ profile: FixtureProfile;+ metric: OutlierStripMetricKey;+ widthPx: number;+ seed?: number;+}) {+ const { bins, fromMs, toMs } = makeFixtureBins(params);+ return {+ ...prepareOutlierSeries({+ bins,+ metric: params.metric,+ fromMs,+ toMs,+ stepSeconds: params.stepSeconds,+ widthPx: params.widthPx,+ }),+ stepMs: params.stepSeconds * 1000,+ widthPx: params.widthPx,+ };+}diff --git a/web/src/features/events/components/outlier-strip/lib/useOutlierStripSettings.ts b/web/src/features/events/components/outlier-strip/lib/useOutlierStripSettings.tsnew file mode 100644index 0000000000..01958de7f7--- /dev/null+++ b/web/src/features/events/components/outlier-strip/lib/useOutlierStripSettings.ts@@ -0,0 +1,38 @@+import { useMemo } from "react";+import { z } from "zod";+import useLocalStorage from "@/src/components/useLocalStorage";++/**+ * The strip's per-user chart settings as ONE zod-validated localStorage+ * object. localStorage is user-editable and cross-tab-writable; validating at+ * a single seam (instead of per-key ad-hoc sanitizers) makes corrupted or+ * legacy values structurally incapable of crashing the page β every field+ * independently falls back to its default via `.catch`.+ */+const outlierStripSettingsSchema = z+ .object({+ mode: z.enum(["cost", "latency", "tokens", "split"]).catch("cost"),+ latencyAgg: z.enum(["max", "p95", "avg"]).catch("max"),+ costAgg: z.enum(["max", "sum"]).catch("max"),+ })+ .catch({ mode: "cost", latencyAgg: "max", costAgg: "max" });++export type OutlierStripSettings = z.infer<typeof outlierStripSettingsSchema>;++export function useOutlierStripSettings(): {+ settings: OutlierStripSettings;+ update: (patch: Partial<OutlierStripSettings>) => void;+} {+ const [raw, setRaw] = useLocalStorage<unknown>(+ "events-pulse-chart-settings",+ {},+ );+ const settings = useMemo(+ () => outlierStripSettingsSchema.parse(raw ?? {}),+ [raw],+ );+ return {+ settings,+ update: (patch) => setRaw({ ...settings, ...patch }),+ };+}