Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(topics): share the summary row builder and record trigger type and session on automatic rows (#19018)

Lysander Kiesel21a88734de76
diff --git a/packages/shared/src/server/repositories/__snapshots__/events.golden.test.ts.snap b/packages/shared/src/server/repositories/__snapshots__/events.golden.test.ts.snap
index 471f3b5333..bae881367b 100644
--- a/packages/shared/src/server/repositories/__snapshots__/events.golden.test.ts.snap
+++ b/packages/shared/src/server/repositories/__snapshots__/events.golden.test.ts.snap
@@ -1834,6 +1834,7 @@ exports[`golden: events metadata map and session resolution > getTraceBatchEvent
output,
e.project_id,
e.trace_id,
+ e.session_id,
e.environment,
e.span_id,
e.parent_span_id,
diff --git a/packages/shared/src/server/repositories/trace-batch.ts b/packages/shared/src/server/repositories/trace-batch.ts
index 28c28f9ec2..f464273f3f 100644
--- a/packages/shared/src/server/repositories/trace-batch.ts
+++ b/packages/shared/src/server/repositories/trace-batch.ts
@@ -7,6 +7,7 @@ import { queryClickhouseStream, TupleParam } from "./clickhouse";
type TraceBatchEventRow = {
project_id: string;
trace_id: string;
+ session_id: string;
environment: string;
span_id: string;
parent_span_id: string | null;
@@ -139,6 +140,7 @@ const buildTraceBatchEventQuery = (props: TraceBatchEventStreamProps) => {
.selectRaw(
"e.project_id",
"e.trace_id",
+ "e.session_id",
"e.environment",
"e.span_id",
"e.parent_span_id",
diff --git a/packages/shared/src/topics/index.ts b/packages/shared/src/topics/index.ts
index d3d81a1a87..26bbf608e7 100644
--- a/packages/shared/src/topics/index.ts
+++ b/packages/shared/src/topics/index.ts
@@ -258,7 +258,8 @@ export type TopicSummary = z.infer<typeof topicSourceSchema> & {
projectId: string;
facetId: string;
facetVersion: number;
- triggerType: "manual_poc";
+ /** Processing path that wrote the row; rows from before the automatic/manual split hold "manual_poc". */
+ triggerType: "automatic" | "manual" | "manual_poc";
environment: string;
traceName: string;
unitStartTime: string;
diff --git a/worker/src/features/topics/README.md b/worker/src/features/topics/README.md
index 8b7b6fa5a8..2ddf850a9c 100644
--- a/worker/src/features/topics/README.md
+++ b/worker/src/features/topics/README.md
@@ -114,7 +114,7 @@ Summary and assignment records use `trace_id` as their source when present;
`session_id` identifies the processed session. At least one ID is required.
The current pipeline processes traces only. `unit_start_time` (`unitStartTime` in
TypeScript) is the first observation's start time for the processed source. Summaries set
-`trigger_type=manual_poc`. Each clustering attempt records its own `started_at`. Failed updates start a fresh
+`trigger_type` to `automatic` (trace-batch) or `manual` (manual processing); rows written before that split hold `manual_poc`. Each clustering attempt records its own `started_at`. Failed updates start a fresh
attempt while keeping the previous published map available.
Summaries snapshot source environment and trace name; assignments copy that
diff --git a/worker/src/features/topics/processTopicsExecution.test.ts b/worker/src/features/topics/processTopicsExecution.test.ts
index 1ff8f90d2e..92042f0ad4 100644
--- a/worker/src/features/topics/processTopicsExecution.test.ts
+++ b/worker/src/features/topics/processTopicsExecution.test.ts
@@ -712,6 +712,7 @@ describe("Topics execution", () => {
environment: "production",
traceName: "Customer support",
unitStartTime: "2026-01-01T00:00:00.000Z",
+ triggerType: "manual",
});
expect(state.numeric).not.toHaveBeenCalled();
expect(state.saveExecution).not.toHaveBeenCalled();
diff --git a/worker/src/features/topics/processTopicsExecution.ts b/worker/src/features/topics/processTopicsExecution.ts
index c86e184f2b..4e553d4593 100644
--- a/worker/src/features/topics/processTopicsExecution.ts
+++ b/worker/src/features/topics/processTopicsExecution.ts
@@ -44,6 +44,7 @@ import { env } from "../../env";
import { nameTopicGroup } from "./models";
import {
ASSEMBLED_TRANSCRIPT_ID,
+ baseTopicSummary,
summarizeTraceFacets,
type TraceFacet,
} from "./summarizeAssembledTrace";
@@ -127,7 +128,19 @@ async function summarizeTrace(
if (isInternalEvalEnvironment(input.environment))
throw new Error("Topics does not process internal Langfuse traces.");
const base = (facet: TraceFacet) =>
- baseSummary(execution, traceId, facet.version, input);
+ baseTopicSummary({
+ projectId: execution.projectId,
+ traceId,
+ sessionId: input.sessionId,
+ unitStartTime: input.unitStartTime,
+ environment: input.environment,
+ traceName: input.traceName,
+ facet: facet.version,
+ summaryModel: execution.input.processingConfig.summaryModel!,
+ embeddingModel: execution.input.embeddingConfig.embeddingModel!,
+ triggerType: "manual",
+ metadata: { executionId: execution.id },
+ });
// Each step records a facet as soon as it is staged, so a later failure keeps it.
await reuseSummaries(metrics, execution, unresolved(), base, results);
await summarizePending(
@@ -171,38 +184,6 @@ function acceptedSummaries(
return results;
}
-function baseSummary(
- execution: ProcessExecution,
- traceId: string,
- facet: TopicFacetVersion,
- input: TraceInput,
-): TopicSummary {
- return {
- projectId: execution.projectId,
- facetId: facet.facetId,
- facetVersion: facet.version,
- traceId,
- sessionId: input.sessionId,
- triggerType: "manual_poc",
- unitStartTime: input.unitStartTime,
- environment: input.environment,
- traceName: input.traceName,
- state: "insufficient_input",
- summary: "",
- embedding: [],
- transcriptId: ASSEMBLED_TRANSCRIPT_ID,
- transcriptVersion: TOPICS_TRANSCRIPT_VERSION,
- summaryModel: execution.input.processingConfig.summaryModel!,
- embeddingModel: execution.input.embeddingConfig.embeddingModel!,
- providedUsageDetails: {},
- usageDetails: {},
- providedCostDetails: {},
- costDetails: {},
- processedAt: new Date().toISOString(),
- metadata: { executionId: execution.id },
- };
-}
-
/** Stages compatible stored summaries when the execution opted into reuse. */
async function reuseSummaries(
metrics: TopicMetrics,
diff --git a/worker/src/features/topics/summarizeAssembledTrace.test.ts b/worker/src/features/topics/summarizeAssembledTrace.test.ts
index 3f39edbe7c..85ec59a3ee 100644
--- a/worker/src/features/topics/summarizeAssembledTrace.test.ts
+++ b/worker/src/features/topics/summarizeAssembledTrace.test.ts
@@ -148,6 +148,7 @@ describe("summarizeAssembledTrace", () => {
const result = await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "langfuse-topics",
@@ -167,6 +168,7 @@ describe("summarizeAssembledTrace", () => {
await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -226,6 +228,7 @@ describe("summarizeAssembledTrace", () => {
await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -239,6 +242,7 @@ describe("summarizeAssembledTrace", () => {
await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:03:00.000Z"),
environment: "default",
@@ -278,6 +282,7 @@ describe("summarizeAssembledTrace", () => {
await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -288,7 +293,11 @@ describe("summarizeAssembledTrace", () => {
});
expect(state.summarize).toHaveBeenCalledOnce();
const [intent, issue] = summaries;
- expect(intent).toMatchObject({ facetId: "facet-1", state: "complete" });
+ expect(intent).toMatchObject({
+ facetId: "facet-1",
+ state: "complete",
+ triggerType: "automatic",
+ });
expect(issue).toMatchObject({
facetId: "facet-2",
state: "not_applicable",
@@ -317,6 +326,7 @@ describe("summarizeAssembledTrace", () => {
await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -350,6 +360,7 @@ describe("summarizeAssembledTrace", () => {
summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -408,6 +419,7 @@ describe("summarizeAssembledTrace", () => {
await summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -445,6 +457,7 @@ describe("summarizeAssembledTrace", () => {
summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -487,6 +500,7 @@ describe("summarizeAssembledTrace", () => {
summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
@@ -525,6 +539,7 @@ describe("summarizeAssembledTrace", () => {
summarize({
projectId: "project-a",
traceId: "trace-1",
+ sessionId: null,
traceTimestamp: "2026-09-22T12:00:00.000Z",
jobEnqueuedAt: new Date("2026-09-22T12:01:00.000Z"),
environment: "default",
diff --git a/worker/src/features/topics/summarizeAssembledTrace.ts b/worker/src/features/topics/summarizeAssembledTrace.ts
index 72ffd8db24..4cc408a040 100644
--- a/worker/src/features/topics/summarizeAssembledTrace.ts
+++ b/worker/src/features/topics/summarizeAssembledTrace.ts
@@ -53,6 +53,7 @@ type TraceFacetResult =
type AssembledTraceInput = {
projectId: string;
traceId: string;
+ sessionId: string | null;
traceTimestamp: string;
jobEnqueuedAt: Date;
environment: string;
@@ -149,7 +150,19 @@ async function summarizeEnabledTrace(
if (pending.length === 0) return { outcome: "unchanged", rows: [] };
const bases = pending.map(({ version }) =>
- baseSummary(input, version, config, embeddingModel),
+ baseTopicSummary({
+ projectId: input.projectId,
+ traceId: input.traceId,
+ sessionId: input.sessionId,
+ unitStartTime: input.traceTimestamp,
+ environment: input.environment,
+ traceName: input.traceName,
+ facet: version,
+ summaryModel: config.summaryModel!,
+ embeddingModel,
+ triggerType: "automatic",
+ metadata: { input: "assembled-transcript" },
+ }),
);
const summarized = await summarizeTraceFacets({
models,
@@ -295,37 +308,39 @@ export async function summarizeTraceFacets(params: {
};
}
-function baseSummary(
- input: {
- projectId: string;
- traceId: string;
- traceTimestamp: string;
- environment: string;
- traceName: string;
- },
- facet: TopicFacetVersion,
- config: ReturnType<typeof topicProcessingConfigSchema.parse>,
- embeddingModel: string,
-): TopicSummary {
+/** The summary row both processing paths start from, before any model call. */
+export function baseTopicSummary(params: {
+ projectId: string;
+ traceId: string;
+ sessionId: string | null;
+ unitStartTime: string;
+ environment: string;
+ traceName: string;
+ facet: TopicFacetVersion;
+ summaryModel: string;
+ embeddingModel: string;
+ triggerType: "automatic" | "manual";
+ metadata: Record<string, unknown>;
+}): TopicSummary {
return {
- projectId: input.projectId,
- facetId: facet.facetId,
- facetVersion: facet.version,
- traceId: input.traceId,
- sessionId: null,
- triggerType: "manual_poc",
- unitStartTime: input.traceTimestamp,
- environment: input.environment,
- traceName: input.traceName,
+ projectId: params.projectId,
+ facetId: params.facet.facetId,
+ facetVersion: params.facet.version,
+ traceId: params.traceId,
+ sessionId: params.sessionId,
+ triggerType: params.triggerType,
+ unitStartTime: params.unitStartTime,
+ environment: params.environment,
+ traceName: params.traceName,
state: "insufficient_input",
summary: "",
embedding: [],
transcriptId: ASSEMBLED_TRANSCRIPT_ID,
transcriptVersion: TOPICS_TRANSCRIPT_VERSION,
- summaryModel: config.summaryModel!,
- embeddingModel,
+ summaryModel: params.summaryModel,
+ embeddingModel: params.embeddingModel,
...NO_USAGE,
processedAt: new Date().toISOString(),
- metadata: { input: "assembled-transcript" },
+ metadata: params.metadata,
};
}
diff --git a/worker/src/queues/__tests__/traceBatchQueue.test.ts b/worker/src/queues/__tests__/traceBatchQueue.test.ts
index fff55c5bd1..484b9522b6 100644
--- a/worker/src/queues/__tests__/traceBatchQueue.test.ts
+++ b/worker/src/queues/__tests__/traceBatchQueue.test.ts
@@ -1048,6 +1048,69 @@ describe("trace batch queue", () => {
vi.mocked(listTopicRules).mockResolvedValue([]);
});
+ it("passes the session of the newest event that has one, breaking timestamp ties by span ID", async () => {
+ vi.mocked(getTraceBatchEventStream).mockImplementation(async function* () {
+ for (const [span, eventTs, sessionId] of [
+ ["a", "2026-09-11 00:00:01.000000", "session-old"],
+ ["b", "2026-09-11 00:00:02.000000", "session-new"],
+ ["d", "2026-09-11 00:00:02.000000", "session-tie"],
+ ["c", "2026-09-11 00:00:03.000000", ""],
+ ])
+ yield {
+ project_id: "project",
+ trace_id: "trace",
+ session_id: sessionId,
+ environment: "default",
+ span_id: span,
+ parent_span_id: null,
+ start_time: "2026-09-11 00:00:00.000000",
+ event_ts: eventTs,
+ type: "GENERATION",
+ name: "generation",
+ input: JSON.stringify([{ role: "user", content: span }]),
+ output: JSON.stringify({ role: "assistant", content: "answer" }),
+ metadata: {},
+ level: "DEFAULT",
+ status_message: null,
+ tool_definitions: {},
+ tool_calls: [],
+ tool_call_names: [],
+ };
+ });
+ vi.mocked(listTopicFacets).mockResolvedValue([
+ { id: "intent" } as TopicFacet,
+ ]);
+ vi.mocked(listTopicRules).mockResolvedValue([
+ { facetIds: ["intent"], sampling: 1 } as TopicRule,
+ ]);
+ const job = {
+ data: {
+ id: "session",
+ name: QueueJobs.TraceBatch,
+ timestamp: new Date(),
+ payload: {
+ traces: [
+ {
+ projectId: "project",
+ traceId: "trace",
+ minStart: 0,
+ maxStart: 1,
+ revision: "r",
+ },
+ ],
+ },
+ },
+ } as Job<TQueueJobTypes[QueueName.TraceBatch]>;
+
+ await traceBatchQueueProcessor(job, undefined);
+
+ expect(
+ vi.mocked(summarizeAssembledTrace).mock.calls.at(-1)?.[0],
+ ).toMatchObject({ traceId: "trace", sessionId: "session-tie" });
+ vi.mocked(listTopicFacets).mockResolvedValue([]);
+ vi.mocked(listTopicRules).mockResolvedValue([]);
+ });
+
it("skips projects without enabled Topics models and pauses a project whose connection is rejected", async () => {
const rows = [
["off", "trace-1"],
diff --git a/worker/src/queues/traceBatchQueue.ts b/worker/src/queues/traceBatchQueue.ts
index a35250d511..a7e52a5d64 100644
--- a/worker/src/queues/traceBatchQueue.ts
+++ b/worker/src/queues/traceBatchQueue.ts
@@ -42,7 +42,10 @@ import { summarizeAssembledTrace } from "../features/topics/summarizeAssembledTr
import { enqueueTopicsAutomation } from "../features/topics/topicsAutomation";
import { recordTraceBatchTranscript } from "../features/traceBatching/traceBatchTranscript";
-type TraceBatchObservation = Observation & { eventTimestamp: string };
+type TraceBatchObservation = Observation & {
+ eventTimestamp: string;
+ sessionId: string | null;
+};
// Rows include a failed trace's valid facets; the batch writes them once.
type TraceOutcome = (
@@ -106,6 +109,27 @@ async function loadProjectRule(projectId: string) {
};
}
+/** Orders events like manual processing: event_ts, then span ID, then environment. */
+function newestEvent(observations: TraceBatchObservation[]) {
+ return observations.reduce<TraceBatchObservation | undefined>(
+ (current, row) => {
+ if (!current) return row;
+ if (row.eventTimestamp !== current.eventTimestamp)
+ return row.eventTimestamp > current.eventTimestamp ? row : current;
+ if (row.id !== current.id) return row.id > current.id ? row : current;
+ return row.environment > current.environment ? row : current;
+ },
+ undefined,
+ );
+}
+
+/** Session of the newest event that has one; events of a trace can carry different or no sessions. */
+function newestSessionId(observations: TraceBatchObservation[]) {
+ return (
+ newestEvent(observations.filter((row) => row.sessionId))?.sessionId ?? null
+ );
+}
+
async function summarizeTraceBatch(
observations: TraceBatchObservation[],
transcript: Transcript | null,
@@ -128,12 +152,8 @@ async function summarizeTraceBatch(
Math.min(...observations.map((row) => row.startTime.getTime())),
).toISOString();
// Match manual processing and discovery, preserving event_ts microseconds.
- const latest = observations.reduce((current, row) => {
- if (row.eventTimestamp !== current.eventTimestamp)
- return row.eventTimestamp > current.eventTimestamp ? row : current;
- if (row.id !== current.id) return row.id > current.id ? row : current;
- return row.environment > current.environment ? row : current;
- });
+ const latest = newestEvent(observations)!;
+ const sessionId = newestSessionId(observations);
let rows: TopicSummary[] = [];
try {
const project = await topics.get(first.projectId);
@@ -148,6 +168,7 @@ async function summarizeTraceBatch(
const result = await summarizeAssembledTrace({
projectId: first.projectId,
traceId,
+ sessionId,
traceTimestamp,
jobEnqueuedAt,
environment: latest.environment,
@@ -469,6 +490,7 @@ export const traceBatchQueueProcessor: Processor<
cost_details: {},
}),
eventTimestamp: event.event_ts,
+ sessionId: event.session_id || null,
});
}
// Reaching EOF completes the last trace; a failed stream must not flush it.