Skip to content

: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.

fix(aio): stop the playground re-sending a superseded completion (#117563)

Carlos Marchal09d966ef1045
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
index cfb81f8fdfa2..fa8c46309658 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.test.ts
@@ -19,6 +19,22 @@ import {
} from './llmPlaygroundRunLogic'
import { llmPlaygroundVariablesLogic } from './llmPlaygroundVariablesLogic'
+// Same contract as fetch-event-source: an error from the request or from onmessage goes to onerror,
+// and the request is sent again unless onerror throws.
+function mockStreamWithRetryContract(
+ produce: (options: any) => void | Promise<void>,
+ onRetry: () => void
+): (url: string, options: any) => Promise<void> {
+ return async (_url, options) => {
+ try {
+ await produce(options)
+ } catch (error) {
+ options.onError(error)
+ onRetry()
+ }
+ }
+}
+
function setPlaygroundAccessLevel(level: AccessControlLevel): void {
window.POSTHOG_APP_CONTEXT = {
...window.POSTHOG_APP_CONTEXT,
@@ -265,9 +281,10 @@ describe('llmPlaygroundRunLogic', () => {
const apiError = new ApiError('fallback message', 400, undefined, {
error: 'Thinking is not supported for this model',
})
- const streamSpy = jest.spyOn(api, 'stream').mockImplementation(async (_url, options: any) => {
- options.onError?.(apiError)
- })
+ const retried = jest.fn()
+ const streamSpy = jest
+ .spyOn(api, 'stream')
+ .mockImplementation(mockStreamWithRetryContract((options) => options.onError(apiError), retried))
const captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)
const logic = llmPlaygroundRunLogic()
@@ -283,8 +300,10 @@ describe('llmPlaygroundRunLogic', () => {
const items = llmPlaygroundRunLogic.values.comparisonItems
expect(items).toHaveLength(1)
expect(items[0].error).toBe(true)
- expect(items[0].response).toContain('**Error:** Thinking is not supported for this model')
+ expect(items[0].response.match(/\*\*Error:\*\* Thinking is not supported for this model/g)).toHaveLength(1)
expect(items[0].response).not.toContain('Stream Connection Error')
+ expect(retried).not.toHaveBeenCalled()
+ expect(captureExceptionSpy).toHaveBeenCalledTimes(1)
expect(captureExceptionSpy).toHaveBeenCalledWith(
apiError,
expect.objectContaining({ tag: 'llma-playground-prompt-run', status: 400 })
@@ -295,11 +314,14 @@ describe('llmPlaygroundRunLogic', () => {
captureExceptionSpy.mockRestore()
})
- it('labels non-ApiError stream failures as connection errors and captures them', async () => {
+ it('labels network failures as connection errors, captures them once and does not retry', async () => {
const connectionError = new Error('network down')
- const streamSpy = jest.spyOn(api, 'stream').mockImplementation(async (_url, options: any) => {
- options.onError?.(connectionError)
- })
+ const retried = jest.fn()
+ const streamSpy = jest.spyOn(api, 'stream').mockImplementation(
+ mockStreamWithRetryContract(() => {
+ throw connectionError
+ }, retried)
+ )
const captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)
const logic = llmPlaygroundRunLogic()
@@ -316,6 +338,8 @@ describe('llmPlaygroundRunLogic', () => {
expect(items).toHaveLength(1)
expect(items[0].error).toBe(true)
expect(items[0].response).toContain('**Stream Connection Error:** network down')
+ expect(retried).not.toHaveBeenCalled()
+ expect(captureExceptionSpy).toHaveBeenCalledTimes(1)
expect(captureExceptionSpy).toHaveBeenCalledWith(
connectionError,
expect.objectContaining({ tag: 'llma-playground-prompt-run', status: undefined })
@@ -326,6 +350,112 @@ describe('llmPlaygroundRunLogic', () => {
captureExceptionSpy.mockRestore()
})
+ it('stops a superseded run silently and keeps submitting until the newer run ends', async () => {
+ let releaseFirstStream: () => void = () => {}
+ const firstStreamGate = new Promise<void>((resolve) => {
+ releaseFirstStream = resolve
+ })
+ let releaseSecondStream: () => void = () => {}
+ const secondStreamGate = new Promise<void>((resolve) => {
+ releaseSecondStream = resolve
+ })
+ const retried = jest.fn()
+ const streamSpy = jest
+ .spyOn(api, 'stream')
+ .mockImplementationOnce(
+ mockStreamWithRetryContract(async (options) => {
+ await firstStreamGate
+ options.onMessage({ data: JSON.stringify({ type: 'text', text: 'stale' }) })
+ }, retried)
+ )
+ .mockImplementationOnce(() => secondStreamGate)
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ const captureExceptionSpy = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)
+ const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
+
+ const logic = llmPlaygroundRunLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ llmPlaygroundPromptsLogic.actions.setModel('gpt-5-mini')
+ llmPlaygroundPromptsLogic.actions.setMessages([{ role: 'user', content: 'hello' }])
+ llmPlaygroundRunLogic.actions.submitPrompt()
+ llmPlaygroundRunLogic.actions.submitPrompt()
+ releaseFirstStream()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(logic.values.submitting).toBe(true)
+ expect(logic.values.comparisonItems.map((item) => item.response)).toEqual([''])
+
+ releaseSecondStream()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.submitting).toBe(false)
+ expect(streamSpy).toHaveBeenCalledTimes(2)
+ expect(retried).not.toHaveBeenCalled()
+ expect(captureSpy.mock.calls.filter(([event]) => event === 'llma playground prompt completed')).toHaveLength(1)
+ expect(captureExceptionSpy).not.toHaveBeenCalled()
+ expect(toastSpy).not.toHaveBeenCalled()
+
+ logic.unmount()
+ streamSpy.mockRestore()
+ captureSpy.mockRestore()
+ captureExceptionSpy.mockRestore()
+ toastSpy.mockRestore()
+ })
+
+ describe('when a streaming run is interrupted', () => {
+ let streamSignal: AbortSignal | undefined
+ let streamSpy: jest.SpyInstance
+ let captureSpy: jest.SpyInstance
+
+ const completedEvents = (): unknown[] =>
+ captureSpy.mock.calls
+ .filter(([event]) => event === 'llma playground prompt completed')
+ .map(([, properties]) => properties)
+
+ beforeEach(async () => {
+ streamSpy = jest.spyOn(api, 'stream').mockImplementation(async (_url, options: any) => {
+ streamSignal = options.signal
+ options.onMessage({ data: JSON.stringify({ type: 'text', text: 'partial' }) })
+ // fetch-event-source resolves, rather than rejects, when its signal aborts.
+ await new Promise((resolve) => options.signal.addEventListener('abort', resolve))
+ })
+ captureSpy = jest.spyOn(posthog, 'capture')
+
+ llmPlaygroundRunLogic.mount()
+ await expectLogic(llmPlaygroundRunLogic).toFinishAllListeners()
+ llmPlaygroundPromptsLogic.actions.setModel('gpt-5-mini')
+ llmPlaygroundPromptsLogic.actions.setMessages([{ role: 'user', content: 'hello' }])
+ llmPlaygroundRunLogic.actions.submitPrompt()
+ await expectLogic(llmPlaygroundRunLogic).toDispatchActions(['addToComparison'])
+ })
+
+ afterEach(() => {
+ streamSpy.mockRestore()
+ captureSpy.mockRestore()
+ })
+
+ it('marks the run as stopped when the user stops it', async () => {
+ llmPlaygroundRunLogic.actions.abortRun()
+ await expectLogic(llmPlaygroundRunLogic).toFinishAllListeners()
+
+ expect(llmPlaygroundRunLogic.values.comparisonItems[0].response).toBe('partial\n\n*Generation stopped.*')
+ expect(llmPlaygroundRunLogic.values.submitting).toBe(false)
+ expect(completedEvents()).toEqual([expect.objectContaining({ aborted: true, success: true })])
+
+ llmPlaygroundRunLogic.unmount()
+ })
+
+ it('ends the stream silently when the user leaves the playground', async () => {
+ llmPlaygroundRunLogic.unmount()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+
+ expect(streamSignal?.aborted).toBe(true)
+ expect(completedEvents()).toEqual([])
+ })
+ })
+
it('captures exceptions thrown before the stream opens', async () => {
const thrownError = new ApiError('fallback message', 400, undefined, {
error: 'Invalid provider key configuration',
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
index df8fd375d0e7..38f9d50bd62e 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundRunLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, beforeUnmount, connect, kea, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -159,6 +159,12 @@ export interface ComparisonItem {
// Kea state avoids storing a non-serializable object in reducers.
let currentAbortController: AbortController | null = null
+// An abandoned run stops streaming and reports nothing, because nobody is waiting for its result.
+function abandonCurrentRun(): void {
+ currentAbortController?.abort()
+ currentAbortController = null
+}
+
export type LLMPlaygroundRunLogicProps = Record<string, never>
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -300,7 +306,9 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
}
},
- submitPrompt: async (_: unknown, breakpoint: () => void) => {
+ submitPrompt: async () => {
+ abandonCurrentRun()
+
// Guarding here rather than only on the Run button, because both message textareas
// submit on Cmd+Enter and bypass the button entirely.
if (values.runAccessDeniedReason) {
@@ -357,6 +365,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
const abortController = new AbortController()
currentAbortController = abortController
+ const isAbandoned = (): boolean => currentAbortController !== abortController
try {
const runs = runnablePrompts.map(async ({ prompt, index, messagesToSend }) => {
// Resolve {{variables}} only in what is sent; the editors keep the raw template.
@@ -388,6 +397,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
let providerKeyId: string | null = null
let selectedModelProvider = ''
let itemAdded = false
+ let reportedStreamError: unknown = undefined
const upsertLiveItem = (): void => {
const payload: ComparisonItem = {
@@ -415,6 +425,32 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
}
}
+ const reportStreamError = (err: unknown): void => {
+ if (err instanceof RateLimitError) {
+ actions.setRateLimited(err.retryAfterSeconds)
+ responseHasError = true
+ upsertLiveItem()
+ return
+ }
+ if (err instanceof ApiError && err.status === 402) {
+ actions.setSubscriptionRequired(true)
+ responseHasError = true
+ upsertLiveItem()
+ return
+ }
+ const { message, status } = describeError(err, 'Unknown error')
+ const errorLabel = err instanceof ApiError ? 'Error' : 'Stream Connection Error'
+ responseText += `\n\n**${errorLabel}:** ${message}`
+ responseHasError = true
+ upsertLiveItem()
+ posthog.captureException(err, {
+ tag: 'llma-playground-prompt-run',
+ model: prompt.model,
+ provider: selectedModelProvider,
+ status,
+ })
+ }
+
upsertLiveItem()
try {
@@ -478,8 +514,7 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
headers: { 'Content-Type': 'application/json' },
signal: abortController.signal,
onMessage: (event) => {
- breakpoint()
- if (!event.data) {
+ if (abortController.signal.aborted || !event.data) {
return
}
@@ -530,46 +565,21 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
}
},
onError: (err) => {
- if (abortController.signal.aborted) {
- return
+ // api.stream can pass the same error to onError twice: once from its onopen
+ // handler, and again when fetch-event-source catches the rethrow below.
+ if (!abortController.signal.aborted && err !== reportedStreamError) {
+ reportedStreamError = err
+ reportStreamError(err)
}
- if (err instanceof RateLimitError) {
- actions.setRateLimited(err.retryAfterSeconds)
- responseHasError = true
- upsertLiveItem()
- return
- }
- if (err instanceof ApiError && err.status === 402) {
- actions.setSubscriptionRequired(true)
- responseHasError = true
- upsertLiveItem()
- return
- }
- const { message, status } = describeError(err, 'Unknown error')
- const errorLabel = err instanceof ApiError ? 'Error' : 'Stream Connection Error'
- responseText += `\n\n**${errorLabel}:** ${message}`
- responseHasError = true
- upsertLiveItem()
- posthog.captureException(err, {
- tag: 'llma-playground-prompt-run',
- model: prompt.model,
- provider: selectedModelProvider,
- status,
- })
+ // fetch-event-source sends the request again whenever onerror returns, which
+ // would charge the user for a duplicate completion. Throwing ends the stream.
+ throw err
},
})
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.RunAiPlayground)
} catch (error) {
- if (abortController.signal.aborted) {
- responseText += `${responseText ? '\n\n' : ''}*Generation stopped.*`
- } else if (error instanceof RateLimitError) {
- actions.setRateLimited(error.retryAfterSeconds)
- responseHasError = true
- } else if (error instanceof ApiError && error.status === 402) {
- actions.setSubscriptionRequired(true)
- responseHasError = true
- } else {
+ if (!isAbandoned() && error !== reportedStreamError) {
const { message, status } = describeError(error, 'Failed to initiate prompt submission.')
responseText += `\n\n**Error:** ${message}`
responseHasError = true
@@ -581,13 +591,20 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
status,
})
}
- upsertLiveItem()
} finally {
if (startTime !== null) {
latencyMs = performance.now() - startTime
}
}
+ if (isAbandoned()) {
+ return
+ }
+ // fetch-event-source resolves rather than rejects on abort, so a stop by the user ends up here.
+ if (abortController.signal.aborted) {
+ responseText += `${responseText ? '\n\n' : ''}*Generation stopped.*`
+ }
+
upsertLiveItem()
posthog.capture('llma playground prompt completed', {
@@ -605,12 +622,15 @@ export const llmPlaygroundRunLogic = kea<llmPlaygroundRunLogicType>([
await Promise.allSettled(runs)
} finally {
- if (currentAbortController === abortController) {
+ abortController.abort()
+ if (!isAbandoned()) {
currentAbortController = null
+ actions.finishSubmitPrompt()
}
- abortController.abort()
- actions.finishSubmitPrompt()
}
},
})),
+ beforeUnmount(() => {
+ abandonCurrentRun()
+ }),
])