Skip to content

Commit f848e37

Browse files
fix(rest): POST /api/v1/batch answers a request-schema refusal with fields[] (#35277)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgRuogP8Tp8XyFXLc92Bxvo6)_ Fixes #34863 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`POST /api/v1/batch`(跨对象批量)请求体不合 schema 时,400 VALIDATION_FAILED 的回答从原样透出 zod `issues` 改为 ADR-0114 的 `fields[]`(`{ field, code, message }`),与同文件的单对象批量入口一致。 - 为什么改:客户端(含 `@objectstack/client` 的 `err.fields`)在这一个入口拿不到字段级错误,只能解析 zod 内部结构;ADR-0114 D3 要求 zod 在边界映射、不透传。 - 风险与回滚:只影响这一个拒收分支的回答体,成功路径与状态码不变;`issues` 键从该回答中移除(实测无客户端、SDK、测试或文档读取它)。回滚即还原 `batch-routes.ts` 一处 hunk。 - 先看:`packages/rest/src/batch-routes.ts` 第 308–322 行(唯一行为改动);`packages/rest/src/cross-object-batch-request-refusal-fields.test.ts`;`.changeset/34863-cross-object-batch-refusal-fields.md`。 - 两分钟验证:`pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/cross-object-batch-request-refusal-fields.test.ts`,预期 3 passed;以管理员 `POST /api/v1/batch` 发 `{"operations":"x"}`,预期 400 且回答带 `fields:[{field:'operations',code:'invalid_type',…}]`、不再带 `issues`。 - 需要你做的:无,席位落地。 ## What changes - `packages/rest/src/batch-routes.ts`: the cross-object batch door's request-schema refusal now maps the `CrossObjectBatchRequestSchema` failure through `zodIssuesToFields(issues, input)`, the same mapper every per-object batch door in this file already uses (`/data/:object/batch`, `createMany`, `updateMany`, `deleteMany`). Status (400) and `code` (`VALIDATION_FAILED`) and `error` text are unchanged. - `issues` dropped, not kept beside `fields`. Measured readers: no `packages/client` source reads `issues` off a batch refusal, `CrossObjectBatchResponseSchema` is the success shape only, no test or doc page names the batch refusal's `issues`, and every `body.issues` reader in `packages/rest` tests is a metadata-save route (422 INVALID_METADATA), not `/batch`. Keeping it would pass Zod through at the boundary, which ADR-0114 D3 forbids. - Changeset: `@objectstack/rest` patch, with the migration sentence (`issues[i].path` reads as `fields[i].field`). - Envelope position (#9559) untouched. ## Tests New `packages/rest/src/cross-object-batch-request-refusal-fields.test.ts`, three cases: the card's two bodies (`{"operations":"x"}` gives `operations`/`invalid_type`; `{}` gives `operations`/`required`) plus an operation missing its object (`operations.0.object`/`required`). Each asserts status 400, `code` VALIDATION_FAILED, every `fields` element parses against `FieldErrorSchema`, no `issues` key, and no engine write or transaction reached. <details><summary>Red leg: the pin against the pre-fix source (commit e8383f1 version of batch-routes.ts), restored after</summary> ```text mutation landed: fields-mapping count=1 raw-issues count=1 × a non-array `operations` is an `invalid_type` on `operations` × an empty body names `operations` as `required` × an operation missing its object is located at its index AssertionError: {"error":"Invalid batch request","code":"VALIDATION_FAILED","issues":[{"expected":"array","code":"invalid_type","path":["operations"],"message":"Invalid input: expected array, received string"}]} Test Files 1 failed (1) Tests 3 failed (3) os-verify-lock: VERDICT command-exit 1 restored: git diff HEAD empty, hash 208dc1a == HEAD blob ``` The red body is the card's reproduction byte for byte (raw zod `issues`, no `fields`). </details> <details><summary>Green leg and the package suite</summary> ```text src/cross-object-batch-request-refusal-fields.test.ts Test Files 1 passed (1) Tests 3 passed (3) os-verify-lock: VERDICT command-exit 0 pnpm --filter @objectstack/rest test Test Files 420 passed (420) Tests 8619 passed | 350 skipped (8969) os-verify-lock: VERDICT command-exit 0 pnpm --filter @objectstack/rest typecheck check:test-typecheck: OK — @objectstack/rest's test layer compiles under packages/rest/tsconfig.test.json os-verify-lock: VERDICT command-exit 0 ``` </details> ## Acceptance notes - Clause-② no, measured: after `pnpm --filter '@objectstack/rest^...' build` and `pnpm --filter @objectstack/rest build`, `packages/rest/dist/index.d.ts` contains neither `Invalid batch request` nor `VALIDATION_FAILED` (the literal lives only in `dist/index.js`); the refusal body is an untyped `res.json` literal, and `@objectstack/spec/api` exports no cross-object batch error schema. Nothing exported widens or narrows. - No out-of-scope findings. ## Verification All readings below are at head `05e98ac3f5` (the final commit; a merge of origin/main into the branch, no file of this diff touched by it). overlap-check: `VERDICT clean exit 0` (merges cleanly with origin/main). `node scripts/check-platform-checklist.mjs --changed-from origin/main` not owed: no exported symbol renamed or removed. <details><summary>Local gate subset (dispatch-gates --commands, reconciled with --ran)</summary> ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:adr-symbol-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 3 pnpm check:engine-double-contract :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:meta-type-normalized :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:route-envelope :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 dispatch-gates --ran: 68 derived famil(ies) accounted for, 67 run, 1 NOT-MEASURED (check:dual-build-cjs-loads exit 3 PREREQUISITE NOT MET: it reads every package's dist/ and only the rest closure is built here; CI's lint run measures it) ``` </details> `test:repo`, the integration tiers and the whole-farm families are CI's; their check-runs are the verdict. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZiaBg6rk7dpy1s9Me)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZiaBg6rk7dpy1s9Me --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4026c44 commit f848e37

3 files changed

Lines changed: 135 additions & 2 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/rest': patch
3+
---
4+
5+
fix(rest): `POST /api/v1/batch` answers a request-schema refusal with the per-field `fields[]` list
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A cross-object batch body the request schema refuses (for example `{"operations":"x"}`, or `{}`) is still answered `400 VALIDATION_FAILED`, but the answer now carries `fields`, the same list of `{ field, code, message }` entries the per-object batch doors (`/data/:object/batch`, `createMany`, `updateMany`, `deleteMany`) answer: `{"operations":"x"}` names `operations` with `invalid_type`, `{}` names `operations` with `required`, and an operation missing its object names `operations.0.object` with `required`. A client's `err.fields` (`@objectstack/client`) is now filled on this door too.
11+
12+
The raw schema-library `issues` list is no longer on this refusal: field errors are mapped at the boundary, never passed through (ADR-0114 D3), and no client, SDK or test read it. A caller that read `issues[i].path` reads `fields[i].field` (the path joined with dots) and `fields[i].code` instead.

‎packages/rest/src/batch-routes.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,9 +308,17 @@ export function registerBatchEndpoints(this: BatchRouteHost, basePath: string):
308308

309309
// Validate the request against the spec contract (Zod-First).
310310
const { CrossObjectBatchRequestSchema } = await import('@objectstack/spec/api');
311-
const parsed = (CrossObjectBatchRequestSchema as any).safeParse(req.body ?? {});
311+
const batchInput = req.body ?? {};
312+
const parsed = (CrossObjectBatchRequestSchema as any).safeParse(batchInput);
312313
if (!parsed.success) {
313-
res.status(400).json({ error: 'Invalid batch request', code: 'VALIDATION_FAILED', issues: parsed.error?.issues });
314+
// ADR-0114 D3: Zod is mapped at the boundary, never passed
315+
// through — the same `fields[]` every per-object batch door
316+
// below answers, so a client reads one refusal shape.
317+
res.status(400).json({
318+
error: 'Invalid batch request',
319+
code: 'VALIDATION_FAILED',
320+
fields: zodIssuesToFields(parsed.error?.issues, batchInput),
321+
});
314322
return;
315323
}
316324
const ops: CrossObjectBatchOp[] = parsed.data.operations;
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// The cross-object batch door's request-schema refusal answers ADR-0114's
4+
// `fields[]` (`POST {basePath}/batch`, `batch-routes.ts`).
5+
//
6+
// A body `CrossObjectBatchRequestSchema` refuses is answered `400
7+
// VALIDATION_FAILED` like every per-object batch door of the same file
8+
// (`/data/:object/batch`, `createMany`, `updateMany`, `deleteMany`): the
9+
// failure mapped through `zodIssuesToFields` into `{ field, code, message }`
10+
// elements of the field-level catalog. ADR-0114 D3 — Zod is mapped at the
11+
// boundary, never passed through — so the raw Zod `issues` list is not on
12+
// the wire, and a client keying on `fields` reads one shape on every batch door.
13+
14+
import { describe, it, expect, vi } from 'vitest';
15+
import { FieldErrorSchema } from '@objectstack/spec/api';
16+
// Paid during collection, not inside a case's clocked window: the route
17+
// source reaches `@objectstack/objectql` through a dynamic import.
18+
import '@objectstack/objectql';
19+
import { RestServer } from './rest-server';
20+
21+
function mockServer() {
22+
return {
23+
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(),
24+
use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined),
25+
};
26+
}
27+
28+
function mockRes() {
29+
const res: any = { statusCode: 200, body: undefined };
30+
res.status = vi.fn((c: number) => { res.statusCode = c; return res; });
31+
res.json = vi.fn((b: any) => { res.body = b; return res; });
32+
res.end = vi.fn(() => res);
33+
return res;
34+
}
35+
36+
/**
37+
* A transactional engine whose every write is a spy: a refused request must
38+
* reach none of them. Never driven past the refusal, so no write double here
39+
* needs a dispatch check of its own.
40+
*/
41+
function makeQl() {
42+
return {
43+
transaction: vi.fn(async (cb: any, ctx: any) => cb({ __trx: true, ctx })),
44+
insert: vi.fn(),
45+
update: vi.fn(),
46+
delete: vi.fn(),
47+
};
48+
}
49+
50+
function buildServer(ql: ReturnType<typeof makeQl>) {
51+
const protocol: any = {
52+
getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '' } }),
53+
getMetaTypes: vi.fn().mockResolvedValue([]),
54+
getMetaItems: vi.fn().mockResolvedValue([]),
55+
createData: vi.fn(),
56+
};
57+
const rest = new RestServer(
58+
mockServer() as any, protocol as any, { api: { requireAuth: false } } as any,
59+
undefined, undefined, undefined, undefined, // kernelManager, envRegistry, defaultEnvIdProvider, authServiceProvider
60+
async () => ql, // objectQLProvider (positional arg #8)
61+
);
62+
(rest as any).resolveExecCtx = async () => ({ userId: 'test-user' });
63+
rest.registerRoutes();
64+
const route = rest.getRoutes().find(
65+
(r) => r.method === 'POST' && (r.metadata?.summary ?? '').startsWith('Cross-object'),
66+
);
67+
expect(route, 'the cross-object batch route is registered').toBeTruthy();
68+
return route!;
69+
}
70+
71+
async function post(body: unknown) {
72+
const ql = makeQl();
73+
const route = buildServer(ql);
74+
const res = mockRes();
75+
await route.handler({ method: 'POST', params: {}, headers: {}, body } as any, res);
76+
return { res, ql };
77+
}
78+
79+
/** The refusal envelope every batch door of this server answers a schema failure with. */
80+
function expectFieldsRefusal(res: any, ql: ReturnType<typeof makeQl>) {
81+
expect(res.statusCode).toBe(400);
82+
expect(res.body.code).toBe('VALIDATION_FAILED');
83+
expect(Array.isArray(res.body.fields), JSON.stringify(res.body)).toBe(true);
84+
expect(res.body.fields.length).toBeGreaterThan(0);
85+
for (const element of res.body.fields) {
86+
const parsed = FieldErrorSchema.safeParse(element);
87+
expect(parsed.success, JSON.stringify(element)).toBe(true);
88+
}
89+
// ADR-0114 D3: mapped at the boundary, never passed through.
90+
expect(res.body).not.toHaveProperty('issues');
91+
expect(ql.transaction).not.toHaveBeenCalled();
92+
expect(ql.insert).not.toHaveBeenCalled();
93+
}
94+
95+
describe('POST {basePath}/batch — a request-schema refusal answers fields[] (ADR-0114)', () => {
96+
it('a non-array `operations` is an `invalid_type` on `operations`', async () => {
97+
const { res, ql } = await post({ operations: 'x' });
98+
expectFieldsRefusal(res, ql);
99+
expect(res.body.fields.map((f: any) => [f.field, f.code])).toEqual([['operations', 'invalid_type']]);
100+
});
101+
102+
it('an empty body names `operations` as `required`', async () => {
103+
const { res, ql } = await post({});
104+
expectFieldsRefusal(res, ql);
105+
expect(res.body.fields.map((f: any) => [f.field, f.code])).toEqual([['operations', 'required']]);
106+
});
107+
108+
it('an operation missing its object is located at its index', async () => {
109+
const { res, ql } = await post({ operations: [{ action: 'create', data: {} }] });
110+
expectFieldsRefusal(res, ql);
111+
expect(res.body.fields.map((f: any) => [f.field, f.code])).toContainEqual(['operations.0.object', 'required']);
112+
});
113+
});

0 commit comments

Comments
 (0)