Skip to content

Commit 25fea77

Browse files
fix(spec): an array in an analytics filter slot is refused once, with the object form shown (#30599)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuTTv3aGs6wx6iRvoDi9ySQ1)_ domain:spec#2 · os-sales · session_01L6bhgUpxbGjLnXrKiVLZzp Fixes #30124 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:仪表盘组件的 `filter`(以及数据集、度量的 `filter`、报表的 `runtimeFilter`)若写成列表视图那种规则数组,`os validate` 原来报两句互相矛盾、不给修法的话;现在只报一句,说明这里要的是按字段写的条件对象,并给出写法 `{ status: { $in: ['new', 'in_progress'] } }`。 - 为什么改:开发者和 AI 在同一个项目里同时写视图和仪表盘,最自然的就是把视图的过滤写法照抄过来,原报错让人卡住。 - 风险与回滚:只改报错文字并去掉重复的那一条;原来接受的照样接受,原来拒绝的照样拒绝,发布的 JSON Schema 不变。回滚即 revert 本 PR。 - 先看:`packages/spec/src/ui/analytics-carrier-filter.ts`(新增的 `prescribeObjectFormForArrayFilter` 与文案常量)→ `packages/spec/src/data/filter-save-door-face-parity.test.ts`(§8)。 - 两分钟验证:`pnpm --filter @objectstack/spec exec vitest run src/data/filter-save-door-face-parity.test.ts`,预期 185 条全过;把 `.check(prescribeObjectFormForArrayFilter())` 删掉后 §8 中 7 条转红。 - 需要你做的:无,席位落地。 ## What changes `FilterConditionSchema` is a record intersected with the `$and` / `$or` / `$not` object, and an array fails both arms: two `invalid_type` issues at the slot, `expected: 'record'` and `expected: 'object'`. Through the ObjectStack error map they print `Expected record but received object.` and `Expected object but received object.` (an array's `typeof` is `object`), which contradict each other and name no fix. The text comes from the spec schema plus its error map, not from the CLI's formatter, so the fix lives in the spec. - **`packages/spec/src/ui/analytics-carrier-filter.ts`.** `analyticsCarrierFilter()` gains one check, `prescribeObjectFormForArrayFilter()`, a `$ZodCheck` with `when: () => true` (the mechanism the view filter element's claimed-branch check in `view.zod.ts` already uses). It runs only when the value is an array and the slot already failed. It keeps the record arm's issue (code `invalid_type`, its `expected`, its path) with a new message, and drops the object arm's twin. The message, exported as `ANALYTICS_FILTER_ARRAY_MESSAGE` from this module (outside the `ui` barrel, so not published API): > This filter is an array, and an analytics filter — a dashboard widget's `filter`, a dataset's or a measure's `filter`, a report's `runtimeFilter` — is the condition OBJECT a query's `where` takes, keyed by field: `{ status: { $in: ['new', 'in_progress'] } }`, not the rule array `[{ field: 'status', operator: 'in', value: ['new', 'in_progress'] }]` a list view's `filter` takes. Write one key per field, holding an operator map (`{ amount: { $gte: 100 } }`) or a bare value for equality (`{ status: 'open' }`); sibling keys AND together, and `$or: [{ … }, { … }]` ORs conditions. - All five carriers of `analyticsCarrierFilter()` get it at once: `DashboardWidgetSchema.filter`, `DatasetSchema.filter`, `DatasetMeasureSchema.filter`, `ReportSchema.runtimeFilter` and `JoinedReportBlockSchema.runtimeFilter`. Every other `FilterConditionSchema` carrier keeps its current text. - The accept set is unchanged: the check never adds an issue to a value that parsed, and never removes the last issue from one that failed. The published JSON Schema is unchanged (`check:generated` reports all 14 artifacts current; `dropped-refinements.baseline.json` already lists each carrier's `filter` site). ## Tests New top-level `describe` §8 in `packages/spec/src/data/filter-save-door-face-parity.test.ts`, the existing harness for the analytics carriers: - For each of the five carriers, the card's rule array is refused with exactly ONE issue at the slot: `code: 'invalid_type'`, the path (`widgets.0.filter`, `filter`, `measures.0.filter`, `runtimeFilter`, `blocks.0.runtimeFilter`), and the message, including the shown object form. - For each carrier, the object form `{ status: { $in: ['new', 'in_progress'] } }` is accepted. - `formatZodError` prints the widget refusal as one issue with the prescription and no `but received object` line. - The message is the issue's own, so it holds with no error map too. - An accept-set battery of 17 values (`undefined`, `null`, scalars, `[]`, `[{}]`, the rule array, an AST tuple array, plain, `$or` / `$and` / `$not` and malformed conditions): the carrier's verdict equals the bare `FilterConditionSchema.optional()` verdict for every one, and every non-array refusal keeps byte-identical issues. ## Verification All readings on head `f5eede77`, repository `objectstack-ai/objectstack`, base `origin/main` `2ffdb649`. <details><summary>Repro through os validate</summary> `examples/app-crm`, the first widget of `pipeline.dashboard.ts` set to the card's `filter: [{ field: 'status', operator: 'in', value: ['new', 'in_progress'] }]` (applied and restored with `scripts/ablation-replace.mjs`; restored blob equals HEAD), `node ../../packages/cli/bin/run.js validate` against the rebuilt CLI closure: ```text ✗ defineStack validation failed (1 issue): ✗ dashboards.0.widgets.0.filter: This filter is an array, and an analytics filter — a dashboard widget's `filter`, a dataset's or a measure's `filter`, a report's `runtimeFilter` — is the condition OBJECT a query's `where` takes, keyed by field: `{ status: { $in: ['new', 'in_progress'] } }`, not the rule array `[{ field: 'status', operator: 'in', value: ['new', 'in_progress'] }]` a list view's `filter` takes. Write one key per field, holding an operator map (`{ amount: { $gte: 100 } }`) or a bare value for equality (`{ status: 'open' }`); sibling keys AND together, and `$or: [{ … }, { … }]` ORs conditions. validate exit 1 ``` Before (`origin/main`, and the ablation leg below), the same slot printed: ```text ✗ widgets.0.filter: Expected record but received object. ✗ widgets.0.filter: Expected object but received object. ``` </details> <details><summary>Tests and ablation</summary> - `pnpm --filter @objectstack/spec test && pnpm --filter @objectstack/spec typecheck` under `os-verify-lock.sh`: `Test Files 815 passed (815)`, `Tests 25672 passed | 1 todo (25673)`, `VERDICT command-exit 0`. - `filter-save-door-face-parity.test.ts`: `Tests 185 passed (185)`. - Ablation (`scripts/ablation-replace.mjs`, the spec tests import `src`, so no dist leg): `.check(prescribeObjectFormForArrayFilter());` replaced by `;`, anchor 1 → 0, blob `a33a04aff58c` → `2122b69f7d5c`: `Tests 7 failed | 178 passed (185)`, the five per-carrier pins, the formatter pin and the no-error-map pin; the accept-set battery stays green, as it should. Restored: blob equals HEAD, `git diff HEAD` empty. </details> <details><summary>Gates</summary> - `pnpm --filter @objectstack/spec build` (VERDICT command-exit 0), then `pnpm --filter @objectstack/spec check:generated`: `All 14 generated artifacts are up to date` (exit 0; the first try exited 1 because `check:test-typecheck`'s tsc ran out of heap at 4096 MB, rerun with 8192 MB). - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `f5eede77`: 78 families, every one run with its exit code captured. Two first runs exited 3 on prerequisites, not verdicts: `check-plugin-teardown-shape --self-test` (pinned fixture commit missing in the shallow clone; fetched, rerun exit 0) and `check:dual-build-cjs-loads` (nine packages without `dist/`; built, rerun exit 0). Every other family exit 0. - `--ran` reconciliation: `78 derived, 78 run, 0 NOT-MEASURED, 0 UNRUN` (a derived zero: all 78 recorded an exit code, none is 3). - `eslint --no-inline-config` on both changed source files: exit 0. `check:nul-bytes`: exit 0. - CI families: this PR's check-runs. </details> ## Acceptance notes - Out of scope by the card: whether a view filter and an analytics filter should take one shape. - The error map's `invalid_type` branch prints `typeof` input, so any OTHER slot that refuses an array still reads `received object`. Not changed here; this PR only fixes the analytics filter slots. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgUpxbGjLnXrKiVLZzp --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1c5cee6 commit 25fea77

3 files changed

Lines changed: 173 additions & 4 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/spec': patch
3+
---
4+
5+
fix(spec): an array in an analytics filter slot is refused once, and the refusal shows the object form
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A dashboard widget `filter`, a dataset or measure `filter`, or a report's `runtimeFilter` written as a list view's rule array (`[{ field: 'status', operator: 'in', value: ['new', 'in_progress'] }]`) used to fail `os validate` with two lines that contradicted each other and named no fix: `Expected record but received object.` and `Expected object but received object.`. It now fails with one `invalid_type` issue at the same path, saying that these slots take the condition object a query's `where` takes and showing it: `{ status: { $in: ['new', 'in_progress'] } }`.
11+
12+
Only the text changes, and the duplicate line goes. Every filter accepted before is accepted, every filter refused before is refused, and the published JSON Schema is unchanged.

‎packages/spec/src/data/filter-save-door-face-parity.test.ts‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ import { describe, expect, it } from 'vitest';
5151
import { z } from 'zod';
5252

5353
import { StandardErrorCode } from '../api/errors.zod';
54-
import { analyticsCarrierFilter } from '../ui/analytics-carrier-filter';
54+
import { formatZodError, objectStackErrorMap } from '../shared/error-map.zod';
55+
import { ANALYTICS_FILTER_ARRAY_MESSAGE, analyticsCarrierFilter } from '../ui/analytics-carrier-filter';
5556
import { DashboardSchema } from '../ui/dashboard.zod';
5657
import { DatasetMeasureSchema, DatasetSchema } from '../ui/dataset.zod';
5758
import { ReportSchema } from '../ui/report.zod';
@@ -818,3 +819,99 @@ describe('§7 — the analytics carrier filter publishes exactly the bare condit
818819
expect(report.properties?.runtimeFilter?.description).toBe('Render-time scope filter');
819820
});
820821
});
822+
823+
// ---------------------------------------------------------------------------
824+
// §8 An array in the slot: one refusal that names the object form (#30124)
825+
// ---------------------------------------------------------------------------
826+
827+
describe('§8 — an array where an analytics filter belongs is refused once, with the object form shown', () => {
828+
// The card's repro: a list view's rule array copied into a widget `filter`.
829+
// Measured on `origin/main` `2ffdb649` before the change: two issues at the
830+
// slot, `invalid_type` / `expected: 'record'` and `expected: 'object'`, read
831+
// through the ObjectStack error map as `Expected record but received
832+
// object.` and `Expected object but received object.`.
833+
const VIEW_RULES = [{ field: 'status', operator: 'in', value: ['new', 'in_progress'] }];
834+
const OBJECT_FORM = { status: { $in: ['new', 'in_progress'] } };
835+
836+
const dashboard = (filter: unknown) => ({
837+
name: 'support',
838+
label: 'Support',
839+
widgets: [{ id: 'open_tickets', type: 'metric', dataset: 'tickets', values: ['ticket_count'], filter }],
840+
});
841+
const dataset = (extra: Record<string, unknown>) => ({
842+
name: 'tickets_ds',
843+
label: 'Tickets',
844+
object: 'ticket',
845+
dimensions: [{ name: 'status', field: 'status', type: 'string' }],
846+
measures: [{ name: 'ticket_count', aggregate: 'count' }],
847+
...extra,
848+
});
849+
const report = (runtimeFilter: unknown) => ({
850+
name: 'tickets', label: 'Tickets', type: 'summary',
851+
dataset: 'tickets', rows: ['status'], values: ['ticket_count'], runtimeFilter,
852+
});
853+
const joinedReport = (runtimeFilter: unknown) => ({
854+
name: 'tickets_joined', label: 'Tickets', type: 'joined',
855+
blocks: [{ name: 'open', label: 'Open', type: 'summary', dataset: 'tickets', rows: ['status'], values: ['ticket_count'], runtimeFilter }],
856+
});
857+
858+
type Parse = (filter: unknown) => { success: boolean; error?: z.ZodError };
859+
const CARRIERS: ReadonlyArray<readonly [label: string, parse: Parse, slot: string]> = [
860+
['dashboard widget filter', (f) => DashboardSchema.safeParse(dashboard(f), { error: objectStackErrorMap }), 'widgets.0.filter'],
861+
['dataset filter', (f) => DatasetSchema.safeParse(dataset({ filter: f }), { error: objectStackErrorMap }), 'filter'],
862+
['measure filter', (f) => DatasetSchema.safeParse(dataset({ measures: [{ name: 'ticket_count', aggregate: 'count', filter: f }] }), { error: objectStackErrorMap }), 'measures.0.filter'],
863+
['report runtimeFilter', (f) => ReportSchema.safeParse(report(f), { error: objectStackErrorMap }), 'runtimeFilter'],
864+
['joined block runtimeFilter', (f) => ReportSchema.safeParse(joinedReport(f), { error: objectStackErrorMap }), 'blocks.0.runtimeFilter'],
865+
];
866+
867+
it.each(CARRIERS)('%s — the view rule array is ONE invalid_type at the slot, carrying the object form', (_label, parse, slot) => {
868+
const parsed = parse(VIEW_RULES);
869+
expect(parsed.success).toBe(false);
870+
const atSlot = parsed.error!.issues.filter((issue) => issue.path.join('.') === slot);
871+
expect(atSlot).toHaveLength(1);
872+
expect(atSlot[0]!.code).toBe('invalid_type');
873+
expect(atSlot[0]!.message).toBe(ANALYTICS_FILTER_ARRAY_MESSAGE);
874+
expect(atSlot[0]!.message).toContain("`{ status: { $in: ['new', 'in_progress'] } }`");
875+
// Nothing else is said about the slot or below it.
876+
expect(parsed.error!.issues.filter((issue) => issue.path.join('.').startsWith(slot))).toHaveLength(1);
877+
});
878+
879+
it.each(CARRIERS)('%s — the object form is accepted', (_label, parse) => {
880+
expect(parse(OBJECT_FORM).success).toBe(true);
881+
});
882+
883+
it('the widget refusal prints as one line naming the fix, with no contradictory twin', () => {
884+
const parsed = DashboardSchema.safeParse(dashboard(VIEW_RULES), { error: objectStackErrorMap });
885+
expect(parsed.success).toBe(false);
886+
const printed = formatZodError(parsed.error!, 'defineStack validation failed');
887+
expect(printed).toContain('(1 issue)');
888+
expect(printed).toContain(`✗ widgets.0.filter: ${ANALYTICS_FILTER_ARRAY_MESSAGE}`);
889+
expect(printed).not.toContain('but received object');
890+
});
891+
892+
it('the message is the same with no error map: it is the issue\'s own, not the map\'s', () => {
893+
const parsed = analyticsCarrierFilter().safeParse([]);
894+
expect(parsed.success).toBe(false);
895+
expect(parsed.error!.issues).toHaveLength(1);
896+
expect(parsed.error!.issues[0]!.message).toBe(ANALYTICS_FILTER_ARRAY_MESSAGE);
897+
expect(parsed.error!.issues[0]!.path).toEqual([]);
898+
});
899+
900+
// The accept set is unchanged: on values with no nested relation (where the
901+
// walk adds nothing) the carrier answers exactly as the bare optional
902+
// condition does, and every non-array refusal keeps its own issues.
903+
const BATTERY: readonly unknown[] = [
904+
undefined, null, 0, 'status', true, [], [{}], VIEW_RULES, [['status', '=', 'open']],
905+
{}, { status: 'open' }, OBJECT_FORM, { $or: [{ status: 'open' }, { priority: 'high' }] },
906+
{ $and: [] }, { $not: { status: 'closed' } }, { $or: 'x' }, { status: { $in: 'new' } },
907+
];
908+
909+
it.each(BATTERY.map((value) => [show(value), value] as const))('%s — same verdict as the bare condition', (_label, value) => {
910+
const bare = FilterConditionSchema.optional().safeParse(value);
911+
const carrier = analyticsCarrierFilter().safeParse(value);
912+
expect(carrier.success).toBe(bare.success);
913+
if (!bare.success && !Array.isArray(value)) {
914+
expect(carrier.error!.issues).toEqual(bare.error.issues);
915+
}
916+
});
917+
});

‎packages/spec/src/ui/analytics-carrier-filter.ts‎

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
* dataset carriers' published JSON Schema did not move with it.
1818
*/
1919

20-
import type { z } from 'zod';
20+
import { z } from 'zod';
2121
import { FieldOperatorsSchema, FilterConditionSchema } from '../data/filter.zod';
2222
import { reportQueryFaceRefusals } from '../data/filter-save-door-refusals';
2323

@@ -205,6 +205,66 @@ function refuseNestedRelationComparands(
205205
* check as `undefined`, which the walk passes.
206206
*/
207207
export function analyticsCarrierFilter() {
208-
return FilterConditionSchema.optional().superRefine((filter, ctx) =>
209-
refuseNestedRelationComparands(filter, ctx));
208+
return FilterConditionSchema.optional()
209+
.superRefine((filter, ctx) => refuseNestedRelationComparands(filter, ctx))
210+
.check(prescribeObjectFormForArrayFilter());
211+
}
212+
213+
// ── [#30124] An array where the condition object belongs ────────────────────
214+
215+
/**
216+
* The words an ARRAY in an analytics carrier's filter slot is refused with:
217+
* which form the slot takes, the form shown, and the neighbouring spelling it
218+
* was most likely copied from — a list view's `filter` is the
219+
* `[{ field, operator, value }]` rule array, and an author (or an AI) writing
220+
* both in one project carries that shape across. The example filter is the
221+
* one that rule array most often spells.
222+
*/
223+
export const ANALYTICS_FILTER_ARRAY_MESSAGE =
224+
'This filter is an array, and an analytics filter — a dashboard widget\'s `filter`, a dataset\'s '
225+
+ 'or a measure\'s `filter`, a report\'s `runtimeFilter` — is the condition OBJECT a query\'s '
226+
+ '`where` takes, keyed by field: `{ status: { $in: [\'new\', \'in_progress\'] } }`, not the '
227+
+ 'rule array `[{ field: \'status\', operator: \'in\', value: [\'new\', \'in_progress\'] }]` '
228+
+ 'a list view\'s `filter` takes. Write one key per field, holding an operator map '
229+
+ '(`{ amount: { $gte: 100 } }`) or a bare value for equality (`{ status: \'open\' }`); '
230+
+ 'sibling keys AND together, and `$or: [{ … }, { … }]` ORs conditions.';
231+
232+
/**
233+
* [#30124] Replace the two type refusals an ARRAY earns in an analytics
234+
* carrier's filter slot with ONE that names the fix.
235+
*
236+
* `FilterConditionSchema` is a record intersected with the `$and` / `$or` /
237+
* `$not` object, and an array fails BOTH arms — two `invalid_type` issues at
238+
* the slot itself, `expected: 'record'` and `expected: 'object'`. Through the
239+
* ObjectStack error map they read `Expected record but received object.` and
240+
* `Expected object but received object.`: two lines that contradict each other
241+
* (an array's `typeof` is `object`) and name no fix.
242+
*
243+
* The check runs only when the slot already failed on an array, and only
244+
* rewrites: it keeps the record arm's issue — its code (`invalid_type`), its
245+
* `expected` and its path — with {@link ANALYTICS_FILTER_ARRAY_MESSAGE} as its
246+
* message, and drops the object arm's twin. Every value refused before is
247+
* refused now and every value accepted is accepted; nothing but the words and
248+
* the duplicate changes. `when: () => true` is what lets a check see a value
249+
* the inner schema refused (the same mechanism as the view filter element's
250+
* claimed-branch check in `./view.zod.ts`).
251+
*
252+
* The check is a dropped refinement like the walk beside it: it has no JSON
253+
* Schema form, and the published body of every carrier is unchanged.
254+
*/
255+
function prescribeObjectFormForArrayFilter(): z.core.$ZodCheck<unknown> {
256+
const check = new z.core.$ZodCheck({ check: 'custom', when: () => true }) as z.core.$ZodCheck<unknown>;
257+
check._zod.check = (payload) => {
258+
if (!Array.isArray(payload.value) || payload.issues.length === 0) return;
259+
const atSlot = (expected: string) => (issue: z.core.$ZodRawIssue) =>
260+
issue.code === 'invalid_type'
261+
&& (issue as { expected?: unknown }).expected === expected
262+
&& (issue.path?.length ?? 0) === 0;
263+
const recordIndex = payload.issues.findIndex(atSlot('record'));
264+
if (recordIndex === -1) return;
265+
payload.issues[recordIndex] = { ...payload.issues[recordIndex]!, message: ANALYTICS_FILTER_ARRAY_MESSAGE };
266+
const objectIndex = payload.issues.findIndex(atSlot('object'));
267+
if (objectIndex !== -1) payload.issues.splice(objectIndex, 1);
268+
};
269+
return check;
210270
}

0 commit comments

Comments
 (0)