Skip to content

Commit 19cc897

Browse files
test(cli): stored-references binds name fixed row ids, and a run with no JSON says why (#33426)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9D4Jsmd91BqTVB7dSii9uJMV)_ Fixes #32976 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:只改一个测试文件。`os migrate stored-references` 集成测试给种子行写死 id(不再随机生成),并且当命令没有输出 JSON 时,测试失败信息会带上退出码、oclif 抛出的错误原文、耗时、argv 和 stderr 尾部。 - 为什么改:偶发失败已复现并定位。行 id 是 16 位 nanoid,字母表含 `-`;bind 命令声明了短参数 `-y`(`--yes`),oclif 会把以 `-y` 开头的参数值当成 `-y` 参数,在解析阶段就拒绝(`Flag --id expects a value`,退出码 2),命令一个字节都没写,所以 16 ms、stdout 为空。概率约 1/4096 每个 id。 - 风险与回滚:只动测试,不发布任何包;回滚即 revert 本 PR。 - 先看:`packages/cli/src/commands/migrate/stored-references.integration.test.ts` 的 `SEEDED_IDS` 注释与 `run()` 里的空 stdout 诊断分支。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run --project integration src/commands/migrate/stored-references.integration.test.ts`,预期 13/13 通过。 - 需要你做的:本 PR 只改测试、不发布任何包,需要挂 `skip-changeset` 标签(dev 未自挂)。产品侧缺陷(以 `-y` 开头的 id 在任何拼写下都无法 bind)已作为发现上报,未在本 PR 修。 ## What changes `packages/cli/src/commands/migrate/stored-references.integration.test.ts` only: 1. **The rows the seed writes carry fixed ids** (`SEEDED_IDS`), so every `bind --id` the file passes is deterministic. Before, the ids were minted by the SQL driver as `nanoid(16)`, whose alphabet contains `-`. 2. **A run that prints no JSON document fails loudly.** `run()` no longer answers a bare `{ unparsed: '' }`: it adds the exit code, the exit signal's own message (an oclif parse refusal throws before the command writes a byte), the elapsed ms, the argv, and the tail of stderr. The CONTROL bind assertion prints that payload as its message. 3. **`bind()` refuses an id that opens with `-`** before it reaches the argv, naming why, instead of an opaque parse refusal. ### Root cause (reproduced, not inferred) oclif 5.1.2's parser (`lib/parser/parse.js`, `parseFlag`) refuses a flag value whenever `findFlag(value)` resolves it to one of the command's flags; `findShortFlag` looks only at the value's second character. `os migrate stored-references bind` declares `yes` with `char: 'y'`, so a row id beginning with `-y` is read as `-y` and refused: `Flag --id expects a value`, exit 2, in **both** spellings, `--id X` and `--id=X`. In the test, that `CLIError` carries `oclif.exit`, so `isExitSignal` swallows it as an ordinary exit and stdout is empty: the exact signature of run 43341064666 (CONTROL failed in 16 ms on `{ unparsed: '' }`, every other case green; next group green on the same shard because the next seed minted different ids). Measured: a sweep of all 4096 two-character prefixes after `-` through the bind's real flag set refuses exactly the 64 that begin `-y` and no other. With three ids bound per run, roughly one run in 1,400 hits it. ### Not fixed here (reported as a finding) The same refusal is a product defect at the public door: a row whose minted id begins with `-y` cannot be bound by `os migrate stored-references bind` in any spelling (`objectstack: INVOCATION ERROR — Flag --id expects a value`, exit 2, 0 bytes on stdout under `--json`). It is a family (any string flag carrying a minted id on a command that declares a short flag; 27 commands declare `-y`), so it is reported to the seat with evidence rather than patched in this test PR. ## Tests <details><summary>Integration file, final head: 13/13</summary> ``` pnpm --filter @objectstack/cli exec vitest run --project integration --maxWorkers=2 src/commands/migrate/stored-references.integration.test.ts Test Files 1 passed (1) Tests 13 passed (13) os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Reproduction (one-time ablation through scripts/ablation-replace.mjs, restored to HEAD)</summary> The `bind()` guard was replaced by `id = '-y' + id` (anchor 1 to 0, blob b4ae844 to d53987cede12) and only the CONTROL bind case run. It failed in 27 ms with the CI signature, now loud: ``` AssertionError: {"unparsed":"","exitCode":2,"thrown":"Flag --id expects a value","ms":13,"argv":["--table","sys_sharing_rule","--id","-ym31693_share_row",...,"--json"],"stderr":""} Tests 1 failed | 12 skipped (13) ablation-replace: ok restored: blob == HEAD (b4ae844) and git diff HEAD is empty ``` </details> <details><summary>CLI unit tier and typecheck (head 01321f6)</summary> ``` pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 Test Files 2 failed | 416 passed (418) Tests 5930 passed | 29 skipped (5959) ``` The two failed files are `test/published-subpath-console.pin.test.ts` and `test/published-subpath-hook-body.pin.test.ts`, both refusing at setup with `packages/cli is not built (./dist/index.js is absent)`: only the CLI's dependency closure was built locally. NOT MEASURED locally, reason: prerequisite (no CLI dist); this diff touches neither. CI's Test Core builds and runs them. ``` pnpm --filter @objectstack/cli typecheck check:test-typecheck: OK — @objectstack/cli's test layer compiles under packages/cli/tsconfig.test.json os-verify-lock: VERDICT command-exit 0 npx eslint --no-inline-config packages/cli/src/commands/migrate/stored-references.integration.test.ts exit 0 ``` </details> ## Verification <details><summary>Derived gate families (dispatch-gates, head 01321f6): 49 exit 0, 4 NOT MEASURED</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 53 commands for the one changed path; each was run and its exit code recorded, and `--ran` reconciled: `53 derived famil(ies) accounted for — 49 run, 4 NOT-MEASURED (4 DERIVED from a recorded exit 3)`. The four exit-3 families refused their own prerequisite (the workspace is not fully built locally): `check:dual-build-cjs-loads`, `check:i18n`, `check:i18n-coverage`, `check:i18n-walk-parity`. NOT MEASURED locally, reason: prerequisite; CI's Lint and Repo Gates runs them. </details> Not merged with `origin/main` before opening: it is 13 commits ahead of the base, none under `packages/cli`, so CI's merge ref is the first joint reading. This PR changes only a test file and publishes nothing, so it needs the `skip-changeset` label (not added by the dev). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cw787kMeaX7oyz7DDC Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3c44a97 commit 19cc897

1 file changed

Lines changed: 43 additions & 9 deletions

File tree

‎packages/cli/src/commands/migrate/stored-references.integration.test.ts‎

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,23 @@ async function rowsOf(dbFile: string, table: string): Promise<Array<Record<strin
170170
}
171171
}
172172

173+
/**
174+
* The ids of the rows the seed writes, and so the `--id` every bind below
175+
* passes: fixed, never minted. A minted id is a 16-character nanoid, whose
176+
* alphabet carries `-`, and oclif reads a flag VALUE whose first two
177+
* characters spell one of the command's short flags as that flag: the bind
178+
* declares `-y` (`--yes`), so an id minted as `-y…` (1 in 4096) is refused
179+
* at parse, `Flag --id expects a value`, exit 2, before the command writes a
180+
* byte, in either spelling, `--id X` or `--id=X`. With minted ids that was a
181+
* case going red at random in about one run in a thousand, in milliseconds,
182+
* on an empty stdout.
183+
*/
184+
const SEEDED_IDS = {
185+
m31693_share: 'm31693_share_row',
186+
m31693_only_a: 'm31693_only_a_row',
187+
suggestion: 'm31693_suggestion_row',
188+
} as const;
189+
173190
/** A database the served platform provisioned, with the rows an older release left (module doc). */
174191
async function seedDatabase(file: string): Promise<void> {
175192
const stack = await bootSchemaStack({
@@ -179,13 +196,14 @@ async function seedDatabase(file: string): Promise<void> {
179196
try {
180197
const ql: IDataEngine = stack.kernel.getService('objectql');
181198
const ctx = { context: { isSystem: true, tenantId: ORG } };
182-
for (const name of ['m31693_share', 'm31693_only_a']) {
199+
for (const name of ['m31693_share', 'm31693_only_a'] as const) {
183200
await ql.insert('sys_sharing_rule', {
184-
name, label: name, object_name: 'm31693a_task', criteria_json: '{}', recipient_type: 'user', recipient_id: 'u1',
201+
id: SEEDED_IDS[name], name, label: name, object_name: 'm31693a_task', criteria_json: '{}', recipient_type: 'user', recipient_id: 'u1',
185202
access_level: 'read', active: false, managed_by: 'package', organization_id: ORG,
186203
}, ctx);
187204
}
188205
await ql.insert('sys_audience_binding_suggestion', {
206+
id: SEEDED_IDS.suggestion,
189207
package_id: A, permission_set_name: 'm31693_env_set', anchor: 'everyone', status: 'pending', organization_id: ORG,
190208
}, ctx);
191209
} finally {
@@ -215,32 +233,48 @@ async function run(command: typeof MigrateStoredReferences | typeof MigrateStore
215233
return true;
216234
}) as typeof process.stdout.write;
217235
const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow);
218-
vi.spyOn(process.stderr, 'write').mockImplementation(swallow);
236+
const stderrWrites = vi.spyOn(process.stderr, 'write').mockImplementation(swallow);
219237
vi.spyOn(console, 'log').mockImplementation(() => {});
220238
vi.spyOn(console, 'warn').mockImplementation(() => {});
221239
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
222240
let thrownExit: number | undefined;
241+
let thrownMessage: string | undefined;
242+
const started = Date.now();
223243
try {
224244
try {
225245
await command.run(argv, { root: CLI_ROOT });
226246
} catch (error) {
227247
if (!isExitSignal(error)) throw error;
228248
thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit;
249+
thrownMessage = (error as Error).message;
229250
}
230251
const raw = stdout.mock.calls.map((c) => String(c[0])).join('').trim();
231-
let payload: any;
232-
try { payload = JSON.parse(raw); } catch { payload = { unparsed: raw.slice(-400) }; }
233252
const stderr = errors.mock.calls.map((c) => c.map(String).join(' ')).join('\n');
234-
return { payload, raw, exitCode: thrownExit ?? (process.exitCode as number | undefined) ?? 0, stderr };
253+
const exitCode = thrownExit ?? (process.exitCode as number | undefined) ?? 0;
254+
let payload: any;
255+
try {
256+
payload = JSON.parse(raw);
257+
} catch {
258+
// Loud, never a bare `{ unparsed: '' }`: a run that printed no JSON
259+
// document says why: its exit code, the exit signal's own message (an
260+
// oclif parse refusal throws before the command writes a byte), how long
261+
// it ran, the argv, and the tail of everything it wrote to stderr.
262+
const stderrTail = [stderr, stderrWrites.mock.calls.map((c) => String(c[0])).join('')].join('\n').trim().slice(-800);
263+
payload = { unparsed: raw.slice(-400), exitCode, thrown: thrownMessage ?? null, ms: Date.now() - started, argv, stderr: stderrTail };
264+
}
265+
return { payload, raw, exitCode, stderr };
235266
} finally {
236267
process.exitCode = savedExit;
237268
vi.restoreAllMocks();
238269
}
239270
}
240271

241272
const report = (db: string) => run(MigrateStoredReferences, ['--database-url', `file:${db}`, '--json']);
242-
const bind = (db: string, table: string, id: string, pkg: string, yes = true) =>
243-
run(MigrateStoredReferencesBind, ['--table', table, '--id', id, '--package', pkg, ...(yes ? ['--yes'] : []), '--database-url', `file:${db}`, '--json']);
273+
const bind = (db: string, table: string, id: string, pkg: string, yes = true) => {
274+
// `SEEDED_IDS` says why an id that opens with `-` may never reach the argv.
275+
if (id.startsWith('-')) throw new Error(`bind(): the row id "${id}" opens with "-", which the bind's flag parser can read as a flag; seed a fixed id`);
276+
return run(MigrateStoredReferencesBind, ['--table', table, '--id', id, '--package', pkg, ...(yes ? ['--yes'] : []), '--database-url', `file:${db}`, '--json']);
277+
};
244278
const shareRow = async (db: string) => (await rowsOf(db, 'sys_sharing_rule')).find((r) => r.name === 'm31693_share')!;
245279
const suggestionRow = async (db: string) => (await rowsOf(db, 'sys_audience_binding_suggestion')).find((r) => r.permission_set_name === 'm31693_env_set')!;
246280

@@ -458,7 +492,7 @@ describe('os migrate stored-references bind', () => {
458492
const db = caseDb(controlDb);
459493
const share = await shareRow(db);
460494
const { payload, exitCode } = await bind(db, 'sys_sharing_rule', String(share.id), A);
461-
expect(payload).toMatchObject({ outcome: 'refused', reason: 'resolved', written: 0 });
495+
expect(payload, JSON.stringify(payload).slice(0, 1600)).toMatchObject({ outcome: 'refused', reason: 'resolved', written: 0 });
462496
expect(exitCode).toBe(1);
463497
expect((await shareRow(db)).package_id ?? null).toBeNull();
464498
}, CASE_TIMEOUT_MS);

0 commit comments

Comments
 (0)