Skip to content

Commit 498fe4e

Browse files
committed
wip(spec): QuerySchema.fields and GetRecordConfigSchema.fields refuse an empty projection
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzfMG4xAptDoRoz9kyT
1 parent 9dacccf commit 498fe4e

8 files changed

Lines changed: 255 additions & 31 deletions

File tree

‎packages/rest/src/data-empty-projection-count-door.test.ts‎

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* |:--|:--|:--|
1414
* | `GET ?$select=`, `?$select=%20`, `?$select=,`, `?select=`, `?fields=` | 200, every column | 400 naming the spelling |
1515
* | `GET ?$count=maybe`, `?$count=1`, `?count=` (with `$top`) | 200, `total` reported | 400 naming the spelling |
16-
* | `POST {"select":""}`, `{"fields":[]}` | 200, every column | 400 naming the key (`select` at the body schema, `VALIDATION_FAILED`, since #26909) |
16+
* | `POST {"select":""}`, `{"fields":[]}` | 200, every column | 400 naming the key at the body schema, `VALIDATION_FAILED` (`select` since #26909, `fields` since #27166) |
1717
* | `POST {"count":"maybe"}` | 400 `VALIDATION_FAILED` (the body schema) | unchanged |
1818
* | `GET /:id?select=`, `?select=,` | 200, every column | `VALIDATION_ERROR` naming `select`, at this route's 404 (it rewrote every 400, as for `?select=nope`); 400 since #26816 |
1919
* | `GET ?$select=label`, `?$count=true` / `false`, absent; `GET /:id?select=label` | 200 | unchanged |
@@ -57,11 +57,6 @@ const REFUSED_GET: ReadonlyArray<readonly [string, Record<string, string>, strin
5757
['count= blank', { $top: '2', count: '' }, 'count', 'must be true or false'],
5858
];
5959

60-
/** name · the JSON body `POST /data/:object/query` receives · the key the refusal names. */
61-
const REFUSED_POST: ReadonlyArray<readonly [string, Record<string, unknown>, string]> = [
62-
['fields: []', { fields: [] }, 'fields'],
63-
];
64-
6560
/**
6661
* [#26909] The body's published schema (`FindDataRequestSchema`) now declares
6762
* the projection the normalizer enforces, so these are refused where every
@@ -74,6 +69,10 @@ const REFUSED_POST_AT_SCHEMA: ReadonlyArray<readonly [string, Record<string, unk
7469
['$select: ","', { $select: ',' }, 'query.$select'],
7570
['select: []', { select: [] }, 'query.select'],
7671
['select: ["label", ""] (the blank member)', { select: ['label', ''] }, 'query.select.1'],
72+
// [#27166] The canonical `fields` takes the same arm on `QuerySchema` itself,
73+
// so it answers what its `$select` alias answers.
74+
['fields: []', { fields: [] }, 'query.fields'],
75+
['fields: ["label", " "] (the blank member)', { fields: ['label', ' '] }, 'query.fields.1'],
7776
];
7877

7978
function createMockServer() {
@@ -162,18 +161,7 @@ describe('[#26644] an empty projection and an unrecognised count flag on the Dat
162161
expect(reads.n - before, 'no read of the object — every refusal precedes the driver').toBe(0);
163162
});
164163

165-
it('POST query: 400 VALIDATION_ERROR naming the body key — no read', async () => {
166-
const before = reads.n;
167-
for (const [name, body, param] of REFUSED_POST) {
168-
const res = await query(body);
169-
expect(res.status, `${name}: ${JSON.stringify(res.body)}`).toBe(400);
170-
expect(res.body.code, name).toBe('VALIDATION_ERROR');
171-
expect(res.body.error, name).toContain(`Query parameter '${param}' names no field`);
172-
}
173-
expect(reads.n - before, 'no read of the object — every refusal precedes the driver').toBe(0);
174-
});
175-
176-
it('POST query: `select` / `$select` naming no field is the schema door\'s 400 VALIDATION_FAILED — no read', async () => {
164+
it('POST query: `fields` / `select` / `$select` naming no field is the schema door\'s 400 VALIDATION_FAILED — no read', async () => {
177165
const before = reads.n;
178166
for (const [name, body, field] of REFUSED_POST_AT_SCHEMA) {
179167
const res = await query(body);

‎packages/services/service-automation/src/builtin/get-record-id-projection.integration.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@
1515
* - a projection that already names `id` is handed over as written (no
1616
* second `id`);
1717
* - no projection stays a whole-row read (no projection is invented);
18-
* - an empty projection is handed over as written, and the engine refuses it
19-
* (#27008): the node fails with that refusal carried, never a whole-row read;
18+
* - an empty projection is refused by the node's own config contract
19+
* (`GetRecordConfigSchema.fields`, #27166), so the engine is never asked:
20+
* the node fails before any read, never a whole-row read;
2021
* - the `find` branch (`limit > 1`) declares no top-level `id` and is not
2122
* touched.
2223
*
@@ -161,18 +162,17 @@ describe('get_record answers the row id as output.id whatever its fields project
161162
expect(result.output).toEqual({ record: whole, id: rowId, object: OBJECT.name });
162163
});
163164

164-
it("empty fields: handed to the engine as written, and the node fails with the engine's refusal carried (#27008)", async () => {
165+
it("empty fields: refused by the node's config contract before any read (#27166)", async () => {
165166
handed.length = 0;
166167
const result = await getRecord.execute(
167168
{ id: 'read', type: 'get_record', config: { objectName: OBJECT.name, filter: { title: 'alpha' }, fields: [] } },
168169
new Map(),
169170
{ runAs: 'system', flowName: 'pin_get_record_id' },
170171
);
171-
expect(handed, 'the node hands the empty projection over unchanged, once').toEqual([{ method: 'findOne', fields: [] }]);
172+
expect(handed, 'the engine is never asked').toEqual([]);
172173
expect(result.success, 'an empty projection is refused, never read as the whole row').toBe(false);
173174
expect(result.output).toBeUndefined();
174-
expect(result.innerRefusal).toMatchObject({ code: 'VALIDATION_ERROR' });
175-
expect(result.error).toMatch(/^get_record\(pin_get_record_id\) failed: ObjectQL\.findOne\('pin_get_record_id'\) names no field in 'fields'/);
175+
expect(result.error).toContain("get_record 'read': config does not satisfy the get_record contract — fields: Name at least one field.");
176176
});
177177

178178
it('a downstream update_record filtering on read.id updates the row the narrowed get_record read', async () => {

‎packages/spec/src/automation/builtin-node-config.zod.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ import { z } from 'zod';
9999
import { EvaluatedExpressionSchema } from '../shared/expression.zod';
100100
import { lazySchema } from '../shared/lazy-schema';
101101
import { strictObject } from '../shared/strict-object';
102+
import { transportProjectionArray } from '../data/projection-names-a-field';
102103
import { refuseCatchallProtoKey, refuseRecordProtoKey } from '../shared/record-proto-key-guard';
103104
import { flowFilterOperands, isExpressionEnvelopeShaped } from './flow-node-expression-paths';
104105
// [#19939] The retirement of the `{…}` template dialect from value slots — the
@@ -622,9 +623,14 @@ export const GetRecordConfigSchema = lazySchema(() => strictObject({
622623
objectName: z.string().describe('Object to query'),
623624
/** Field/value pairs to match; each operand an envelope, a query placeholder or a literal ({@link flowFilterSlotSchema}). */
624625
filter: flowFilterSlotSchema(`Field/value pairs to match: ${FILTER_OPERAND_DESCRIPTION}`).optional(),
625-
/** Field projection — only these fields are read (default: all). */
626-
fields: z.array(z.string()).optional()
627-
.describe('Field projection — only these fields are read (default: all)'),
626+
/**
627+
* Field projection — only these fields are read; omit it to read all. At
628+
* least one name, none blank: the executor hands it to `data.find` /
629+
* `findOne` as written, and the engine refuses an empty projection there
630+
* (#27166), so the list is refused at save instead of at run.
631+
*/
632+
fields: transportProjectionArray(z.string()).optional()
633+
.describe('Field projection — only these fields are read; omit it to read all. An empty list or a blank name is refused'),
628634
/**
629635
* Max records — a positive integer; >1 returns a `records` list, otherwise a
630636
* single `record`. The executor hands it to `data.find` as the query's LIMIT

‎packages/spec/src/data/data-engine.zod.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { FilterConditionSchema, FilterArraySchema, parseFilterAST } from './filt
55
import type { FilterArray, FilterCondition } from './filter.zod';
66
import { SortNodeSchema, QuerySchema, FullTextSearchSchema, FieldNodeSchema, AggregationNodeSchema, GroupByNodeSchema, QUERY_CURSOR_REMOVED, QUERY_DISTINCT_REMOVED } from './query.zod';
77
import type { QueryAST, QueryInput } from './query.zod';
8+
import { PROJECTION_NAMES_NO_FIELD, transportProjectionArray } from './projection-names-a-field';
89
import { retiredKey } from '../shared/retired-key';
910
import { ExecutionContextSchema } from '../kernel/execution-context.zod';
1011

@@ -102,11 +103,13 @@ export const BaseEngineOptionsSchema = lazySchema(() => z.object({
102103
* too. It is declared ahead of both because
103104
* `RpcQueryOptionsSchema` extends `EngineQueryOptionsSchema` at module load,
104105
* which runs the lazy factory before any later `const` exists.
106+
*
107+
* [#27166] The array arm and its sentence live in
108+
* `./projection-names-a-field.ts`, because `QuerySchema.fields` (and so every
109+
* nested `expand` value) and the flow `get_record` node's `fields` take it too,
110+
* and `./query.zod.ts` cannot import this module.
105111
*/
106-
const PROJECTION_NAMES_NO_FIELD = 'Name at least one field';
107112
const TransportProjectionStringSchema = z.string().regex(/[^\s,]/, PROJECTION_NAMES_NO_FIELD);
108-
const transportProjectionArray = <T extends z.ZodString>(member: T) =>
109-
z.array(member.regex(/\S/, 'A field name cannot be blank')).min(1, PROJECTION_NAMES_NO_FIELD);
110113
const PROJECTION_ACCEPT_SET = 'at least one field name; a value naming no field (blank, only commas and spaces, '
111114
+ 'an empty list, or a list with a blank name) is refused';
112115

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#27166] The QueryAST's own `fields` (and so every nested `expand` value)
5+
* and the flow `get_record` node's `fields` take the projection's array arm
6+
* the other published declarations take: at least one name, none blank. The
7+
* in-process engine refuses an empty projection at its `find` / `findOne`
8+
* entry, top level and at any `expand` depth (#27008), and the `get_record`
9+
* executor hands its authored `fields` to that entry as written, so a
10+
* declaration admitting `[]` admitted a shape the runtime refuses.
11+
*
12+
* Every refusal is pinned against the sentence `EngineQueryOptionsSchema.fields`
13+
* gives for the same value, so the declarations cannot drift apart.
14+
*/
15+
16+
import { describe, it, expect } from 'vitest';
17+
import { QuerySchema } from './query.zod';
18+
import { EngineQueryOptionsSchema, QueryTransportParamsSchema, QueryWithTransportSchema } from './data-engine.zod';
19+
import { GetRecordConfigSchema } from '../automation/builtin-node-config.zod';
20+
import { flowNodeConfigRefusals } from '../automation/flow-node-config-refusals';
21+
import { defineStack } from '../stack.zod';
22+
23+
type Path = ReadonlyArray<string | number>;
24+
25+
const REFUSED: ReadonlyArray<readonly [string, string[], Path]> = [
26+
['an empty list', [], []],
27+
['a list with a blank name', ['name', ''], [1]],
28+
['a list with a whitespace name', ['name', ' '], [1]],
29+
];
30+
const KEPT: ReadonlyArray<readonly [string, string[]]> = [
31+
['one name', ['name']],
32+
['two names', ['name', 'email']],
33+
];
34+
35+
/** The first issue a schema raises for `input`, or a failed expectation when it parses. */
36+
function firstIssue(schema: { safeParse(v: unknown): { success: boolean; error?: { issues: Array<{ message: string; path: PropertyKey[] }> } } }, input: unknown) {
37+
const parsed = schema.safeParse(input);
38+
expect(parsed.success, `refuses ${JSON.stringify(input)}`).toBe(false);
39+
return parsed.error!.issues[0]!;
40+
}
41+
42+
/** The sentence the engine-side declaration gives for the same projection value. */
43+
const engineMessage = (value: string[]) => firstIssue(EngineQueryOptionsSchema, { fields: value }).message;
44+
45+
describe('QuerySchema.fields admits exactly what EngineQueryOptionsSchema.fields admits', () => {
46+
it.each(REFUSED)('refuses %s at the top level, in the engine declaration\'s words', (_name, value, tail) => {
47+
const issue = firstIssue(QuerySchema, { object: 'task', fields: value });
48+
expect(issue.path).toEqual(['fields', ...tail]);
49+
expect(issue.message).toBe(engineMessage(value));
50+
});
51+
52+
it.each(REFUSED)('refuses %s on an expand entry, naming the entry', (_name, value, tail) => {
53+
const issue = firstIssue(QuerySchema, { object: 'task', fields: ['title', 'project_id'], expand: { project_id: { object: 'project', fields: value } } });
54+
expect(issue.path).toEqual(['expand', 'project_id', 'fields', ...tail]);
55+
expect(issue.message).toBe(engineMessage(value));
56+
});
57+
58+
it.each(REFUSED)('refuses %s on a second-level expand entry', (_name, value, tail) => {
59+
const query = {
60+
object: 'task',
61+
expand: { project_id: { object: 'project', expand: { org_id: { object: 'org', fields: value } } } },
62+
};
63+
const issue = firstIssue(QuerySchema, query);
64+
expect(issue.path).toEqual(['expand', 'project_id', 'expand', 'org_id', 'fields', ...tail]);
65+
expect(issue.message).toBe(engineMessage(value));
66+
});
67+
68+
it.each(REFUSED)('EngineQueryOptionsSchema.expand refuses %s on an entry, as the engine entry does', (_name, value, tail) => {
69+
const issue = firstIssue(EngineQueryOptionsSchema, { expand: { project_id: { object: 'project', fields: value } } });
70+
expect(issue.path).toEqual(['expand', 'project_id', 'fields', ...tail]);
71+
expect(issue.message).toBe(engineMessage(value));
72+
});
73+
74+
it.each(REFUSED)('the transport-aware query slot refuses canonical `fields` %s as it refuses `$select`', (_name, value, tail) => {
75+
const issue = firstIssue(QueryWithTransportSchema, { object: 'task', fields: value });
76+
expect(issue.path).toEqual(['fields', ...tail]);
77+
expect(issue.message).toBe(firstIssue(QueryTransportParamsSchema, { $select: value }).message);
78+
});
79+
80+
it.each(KEPT)('keeps %s unchanged, at the top level and on an expand entry', (_name, value) => {
81+
const query = { object: 'task', fields: value, expand: { project_id: { object: 'project', fields: value } } };
82+
const parsed = QuerySchema.parse(query);
83+
expect(parsed.fields).toEqual(value);
84+
expect(parsed.expand?.project_id?.fields).toEqual(value);
85+
});
86+
87+
it('keeps an absent projection: absent still reads every column', () => {
88+
const parsed = QuerySchema.parse({ object: 'task', expand: { project_id: { object: 'project' } } });
89+
expect(parsed.fields).toBeUndefined();
90+
expect(parsed.expand?.project_id?.fields).toBeUndefined();
91+
});
92+
});
93+
94+
describe('GetRecordConfigSchema.fields: an empty projection is refused at save, not at run', () => {
95+
const config = (fields: unknown) => ({ objectName: 'gr_task', filter: { title: 'alpha' }, fields });
96+
97+
it.each(REFUSED)('refuses %s, in the engine declaration\'s words', (_name, value, tail) => {
98+
const issue = firstIssue(GetRecordConfigSchema, config(value));
99+
expect(issue.path).toEqual(['fields', ...tail]);
100+
expect(issue.message).toBe(engineMessage(value));
101+
});
102+
103+
it.each(REFUSED)('the save door\'s node judge refuses %s at `fields`, naming the blank member', (_name, value, tail) => {
104+
const at = `fields${tail.map((i) => `[${i}]`).join('')}`;
105+
expect(flowNodeConfigRefusals('get_record', config(value)).map(({ code, params, path }) => ({ code, params, path }))).toEqual([
106+
{ code: 'node-config-refused-by-contract', params: { nodeType: 'get_record', key: at }, path: at },
107+
]);
108+
});
109+
110+
it('defineStack refuses a get_record node with `fields: []` at its config path', () => {
111+
const stack = {
112+
manifest: { id: 'com.example.projection', name: 'projection', version: '1.0.0', type: 'app', namespace: 'gr' },
113+
objects: [{ name: 'gr_task', label: 'Task', fields: { title: { type: 'text', label: 'Title' } } }],
114+
flows: [{
115+
name: 'gr_read',
116+
label: 'Read',
117+
type: 'autolaunched',
118+
nodes: [
119+
{ id: 'start', type: 'start', label: 'Start' },
120+
{ id: 'read', type: 'get_record', label: 'Read', config: config([]) },
121+
{ id: 'end', type: 'end', label: 'End' },
122+
],
123+
edges: [
124+
{ id: 'e1', source: 'start', target: 'read' },
125+
{ id: 'e2', source: 'read', target: 'end' },
126+
],
127+
}],
128+
};
129+
let refusal: { code?: unknown; status?: unknown; issues?: Array<{ path: unknown[] }> } | undefined;
130+
try {
131+
defineStack(stack as never);
132+
} catch (e) {
133+
refusal = e as typeof refusal;
134+
}
135+
expect(refusal, 'defineStack must refuse the flow').toBeDefined();
136+
expect({ code: refusal!.code, status: refusal!.status }).toEqual({ code: 'STACK_SCHEMA_INVALID', status: 422 });
137+
expect(refusal!.issues!.map((i) => i.path.join('.'))).toEqual(['flows.0.nodes.1.config.fields']);
138+
});
139+
140+
it.each(KEPT)('keeps %s unchanged, and the node judge finds nothing', (_name, value) => {
141+
expect(GetRecordConfigSchema.parse(config(value)).fields).toEqual(value);
142+
expect(flowNodeConfigRefusals('get_record', config(value))).toEqual([]);
143+
});
144+
145+
it('keeps an absent projection: the node reads every field', () => {
146+
expect(GetRecordConfigSchema.parse({ objectName: 'gr_task' }).fields).toBeUndefined();
147+
expect(flowNodeConfigRefusals('get_record', { objectName: 'gr_task' })).toEqual([]);
148+
});
149+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { z } from 'zod';
4+
5+
/**
6+
* The array arm of the projection rule every published declaration of a
7+
* read's projection shares: a list names at least one field, and no member is
8+
* blank. Absent means "every column", so an empty projection read as absent is
9+
* a widening; it is refused instead, in one sentence.
10+
*
11+
* Declared in its own module, outside the `data` barrel, because its readers
12+
* sit on both sides of an import edge: `./query.zod.ts` (the QueryAST's own
13+
* `fields`, and so every nested `expand` value), `./data-engine.zod.ts` (the
14+
* transport and engine-side spellings, which import `./query.zod.ts`) and
15+
* `../automation/builtin-node-config.zod.ts` (the flow `get_record` node's
16+
* `fields`). The accept set and its history are documented beside the
17+
* transport arms in `./data-engine.zod.ts`.
18+
*
19+
* [#27166] The QueryAST and `get_record` declarations joined once the
20+
* in-process engine refused an empty projection at its `find` / `findOne`
21+
* entry, top level and at any `expand` depth.
22+
*/
23+
export const PROJECTION_NAMES_NO_FIELD = 'Name at least one field';
24+
25+
export const transportProjectionArray = <T extends z.ZodString>(member: T) =>
26+
z.array(member.regex(/\S/, 'A field name cannot be blank')).min(1, PROJECTION_NAMES_NO_FIELD);

0 commit comments

Comments
 (0)