Skip to content

Commit 1bf5763

Browse files
committed
fix(gray-screen): address pre-merge check failures
- stop printing task descriptions in analyze-session output - always close browser, page, sampler and server in webview-heap-matrix - move render-stress option parsing into lib.mjs so it is unit tested
1 parent 25b8b68 commit 1bf5763

6 files changed

Lines changed: 98 additions & 34 deletions

File tree

‎scripts/gray-screen/__tests__/lib.test.mjs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ import { afterEach, beforeEach, describe, it } from "node:test"
77
import {
88
integerFlag,
99
parseFlagArgs,
10+
parseStressArgs,
1011
resolveBuildDir,
1112
resolveServedFile,
13+
stressConfig,
1214
validateRelativeDir,
1315
writeTaskAtomically,
1416
} from "../lib.mjs"
@@ -42,6 +44,29 @@ describe("parseFlagArgs / integerFlag", () => {
4244
})
4345
})
4446

47+
describe("stressConfig", () => {
48+
const config = (...argv) => stressConfig(parseStressArgs(argv))
49+
50+
it("defaults to the session scenario and accepts the documented ones", () => {
51+
assert.equal(config().scenario, "session")
52+
assert.equal(config().heapMb, 1024)
53+
assert.equal(config("--scenario", "md").heapMb, 4096)
54+
assert.equal(config("--scenario", "command", "--rate", "50").rate, 50)
55+
assert.equal(config("--headed").headed, true)
56+
})
57+
58+
it("rejects an unsupported scenario", () => {
59+
assert.throws(() => config("--scenario", "bogus"), /Invalid --scenario "bogus"/)
60+
})
61+
62+
it("rejects invalid numbers, including a flag without a value", () => {
63+
assert.throws(() => config("--pushes", "abc"), /--pushes must be an integer/)
64+
assert.throws(() => config("--seconds", "1x"), /--seconds/)
65+
assert.throws(() => config("--rate", "0"), /--rate/)
66+
assert.throws(() => config("--pushes", "--headed"), /--pushes/)
67+
})
68+
})
69+
4570
describe("validateRelativeDir", () => {
4671
it("accepts plain relative paths", () => {
4772
for (const ok of [".mock-session", "a", "src/mock_1", "a.b/c-d"]) assert.equal(validateRelativeDir(ok), ok)

‎scripts/gray-screen/__tests__/tools.test.mjs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,19 @@ describe("analyze-session", () => {
108108
assert.equal(analyze().status, 0)
109109
})
110110

111+
it("never prints the task description from history_item.json", () => {
112+
const taskDir = path.join(tmp, "tasks", "private-task")
113+
fs.mkdirSync(taskDir, { recursive: true })
114+
fs.writeFileSync(path.join(taskDir, "ui_messages.json"), JSON.stringify([{ ts: 1, type: "say", say: "text", text: "x" }]))
115+
fs.writeFileSync(path.join(taskDir, "history_item.json"), JSON.stringify({ task: "Jane Doe api key sk-SECRET" }))
116+
117+
const result = analyze()
118+
119+
assert.equal(result.status, 0, result.stderr)
120+
assert.match(result.stdout, /\[private-\]/)
121+
assert.doesNotMatch(result.stdout, /Jane|SECRET/)
122+
})
123+
111124
it("rejects a non-numeric --top", () => {
112125
for (const top of ["abc", "0", "1.5"]) {
113126
const result = analyze("--top", top)

‎scripts/gray-screen/analyze-session.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,9 +127,8 @@ for (const r of results) {
127127
const fieldTotal = Object.values(r.fields).reduce((a, b) => a + b.bytes, 0) || 1
128128
const [topKey, topVal] = Object.entries(r.fields).sort((a, b) => b[1].bytes - a[1].bytes)[0] ?? ["-", { bytes: 0 }]
129129
const text = r.latin1Bytes + r.twoByteBytes || 1
130-
const meta = taskMeta(r.taskId)
131130
console.log(
132-
`${mb(r.fileBytes).padStart(7)} ${String(r.count).padStart(5)} ${mb(toolBytes).padStart(9)} ${String(editCount).padStart(9)} ${`${topKey} ${(100 * topVal.bytes / fieldTotal).toFixed(0)}%`.padEnd(30)} ${(100 * r.twoByteBytes / text).toFixed(0).padStart(5)}% ${mb(r.imageBytes).padStart(5)} ${`${r.maxRun} (${mb(r.maxRunBytes)})`.padEnd(20)} ${(meta.task ?? "").slice(0, 28).replace(/\s+/g, " ")} [${r.taskId.slice(0, 8)}]`,
131+
`${mb(r.fileBytes).padStart(7)} ${String(r.count).padStart(5)} ${mb(toolBytes).padStart(9)} ${String(editCount).padStart(9)} ${`${topKey} ${(100 * topVal.bytes / fieldTotal).toFixed(0)}%`.padEnd(30)} ${(100 * r.twoByteBytes / text).toFixed(0).padStart(5)}% ${mb(r.imageBytes).padStart(5)} ${`${r.maxRun} (${mb(r.maxRunBytes)})`.padEnd(20)} [${r.taskId.slice(0, 8)}]`,
133132
)
134133
}
135134

‎scripts/gray-screen/lib.mjs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,48 @@ export function integerFlag(name, value, min) {
2222
return number
2323
}
2424

25+
/** `--flag value` pairs for the stress harness; a flag without a value (or followed by another flag) is `"true"`. */
26+
export function parseStressArgs(argv) {
27+
const entries = []
28+
29+
argv.forEach((cur, i) => {
30+
if (!cur.startsWith("--")) return
31+
const value = argv[i + 1]
32+
entries.push([cur.slice(2), value === undefined || value.startsWith("--") ? "true" : value])
33+
})
34+
35+
return Object.fromEntries(entries)
36+
}
37+
38+
export const STRESS_SCENARIOS = ["session", "command", "md"]
39+
40+
/** Validated webview-render-stress options; throws on an unknown scenario or an invalid number. */
41+
export function stressConfig(args) {
42+
const scenario = args["scenario"] ?? "session"
43+
if (!STRESS_SCENARIOS.includes(scenario)) {
44+
throw new Error(`Invalid --scenario "${scenario}": use ${STRESS_SCENARIOS.join(", ")}.`)
45+
}
46+
47+
const int = (name, fallback, min) => integerFlag(name, args[name] ?? fallback, min)
48+
49+
return {
50+
scenario,
51+
start: int("start", 5000, 0),
52+
pushes: int("pushes", 300, 0),
53+
grow: int("grow", 4, 0),
54+
chunks: int("chunks", 20, 1),
55+
rate: int("rate", 200, 1),
56+
seconds: int("seconds", 60, 1),
57+
heapMb: int("heap-mb", scenario === "md" ? 4096 : 1024, 64),
58+
textBytes: int("text-bytes", scenario === "md" ? 15000 : 800, 1),
59+
turns: int("turns", 40, 1),
60+
chunkMs: int("chunk-ms", 15, 0),
61+
mermaidEvery: int("mermaid-every", 10, 0),
62+
url: args["url"],
63+
headed: args["headed"] === "true",
64+
}
65+
}
66+
2567
/** A plain relative path that is safe to interpolate into shell commands and to resolve under a workspace. */
2668
export function validateRelativeDir(dir) {
2769
const segments = dir.split("/")

‎scripts/gray-screen/webview-heap-matrix.mjs‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -266,10 +266,14 @@ const pageDriverAsync = async ({ toolMb, hz, seconds, batchable, twoByte }) => {
266266
return { posts: received, sent, backlog: sent - received }
267267
}
268268

269-
const browser = await chromium.launch({ headless: true, args: [`--js-flags=--max-old-space-size=${heapMb}`] })
270269
const rows = []
270+
let browser
271+
try {
272+
browser = await chromium.launch({ headless: true, args: [`--js-flags=--max-old-space-size=${heapMb}`] })
271273
for (const exp of EXPERIMENTS.filter((e) => !only || only.includes(e.name))) {
272274
const page = await browser.newPage()
275+
let sampler
276+
try {
273277
let crashed = false
274278
let crashAt = null
275279
page.on("crash", () => {
@@ -295,7 +299,7 @@ for (const exp of EXPERIMENTS.filter((e) => !only || only.includes(e.name))) {
295299
peak = 0
296300
samplingFrom = Date.now()
297301
})
298-
const sampler = setInterval(async () => {
302+
sampler = setInterval(async () => {
299303
if (crashed) return
300304
try {
301305
const h = await heap()
@@ -318,10 +322,15 @@ for (const exp of EXPERIMENTS.filter((e) => !only || only.includes(e.name))) {
318322
}
319323
rows.push({ name: exp.name, mode: exp.mode, toolMb: exp.toolMb, twoByte: !!exp.twoByte, ballastMb: exp.ballastMb ?? 0, rate: exp.mode === "both" ? `${exp.hz}t+${exp.chunkHz}c` : exp.hz, hydratePeakMB: hydratePeak, baseMB: baseMb, peakMB: peak, afterGC: floorMb, crashAfterSec: crashed ? (samplingFrom === null ? "during-hydration" : ((crashAt - samplingFrom) / 1000).toFixed(1)) : "-", to1GBsec: tTo1G ?? "-", posts: result.posts ?? "-", sent: result.sent ?? "-", backlog: result.backlog ?? "-", result: result.error ?? "ok" })
320324
console.log(JSON.stringify(rows.at(-1)))
321-
await page.close().catch(() => {})
325+
} finally {
326+
clearInterval(sampler)
327+
await page.close().catch(() => {})
328+
}
329+
}
330+
} finally {
331+
await browser?.close().catch(() => {})
332+
httpServer.close()
322333
}
323-
await browser.close()
324-
httpServer.close()
325334

326335
console.log("\nname".padEnd(28) + "mode".padEnd(8) + "toolMB".padEnd(8) + "rate".padEnd(10) + "hydrPk".padEnd(8) + "baseMB".padEnd(8) + "peakMB".padEnd(9) + "afterGC".padEnd(9) + "to1GB(s)".padEnd(10) + "posts".padEnd(7) + "sent".padEnd(6) + "backlog".padEnd(9) + "crashAfter(s)".padEnd(15) + "result")
327336
for (const r of rows) {

‎scripts/gray-screen/webview-render-stress.mjs‎

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,41 +28,17 @@ import http from "node:http"
2828
import { createRequire } from "node:module"
2929
import path from "node:path"
3030
import { fileURLToPath } from "node:url"
31-
import { integerFlag, resolveBuildDir, resolveServedFile } from "./lib.mjs"
31+
import { parseStressArgs, resolveBuildDir, resolveServedFile, stressConfig } from "./lib.mjs"
3232

3333
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..")
3434
const webviewDir = path.join(root, "webview-ui")
3535
const require = createRequire(path.join(webviewDir, "package.json"))
3636
const { chromium } = require("@playwright/test")
3737

38-
const args = Object.fromEntries(
39-
process.argv.slice(2).reduce((acc, cur, i, all) => {
40-
if (cur.startsWith("--")) acc.push([cur.slice(2), all[i + 1]?.startsWith("--") || all[i + 1] === undefined ? "true" : all[i + 1]])
41-
return acc
42-
}, []),
43-
)
44-
const SCENARIOS = ["session", "command", "md"]
45-
const int = (name, fallback, min) => integerFlag(name, args[name] ?? fallback, min)
38+
const args = parseStressArgs(process.argv.slice(2))
4639
let cfg
4740
try {
48-
const scenario = args["scenario"] ?? "session"
49-
if (!SCENARIOS.includes(scenario)) throw new Error(`Invalid --scenario "${scenario}": use ${SCENARIOS.join(", ")}.`)
50-
cfg = {
51-
scenario,
52-
start: int("start", 5000, 0),
53-
pushes: int("pushes", 300, 0),
54-
grow: int("grow", 4, 0),
55-
chunks: int("chunks", 20, 1),
56-
rate: int("rate", 200, 1),
57-
seconds: int("seconds", 60, 1),
58-
heapMb: int("heap-mb", scenario === "md" ? 4096 : 1024, 64),
59-
textBytes: int("text-bytes", scenario === "md" ? 15000 : 800, 1),
60-
turns: int("turns", 40, 1),
61-
chunkMs: int("chunk-ms", 15, 0),
62-
mermaidEvery: int("mermaid-every", 10, 0),
63-
url: args["url"],
64-
headed: args["headed"] === "true",
65-
}
41+
cfg = stressConfig(args)
6642
} catch (e) {
6743
console.error(e.message)
6844
process.exit(1)

0 commit comments

Comments
 (0)