Skip to content

Commit 660e7cd

Browse files
fix(spec)!: a query where of the wrong kind answers one fields[] entry that names the shapes it takes (#37205)
repo:objectstack#7 · os-alice · session_011y7As5bdhV5T4N9vpjmZzH Fixes #35500 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — no skills/ page names the `query.where` refusal or its `Invalid input` entries, or reads `fields[]` / `issues[]` by position or count ## 维护者速读 - 用户能看到什么变化:通过数据接口查询时,如果筛选条件写成了数字、字符串或空值,被拒时只返回一条说明,写清筛选条件应该是条件对象还是筛选数组;不再返回两条一模一样、什么也没说的「输入无效」。 - 为什么做:修的是数据接口查询被拒时原因说不清的问题(上一张同类卡的后续)。主要调用方是通过数据接口写查询的 AI,它看不到原因只能乱猜重试。 - 出错会怎样:按条数或位置读错误清单、或专找那句「输入无效」的调用方会读到不同内容;正常查询不受影响,元数据保存的错误清单在同类嵌套情况下也少一条;不涉及存储数据,撤回这一个 PR 即可恢复。 - 要你做什么:批准或合并这个 PR;它是申报了收窄的破坏性改动,席位不能自己落地。 ## What changes A query's `where` on the data API is `z.union([FilterArraySchema, DataEngineFilterSchema])`, and both members are unions themselves. Handed `42`, a string or `null`, each member failed only because the value was the wrong kind, but the shared branch selection did not read a member that is a union as a kind mismatch. So it selected both members, and each emitted its own unexplained `{ field: 'query.where', code: 'invalid_shape', message: 'Invalid input' }`. The caller got two identical entries and no cause. Measured at `main` `236c8044acb`, after #37083 had already dropped the explained outer head. #37083 is not released yet and ships in the same release as this, so a released client's before is the card's reading at `f6902e950`: three identical entries for `where: 42`, and five entries (four bare) for the malformed AST. The changeset's FROM lines are written against that. - Policy (`packages/spec/src/shared/union-branch-policy.ts`): `isKindMismatchOnly` now also counts a branch-root `invalid_union` with zod's bare default message whose every branch is itself kind-mismatch-only, by the same rule, so depth does not matter. A nested union that declares its own `error` sentence stays informative. A nested union with `errors: []` keeps its old reading. `ZOD_UNION_DEFAULT_MESSAGE` moves into this module, because the selection now reads it; the mapper re-exports it unchanged for its pin, and it stays package-internal. - The same rule in `@objectstack/metadata-protocol`'s copy (`protocol-metadata-issues.ts`), so the data API's `fields[]`, the terminal renderer and the four lists `zodIssuesToMetadataIssues` feeds reach one verdict. Those four are a refused save's `issues[]` (`422 INVALID_METADATA`), a stored item's `_diagnostics.errors`, the seed-request refusal's `issues`, and the unmanaged-import `400`. This is what ruling record 7010280743 requires: the two machine lists say the same thing. - The cause sentence (`packages/spec/src/data/data-engine.zod.ts`, `TransportFilterValueSchema`): a value of the wrong kind (not an object or array) gets one sentence naming both accepted shapes, a condition object such as `{ "status": "open" }` or a filter array such as `["status", "=", "open"]`. An array or an object keeps zod's default, so its located causes speak and the bare head is still dropped in their favour. It covers every spelling of the slot (`where`, `$filter`, `filter`, `filters`) for a number, a string or a boolean. `null` is refused with it only on `where`; the other three spellings are `.nullable()` and accept `null` as no filter. - Selection side effect: such a member was one issue long, so under "fewest issues wins" it could out-rank a sibling member with several located causes. That sibling is now selected, so in that case a list gains its located entries where one bare entry stood. - Changeset: `@objectstack/spec` and `@objectstack/metadata-protocol` patch, `fix(spec)!`, BREAKING banner, FROM / TO, one ADR-0087 marker (`not-required (no-migration-prescription)`). The claim's file surface was widened to the policy layer before this was built (seat decision, option A of os-dev-report 7146729179; the amendment is on the card). ## Tests All readings below are from the shared verify lock on a shared box. <details><summary>New pins</summary> - `packages/spec/src/api/zod-issues-to-fields.test.ts`, new describe: through the real `FindDataRequestSchema`, `42`, a string, `null` and a boolean each answer exactly one entry, `[['query.where', 'invalid_shape']]`, whose message is not zod's default and names both shapes. `$filter` answers the same entry at `query.$filter`. The malformed AST `[['status','=','open'],'and']` answers exactly `[query.where min_items, query.where.1 invalid_shape 'Invalid input']`. CONTROL: a filter object, a filter array and a logical filter array still parse. Plus a synthetic union of bare-kind unions answering one entry. - `packages/spec/src/shared/union-branch-policy.parity.test.ts`: a new corpus fixture (renderer and wire agree pair for pair), the recursion, a sentence-carrying nested union staying informative, and `errors: []` keeping its reading. `ZOD_UNION_DEFAULT_MESSAGE` was added to the package-internal roster. - `packages/metadata-protocol/src/union-branch-policy.cross-package-parity.test.ts`: two section-2 fixtures, a synthetic nested bare-kinds union and the real query door with `where: 42`. All three walks give the same paths and messages. `ZOD_UNION_DEFAULT_MESSAGE` was added to the section-1 symbol roster. - `packages/metadata-protocol/src/protocol.save-union-issues.test.ts`: the envelope walk says the nested bare-kinds union once, a sentence-carrying member is still heard, and a CONTROL member with a located cause is still expanded. - `packages/rest/src/zod-union-fields.test.ts`, new top-level describe, which runs the real `POST /api/v1/data/:object/query` route over ObjectQL, SqlDriver (sqlite) and the metadata protocol. For `42`, a string and `null`: `400`, `code: 'VALIDATION_FAILED'`, exactly `[['query.where', 'invalid_shape']]` with the shape sentence, and the driver is never read. For the malformed AST: `400 VALIDATION_FAILED` with `fields` equal to the two entries above, and no read. CONTROL: a filter object and a filter array are served `200` with the right rows. The new pins assert the `field`, `code`, status and entry count exactly. They check the sentence by the two shapes it names (`condition object`, `filter array`), not by its full wording. </details> <details><summary>Package suites (head 2af665d, before the merge of origin/main)</summary> - `pnpm --filter @objectstack/spec exec vitest run --maxWorkers=2`: Test Files 983 passed (983); Tests 29875 passed, 1 todo. VERDICT command-exit 0. - `pnpm --filter @objectstack/metadata-protocol test`: Test Files 369 passed, 9 skipped (378); Tests 23394 passed, 45 skipped. VERDICT command-exit 0. - `pnpm --filter @objectstack/rest test`: Test Files 429 passed (429); Tests 8823 passed, 351 skipped. VERDICT command-exit 0. The first attempt got exit 99 (no lock turn, NOT MEASURED) and was re-run on the same slot. - `typecheck` for spec, metadata-protocol and rest: VERDICT command-exit 0. </details> <details><summary>Final head 16f479c (merges of origin/main up to 3b4f0b9; the branch's delta against main is exactly the 10 files above)</summary> - The dogfood closure was rebuilt (`pnpm --filter '@objectstack/dogfood^...' build`, VERDICT command-exit 0). `pnpm --filter @objectstack/spec check:generated`: exit 0, no artifact moved. - Affected files re-run: spec 2 files 56/56, metadata-protocol 2 files 64/64, rest 1 file 23/23. VERDICT command-exit 0. </details> <details><summary>Ablation (one time, not kept)</summary> - Mutation through `scripts/ablation-replace.mjs` in `union-branch-policy.ts`: the anchor `|| isKindMismatchOnlyUnion(issue)),` was replaced by a marker comment, which turns the nested rule off. Anchor 1 to 0, marker 0 to 1, blob `8f72bb114a75` to `c2e73abc2818`. - Mutated leg, `zod-issues-to-fields.test.ts` and `union-branch-policy.parity.test.ts`: Test Files 2 failed (2); Tests 10 failed, 46 passed (56). The failures were every door case (`42`, string, `null`, boolean, `$filter`, malformed AST), the synthetic nested union, the new parity fixture, "both walks say the union once" and "the rule recurses". The sentence-carrying and `errors: []` pins stay green under the mutation, as expected: they pin the rule's edges, not the rule. - Restore proven by blob: after restore it equals the HEAD blob `8f72bb114a75`, and `git diff HEAD` is empty. Restored leg: 2 files, 56/56 passed. - Scope: both suites import `src` relatively, so they need no rebuild. The metadata-protocol and rest pins resolve `@objectstack/spec` through `dist/` and were not ablated. </details> ## Acceptance notes - Renderer: `formatZodError` / the CLI take the same rule, because they share the policy. A wrong-kind `where` prints one line, not one per member. - Positional reader: `readDeclaredQueryNumber` (`rest-server.ts`) reads `fields[0]?.message`. A declared number schema has no nested bare-kinds union, so it does not move. - Docs: `content/docs/api/error-handling-server.mdx` already says a bare union entry is "kept only when nothing does", and that stays true, so it is not edited. - Noted, not fixed (same door, different defect): `query.$filter: { "$and": 42 }` answers `field: 'query.where.$and'`, `code: 'required'`. The value is present, and the field names the folded slot, not the one the caller sent. Reported to the seat for filing. - Read first, by risk: `packages/spec/src/shared/union-branch-policy.ts` (`isKindMismatchOnlyUnion`), then `TransportFilterValueSchema` in `data-engine.zod.ts`, then `union-branch-policy.cross-package-parity.test.ts` section 2. - Two-minute check: `pnpm --filter @objectstack/spec exec vitest run --maxWorkers=2 src/api/zod-issues-to-fields.test.ts`. Every test should be green, including the describe "a wrong-typed query where answers one entry that names the shapes". - A contract-tier review is owed: this is a declared narrowing. ## Verification <details><summary>Rework round (changeset prose only), head ecc795b</summary> - Seat REWORK 7152541028, items 1 to 4: the FROM lines now give the released behaviour, `null` is scoped to `where`, the four metadata lists and their readers are named in the BREAKING banner, and the out-ranking effect is stated. The contract review PASS 7152531147 at `16f479c57d6` read no code finding, and this round changes no code: the delta from that head is `.changeset/where-wrong-kind-one-entry.md` alone. No generated reference reads a changeset, so no `Regen-provenance:` line is needed. - `node scripts/check-adr-0087-registration.mjs`: exit 0. - Gate sweep at `ecc795b1905`: `dispatch-gates --commands --repo objectstack-ai/objectstack` derived 89 families; `--ran` gave 88 run, 1 NOT-MEASURED (`pnpm check:dual-build-cjs-loads`, exit 3, PREREQUISITE NOT MET: this fresh worktree built only the dogfood closure; CI runs it in `Build Core`), 0 UNRUN. - Dogfood battery re-pinned on `ecc795b1905`, because the seat's L1 checklist pins `dogfood_battery` to the PR head, whatever the delta. `pnpm --filter @objectstack/dogfood test` ran as its own command under the verify lock: `VERDICT command-exit 0 · held the lock 2403s`, Test Files 487 passed, 3 skipped (490); Tests 4128 passed, 68 skipped (4196); 0 failed. </details> <details><summary>Gate sweep: dispatch-gates --commands, 89 families, head 16f479c</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 89 families. Each was run with its exit code recorded before any pipe. `--ran`: 89 derived, 89 run, 0 NOT-MEASURED, 0 UNRUN, exit 0. - Extra: `pnpm check:error-code-casing` exit 0 and `node scripts/check-adr-0087-registration.mjs` exit 0 (one declared-breaking changeset, disposition `not-required (no-migration-prescription)`). - `test:repo` was not run locally; CI owns it. </details> <details><summary>Dogfood battery (narrowing arm), head 16f479c</summary> - `pnpm --filter @objectstack/dogfood test` as its own command under the shared verify lock: full battery, no shard, no path, run after building the dogfood closure. `os-verify-lock: VERDICT command-exit 0 · held the lock 2197s`. Test Files 487 passed, 3 skipped (490); Tests 4128 passed, 68 skipped (4196); 0 failed. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_011y7As5bdhV5T4N9vpjmZzH)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d7f299c commit 660e7cd

10 files changed

Lines changed: 414 additions & 19 deletions
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/metadata-protocol': patch
4+
---
5+
6+
fix(spec)!: a query `where` of the wrong kind is refused with one `fields[]` entry that names the shapes it takes, not one bare "Invalid input" per union member
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
Skills-docs: none (no skills/ page names the `query.where` refusal, its `Invalid input` entries, or reads `fields[]` / `issues[]` by position or count)
11+
12+
What narrows: the union-branch selection that every refusal list shares now reads a member that is itself a union, failing only because the value is the wrong kind for every one of its own members, as the kind mismatch it is. Such a member is no longer selected, so it no longer adds its own unexplained `invalid_shape` / `Invalid input` entry. The rule lives in `@objectstack/spec`'s branch-selection policy, so the data API's `fields[]` (`zodIssuesToFields`) and the terminal renderer (`formatZodError`) both take it, and `@objectstack/metadata-protocol`'s copy takes the same rule, pinned equal by the cross-package parity test. That copy (`zodIssuesToMetadataIssues`) feeds four lists: the `issues[]` of a refused metadata save (`422 INVALID_METADATA`), a stored item's `_diagnostics.errors`, the seed-request refusal's `issues`, and the unmanaged-import `400`. A nested union declared with its own `error` sentence is still selected, because that sentence is a prescription.
13+
14+
Such a member was one issue long, so under "fewest issues wins" it could out-rank a sibling member with several located causes. That sibling is now the one selected, so in that case a list gains its located entries where one bare entry stood.
15+
16+
The query door's `where` (and its `$filter` / `filter` / `filters` spellings) is such a union of unions: a filter array or a filter object. A number, a string or a boolean on any of those spellings, and `null` on `where` (the other three accept `null` as no filter), now carries one sentence naming both accepted shapes, a condition object such as `{ "status": "open" }` or a filter array such as `["status", "=", "open"]`. An array or an object still answers its located causes.
17+
18+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: what moves is which entries a refusal's fields and issues lists carry, and the message of one of them, computed afresh on every refused request and every diagnostics read. The accept set is unchanged. The one reading instruction is in the body: read entries by field (or path) and code, never by index or count. -->
19+
20+
**BREAKING** for a client that counts a refused request's `fields[]` entries, reads them by position, or matches the bare `Invalid input` text on the `query.where` entry; for a reader that counts or reads by position a refused metadata save's `issues[]`, a stored item's `_diagnostics.errors`, the seed-request refusal's `issues` or the unmanaged-import refusal; and for anything that counts the terminal renderer's lines for such a refusal. The dropped entries named only the slot, once per union member, and said nothing about what to send. Read entries by `field` (or `path`) and `code`.
21+
22+
The FROM lines below are what the released packages answer. The data API's explained-head drop (`fields-bare-union-head`, the same producer) ships in the same release, and accounts for part of the difference: it removes the explained union heads, and this change removes the unexplained per-member ones.
23+
24+
For `POST /api/v1/data/:object/query` with `{ "where": 42 }` (a string or a boolean alike, and `null` on `where`):
25+
26+
- FROM: `fields` was three identical entries, each `{ field: 'query.where', code: 'invalid_shape', message: 'Invalid input' }`.
27+
- TO: `fields` is `[{ field: 'query.where', code: 'invalid_shape', message: 'A filter is a condition object, such as { "status": "open" } … or a filter array, such as ["status", "=", "open"] …' }]`.
28+
29+
For `{ "where": [["status", "=", "open"], "and"] }`:
30+
31+
- FROM: `fields` held five entries, four of them a bare `invalid_shape` / `Invalid input`, and the one located cause, `min_items` at `query.where`.
32+
- TO: `fields` holds `min_items` at `query.where` and the bare `invalid_shape` at `query.where.1`, the element that is not a filter.
33+
34+
The fix for a caller that matched the bare text on `query.where`: match `field: 'query.where'` with `code: 'invalid_shape'`, whatever the message.
35+
36+
The four metadata lists move the same way, only where the schema has such a nested union of kinds: one `invalid_union` entry for the slot instead of one per member, or the located causes of the sibling member that now out-ranks it.

‎packages/metadata-protocol/src/protocol-metadata-issues.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,15 +137,36 @@ function issuePathOf(issue: ZodIssueLike): Array<string | number> {
137137
* emitting it is the "N branches, N times the noise" failure. An empty branch
138138
* (zod's "matched multiple" variant carries `errors: []`) counts as
139139
* uninformative too — `every` on an empty list is `true`.
140+
*
141+
* [#35500] A branch that is itself a union counts the same way when that union
142+
* only says "not my kind" either: one `invalid_union` at the branch root,
143+
* carrying zod's bare {@link ZOD_UNION_DEFAULT_MESSAGE}, whose every branch is
144+
* in turn kind-mismatch-only (this same rule, so the depth does not matter).
145+
* Read as informative, each such member emitted its own unexplained bare head,
146+
* one identical `Invalid input` entry per member. A nested union carrying its
147+
* schema's own `error` sentence stays informative, and one with no branches
148+
* keeps the reading it always had. The same rule as `isKindMismatchOnly` in
149+
* `spec/src/shared/union-branch-policy.ts`, held equal by
150+
* `union-branch-policy.cross-package-parity.test.ts` §2.
140151
*/
141152
function isKindMismatchOnly(issues: readonly ZodIssueLike[]): boolean {
142153
return issues.every(
143154
(issue) =>
144155
issuePathOf(issue).length === 0
145-
&& (issue?.code === 'invalid_type' || issue?.code === 'invalid_value'),
156+
&& (issue?.code === 'invalid_type' || issue?.code === 'invalid_value'
157+
|| isKindMismatchOnlyUnion(issue)),
146158
);
147159
}
148160

161+
/** The nested half of {@link isKindMismatchOnly}: a bare union of kinds. */
162+
function isKindMismatchOnlyUnion(issue: ZodIssueLike): boolean {
163+
if (issue?.code !== 'invalid_union' || issue.message !== ZOD_UNION_DEFAULT_MESSAGE) return false;
164+
const branches = issue.errors;
165+
return Array.isArray(branches)
166+
&& branches.length > 0
167+
&& branches.every((branch) => Array.isArray(branch) && isKindMismatchOnly(branch as ZodIssueLike[]));
168+
}
169+
149170
/** True when a branch carries the #4001 campaign's unknown-key prescription. */
150171
function carriesUnknownKey(issues: readonly ZodIssueLike[]): boolean {
151172
return issues.some((issue) => issue?.code === 'unrecognized_keys');

‎packages/metadata-protocol/src/protocol.save-union-issues.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,3 +672,33 @@ describe('#26711 the view write door refuses an unknown top-level key', () => {
672672
expect(JSON.stringify(served._diagnostics)).toContain('zzz_junk_key');
673673
});
674674
});
675+
676+
describe('#35500 a member that is itself a bare union of kinds explains nothing', () => {
677+
const kindsOnly = z.object({
678+
u: z.union([z.union([z.string(), z.number()]), z.union([z.boolean(), z.array(z.string())])]),
679+
});
680+
const issuesOf = (schema: z.ZodTypeAny, value: unknown) => {
681+
const r = schema.safeParse(value);
682+
expect(r.success, 'the fixture must actually fail to parse').toBe(false);
683+
return (r as { error: { issues: unknown[] } }).error.issues;
684+
};
685+
686+
it('the union is said once — not one bare entry per member', () => {
687+
expect(zodIssuesToMetadataIssues(issuesOf(kindsOnly, { u: {} }))).toEqual([
688+
{ path: 'u', message: ZOD_UNION_DEFAULT_MESSAGE, code: 'invalid_union' },
689+
]);
690+
});
691+
692+
it('a nested union carrying its own sentence is still heard', () => {
693+
const sentence = 'Write a string or a number.';
694+
const schema = z.object({ u: z.union([z.union([z.string(), z.number()], { error: sentence }), z.boolean()]) });
695+
expect(zodIssuesToMetadataIssues(issuesOf(schema, { u: {} }))).toEqual([
696+
{ path: 'u', message: sentence, code: 'invalid_union' },
697+
]);
698+
});
699+
700+
it('CONTROL — a member with a located cause is still selected and expanded', () => {
701+
const schema = z.object({ u: z.union([z.union([z.string(), z.number()]), z.object({ a: z.string() }).strict()]) });
702+
expect(zodIssuesToMetadataIssues(issuesOf(schema, { u: { a: 1 } })).map((e) => [e.path, e.code])).toEqual([['u.a', 'invalid_type']]);
703+
});
704+
});

‎packages/metadata-protocol/src/union-branch-policy.cross-package-parity.test.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
*
4646
* A parity test whose halves share a code path proves nothing. These do not,
4747
* and it is structural rather than a matter of care: §1 asserts that not one of
48-
* the seven policy symbols is reachable from ANY public entry point of
48+
* the eight policy symbols is reachable from ANY public entry point of
4949
* `@objectstack/spec`, so `protocol.ts` cannot be importing the shared module
5050
* even if a future author wanted it to. Its copy is the only thing it can run.
5151
*
@@ -112,7 +112,7 @@ import { z } from 'zod';
112112
// renderer (#4971) and `/api`'s ADR-0114 wire mapper (#8124). Both delegate
113113
// branch selection to the package-internal policy module #8318 extracted.
114114
import { formatZodIssue } from '@objectstack/spec';
115-
import { zodIssuesToFields } from '@objectstack/spec/api';
115+
import { FindDataRequestSchema, zodIssuesToFields } from '@objectstack/spec/api';
116116
// This package's own copy of the ranking, at the surface every producer here
117117
// calls: `saveMetaItem`'s 422 (#5364) and `computeMetadataDiagnostics` (#5598).
118118
import { zodIssuesToMetadataIssues } from './protocol.js';
@@ -314,10 +314,27 @@ const FIXTURES: readonly Fixture[] = [
314314
expectedPaths: ['outer', 'outer.inner', 'outer.inner.a'],
315315
machinePaths: ['outer.inner.a'],
316316
},
317+
{
318+
// [#35500] Read as informative, each member emitted its own unexplained
319+
// bare head: one identical entry per member, in all three walks.
320+
rule: 'kind-mismatch drop, nested — a member that is itself a bare union of kinds is not selected',
321+
schema: z.object({ u: z.union([z.union([z.string(), z.number()]), z.union([z.boolean(), z.array(z.string())])]) }),
322+
value: { u: {} },
323+
expectedPaths: ['u'],
324+
},
325+
{
326+
// [#35500] The measured case: the data API's own query parse, `where`
327+
// of the wrong kind. Its union carries the slot's own sentence, said
328+
// once by all three walks.
329+
rule: 'kind-mismatch drop, nested — a query where of the wrong kind is the slot\'s one sentence',
330+
schema: FindDataRequestSchema as unknown as z.ZodTypeAny,
331+
value: { object: 'account', query: { object: 'account', where: 42 } },
332+
expectedPaths: ['query.where'],
333+
},
317334
];
318335

319336
describe('#8660 §1 the two sides cannot be sharing an implementation', () => {
320-
/** The seven symbols `spec/src/shared/union-branch-policy.ts` declares. */
337+
/** The eight symbols `spec/src/shared/union-branch-policy.ts` declares. */
321338
const POLICY_SYMBOLS = [
322339
'selectUnionBranches',
323340
'isKindMismatchOnly',
@@ -326,6 +343,7 @@ describe('#8660 §1 the two sides cannot be sharing an implementation', () => {
326343
'CONTAINER_ISSUE_CODES',
327344
'NESTED_EXPANSION_DEPTH_LIMIT',
328345
'UNION_BRANCH_SELECTION_LIMIT',
346+
'ZOD_UNION_DEFAULT_MESSAGE',
329347
] as const;
330348

331349
/**
@@ -422,7 +440,7 @@ describe('#8660 §3 the corpus cannot be passing vacuously', () => {
422440
});
423441

424442
it('the corpus exercises expansion, not just the union head', () => {
425-
// Six of the eight fixtures must reach BELOW the top-level issue; if a
443+
// Six of the ten fixtures must reach BELOW the top-level issue; if a
426444
// future edit flattened them, every parity assertion above would still
427445
// pass while asserting nothing about branch selection.
428446
const expanded = FIXTURES.filter((f) => f.expectedPaths.length > 1);

‎packages/rest/src/zod-union-fields.test.ts‎

Lines changed: 124 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { describe, it, expect } from 'vitest';
3+
import { describe, it, expect, afterEach } from 'vitest';
44
import { z } from 'zod';
55
import { FieldErrorCode } from '@objectstack/spec/api';
6+
import { ObjectQL } from '@objectstack/objectql';
7+
import { SqlDriver } from '@objectstack/driver-sql';
8+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
9+
import { installDefaultOrganization } from './default-organization.testkit.js';
610
// `.js` extension deliberately: under `moduleResolution: NodeNext` an
711
// extensionless relative import does not resolve, every symbol it names becomes
812
// `any`, and each callback over those symbols then reports TS7006 (AGENTS.md
913
// §Build & Test). This is the same spelling `rest-server.ts` itself uses.
10-
import { zodIssuesToFields } from './rest-server.js';
11-
// Pays the first load of the engine `rest-server.ts` reaches through a dynamic
12-
// import at collection, never inside a clocked case (check:test-source-alias).
13-
import '@objectstack/objectql';
14+
import { RestServer, zodIssuesToFields } from './rest-server.js';
1415

1516
/**
1617
* `invalid_union` expansion on the wire (#5014).
@@ -332,3 +333,121 @@ describe('zodIssuesToFields — invalid_key / invalid_element descent (#5389)',
332333
.toEqual([{ field: 'm', code: 'invalid_shape', message: 'Invalid value' }]);
333334
});
334335
});
336+
337+
/**
338+
* [#35500] `POST /api/v1/data/:object/query` with a `where` of the wrong kind,
339+
* through the real route over a real engine and driver.
340+
*
341+
* `where` on that door is `z.union([FilterArraySchema, DataEngineFilterSchema])`,
342+
* and both members are themselves unions. A number, a string or `null` used to
343+
* answer one bare `{field: 'query.where', code: 'invalid_shape', message:
344+
* 'Invalid input'}` per member and nothing that said what to send, so an AI
345+
* caller had nothing to retry with. A member that is itself a bare union of
346+
* kinds is now read as the kind mismatch it is, and the slot's own sentence
347+
* names the two shapes it takes.
348+
*/
349+
describe('[#35500] POST /data/:object/query — a wrong-typed where answers one entry that names the shapes', () => {
350+
const OBJECT = 'where_shape_35500';
351+
const TASKS = {
352+
name: OBJECT,
353+
label: 'Where shape 35500',
354+
fields: {
355+
status: { name: 'status', type: 'text' as const },
356+
amount: { name: 'amount', type: 'number' as const },
357+
},
358+
};
359+
const ROWS = [
360+
{ id: 'r1', status: 'open', amount: 50 },
361+
{ id: 'r2', status: 'done', amount: 500 },
362+
];
363+
364+
const live: ObjectQL[] = [];
365+
afterEach(async () => {
366+
while (live.length) {
367+
try { await live.pop()?.destroy(); } catch { /* noop */ }
368+
}
369+
});
370+
371+
const noop = () => {};
372+
const mockServer = () => ({ get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} });
373+
const makeRes = () => {
374+
const res: any = {
375+
write: () => true, end: () => {},
376+
header: () => res,
377+
status: (code: number) => { res._status = code; return res; },
378+
json: (body: any) => { res._json = body; return res; },
379+
};
380+
return res;
381+
};
382+
383+
async function boot() {
384+
const driver: any = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
385+
const engine = new ObjectQL();
386+
live.push(engine);
387+
engine.registerDriver(driver, true);
388+
await engine.init();
389+
engine.registry.registerObject(TASKS as any);
390+
await engine.syncSchemas();
391+
await installDefaultOrganization(engine);
392+
await engine.insert(OBJECT, ROWS as any);
393+
394+
const calls = { find: 0 };
395+
const find = driver.find.bind(driver);
396+
driver.find = (o: string, ...rest: unknown[]) => { if (o === OBJECT) calls.find += 1; return find(o, ...rest); };
397+
398+
const protocol = new ObjectStackProtocolImplementation(engine as any);
399+
const rest = new RestServer(mockServer() as any, protocol as any, { api: { requireAuth: false } } as any);
400+
(rest as any).resolveExecCtx = async () => ({ userId: 'test-user' });
401+
rest.registerRoutes();
402+
const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/data/:object/query');
403+
expect(route).toBeDefined();
404+
const post = async (body: Record<string, unknown>) => {
405+
const res = makeRes();
406+
// What the wire carries: JSON.
407+
await route!.handler({ params: { object: OBJECT }, body: JSON.parse(JSON.stringify(body)) } as any, res);
408+
return res;
409+
};
410+
return { post, calls };
411+
}
412+
413+
it.each([
414+
['42', 42],
415+
['a string', 'status = open'],
416+
['null', null],
417+
])('%s: 400 VALIDATION_FAILED with exactly one fields[] entry, before any read', async (_name, where) => {
418+
const { post, calls } = await boot();
419+
const res = await post({ where });
420+
expect(res._status).toBe(400);
421+
expect(res._json.code).toBe('VALIDATION_FAILED');
422+
expect(res._json.fields.map((f: any) => [f.field, f.code])).toEqual([['query.where', 'invalid_shape']]);
423+
// The entry names both accepted shapes instead of zod's bare default.
424+
expect(res._json.fields[0].message).not.toBe('Invalid input');
425+
expect(res._json.fields[0].message).toContain('condition object');
426+
expect(res._json.fields[0].message).toContain('filter array');
427+
expect(calls.find).toBe(0);
428+
});
429+
430+
it('a malformed AST: 400 VALIDATION_FAILED with its located causes and no duplicate Invalid input', async () => {
431+
const { post, calls } = await boot();
432+
const res = await post({ where: [['status', '=', 'open'], 'and'] });
433+
expect(res._status).toBe(400);
434+
expect(res._json.code).toBe('VALIDATION_FAILED');
435+
expect(res._json.fields).toEqual([
436+
{ field: 'query.where', code: 'min_items', message: expect.any(String) },
437+
{ field: 'query.where.1', code: 'invalid_shape', message: 'Invalid input' },
438+
]);
439+
expect(calls.find).toBe(0);
440+
});
441+
442+
it('CONTROL: a valid filter object and a valid filter array are still served', async () => {
443+
const { post, calls } = await boot();
444+
const asObject = await post({ where: { status: 'open' } });
445+
expect(asObject._status ?? 200).toBe(200);
446+
expect(asObject._json.records.map((r: any) => r.id)).toEqual(['r1']);
447+
448+
const asArray = await post({ where: ['amount', '>', 100] });
449+
expect(asArray._status ?? 200).toBe(200);
450+
expect(asArray._json.records.map((r: any) => r.id)).toEqual(['r2']);
451+
expect(calls.find).toBe(2);
452+
});
453+
});

0 commit comments

Comments
 (0)