Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(test-isolation): our own implementation of the #5467 fix (#5467)
time-attacka1234b64a986
diff --git a/scripts/check-test-isolation.sh b/scripts/check-test-isolation.shindex 3f750b738c..83086724e6 100755--- a/scripts/check-test-isolation.sh+++ b/scripts/check-test-isolation.sh@@ -18,13 +18,15 @@# R4: any file that creates `new PGLiteEngine(` must call `.disconnect(`# inside an `afterAll(` block. Without disconnect, engines leak across# file boundaries within a shard process.-# R5: any file that calls `configureGateway(` must also call-# `resetGateway(` (in afterAll/afterEach). The AI gateway is-# PROCESS-GLOBAL; a leaked config (embed model/dims, keys, base URLs)-# reaches every later file in the shard and sizes its PGLite schema,-# so e.g. a leaked LiteLLM embed model made eval-canary fail with-# "expected 1280 dimensions, not 1536" once a shard reshuffle put the-# leaker first. Comment-only mentions are ignored.+# R5: a file whose code calls `configureGateway(` must also call+# `resetGateway(` in its code (normally from afterAll/afterEach). The+# AI gateway is one object per process, so whatever a file configures+# (embedding model and width, keys, base URLs) is still in force for+# the next file the shard loads, and that file's PGLite schema is sized+# from it: eval-canary once failed "expected 1280 dimensions, not 1536"+# after a reshuffle ran a LiteLLM-configuring file first. Comments do+# not count either way. A file whose only calls run inside a spawned+# child's script string carries `isolation-lint: R5-subprocess-only`.## Scope:# - Recursively scans `test/**/*.test.ts`.@@ -116,6 +118,31 @@ ENV_MUTATION_PATTERN='process\.env\.[A-Za-z_][A-Za-z_0-9]*[[:space:]]*=[^=]|procMODULE_MOCK_PATTERN='mock\.module[[:space:]]*\('ENGINE_PATTERN='new PGLiteEngine[[:space:]]*\('GATEWAY_PATTERN='configureGateway[[:space:]]*\('+GATEWAY_OPT_OUT='isolation-lint: R5-subprocess-only'+# Comment removal for R5, line by line: a block comment that opens at the+# start of a line (JSDoc included) is dropped through its closing */, and a+# // comment is dropped from the // to the end of the line when it follows+# the line start, whitespace or punctuation (so a URL's :// survives).+# Block comments opening mid-line are left alone: a glob such as+# 'test/*.ts' would otherwise swallow the rest of the file.+GATEWAY_CODE_SCAN='+ in_block {+ if (index($0, "*/") == 0) next+ in_block = 0+ next+ }+ /^[[:space:]]*\/\*/ {+ if (index(substr($0, index($0, "/*") + 2), "*/") == 0) in_block = 1+ next+ }+ {+ code = $0+ sub(/(^|[[:space:];,(){}])\/\/.*$/, "", code)+ if (code ~ /resetGateway[[:space:]]*\(/) restored = 1+ if (code ~ /configureGateway[[:space:]]*\(/) calls = calls NR ":" $0 "\n"+ }+ END { if (calls != "" && !restored) printf "%s", calls }+'CANDIDATES="$(guard_candidates -E -e "$ENV_MUTATION_PATTERN" -e "$MODULE_MOCK_PATTERN" -e "$ENGINE_PATTERN" -e "$GATEWAY_PATTERN" <<< "$FILE_LIST")"violations=0@@ -181,18 +208,13 @@ while IFS= read -r f; dofifi- # R5: configureGateway() requires a resetGateway() restore. Comment lines- # (// or JSDoc *) are stripped first so prose mentions don't count. A call- # that only runs in a spawned child process (template-string script) cannot- # leak; such a file opts out with a `isolation-lint: R5-subprocess-only`- # comment naming why.- cg_lines=$(grep -nE "$GATEWAY_PATTERN" "$f" 2>/dev/null \- | grep -vE '^[0-9]+:[[:space:]]*(//|\*|/\*)' || true)- if [ -n "$cg_lines" ] && ! grep -qF 'isolation-lint: R5-subprocess-only' "$f" 2>/dev/null; then- reset_lines=$(grep -nE 'resetGateway[[:space:]]*\(' "$f" 2>/dev/null \- | grep -vE '^[0-9]+:[[:space:]]*(//|\*|/\*)' || true)- if [ -z "$reset_lines" ]; then- emit_violation "$f" "R5" "calls configureGateway() but never resetGateway(); the process-global gateway leaks to later files in the shard. Add afterAll(() => resetGateway()) or rename to *.serial.test.ts" "$cg_lines"+ # R5: gateway configured but never restored. GATEWAY_CODE_SCAN reads the+ # file with comments removed and prints the configureGateway lines only+ # when no resetGateway call is left.+ if grep -qE "$GATEWAY_PATTERN" "$f" 2>/dev/null && ! grep -qF "$GATEWAY_OPT_OUT" "$f" 2>/dev/null; then+ unrestored=$(awk "$GATEWAY_CODE_SCAN" "$f" 2>/dev/null || true)+ if [ -n "$unrestored" ]; then+ emit_violation "$f" "R5" "configureGateway() with no resetGateway(); the gateway is process-global, so this config reaches every later file in the shard. Add afterAll(() => resetGateway()) or rename to *.serial.test.ts" "$unrestored"fifidone <<EOF@@ -208,8 +230,8 @@ if [ $violations -gt 0 ]; thenecho " - For mock.module(), rename to *.serial.test.ts (quarantine)"echo " - For PGLiteEngine, follow the canonical pattern in"echo " test/helpers/reset-pglite.ts JSDoc and CLAUDE.md."- echo " - For configureGateway(), add afterAll(() => resetGateway())"- echo " (restores the preload's legacy 1536-d baseline)."+ echo " - For configureGateway(), call resetGateway() in afterAll; it"+ echo " puts back the preload's baseline gateway for the next file."echoecho "Or, if this is a baseline file from before the lint shipped,"echo "add it to scripts/check-test-isolation.allowlist (with a TODO"diff --git a/test/scripts/check-test-isolation.test.ts b/test/scripts/check-test-isolation.test.tsindex bf6db1ab8a..c460435857 100644--- a/test/scripts/check-test-isolation.test.ts+++ b/test/scripts/check-test-isolation.test.ts@@ -236,90 +236,78 @@ describe('check-test-isolation.sh', () => {});});- describe('R5 — configureGateway() requires resetGateway()', () => {- it('flags configureGateway without any resetGateway', () => {- const r = runLintIn([- {- path: 'gw-leak.test.ts',- contents:- `import { beforeAll } from 'bun:test';\n` +- `import { configureGateway } from '../src/core/ai/gateway.ts';\n` +- `beforeAll(() => configureGateway({ embedding_model: 'litellm:x', env: {} }));\n`,- },- ]);+ describe('R5: a configured gateway must be reset', () => {+ const IMPORTS = `import { afterAll, afterEach, beforeAll, test } from 'bun:test';\n` ++ `import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';\n`;+ const CONFIGURE = `beforeAll(() => configureGateway({ embedding_model: 'litellm:example-embed', env: {} }));\n`;+ const lintOne = (contents: string, path = 'gateway-user.test.ts') => runLintIn([{ path, contents }]);++ it('flags a file that configures the gateway and never resets it, naming the call line', () => {+ const r = lintOne(IMPORTS + CONFIGURE + `test('t', () => {});\n`);expect(r.status).toBe(1);- expect(r.stdout).toContain('R5');- expect(r.stdout).toContain('gw-leak.test.ts');+ expect(r.stdout).toContain('test/gateway-user.test.ts');+ expect(r.stdout).toContain('rule R5');+ expect(r.stdout).toContain('3:beforeAll(() => configureGateway(');});- it('flags a dynamic-import configureGateway call', () => {- const r = runLintIn([- {- path: 'gw-dyn.test.ts',- contents: `test('x', async () => { (await import('../src/core/ai/gateway.ts')).configureGateway({ env: {} }); });\n`,- },- ]);- expect(r.status).toBe(1);- expect(r.stdout).toContain('R5');+ it('control: the same file with an afterEach reset passes', () => {+ const r = lintOne(IMPORTS + CONFIGURE + `afterEach(() => resetGateway());\n`);+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('check-test-isolation: OK');});- it('does NOT flag configureGateway paired with afterAll(resetGateway)', () => {- const r = runLintIn([- {- path: 'gw-ok.test.ts',- contents:- `import { beforeAll, afterAll } from 'bun:test';\n` +- `import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';\n` +- `beforeAll(() => configureGateway({ env: {} }));\n` +- `afterAll(() => resetGateway());\n`,- },- ]);- expect(r.status).toBe(0);+ it('flags a call through a dynamic import and a call with a space before the paren', () => {+ for (const call of [+ `test('t', async () => { (await import('../src/core/ai/gateway.ts')).configureGateway({ env: {} }); });\n`,+ `beforeAll(() => configureGateway ({ env: {} }));\n`,+ ]) {+ const r = lintOne(call);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('rule R5');+ }});- it('a resetGateway() mention inside a comment does NOT satisfy R5', () => {- const r = runLintIn([- {- path: 'gw-comment-reset.test.ts',- contents:- `// a co-sharded test that calls resetGateway() would reshuffle us\n` +- `configureGateway({ env: {} });\n`,- },- ]);- expect(r.status).toBe(1);- expect(r.stdout).toContain('R5');+ it('a reset that only appears in a comment does not count', () => {+ for (const reset of [+ `// afterAll(() => resetGateway()) is handled by a sibling file\n`,+ `/**\n * The suite would call resetGateway() here.\n */\n`,+ `test('t', () => {}); // TODO resetGateway()\n`,+ ]) {+ const r = lintOne(IMPORTS + CONFIGURE + reset);+ expect(r.status).toBe(1);+ expect(r.stdout).toContain('rule R5');+ }});- it('a configureGateway() mention only in comments is NOT flagged', () => {- const r = runLintIn([- {- path: 'gw-comment-only.test.ts',- contents:- `/**\n * configureGateway() pushes the snapshot (push seam)\n */\n` +- `// configureGateway() is not called here\n` +- `test('x', () => {});\n`,- },- ]);- expect(r.status).toBe(0);+ it('a configureGateway mention that only appears in a comment is not a call', () => {+ for (const mention of [+ `// configureGateway() is set up by the preload\n`,+ `/*\n configureGateway({ env: {} });\n*/\n`,+ `test('t', () => {}); // unlike configureGateway(), this needs no reset\n`,+ ]) {+ expect(lintOne(mention + `test('u', () => {});\n`).status).toBe(0);+ }});- it('skips *.serial.test.ts', () => {- const r = runLintIn([- { path: 'gw.serial.test.ts', contents: `configureGateway({ env: {} });\n` },- ]);+ it('a URL or a glob on a code line does not hide the reset', () => {+ const r = lintOne(+ IMPORTS + CONFIGURE ++ `const fixtures = 'test/*.json';\n` ++ `afterAll(() => { const u = 'http://localhost:4000'; void u; resetGateway(); });\n`,+ );expect(r.status).toBe(0);});- it('honors the R5-subprocess-only pragma (call runs in a spawned child)', () => {- const r = runLintIn([- {- path: 'gw-subprocess.test.ts',- contents:- `// isolation-lint: R5-subprocess-only — script string runs in a child process\n` +- `const script = \`\n configureGateway({ env: {} });\n\`;\n`,- },- ]);- expect(r.status).toBe(0);+ it('the subprocess opt-out exempts a file whose call runs in a child script', () => {+ const body = 'const child = `\n configureGateway({ env: {} });\n`;\nvoid child;\n';+ expect(lintOne(`// isolation-lint: R5-subprocess-only (runs in the spawned child)\n` + body).status).toBe(0);+ const control = lintOne(body);+ expect(control.status).toBe(1);+ expect(control.stdout).toContain('rule R5');+ });++ it('serial files are out of scope for R5', () => {+ expect(lintOne(IMPORTS + CONFIGURE, 'gateway-user.serial.test.ts').status).toBe(0);});});