long-session.bench.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /** Required browser budgets for opening, paging and continuing synthetic long history. */
  2. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { performance } from 'node:perf_hooks'
  6. import { chromium, type Page, type CDPSession, type Locator } from 'playwright'
  7. import { expect, it } from 'vitest'
  8. import { launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from '../../apps/web/tests/scaffold.ts'
  9. import { newEnglishPage } from '../../apps/web/tests/support.ts'
  10. import { ciTimeBudget, PERFORMANCE_BUDGET_HEADROOM } from '../support/calibration.ts'
  11. import { HISTORY_TURNS, SESSION_ID, FIRST, DONE, DELTAS, PACE_MS, syntheticHistory, syntheticReply } from './synthetic-history.ts'
  12. const SAMPLES = 3
  13. const TAIL = '[data-chat-flow-key^="9:turn-tail"]'
  14. const REFERENCE = { open: 200, page: 260, trajectory: 160, first: 1100, streamTask: 1800, input: 500, streamWall: 1000 }
  15. const EXPECTED_OPEN_CI_MS = 900
  16. const EXPECTED_PAGE_CI_MS = 700
  17. const EXPECTED_TRAJECTORY_CI_MS = 500
  18. const OPEN_BUDGET_MS = Math.ceil(EXPECTED_OPEN_CI_MS * PERFORMANCE_BUDGET_HEADROOM)
  19. const PAGE_BUDGET_MS = Math.ceil(EXPECTED_PAGE_CI_MS * PERFORMANCE_BUDGET_HEADROOM)
  20. const TRAJECTORY_BUDGET_MS = Math.ceil(EXPECTED_TRAJECTORY_CI_MS * PERFORMANCE_BUDGET_HEADROOM)
  21. const REPLAY_DURATION_MS = (DELTAS + 4) * PACE_MS
  22. async function painted(page: Page): Promise<void> {
  23. // Two rAF callbacks include a rendering opportunity, not a GPU presentation timestamp.
  24. await page.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))))
  25. }
  26. async function measure(page: Page, action: () => Promise<void>): Promise<number> {
  27. const start = performance.now()
  28. await action()
  29. await painted(page)
  30. return performance.now() - start
  31. }
  32. async function taskMs(cdp: CDPSession): Promise<number> {
  33. const result = await cdp.send('Performance.getMetrics')
  34. const metric = result.metrics.find(metric => metric.name === 'TaskDuration')
  35. if (metric === undefined) throw new Error('Chromium TaskDuration missing')
  36. return metric.value * 1000
  37. }
  38. function median(values: number[]): number {
  39. return values.toSorted((a, b) => a - b)[Math.floor(values.length / 2)]!
  40. }
  41. function expectEndpointWithinBudget(value: number, budget: number): void {
  42. expect(value).toBeLessThanOrEqual(budget)
  43. }
  44. function expectInputOverlap(value: boolean): void {
  45. expect(value).toBe(true)
  46. }
  47. async function watchInputOverlap(composer: Locator): Promise<void> {
  48. await composer.evaluate((element, markers) => {
  49. element.removeAttribute('data-benchmark-input-witness')
  50. element.removeAttribute('data-benchmark-input-overlap')
  51. element.removeAttribute('data-benchmark-input-timing')
  52. element.addEventListener('input', (event) => {
  53. const transcript = Array.from(document.querySelectorAll('[data-chat-flow-kind="assistant-step"]')).at(-1)?.textContent ?? ''
  54. element.setAttribute('data-benchmark-input-overlap', String(event.isTrusted && transcript.includes(markers.first) && !transcript.includes(markers.done)))
  55. element.setAttribute('data-benchmark-input-witness', JSON.stringify({ trusted: event.isTrusted, first: transcript.includes(markers.first), done: transcript.includes(markers.done) }))
  56. element.setAttribute('data-benchmark-input-timing', JSON.stringify({ atMs: window.performance.now(), eventAtMs: event.timeStamp, focused: document.activeElement === element }))
  57. }, { once: true })
  58. }, { first: FIRST, done: DONE })
  59. }
  60. it('accepts recorded hosted open samples and rejects slower endpoints', () => {
  61. for (const value of [681.276514, 541.051233]) {
  62. expect(() => expectEndpointWithinBudget(value, ciTimeBudget(REFERENCE.open))).toThrow()
  63. expectEndpointWithinBudget(value, OPEN_BUDGET_MS)
  64. }
  65. const repeatedMedian = median([875.306861, 1083.683529, 814.700998])
  66. expect(repeatedMedian).toBe(875.306861)
  67. expect(() => expectEndpointWithinBudget(repeatedMedian, ciTimeBudget(REFERENCE.open))).toThrow()
  68. expect(() => expectEndpointWithinBudget(repeatedMedian, 875)).toThrow()
  69. expectEndpointWithinBudget(repeatedMedian, OPEN_BUDGET_MS)
  70. expect(OPEN_BUDGET_MS).toBe(1125)
  71. expect(() => expectEndpointWithinBudget(OPEN_BUDGET_MS + 1, OPEN_BUDGET_MS)).toThrow()
  72. expect(() => expectEndpointWithinBudget(2000, OPEN_BUDGET_MS)).toThrow()
  73. })
  74. it('accepts recorded hosted paging and Trajectory medians and rejects slower endpoints', () => {
  75. const endpoints = [
  76. { samples: [843.941625, 672.834329, 684.461818], reference: REFERENCE.page, budget: PAGE_BUDGET_MS, expectedBudget: 875 },
  77. { samples: [605.788061, 367.754027, 485.931656], reference: REFERENCE.trajectory, budget: TRAJECTORY_BUDGET_MS, expectedBudget: 625 },
  78. ]
  79. for (const { samples, reference, budget, expectedBudget } of endpoints) {
  80. const value = median(samples)
  81. expect(() => expectEndpointWithinBudget(value, ciTimeBudget(reference))).toThrow()
  82. expectEndpointWithinBudget(value, budget)
  83. expect(budget).toBe(expectedBudget)
  84. expect(() => expectEndpointWithinBudget(budget + 1, budget)).toThrow()
  85. }
  86. })
  87. it('opens, pages, navigates and streams into a 240-turn browser history', async () => {
  88. if (webSnapshotMode() !== 'replay') throw new Error('browser benchmarks require keyless replay mode')
  89. const samples: { open: number; page: number; trajectory: number; first: number; streamTask: number; streamWall: number; input: number; inputOverlapped: boolean; heapMb: number; nodes: number }[] = []
  90. for (let sample = 0; sample < SAMPLES; sample++) {
  91. const failures: unknown[] = []
  92. const root = await mkdtemp(join(tmpdir(), 'dsh-browser-benchmark-'))
  93. try {
  94. const replayOverride = join(root, 'reply.json')
  95. await writeFile(replayOverride, JSON.stringify([{ kind: 'chunks', chunks: syntheticReply() }]))
  96. const scaffold = await launchWebScaffold({ replayFixture: join(root, 'override-only.jsonl'), replayOverride, paceMs: PACE_MS, replayContextWindow: 10000000 })
  97. try {
  98. const history = syntheticHistory()
  99. await seedSession(scaffold, history, SESSION_ID)
  100. console.log(JSON.stringify({ benchmark: 'long-session-browser/fixture', bytes: Buffer.byteLength(history) }))
  101. const browser = await chromium.launch({ headless: true })
  102. try {
  103. const page = await newEnglishPage(browser)
  104. const consoleWatch = watchConsole(page)
  105. page.setDefaultTimeout(30000)
  106. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  107. expect(new URL(page.url()).origin).toBe(scaffold.baseUrl)
  108. console.log(JSON.stringify({ benchmark: 'long-session-browser/server', url: scaffold.baseUrl, browser: browser.version(), sample }))
  109. await page.waitForSelector('[class*="frame"]')
  110. await page.getByRole('treeitem').first().click()
  111. const result = page.getByRole('treeitem').nth(1)
  112. await result.waitFor()
  113. const open = await measure(page, async () => {
  114. await result.click()
  115. await page.locator(TAIL).last().waitFor()
  116. await page.locator('[data-composer-input][contenteditable="true"]').last().waitFor()
  117. })
  118. const pages: number[] = []
  119. const initialTurns = await page.locator(TAIL).count()
  120. expect(initialTurns).toBeGreaterThan(0)
  121. expect(initialTurns).toBeLessThan(HISTORY_TURNS)
  122. let count = initialTurns
  123. while (count < HISTORY_TURNS) {
  124. pages.push(await measure(page, async () => {
  125. await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
  126. await page.waitForFunction(({ selector, previous }) => document.querySelectorAll(selector).length > previous, { selector: TAIL, previous: count })
  127. }))
  128. count = await page.locator(TAIL).count()
  129. }
  130. const trajectory = await measure(page, async () => {
  131. await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
  132. await page.getByRole('searchbox', { name: 'Search trajectory', exact: true }).waitFor()
  133. await page.getByRole('row').last().waitFor()
  134. })
  135. await page.getByRole('tab', { name: 'Chat', exact: true }).click()
  136. await page.waitForFunction(({ selector, expected }) => document.querySelectorAll(selector).length === expected, { selector: TAIL, expected: HISTORY_TURNS })
  137. const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
  138. await composer.fill('Continue the synthetic review and summarize the validation. '.repeat(30))
  139. const cdp = await page.context().newCDPSession(page)
  140. await cdp.send('Performance.enable')
  141. const beforeTask = await taskMs(cdp)
  142. const settled = scaffold.whenTurnSettled(60000).then(
  143. () => ({ ok: true as const }),
  144. (error: unknown) => ({ ok: false as const, error }),
  145. )
  146. await watchInputOverlap(composer)
  147. const started = performance.now()
  148. await page.keyboard.press('Enter')
  149. const reply = page.locator('[data-chat-flow-kind="assistant-step"]').last()
  150. await reply.getByText(FIRST, { exact: false }).last().waitFor()
  151. const first = performance.now() - started
  152. const firstObservation = await composer.evaluate((element, markers) => {
  153. const transcript = Array.from(document.querySelectorAll('[data-chat-flow-kind="assistant-step"]')).at(-1)?.textContent ?? ''
  154. return { atMs: window.performance.now(), focused: document.activeElement === element, first: transcript.includes(markers.first), done: transcript.includes(markers.done) }
  155. }, { first: FIRST, done: DONE })
  156. // Keep focus across submission; mouse actionability must not delay the input probe.
  157. const input = await measure(page, async () => {
  158. await page.keyboard.type('next synthetic question')
  159. await expect.poll(() => composer.textContent()).toBe('next synthetic question')
  160. })
  161. const inputOverlapped = await composer.getAttribute('data-benchmark-input-overlap') === 'true'
  162. console.log(JSON.stringify({ benchmark: 'long-session-browser/input', sample, first, input, firstObservation, witness: await composer.getAttribute('data-benchmark-input-witness'), inputTiming: await composer.getAttribute('data-benchmark-input-timing') }))
  163. expectInputOverlap(inputOverlapped)
  164. await reply.getByText(DONE, { exact: false }).last().waitFor()
  165. const settlement = await settled
  166. if (!settlement.ok) throw settlement.error
  167. await page.waitForFunction(({ selector, expected }) => document.querySelectorAll(selector).length === expected, { selector: TAIL, expected: HISTORY_TURNS + 1 })
  168. await painted(page)
  169. const streamWall = performance.now() - started
  170. const streamTask = await taskMs(cdp) - beforeTask
  171. await cdp.send('HeapProfiler.collectGarbage')
  172. const metrics = (await cdp.send('Performance.getMetrics')).metrics
  173. const heap = metrics.find(metric => metric.name === 'JSHeapUsedSize')
  174. if (heap === undefined) throw new Error('Chromium heap metric missing')
  175. samples.push({ open, page: Math.max(...pages), trajectory, first, streamTask, streamWall, input, inputOverlapped, heapMb: heap.value / 1048576, nodes: await page.locator('*').count() })
  176. console.log(JSON.stringify({ benchmark: 'long-session-browser/sample', sample, initialTurns, pages, ...samples.at(-1) }))
  177. await watchInputOverlap(composer)
  178. await composer.click()
  179. await page.keyboard.type('!')
  180. const lateInputOverlapped = await composer.getAttribute('data-benchmark-input-overlap') === 'true'
  181. expect(await composer.getAttribute('data-benchmark-input-witness')).toBe(JSON.stringify({ trusted: true, first: true, done: true }))
  182. expect(() => expectInputOverlap(lateInputOverlapped)).toThrow()
  183. expect(consoleWatch.pageErrors).toEqual([])
  184. expect(consoleWatch.warnings).toEqual([])
  185. } catch (error) { failures.push(error) } finally {
  186. await browser.close().catch((error: unknown) => failures.push(error))
  187. }
  188. } catch (error) { failures.push(error) } finally {
  189. await scaffold.close().catch((error: unknown) => failures.push(error))
  190. }
  191. } catch (error) { failures.push(error) } finally {
  192. await rm(root, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  193. }
  194. if (failures.length > 0) throw new AggregateError(failures, 'browser benchmark failed')
  195. }
  196. const aggregate = Object.fromEntries(Object.keys(REFERENCE).map(key => [key, median(samples.map(sample => sample[key as keyof typeof REFERENCE]))]))
  197. const budgets: Record<string, number> = {
  198. ...Object.fromEntries(Object.entries(REFERENCE).map(([key, value]) => [key, ciTimeBudget(value) + (key === 'streamWall' ? REPLAY_DURATION_MS : 0)])),
  199. open: OPEN_BUDGET_MS, page: PAGE_BUDGET_MS, trajectory: TRAJECTORY_BUDGET_MS,
  200. }
  201. console.log(JSON.stringify({ benchmark: 'long-session-browser/median', turns: HISTORY_TURNS, deltas: DELTAS, paceMs: PACE_MS, samples, aggregate, referenceMs: REFERENCE, expectedOpenCiMs: EXPECTED_OPEN_CI_MS, expectedPageCiMs: EXPECTED_PAGE_CI_MS, expectedTrajectoryCiMs: EXPECTED_TRAJECTORY_CI_MS, budgets }))
  202. for (const [key, value] of Object.entries(aggregate)) expectEndpointWithinBudget(value, budgets[key]!)
  203. })