Skip to content

Commit bc3ec37

Browse files
test(app-shell): pre-filter the Studio address guard's walk before parsing (#37198)
Fixes #37174 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:只改界面工作区里的一份守卫测试,产品代码一行未动。 - 为什么做:这份「禁止手拼工作室地址」的守卫在繁忙的 CI 分片上超时,把一个无关的合并请求两次挤出合并队列,这次修复为它解围。 - 出错会怎样:最坏是守卫漏看某个文件里的手拼地址;新加的对照测试正是为这种情况变红而设,改动随时可直接撤回。 - 要你做什么:无。 ## What changes Test-only: one file, `ui/packages/app-shell/src/views/studio-design/studioAddress.guard.test.ts`. No product file, no published file (`@object-ui/app-shell` is private and ships `dist` only), hence `skip-changeset`. This unblocks PR #37114, whose Test UI shard timed out on this case twice (queue run 45501281672; PR job 138901843717). - **Pre-filter before parsing.** The walk case TypeScript-parsed every non-test ui source (2,378 files at this head) inside the default 15 s budget. A raw-text gate, `maySpellStudioAddress`, now keeps the parse to the sources that may spell an address (123 of 2,378 here). - **The gate is a superset of the matcher by construction, and wider than the card's two words.** Reading the matcher showed `/studio` plus `STUDIO_ROOT_PATH` is not exact: - The matcher also flags a template or `+` on `STUDIO_LANDING_PATH` (it is in `ROOT_NAMES`). - The matcher reads COOKED literal text, so `'\x2fstudio'`, `'\57\163tudio'`, `'/stud\u{69}o'` and a line continuation inside the word all cook to `/studio` while the raw text holds no `/studio`. Identifiers cook `\u` escapes the same way (`STUDIO_ROOT_PATH`). - So the gate matches each of the three words with every character in any of those spellings (itself, identity escape, `\x`, `\u`, `\u{}`, legacy octal), with line continuations allowed between characters. - A JSX attribute string is not cooked (TypeScript keeps `&#47;` as is), so its raw text is its text. - The header comment on the gate gives the argument. - **New control, "the pre-filter keeps every source the matcher flags".** It runs over one shared fixture list, `FLAGGED_SPELLINGS`: the first case's eight spellings plus ten escaped and `STUDIO_LANDING_PATH` forms. Each fixture's only hit is that spelling. The control asserts the matcher flags it once and the gate passes it. It also asserts that the builder file fires the matcher and passes the gate, and that a source naming no address is dropped. The first case now asserts the matcher over the same list, so the two cannot drift apart. - **Existing controls kept.** The walk still has to reach `StudioDesignSurface.tsx` and `StudioRoute.tsx`, and the builder still fires the matcher inside the walk case. - **Explicit budget.** The walk case now runs under `{ timeout: 60_000 }` as the second line of defence; the measured wall time is below. ## Tests <details><summary>Wall time of the walk case, before and after (local, shared box, under os-verify-lock)</summary> - Before (base `95734fef75`, unchanged file): `no ui source outside the builder spells one 4471ms`. File total: `Duration 5.79s`. - After (`45151aec2b`): `no ui source outside the builder spells one 873ms`; `the pre-filter keeps every source the matcher flags 18ms`. File total: `Duration 1.48s`, `Tests 3 passed (3)`. - Probe at the same tree: walk 24 ms, reading every file 166 ms, the gate's regex over all 2,378 texts 47 ms. The rest of the before figure was the parse. </details> <details><summary>Ablation 1: the gate drops everything (`MAY_SPELL_STUDIO_ADDRESS.test(text) && false`)</summary> Made through `scripts/ablation-replace.mjs`. Result: `ok mutation landed: anchor 1 -> 0, blob fdd866a -> b763c5694c5f`. - `× the pre-filter keeps every source the matcher flags`, failing with `AssertionError: const a = '/studio';: expected false to be true`. `Tests 1 failed | 2 passed (3)`. - The walk case stayed GREEN under this ablation (196 ms, no file parsed, so no offender). That is the hole the new control closes. - Restore: `ok restored: blob == HEAD (fdd866a) and git diff HEAD is empty`. </details> <details><summary>Ablation 2: the card's two-word filter (`/studio` or `STUDIO_ROOT_PATH` as plain substrings)</summary> Made through the same tool. Result: `ok mutation landed: anchor 1 -> 0, blob fdd866a -> dbb5d30c77b9`. - `× the pre-filter keeps every source the matcher flags`, failing with `AssertionError: const a2 = '\x2Fstudio';: expected false to be true`. `Tests 1 failed | 2 passed (3)`. - Restore: `ok restored: blob == HEAD (fdd866a) and git diff HEAD is empty`. </details> <details><summary>Derived gates at 45151ae (`dispatch-gates.mjs --commands`, 27 commands)</summary> - 26 of 27 exited 0 on the first pass. - `pnpm --dir ui exec vitest run scripts/` first went red, 22 files failing with `Cannot find package '@objectstack/spec/ui'`: the fresh worktree had no `packages/spec/dist`. After `pnpm --filter @objectstack/spec build` it went green: `Test Files 172 passed | 2 skipped (174)`, `Tests 5131 passed | 2 skipped (5133)`, `VERDICT command-exit 0`. - `node scripts/check-nul-bytes.mjs` and a control-byte grep over the file are clean. `eslint --no-inline-config` on the file exits 0. </details> - Whole `@object-ui/app-shell` package suite (2,443 test files, `--maxWorkers=2` on a shared box): NOT MEASURED. Reason: still running after 70 minutes when this PR was opened. The CI `Test UI` shards own that verdict. ## Acceptance notes - The two-word pre-filter the card proposed would have missed `STUDIO_LANDING_PATH` and every escaped spelling (ablation 2). The filter was widened to stay an exact superset, as the dispatch asked. - On today's tree the widened gate passes the same 123 files the two-word filter would. The widening costs no parse time. - `node scripts/pm/overlap-check.mjs`: `VERDICT clean exit 0` (origin/main `95734fef75`, 0 PR heads share the file). ## Verification **Read first:** 1. The doc comment above `STUDIO_ADDRESS_WORDS` and the regex builder under it. This is the risk hunk: the superset argument lives there. 2. The `FLAGGED_SPELLINGS` list and the new control case. 3. The walk case's `maySpellStudioAddress` early return and its `{ timeout: 60_000 }`. **Two-minute check:** from `ui/`, run `pnpm --filter @object-ui/app-shell exec vitest run --root ../.. --reporter=verbose packages/app-shell/src/views/studio-design/studioAddress.guard.test.ts`. Expect three passing cases, with the walk case at about 1 s instead of about 4.5 s. --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYpEsWWE9Y5YtSsDgqZ)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 886e970 commit bc3ec37

1 file changed

Lines changed: 108 additions & 10 deletions

File tree

‎ui/packages/app-shell/src/views/studio-design/studioAddress.guard.test.ts‎

Lines changed: 108 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -126,17 +126,90 @@ function handBuiltStudioAddresses(fileName: string, text: string): string[] {
126126
return hits;
127127
}
128128

129+
/**
130+
* The cheap gate in front of the parser: may this source text hold anything
131+
* `handBuiltStudioAddresses` flags? Parsing every ui source takes seconds and
132+
* all but a few files hold none, so only the files that pass are parsed.
133+
*
134+
* It is a superset of the matcher by construction. The matcher flags three
135+
* node shapes, and each one needs a token whose COOKED text is one of three
136+
* words:
137+
*
138+
* - a string or template literal (or a template head) whose text starts with
139+
* `/studio`;
140+
* - a template whose first span is the identifier `STUDIO_ROOT_PATH` or
141+
* `STUDIO_LANDING_PATH`;
142+
* - `+` with one of those identifiers on its left.
143+
*
144+
* A JSX attribute string is not cooked (`&#47;` stays `&#47;`), so its raw text
145+
* is its text. A JS string or template is cooked, and its raw text can spell
146+
* each character as itself, an identity escape (`\/`, `\s`), `\xHH`, `\uHHHH`,
147+
* `\u{H…}` or a legacy octal escape (`\57`), with line continuations (a
148+
* backslash before a line break, which cook to nothing) between characters. An
149+
* identifier can spell a character as `\uHHHH` or `\u{H…}`. So the gate looks
150+
* for each word with every character in any of those spellings, and with
151+
* continuations allowed between them: a literal or identifier the matcher can
152+
* flag always leaves one of these in the raw text. Extra spellings
153+
* (`\t` read as `t`) only cost a parse, never a miss.
154+
*/
155+
const STUDIO_ADDRESS_WORDS = ['/studio', ...ROOT_NAMES];
156+
157+
const hexDigits = (code: number, width: number): string =>
158+
[...code.toString(16).padStart(width, '0')].map((d) => (/[a-f]/.test(d) ? `[${d}${d.toUpperCase()}]` : d)).join('');
159+
160+
const anySpellingOf = (char: string): string => {
161+
const code = char.charCodeAt(0);
162+
const plain = char.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
163+
return `(?:${[
164+
plain,
165+
`\\\\${plain}`,
166+
`\\\\x${hexDigits(code, 2)}`,
167+
`\\\\u${hexDigits(code, 4)}`,
168+
`\\\\u\\{0*${hexDigits(code, 1)}\\}`,
169+
`\\\\0*${code.toString(8)}`,
170+
].join('|')})`;
171+
};
172+
173+
const LINE_CONTINUATIONS = '(?:\\\\(?:\\r\\n|[\\n\\r\\u2028\\u2029]))*';
174+
175+
const MAY_SPELL_STUDIO_ADDRESS = new RegExp(
176+
STUDIO_ADDRESS_WORDS.map((word) => [...word].map(anySpellingOf).join(LINE_CONTINUATIONS)).join('|'),
177+
);
178+
179+
function maySpellStudioAddress(text: string): boolean {
180+
return MAY_SPELL_STUDIO_ADDRESS.test(text);
181+
}
182+
183+
/**
184+
* Every spelling the matcher flags, one hit per fixture: the first case holds
185+
* the matcher to them, the pre-filter control holds the gate to them.
186+
*/
187+
const FLAGGED_SPELLINGS = [
188+
"const a = '/studio';",
189+
'const b = `/studio/${pkg}/data`;',
190+
'const c = "/studio?new=package";',
191+
'const d = <Link to="/studio" />;',
192+
'const d2 = <Tab path="/studio" />;',
193+
'const d3 = <Route path={`/studio/${pkg}`} />;',
194+
'const e = `${STUDIO_ROOT_PATH}/${pkg}`;',
195+
"const f = STUDIO_ROOT_PATH + '/' + pkg;",
196+
// The same addresses with escapes in them: cooked, they are the same text.
197+
"const a1 = '\\/studio';",
198+
"const a2 = '\\x2Fstudio';",
199+
"const a3 = '\\u002fstud\\u{69}o';",
200+
"const a4 = '\\57\\163tudio';",
201+
"const a5 = '/stu\\\ndio';",
202+
'const b1 = `\\x2fstudio/${pkg}`;',
203+
'const e1 = `${STUDIO_LANDING_PATH}/${pkg}`;',
204+
'const e2 = `${STUDIO\\u005FROOT_PATH}/${pkg}`;',
205+
"const f1 = STUDIO_LANDING_PATH + '/' + pkg;",
206+
"const f2 = STUDIO_\\u{52}OOT_PATH + '/' + pkg;",
207+
];
208+
129209
describe('no Studio address is built by hand under ui/ (objectstack#36895)', () => {
130210
it('the matcher sees each spelling and spares prose and look-alikes', () => {
131211
const scan = (text: string) => handBuiltStudioAddresses('x.tsx', text);
132-
expect(scan("const a = '/studio';")).toHaveLength(1);
133-
expect(scan('const b = `/studio/${pkg}/data`;')).toHaveLength(1);
134-
expect(scan('const c = "/studio?new=package";')).toHaveLength(1);
135-
expect(scan('const d = <Link to="/studio" />;')).toHaveLength(1);
136-
expect(scan('const d2 = <Tab path="/studio" />;')).toHaveLength(1);
137-
expect(scan('const d3 = <Route path={`/studio/${pkg}`} />;')).toHaveLength(1);
138-
expect(scan('const e = `${STUDIO_ROOT_PATH}/${pkg}`;')).toHaveLength(1);
139-
expect(scan("const f = STUDIO_ROOT_PATH + '/' + pkg;")).toHaveLength(1);
212+
for (const spelling of FLAGGED_SPELLINGS) expect(scan(spelling), spelling).toHaveLength(1);
140213
// Not an address.
141214
expect(scan("const g = '/studios';")).toEqual([]);
142215
expect(scan("const h = '/api/v1/studio/runtime-config';")).toEqual([]);
@@ -150,7 +223,28 @@ describe('no Studio address is built by hand under ui/ (objectstack#36895)', ()
150223
expect(scan('const l = studioHomePath(pkg);')).toEqual([]);
151224
});
152225

153-
it('no ui source outside the builder spells one', () => {
226+
it('the pre-filter keeps every source the matcher flags', () => {
227+
// Each fixture's only hit is one spelling, so a gate that drops any of
228+
// them would hide exactly that spelling from the walk below.
229+
for (const spelling of FLAGGED_SPELLINGS) {
230+
expect(handBuiltStudioAddresses('x.tsx', spelling), spelling).toHaveLength(1);
231+
expect(maySpellStudioAddress(spelling), spelling).toBe(true);
232+
}
233+
// The one file allowed to spell the root fires the matcher and passes.
234+
const builder = path.join(UI_ROOT, 'packages/app-shell/src/views/studio-design/studioAddress.ts');
235+
const builderText = readFileSync(builder, 'utf8');
236+
expect(handBuiltStudioAddresses(builder, builderText).length).toBeGreaterThan(0);
237+
expect(maySpellStudioAddress(builderText)).toBe(true);
238+
// And it does filter: a source naming no Studio address is skipped.
239+
expect(maySpellStudioAddress("const i = 'studio:builder';\nconst p = '\\t';")).toBe(false);
240+
});
241+
242+
// The walk reads every ui source; the pre-filter keeps the parse to the few
243+
// that may spell an address (about 120 of 2,400 today). Measured locally:
244+
// 4.5 s with every file parsed, 0.9 s with the pre-filter. The explicit budget
245+
// is the second line of defence for a loaded CI shard, where the default 15 s
246+
// ran out.
247+
it('no ui source outside the builder spells one', { timeout: 60_000 }, () => {
154248
const files = uiSources();
155249
const rel = (file: string) => path.relative(UI_ROOT, file).split(path.sep).join('/');
156250
const names = new Set(files.map(rel));
@@ -163,7 +257,11 @@ describe('no Studio address is built by hand under ui/ (objectstack#36895)', ()
163257

164258
const offenders = files
165259
.filter((file) => !ALLOWED.has(rel(file)))
166-
.flatMap((file) => handBuiltStudioAddresses(file, readFileSync(file, 'utf8')).map((h) => `${rel(file)}:${h}`));
260+
.flatMap((file) => {
261+
const text = readFileSync(file, 'utf8');
262+
if (!maySpellStudioAddress(text)) return [];
263+
return handBuiltStudioAddresses(file, text).map((h) => `${rel(file)}:${h}`);
264+
});
167265
expect(offenders).toEqual([]);
168266
});
169267
});

0 commit comments

Comments
 (0)