:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(aio): skip repeat temporal starts for trace and session evals (#109578)
posthog[bot]9a2cd6c16142
diff --git a/nodejs/src/ai-observability/services/temporal.service.test.ts b/nodejs/src/ai-observability/services/temporal.service.test.tsindex d089b7960aeb..658fab228cc4 100644--- a/nodejs/src/ai-observability/services/temporal.service.test.ts+++ b/nodejs/src/ai-observability/services/temporal.service.test.ts@@ -63,6 +63,8 @@ describe('TemporalService', () => {})afterEach(() => {+ jest.useRealTimers()+ jest.restoreAllMocks()jest.clearAllMocks()})@@ -389,23 +391,6 @@ describe('TemporalService', () => {})})- it('collapses every trace of one session onto the same workflow id', async () => {- for (const traceId of ['trace-1', 'trace-2']) {- await service.startAggregateEvaluationWorkflow({- evaluationId: 'eval-123',- event: createMockEvent(),- target: 'session',- traceId,- sessionId: null,- aiSessionId: 'ai-session-9',- settle: { strategy: 'inactivity', quiet_period_seconds: 3600, max_age_seconds: 86400 },- })- }-- const calls = (mockClient.workflow.start as jest.Mock).mock.calls- expect(calls[0][1].workflowId).toEqual(calls[1][1].workflowId)- })-it('returns null when the trace was already evaluated', async () => {;(mockClient.workflow.start as jest.Mock).mockRejectedValueOnce(new WorkflowExecutionAlreadyStartedError('done', 'llma-trace-eval-x', 'run-aggregate-evaluation')@@ -424,32 +409,73 @@ describe('TemporalService', () => {expect(result).toBeNull()})- it('produces the same workflow id for every event of the same trace', async () => {- await service.startAggregateEvaluationWorkflow({- evaluationId: 'eval-123',- event: createMockEvent({ uuid: 'event-1' }),- target: 'trace',- traceId: 'trace-789',- sessionId: null,- aiSessionId: null,- settle: { strategy: 'fixed_window', window_seconds: 1800 },- })- await service.startAggregateEvaluationWorkflow({- evaluationId: 'eval-123',- event: createMockEvent({ uuid: 'event-2' }),- target: 'trace',- traceId: 'trace-789',- sessionId: null,- aiSessionId: null,- settle: { strategy: 'fixed_window', window_seconds: 1800 },- })+ it.each([+ {+ name: 'every event of one trace',+ target: 'trace' as const,+ units: [+ { uuid: 'event-1', traceId: 'trace-789', aiSessionId: null },+ { uuid: 'event-2', traceId: 'trace-789', aiSessionId: null },+ ],+ workflowId: 'llma-trace-eval-eval-123-trace-789',+ },+ {+ name: 'every trace of one session',+ target: 'session' as const,+ units: [+ { uuid: 'event-1', traceId: 'trace-1', aiSessionId: 'ai-session-9' },+ { uuid: 'event-2', traceId: 'trace-2', aiSessionId: 'ai-session-9' },+ ],+ workflowId: 'llma-session-eval-eval-123-ai-session-9',+ },+ ])('starts one workflow for $name until the dedup window ends', async ({ target, units, workflowId }) => {+ // lru-cache reads the clock through the performance object it captured at import. Fake+ // timers replace that global object, so only a spy on the method moves the cache clock.+ // The fake timers still have to run, because lru-cache holds each clock reading until a+ // timer clears it.+ let now = performance.now()+ jest.spyOn(performance, 'now').mockImplementation(() => now)+ jest.useFakeTimers({ doNotFake: ['performance'] })+ const advanceClock = (ms: number): void => {+ now += ms+ jest.advanceTimersByTime(ms)+ }+ const starts = () =>+ units.map(+ ({ uuid, traceId, aiSessionId }) =>+ () =>+ service.startAggregateEvaluationWorkflow({+ evaluationId: 'eval-123',+ event: createMockEvent({ uuid }),+ target,+ traceId,+ sessionId: null,+ aiSessionId,+ settle: { strategy: 'fixed_window', window_seconds: 1800 },+ })+ )++ await Promise.all(starts().map((start) => start()))+ for (const start of starts()) {+ await start()+ }const calls = (mockClient.workflow.start as jest.Mock).mock.calls- expect(calls[0][1].workflowId).toEqual(calls[1][1].workflowId)- expect(calls[0][1].workflowId).not.toContain('event-1')+ expect(calls).toHaveLength(1)+ expect(calls[0][1].workflowId).toEqual(workflowId)++ const [repeatStart] = starts()+ advanceClock(40_000)+ await repeatStart()+ expect(calls).toHaveLength(1)++ advanceClock(40_000)+ await repeatStart()+ expect(calls).toHaveLength(2)+ expect(calls[1][1].workflowId).toEqual(workflowId)})- it('rethrows non-dedup start failures', async () => {+ it('rethrows non-dedup start failures and lets the next start retry', async () => {;(mockClient.workflow.start as jest.Mock).mockRejectedValue(new Error('Temporal unavailable'))await expect(@@ -463,6 +489,19 @@ describe('TemporalService', () => {settle: { strategy: 'fixed_window', window_seconds: 1800 },})).rejects.toThrow('Temporal unavailable')+ ;(mockClient.workflow.start as jest.Mock).mockResolvedValue(mockWorkflowHandle)+ await expect(+ service.startAggregateEvaluationWorkflow({+ evaluationId: 'eval-123',+ event: createMockEvent(),+ target: 'trace',+ traceId: 'trace-789',+ sessionId: null,+ aiSessionId: null,+ settle: { strategy: 'fixed_window', window_seconds: 1800 },+ })+ ).resolves.toBe(mockWorkflowHandle)+ expect(mockClient.workflow.start).toHaveBeenCalledTimes(2)})})diff --git a/nodejs/src/ai-observability/services/temporal.service.ts b/nodejs/src/ai-observability/services/temporal.service.tsindex b2db111d5b14..15f4843844ce 100644--- a/nodejs/src/ai-observability/services/temporal.service.ts+++ b/nodejs/src/ai-observability/services/temporal.service.ts@@ -9,6 +9,7 @@ import {} from '@temporalio/client'import * as crypto from 'crypto'import fs from 'fs/promises'+import { LRUCache } from 'lru-cache'import { Counter } from 'prom-client'import { EncryptionCodec } from '~/common/temporal/codec'@@ -171,6 +172,11 @@ const temporalWorkflowsStarted = new Counter({labelNames: ['status', 'payload'],})+// A skip only delays the retry of a failed run: a running workflow ignores the start, and a+// completed one rejects it. Keep the window short so that delay stays short.+const AGGREGATE_START_DEDUP_TTL_MS = 60_000+const AGGREGATE_START_DEDUP_MAX_ENTRIES = 50_000+export interface AggregateEvaluationStart {evaluationId: stringevent: RawKafkaEvent@@ -196,6 +202,10 @@ export function workflowSafeId(id: string): string {export class TemporalService {private client?: Clientprivate connecting?: Promise<Client>+ private recentAggregateStarts = new LRUCache<string, Promise<WorkflowHandle | null>>({+ max: AGGREGATE_START_DEDUP_MAX_ENTRIES,+ ttl: AGGREGATE_START_DEDUP_TTL_MS,+ })constructor(private config: TemporalServiceConfig) {}@@ -346,16 +356,41 @@ export class TemporalService {* evaluation for as long as the closed workflow stays inside Temporal's retention window,* which also caps the damage from runaway shared ids ("0", "fixed_id", ...). Returns null when* the unit was already evaluated.+ *+ * Each of those no-op starts still costs Temporal a failed create and a conflict lookup, and+ * concurrent starts on one id queue behind each other. So repeat starts for an id inside a short+ * window reuse the first start and do not call Temporal.*/async startAggregateEvaluationWorkflow(options: AggregateEvaluationStart): Promise<WorkflowHandle | null> {- const { evaluationId, event, target, traceId, sessionId, aiSessionId, settle } = options- const client = await this.ensureConnected()-+ const { evaluationId, target, traceId, aiSessionId } = optionsconst workflowId =target === 'session'? `llma-session-eval-${evaluationId}-${workflowSafeId(aiSessionId ?? '')}`: `llma-trace-eval-${evaluationId}-${workflowSafeId(traceId)}`+ const recentStart = this.recentAggregateStarts.get(workflowId)+ if (recentStart) {+ temporalWorkflowsStarted.labels({ status: 'deduplicated' }).inc()+ return await recentStart+ }++ const start = this.requestAggregateEvaluationWorkflow(workflowId, options)+ this.recentAggregateStarts.set(workflowId, start)+ start.catch(() => {+ if (this.recentAggregateStarts.peek(workflowId) === start) {+ this.recentAggregateStarts.delete(workflowId)+ }+ })+ return await start+ }++ private async requestAggregateEvaluationWorkflow(+ workflowId: string,+ options: AggregateEvaluationStart+ ): Promise<WorkflowHandle | null> {+ const { evaluationId, event, target, traceId, sessionId, aiSessionId, settle } = options+ const client = await this.ensureConnected()+try {const handle = await client.workflow.start('run-aggregate-evaluation', {args: [