perf(terminal): eliminate adverse control and frame-gate cases (#11045)

* perf(terminal): eliminate dense control and frame gate regressions

* test(terminal): keep gate labels in valid expect shape

* test(terminal): expose the surviving sub-threshold control-density case

The only adverse strip fixture sat at 50% control density, which is exactly
where the fallback fires and wins. A shape at 31 controls per 64-unit block
evades the trigger and still loses to the per-character legacy (0.67x), so the
benchmark structurally could not show it.

Add that fixture, pin both density literals in the staleness guard so a retune
fails loudly instead of silently measuring a boundary that moved, and export
the probe constant the equivalence test was hardcoding.
This commit is contained in:
Neil
2026-07-27 23:28:05 -07:00
committed by GitHub
parent a8660839ee
commit c25d85cc4c
7 changed files with 533 additions and 96 deletions
@@ -1,6 +1,54 @@
#!/usr/bin/env node
// Mirrors the complete pre/post stripTerminalControl paths at their production size caps.
// Compares legacy, slice-run, and production-adaptive control stripping.
import { spawnSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import nodeModule from 'node:module'
import { performance } from 'node:perf_hooks'
import { fileURLToPath } from 'node:url'
if (!process.execArgv.includes('--experimental-transform-types')) {
const result = spawnSync(
process.execPath,
['--experimental-transform-types', '--no-warnings', import.meta.filename],
{ stdio: 'inherit' }
)
process.exit(result.status ?? 1)
}
nodeModule.registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier.startsWith('.') && !/\.[cm]?[jt]s$/.test(specifier) && context.parentURL) {
const candidate = new URL(`${specifier}.ts`, context.parentURL)
if (existsSync(fileURLToPath(candidate))) {
return { url: candidate.href, shortCircuit: true }
}
}
return nextResolve(specifier, context)
}
})
const PRODUCTION_SOURCE = readFileSync(
new URL('../../src/shared/terminal-control-stripping.ts', import.meta.url),
'utf8'
)
for (const marker of [
'export function stripTerminalControl(data: string): string',
'strippedInBlock === CONTROL_DENSITY_FALLBACK_COUNT',
'output += withoutAnsi.slice(runStart, index)',
// Retuning either density constant changes which fixtures sit above/below the trigger, so
// pin the literals rather than the names: a silent retune would leave the sub-threshold
// fixture measuring a boundary that no longer exists.
'const CONTROL_DENSITY_BLOCK_CODE_UNITS = 64',
'const CONTROL_DENSITY_FALLBACK_COUNT = 32'
]) {
if (!PRODUCTION_SOURCE.includes(marker)) {
throw new Error(`terminal-control-stripping.ts no longer contains \`${marker}\``)
}
}
const { stripTerminalControl: stripAdaptive } = await import(
new URL('../../src/shared/terminal-control-stripping.ts', import.meta.url).href
)
const ESC = String.fromCharCode(0x1b)
const BEL = String.fromCharCode(0x07)
@@ -15,6 +63,9 @@ const INCOMPLETE_ANSI_ESCAPE_RE = new RegExp(
const HISTORY_LIMIT = 300
const SCAN_LIMIT = 4096
const SAMPLE_ID_LENGTH = 24
// Mirrors terminal-control-stripping.ts; the marker guard above fails if either is retuned.
const CONTROL_DENSITY_BLOCK_CODE_UNITS = 64
const CONTROL_DENSITY_FALLBACK_COUNT = 32
const ITERATIONS = Number(process.env.ORCA_STRIP_BENCH_ITERATIONS ?? '501')
let resultChecksum = 0
let validatedPairs = 0
@@ -75,6 +126,25 @@ function stripSliceRuns(data) {
return runStart === 0 ? withoutAnsi : output + withoutAnsi.slice(runStart)
}
function adaptiveFallbackIndex(data) {
const withoutAnsi = data.replace(ANSI_ESCAPE_RE, '').replace(INCOMPLETE_ANSI_ESCAPE_RE, '')
let strippedInBlock = 0
let blockEnd = 64
for (let index = 0; index < withoutAnsi.length; index += 1) {
if (index === blockEnd) {
strippedInBlock = 0
blockEnd += 64
}
if (isStrippedCode(withoutAnsi.charCodeAt(index))) {
strippedInBlock += 1
if (strippedInBlock === 32) {
return index
}
}
}
return -1
}
function fixedSampleId(sampleId) {
return `sample:${sampleId}`.padEnd(SAMPLE_ID_LENGTH, '_').slice(0, SAMPLE_ID_LENGTH)
}
@@ -95,6 +165,26 @@ function makeTuiFixture(length, sampleId, strippedControl) {
return text + 'x'.repeat(length - text.length)
}
// 31 controls per 64-unit block: one below the fallback trigger, so the adaptive path keeps
// slice-run bookkeeping on a shape dense enough to lose to the per-character legacy. This is the
// worst surviving case; it exists so the narrowed adverse window stays visible instead of hiding
// behind the 50% fixture, where the fallback fires and wins.
function makeSubThresholdDenseFixture(length, sampleId, strippedControl) {
const id = fixedSampleId(sampleId)
const units = []
for (let index = 0; index < length; index += 1) {
const blockOffset = index % CONTROL_DENSITY_BLOCK_CODE_UNITS
if (index < id.length) {
units.push(id[index])
} else if (blockOffset % 2 === 1 && blockOffset < (CONTROL_DENSITY_FALLBACK_COUNT - 1) * 2) {
units.push(strippedControl)
} else {
units.push(String.fromCharCode(97 + (index % 26)))
}
}
return units.join('')
}
function makeDenseFixture(length, sampleId, strippedControl) {
const prefix = `\x1b[35m${fixedSampleId(sampleId)}`
const suffix = '\x1b[0m'
@@ -120,33 +210,35 @@ function consumeOutput(output) {
resultChecksum ^= output.charCodeAt(Math.floor(output.length / 2))
}
function recordPair(fixture, sampleId, perCharFirst, samples) {
const perCharFixture = fixture.make(sampleId, perCharFirst ? '\x01' : '\x02')
const sliceRunsFixture = fixture.make(sampleId, perCharFirst ? '\x02' : '\x01')
if (
perCharFixture === sliceRunsFixture ||
perCharFixture.length !== fixture.length ||
sliceRunsFixture.length !== fixture.length
) {
const IMPLEMENTATIONS = [
['perChar', stripPerChar, '\x01'],
['sliceRuns', stripSliceRuns, '\x02'],
['adaptive', stripAdaptive, '\x03']
]
function recordRotation(fixture, sampleId, lead, samples) {
const inputs = IMPLEMENTATIONS.map(([name, strip, control]) => ({
name,
strip,
input: fixture.make(sampleId, control)
}))
if (inputs.some(({ input }) => input.length !== fixture.length)) {
throw new Error(`invalid inputs for ${fixture.label}, sample ${sampleId}`)
}
let perCharResult
let sliceRunsResult
if (perCharFirst) {
perCharResult = measure(stripPerChar, perCharFixture)
sliceRunsResult = measure(stripSliceRuns, sliceRunsFixture)
} else {
sliceRunsResult = measure(stripSliceRuns, sliceRunsFixture)
perCharResult = measure(stripPerChar, perCharFixture)
const results = new Map()
for (let offset = 0; offset < inputs.length; offset += 1) {
const entry = inputs[(lead + offset) % inputs.length]
results.set(entry.name, measure(entry.strip, entry.input))
}
if (perCharResult.output !== sliceRunsResult.output) {
const outputs = [...results.values()].map(({ output }) => output)
if (new Set(outputs).size !== 1) {
throw new Error(`strip mismatch for ${fixture.label}, sample ${sampleId}`)
}
consumeOutput(perCharResult.output)
consumeOutput(sliceRunsResult.output)
for (const [name, result] of results) {
consumeOutput(result.output)
samples[name].push(result.elapsed)
}
validatedPairs += 1
samples.perChar.push(perCharResult.elapsed)
samples.sliceRuns.push(sliceRunsResult.elapsed)
}
const denseBodyLength = SCAN_LIMIT - '\x1b[35m'.length - SAMPLE_ID_LENGTH - '\x1b[0m'.length
@@ -171,32 +263,68 @@ const fixtures = [
label: `${SCAN_LIMIT} scan ${denseControlPercent}% C0`,
length: SCAN_LIMIT,
make: (sampleId, control) => makeDenseFixture(SCAN_LIMIT, sampleId, control)
},
{
label: `${SCAN_LIMIT} scan 31/block C0`,
length: SCAN_LIMIT,
make: (sampleId, control) => makeSubThresholdDenseFixture(SCAN_LIMIT, sampleId, control)
}
]
const selectorFixtures = [
{ label: '31 controls', data: `${'\x01'.repeat(31)}${'a'.repeat(33)}`, expected: -1 },
{ label: '32 controls', data: `${'\x01'.repeat(32)}${'a'.repeat(32)}`, expected: 31 },
{
label: 'block reset at 64',
data: `${'\x01'.repeat(31)}${'a'.repeat(33)}${'\x01'.repeat(32)}`,
expected: 95
},
{
label: 'late dense block',
data: `${'a'.repeat(64 * 3)}${'\x01'.repeat(32)}tail`,
expected: 223
},
{
label: 'routine TUI',
data: makeTuiFixture(SCAN_LIMIT, 'selector', '\x01'),
expected: -1
},
{
label: '31/block never triggers',
data: makeSubThresholdDenseFixture(SCAN_LIMIT, 'selector', '\x01'),
expected: -1
}
]
for (const fixture of selectorFixtures) {
const actual = adaptiveFallbackIndex(fixture.data)
if (actual !== fixture.expected) {
throw new Error(`${fixture.label} fallback index ${actual}, expected ${fixture.expected}`)
}
}
const pad = (value, width) => String(value).padStart(width)
console.log('Complete stripTerminalControl path. Lower is better.')
console.log(`iterations=${ITERATIONS} (${ITERATIONS * 3} rotated samples/implementation, median)`)
console.log(
`iterations=${ITERATIONS} (${ITERATIONS * 2} first-touch samples/implementation, counterbalanced median)`
)
console.log(
`${pad('fixture', 25)} ${pad('per-char', 11)} ${pad('slice runs', 12)} ${pad('speedup', 9)}`
`${pad('fixture', 25)} ${pad('per-char', 11)} ${pad('slice runs', 12)} ${pad('adaptive', 11)} ${pad('vs legacy', 10)} ${pad('vs slice', 9)}`
)
for (const fixture of fixtures) {
const samples = { perChar: [], sliceRuns: [] }
const samples = { perChar: [], sliceRuns: [], adaptive: [] }
for (let index = 0; index < ITERATIONS; index += 1) {
const orders = index % 2 === 0 ? [true, false] : [false, true]
for (const perCharFirst of orders) {
const orderLabel = perCharFirst ? 'per-first' : 'slice-first'
recordPair(fixture, `${index}:${orderLabel}`, perCharFirst, samples)
for (let lead = 0; lead < IMPLEMENTATIONS.length; lead += 1) {
recordRotation(fixture, `${index}:lead-${lead}`, lead, samples)
}
}
const perChar = median(samples.perChar)
const sliceRuns = median(samples.sliceRuns)
const adaptive = median(samples.adaptive)
console.log(
`${pad(fixture.label, 25)} ${pad(`${(perChar * 1000).toFixed(1)} us`, 11)} ${pad(`${(sliceRuns * 1000).toFixed(1)} us`, 12)} ${pad(`${(perChar / sliceRuns).toFixed(2)}x`, 9)}`
`${pad(fixture.label, 25)} ${pad(`${(perChar * 1000).toFixed(1)} us`, 11)} ${pad(`${(sliceRuns * 1000).toFixed(1)} us`, 12)} ${pad(`${(adaptive * 1000).toFixed(1)} us`, 11)} ${pad(`${(perChar / adaptive).toFixed(2)}x`, 10)} ${pad(`${(sliceRuns / adaptive).toFixed(2)}x`, 9)}`
)
}
console.log(`\nvalidated=${validatedPairs} measured pairs, result checksum=${resultChecksum >>> 0}`)
console.log(
`\nvalidated=${validatedPairs} measured rotations, result checksum=${resultChecksum >>> 0}`
)
console.log(`selector checks=${selectorFixtures.length}`)
console.log('Production calls are bounded to 4096, 4096, 300, and 301 code units.')
@@ -8,10 +8,8 @@
// `chunk += part`. The gate in front of it (terminalStreamByteLengthExceeds) ran the
// same per-code-point walk over the whole payload a second time.
//
// The fix: one charCodeAt scan computing the UTF-8 width inline with no per-code-point
// string, chunk text taken as data.slice(chunkStart, end), and a gate of
// `data.length > CHUNK || Buffer.byteLength(data, 'utf8') > CHUNK` -- sound because a
// string's UTF-8 length is never below its UTF-16 length.
// The fix: one charCodeAt scan computing UTF-8 width inline, slices for chunk text,
// and bounded byte probes when UTF-16 length alone cannot prove fit or overflow.
//
// BOTH arms run the complete production path, encodeTerminalStreamText included, and
// their emitted frames (base64 + seq + opcode) are compared before any timing, so an
@@ -48,11 +46,13 @@ nodeModule.registerHooks({
})
const ITERATIONS = Number(process.env.ORCA_FRAME_CHUNK_BENCH_ITERATIONS ?? '40')
const GATE_ITERATIONS = Number(process.env.ORCA_FRAME_GATE_BENCH_ITERATIONS ?? '2000')
const WARMUP = Number(process.env.ORCA_FRAME_CHUNK_BENCH_WARMUP ?? '8')
const ROUNDS = Number(process.env.ORCA_FRAME_CHUNK_BENCH_ROUNDS ?? '6')
for (const [name, value] of [
['ORCA_FRAME_CHUNK_BENCH_ITERATIONS', ITERATIONS],
['ORCA_FRAME_GATE_BENCH_ITERATIONS', GATE_ITERATIONS],
['ORCA_FRAME_CHUNK_BENCH_WARMUP', WARMUP],
['ORCA_FRAME_CHUNK_BENCH_ROUNDS', ROUNDS]
]) {
@@ -73,12 +73,19 @@ const CLIPBOARD_SOURCE = readFileSync(
'utf8'
)
// Why re-read the sources: this benchmark's claim is that the OLD arm paid a
// measureClipboardTextByteLength call per code point and the NEW one pays a single
// Buffer.byteLength gate. Match the CALL form, not a bare word -- a comment naming
// the function would satisfy a substring check.
// Match executable source markers so a stale benchmark fails instead of misleading.
for (const [source, label, marker] of [
[CHUNK_SOURCE, 'terminal-output-frame-chunks.ts', "Buffer.byteLength(data, 'utf8')"],
[
CHUNK_SOURCE,
'terminal-output-frame-chunks.ts',
'export function exceedsTerminalStreamChunkBytes(data: string): boolean'
],
[CHUNK_SOURCE, 'terminal-output-frame-chunks.ts', 'TERMINAL_STREAM_BYTE_PROBE_CODE_UNITS'],
[
CHUNK_SOURCE,
'terminal-output-frame-chunks.ts',
'terminalStreamByteLength(data.slice(start, end))'
],
[CHUNK_SOURCE, 'terminal-output-frame-chunks.ts', 'const text = data.slice(chunkStart, end)'],
[CHUNK_SOURCE, 'terminal-output-frame-chunks.ts', 'data.charCodeAt(index + 1)'],
[CLIPBOARD_SOURCE, 'clipboard-text.ts', 'export function measureClipboardTextByteLength('],
@@ -103,10 +110,17 @@ const { measureClipboardTextByteLength } = await import(
const { TerminalStreamOpcode, encodeTerminalStreamJson, encodeTerminalStreamText } = await import(
new URL('../../src/shared/terminal-stream-protocol.ts', import.meta.url).href
)
const { iterateTerminalOutputFrameChunks } = await import(
const { exceedsTerminalStreamChunkBytes, iterateTerminalOutputFrameChunks } = await import(
new URL('../../src/main/runtime/rpc/terminal-output-frame-chunks.ts', import.meta.url).href
)
function previousGate(data) {
return (
data.length > TERMINAL_STREAM_CHUNK_BYTES ||
Buffer.byteLength(data, 'utf8') > TERMINAL_STREAM_CHUNK_BYTES
)
}
// Pre-fix arm: the exact code that shipped, including the second full walk in the gate.
function* iterateBefore(data, meta) {
const rawLength = meta?.rawLength ?? data.length
@@ -260,6 +274,11 @@ const fixtures = [
data: repeatTo(LONE_HIGH, 64 * 1024),
meta: (data) => ({ seq: 5_000_000, rawLength: data.length })
},
{
label: 'late-wide gate miss (3 chunks)',
data: `${'a'.repeat(16_000)}${'\u20ac'.repeat(32_000)}`,
meta: (data) => ({ seq: 5_000_000, rawLength: data.length })
},
{
label: 'ascii 512KiB (snapshot chunking)',
data: 'x'.repeat(512 * 1024),
@@ -309,6 +328,38 @@ function measureInterleaved(data, meta) {
return { beforeMs: median(beforeSamples), afterMs: median(afterSamples) }
}
let gateChecksum = 0
function drainGate(gate, data) {
gateChecksum = Math.imul(gateChecksum ^ (gate(data) ? 1 : 0), 16777619) >>> 0
}
function measureGateInterleaved(data) {
for (let index = 0; index < WARMUP * 10; index += 1) {
drainGate(previousGate, data)
drainGate(exceedsTerminalStreamChunkBytes, data)
}
const previousSamples = []
const boundedSamples = []
for (let round = 0; round < ROUNDS; round += 1) {
const run = (gate, samples) => {
const start = performance.now()
for (let index = 0; index < GATE_ITERATIONS; index += 1) {
drainGate(gate, data)
}
samples.push((performance.now() - start) / GATE_ITERATIONS)
}
if (round % 2 === 0) {
run(previousGate, previousSamples)
run(exceedsTerminalStreamChunkBytes, boundedSamples)
} else {
run(exceedsTerminalStreamChunkBytes, boundedSamples)
run(previousGate, previousSamples)
}
}
return { previousMs: median(previousSamples), boundedMs: median(boundedSamples) }
}
const pad = (value, width) => String(value).padStart(width)
console.log('iterateTerminalOutputFrameChunks, per flushed batch. Lower is better.')
console.log(
@@ -342,6 +393,39 @@ for (const fixture of fixtures) {
console.log(
`\nvalidated=${comparedFixtures} fixtures frame-identical before timing, checksum=${frameChecksum >>> 0}`
)
const gateFixtures = [
{ label: 'ascii 4KiB fit proof', data: 'x'.repeat(4 * 1024) },
{
label: 'three-byte exact-cap fit proof',
data: '\u20ac'.repeat(TERMINAL_STREAM_CHUNK_BYTES / 3)
},
{
label: 'late-wide fit after probes',
data: `${'a'.repeat(16_000)}${'\u20ac'.repeat(11_000)}`
},
{
label: 'late-wide miss during probes',
data: `${'a'.repeat(16_000)}${'\u20ac'.repeat(32_000)}`
},
{ label: 'ascii 64KiB overflow proof', data: 'x'.repeat(64 * 1024) }
]
console.log('\nTerminal frame-fit gate only. Lower is better.')
console.log(
`${pad('fixture', 34)} ${pad('result', 8)} ${pad('whole scan', 12)} ${pad('bounded', 11)} ${pad('speedup', 9)}`
)
for (const fixture of gateFixtures) {
const previous = previousGate(fixture.data)
const bounded = exceedsTerminalStreamChunkBytes(fixture.data)
if (previous !== bounded) {
throw new Error(`gate result differs for ${fixture.label}`)
}
const { previousMs, boundedMs } = measureGateInterleaved(fixture.data)
console.log(
`${pad(fixture.label, 34)} ${pad(bounded ? 'miss' : 'fit', 8)} ${pad(`${(previousMs * 1000).toFixed(2)} us`, 12)} ${pad(`${(boundedMs * 1000).toFixed(2)} us`, 11)} ${pad(boundedMs > 0 ? `${(previousMs / boundedMs).toFixed(2)}x` : 'n/a', 9)}`
)
}
console.log(`gate fixtures=${gateFixtures.length}, checksum=${gateChecksum >>> 0}`)
console.log(
'Every byte of remote terminal output crosses this function; the batcher flushes at\nTERMINAL_OUTPUT_BATCH_MAX_BYTES (64 KiB) or every 5 ms, so a busy remote agent pane\nruns it tens of times a second per subscribed stream.'
)