long-session.bench.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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.addEventListener('input', (event) => {
  52. const transcript = Array.from(document.querySelectorAll('[data-chat-flow-kind="assistant-step"]')).at(-1)?.textContent ?? ''
  53. element.setAttribute('data-benchmark-input-overlap', String(event.isTrusted && transcript.includes(markers.first) && !transcript.includes(markers.done)))
  54. element.setAttribute('data-benchmark-input-witness', JSON.stringify({ trusted: event.isTrusted, first: transcript.includes(markers.first), done: transcript.includes(markers.done) }))
  55. }, { once: true })
  56. }, { first: FIRST, done: DONE })
  57. }
  58. it('accepts recorded hosted open samples and rejects slower endpoints', () => {
  59. for (const value of [681.276514, 541.051233]) {
  60. expect(() => expectEndpointWithinBudget(value, ciTimeBudget(REFERENCE.open))).toThrow()
  61. expectEndpointWithinBudget(value, OPEN_BUDGET_MS)
  62. }
  63. const repeatedMedian = median([875.306861, 1083.683529, 814.700998])
  64. expect(repeatedMedian).toBe(875.306861)
  65. expect(() => expectEndpointWithinBudget(repeatedMedian, ciTimeBudget(REFERENCE.open))).toThrow()
  66. expect(() => expectEndpointWithinBudget(repeatedMedian, 875)).toThrow()
  67. expectEndpointWithinBudget(repeatedMedian, OPEN_BUDGET_MS)
  68. expect(OPEN_BUDGET_MS).toBe(1125)
  69. expect(() => expectEndpointWithinBudget(OPEN_BUDGET_MS + 1, OPEN_BUDGET_MS)).toThrow()
  70. expect(() => expectEndpointWithinBudget(2000, OPEN_BUDGET_MS)).toThrow()
  71. })
  72. it('accepts recorded hosted paging and Trajectory medians and rejects slower endpoints', () => {
  73. const endpoints = [
  74. { samples: [843.941625, 672.834329, 684.461818], reference: REFERENCE.page, budget: PAGE_BUDGET_MS, expectedBudget: 875 },
  75. { samples: [605.788061, 367.754027, 485.931656], reference: REFERENCE.trajectory, budget: TRAJECTORY_BUDGET_MS, expectedBudget: 625 },
  76. ]
  77. for (const { samples, reference, budget, expectedBudget } of endpoints) {
  78. const value = median(samples)
  79. expect(() => expectEndpointWithinBudget(value, ciTimeBudget(reference))).toThrow()
  80. expectEndpointWithinBudget(value, budget)
  81. expect(budget).toBe(expectedBudget)
  82. expect(() => expectEndpointWithinBudget(budget + 1, budget)).toThrow()
  83. }
  84. })
  85. it('opens, pages, navigates and streams into a 240-turn browser history', async () => {
  86. if (webSnapshotMode() !== 'replay') throw new Error('browser benchmarks require keyless replay mode')
  87. const samples: { open: number; page: number; trajectory: number; first: number; streamTask: number; streamWall: number; input: number; inputOverlapped: boolean; heapMb: number; nodes: number }[] = []
  88. for (let sample = 0; sample < SAMPLES; sample++) {
  89. const failures: unknown[] = []
  90. const root = await mkdtemp(join(tmpdir(), 'dsh-browser-benchmark-'))
  91. try {
  92. const replayOverride = join(root, 'reply.json')
  93. await writeFile(replayOverride, JSON.stringify([{ kind: 'chunks', chunks: syntheticReply() }]))
  94. const scaffold = await launchWebScaffold({ replayFixture: join(root, 'override-only.jsonl'), replayOverride, paceMs: PACE_MS, replayContextWindow: 10000000 })
  95. try {
  96. const history = syntheticHistory()
  97. await seedSession(scaffold, history, SESSION_ID)
  98. console.log(JSON.stringify({ benchmark: 'long-session-browser/fixture', bytes: Buffer.byteLength(history) }))
  99. const browser = await chromium.launch({ headless: true })
  100. try {
  101. const page = await newEnglishPage(browser)
  102. const consoleWatch = watchConsole(page)
  103. page.setDefaultTimeout(30000)
  104. await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
  105. expect(new URL(page.url()).origin).toBe(scaffold.baseUrl)
  106. console.log(JSON.stringify({ benchmark: 'long-session-browser/server', url: scaffold.baseUrl, browser: browser.version(), sample }))
  107. await page.waitForSelector('[class*="frame"]')
  108. await page.getByRole('treeitem').first().click()
  109. const result = page.getByRole('treeitem').nth(1)
  110. await result.waitFor()
  111. const open = await measure(page, async () => {
  112. await result.click()
  113. await page.locator(TAIL).last().waitFor()
  114. await page.locator('[data-composer-input][contenteditable="true"]').last().waitFor()
  115. })
  116. const pages: number[] = []
  117. const initialTurns = await page.locator(TAIL).count()
  118. expect(initialTurns).toBeGreaterThan(0)
  119. expect(initialTurns).toBeLessThan(HISTORY_TURNS)
  120. let count = initialTurns
  121. while (count < HISTORY_TURNS) {
  122. pages.push(await measure(page, async () => {
  123. await page.getByRole('button', { name: 'Load earlier', exact: true }).click()
  124. await page.waitForFunction(({ selector, previous }) => document.querySelectorAll(selector).length > previous, { selector: TAIL, previous: count })
  125. }))
  126. count = await page.locator(TAIL).count()
  127. }
  128. const trajectory = await measure(page, async () => {
  129. await page.getByRole('tab', { name: 'Trajectory', exact: true }).click()
  130. await page.getByRole('searchbox', { name: 'Search trajectory', exact: true }).waitFor()
  131. await page.getByRole('row').last().waitFor()
  132. })
  133. await page.getByRole('tab', { name: 'Chat', exact: true }).click()
  134. await page.waitForFunction(({ selector, expected }) => document.querySelectorAll(selector).length === expected, { selector: TAIL, expected: HISTORY_TURNS })
  135. const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
  136. await composer.fill('Continue the synthetic review and summarize the validation. '.repeat(30))
  137. const cdp = await page.context().newCDPSession(page)
  138. await cdp.send('Performance.enable')
  139. const beforeTask = await taskMs(cdp)
  140. const settled = scaffold.whenTurnSettled(60000).then(
  141. () => ({ ok: true as const }),
  142. (error: unknown) => ({ ok: false as const, error }),
  143. )
  144. await watchInputOverlap(composer)
  145. const started = performance.now()
  146. await page.locator('[data-composer-seat]').getByRole('button', { name: 'Send message', exact: true }).click()
  147. const reply = page.locator('[data-chat-flow-kind="assistant-step"]').last()
  148. await reply.getByText(FIRST, { exact: false }).last().waitFor()
  149. const first = performance.now() - started
  150. // Observe the actual trusted input event, not state before asynchronous click/typing.
  151. const input = await measure(page, async () => {
  152. await composer.click()
  153. await page.keyboard.type('next synthetic question')
  154. await expect.poll(() => composer.textContent()).toBe('next synthetic question')
  155. })
  156. const inputOverlapped = await composer.getAttribute('data-benchmark-input-overlap') === 'true'
  157. console.log(JSON.stringify({ benchmark: 'long-session-browser/input', sample, first, input, witness: await composer.getAttribute('data-benchmark-input-witness') }))
  158. expectInputOverlap(inputOverlapped)
  159. await reply.getByText(DONE, { exact: false }).last().waitFor()
  160. const settlement = await settled
  161. if (!settlement.ok) throw settlement.error
  162. await page.waitForFunction(({ selector, expected }) => document.querySelectorAll(selector).length === expected, { selector: TAIL, expected: HISTORY_TURNS + 1 })
  163. await painted(page)
  164. const streamWall = performance.now() - started
  165. const streamTask = await taskMs(cdp) - beforeTask
  166. await cdp.send('HeapProfiler.collectGarbage')
  167. const metrics = (await cdp.send('Performance.getMetrics')).metrics
  168. const heap = metrics.find(metric => metric.name === 'JSHeapUsedSize')
  169. if (heap === undefined) throw new Error('Chromium heap metric missing')
  170. samples.push({ open, page: Math.max(...pages), trajectory, first, streamTask, streamWall, input, inputOverlapped, heapMb: heap.value / 1048576, nodes: await page.locator('*').count() })
  171. console.log(JSON.stringify({ benchmark: 'long-session-browser/sample', sample, initialTurns, pages, ...samples.at(-1) }))
  172. await watchInputOverlap(composer)
  173. await composer.click()
  174. await page.keyboard.type('!')
  175. const lateInputOverlapped = await composer.getAttribute('data-benchmark-input-overlap') === 'true'
  176. expect(await composer.getAttribute('data-benchmark-input-witness')).toBe(JSON.stringify({ trusted: true, first: true, done: true }))
  177. expect(() => expectInputOverlap(lateInputOverlapped)).toThrow()
  178. expect(consoleWatch.pageErrors).toEqual([])
  179. expect(consoleWatch.warnings).toEqual([])
  180. } catch (error) { failures.push(error) } finally {
  181. await browser.close().catch((error: unknown) => failures.push(error))
  182. }
  183. } catch (error) { failures.push(error) } finally {
  184. await scaffold.close().catch((error: unknown) => failures.push(error))
  185. }
  186. } catch (error) { failures.push(error) } finally {
  187. await rm(root, { recursive: true, force: true }).catch((error: unknown) => failures.push(error))
  188. }
  189. if (failures.length > 0) throw new AggregateError(failures, 'browser benchmark failed')
  190. }
  191. const aggregate = Object.fromEntries(Object.keys(REFERENCE).map(key => [key, median(samples.map(sample => sample[key as keyof typeof REFERENCE]))]))
  192. const budgets: Record<string, number> = {
  193. ...Object.fromEntries(Object.entries(REFERENCE).map(([key, value]) => [key, ciTimeBudget(value) + (key === 'streamWall' ? REPLAY_DURATION_MS : 0)])),
  194. open: OPEN_BUDGET_MS, page: PAGE_BUDGET_MS, trajectory: TRAJECTORY_BUDGET_MS,
  195. }
  196. 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 }))
  197. for (const [key, value] of Object.entries(aggregate)) expectEndpointWithinBudget(value, budgets[key]!)
  198. })