Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit f391ede

Browse files
os-justinclaude
andauthored
fix(core): refuse a bare array comparand in convertFiltersToAST (#8551)
* fix(core): refuse a bare array comparand in convertFiltersToAST `{ tags: ['a', 'b'] }` used to reach the simple-equality arm and lower to `['tags', '=', ['a', 'b']]` — an array in a scalar-equality slot that the spec's doors pass through unjudged, driver-sql refuses with 400 INVALID_FILTER, and every in-memory matcher answers with an empty list. The author learned nothing at lowering time. It is now refused HERE with a FilterOperatorError (INVALID_FILTER / 400) that names the field, prints the comparand, says it is deliberately not read as membership, and prescribes `{ $in: [...] }` / `{ $nin: [...] }` / `{ $between: [min, max] }` — the third member of the family `$regex` and `$not` already belong to. `$in` / `$nin` / `$between` members, `$and` / `$or` groups and stored ViewFilterRule values keep lowering untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YBWFb5YgMU5dw8p2VKj16S * docs(changeset): say precisely which backends answered the bare-array shape PR #8529's own header records that a document store reads the array comparand natively; "no backend honoured" overstated it. The changeset now says no RULED contract ever answered the shape. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YBWFb5YgMU5dw8p2VKj16S --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3f775ee commit f391ede

4 files changed

Lines changed: 342 additions & 2 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
'@object-ui/core': patch
3+
---
4+
5+
`convertFiltersToAST` now refuses a bare ARRAY in comparand position —
6+
`{ tags: ['a', 'b'] }` — with a `FilterOperatorError` (`INVALID_FILTER` / 400)
7+
that names the field, prints the comparand and prescribes the spelling that
8+
works, instead of lowering it to `['tags', '=', ['a', 'b']]` (objectui#8530).
9+
10+
That node was never answerable: the ObjectQL filter AST has no array-equality,
11+
so `@objectstack/driver-sql` refused it with `400 INVALID_FILTER` from the wire
12+
and every in-memory matcher (`@objectstack/formula`, `ValueDataSource` since
13+
objectui#8514) excluded every row. The author found out two layers away, as a
14+
failed list or an empty one. The refusal now lands at lowering time, where the
15+
field and the offending value are still in hand — the same treatment this file
16+
already gives `$regex` and `$not`, the two other shapes it cannot lower.
17+
18+
It is deliberately NOT read as membership. `{ tags: [...] }` and
19+
`{ tags: { $in: [...] } }` are different statements and the second is already
20+
spellable; rewriting one into the other would guess at intent and silently
21+
change which rows a stored view returns — the lenient second contract
22+
objectui#8514 was resolved against on this same data shape one layer down. The
23+
error message says so, and names `$in` / `$nin` / `$between` as the spellings to
24+
use. `$in` / `$nin` / `$between` members, `$and` / `$or` groups and stored
25+
`ViewFilterRule` values (`in` / `between`) are legitimately arrays and keep
26+
lowering exactly as before.
27+
28+
Every producer in this repository already spells a multi-value comparand
29+
`{ $in: [...] }` (measured across the `$filter` literals and record builders
30+
under `packages/*/src` and `apps/*/src`), so no shipped surface changes
31+
behaviour; only a hand-authored `{ field: [...] }` now fails at the producer
32+
instead of the consumer. No ruled contract ever answered that shape — the spec
33+
leaves an array outside `$in` / `$nin` / `$between` unruled, `driver-sql` and the
34+
in-memory matchers refuse it, and only a document store's native array-equality
35+
happened to read it — so nothing a backend was promised is taken away.
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* A bare ARRAY in comparand position through the repo's ONE lowering —
11+
* objectui#8530.
12+
*
13+
* ## The defect
14+
*
15+
* `convertFiltersToAST` ended its per-field loop with a simple-equality `else`
16+
* that was reached for every non-object value — arrays included. So
17+
* `{ tags: ['a', 'b'] }` became `['tags', '=', ['a', 'b']]`: an array sitting
18+
* in a scalar-equality slot. Nothing answers that node with a row.
19+
*
20+
* MEASURED (this file, section 1) — the spec's own doors do not catch it:
21+
* `isFilterAST` is `true` and `parseFilterAST` hands back `{ tags: [...] }`
22+
* unjudged, because `assertListComparandShapes` rules only on `$in` / `$nin` /
23+
* `$between`. The refusal therefore arrived two layers away — `driver-sql`'s
24+
* `400 INVALID_FILTER` from the wire, or an empty list from every in-memory
25+
* matcher — and the author learned nothing at lowering time.
26+
*
27+
* ## The ruling (objectui#8530, PM comment 5583351371)
28+
*
29+
* Throw `FilterOperatorError`, matching the file's two existing refusals of
30+
* shapes it cannot lower (`$regex`, `$not`). ⛔ NOT lowered to `in`:
31+
* `{ tags: [...] }` and `{ tags: { $in: [...] } }` are different statements,
32+
* the second is already spellable, and rewriting one into the other is the
33+
* lenient second contract objectui#8514 was resolved against on this same data
34+
* shape one layer down.
35+
*
36+
* ## What carries the weight here — the NON-regression axis
37+
*
38+
* The caricature of this fix throws on everything array-shaped. It passes every
39+
* "the bare array is now refused" assertion in section 1 and breaks `$in` /
40+
* `$nin` / `$between` members, `$and` / `$or` groups and stored `ViewFilterRule`
41+
* values with `in` / `between` — all legitimately arrays. Section 2 is what
42+
* discriminates the fix from the caricature, and it asserts PRODUCED values put
43+
* through the spec's own doors, not the absence of a throw: a lowering that
44+
* emits nothing would pass "does not throw" and still be the caricature's
45+
* silent twin.
46+
*
47+
* Section 1's refusals assert the envelope (`code` + `httpStatus`, ADR-0112 /
48+
* objectui#3066) on a CAPTURED error, so the message-quality assertions run
49+
* unconditionally in the leg they were written for rather than sitting inside
50+
* a `catch` that a non-throwing lowering never enters.
51+
*/
52+
53+
import { describe, it, expect } from 'vitest';
54+
import { isFilterAST, parseFilterAST } from '@objectstack/spec/data';
55+
import {
56+
convertFiltersToAST,
57+
toFilterNode,
58+
mergeFilterNodes,
59+
FilterOperatorError,
60+
} from '../filter-converter';
61+
62+
/**
63+
* Run the lowering and hand back the refusal it raised. Fails the test — on
64+
* the FIRST line, with the produced value in the message — when it did not
65+
* refuse, so no later assertion is silently skipped.
66+
*/
67+
function captureRefusal(run: () => unknown): FilterOperatorError {
68+
let caught: unknown;
69+
let produced: unknown;
70+
try {
71+
produced = run();
72+
} catch (e) {
73+
caught = e;
74+
}
75+
expect(
76+
caught,
77+
`expected the lowering to refuse, it produced ${JSON.stringify(produced)}`,
78+
).toBeInstanceOf(FilterOperatorError);
79+
return caught as FilterOperatorError;
80+
}
81+
82+
// ---------------------------------------------------------------------------
83+
// 1. The bare array is refused — with the envelope and an actionable message
84+
// ---------------------------------------------------------------------------
85+
86+
describe('objectui#8530 — a bare array in comparand position is refused', () => {
87+
it('records why the producer must refuse: the spec doors pass the old node unjudged', () => {
88+
// The pre-fix emission. Both spec doors accept it, so nothing between this
89+
// file and the driver would have said a word. If the spec ever starts
90+
// refusing it, this pin reddens and the reader learns the refusal now has
91+
// a sibling — not that the producer arm can go.
92+
const preFixNode = ['tags', '=', ['a', 'b']];
93+
expect(isFilterAST(preFixNode)).toBe(true);
94+
expect(parseFilterAST(preFixNode)).toEqual({ tags: ['a', 'b'] });
95+
});
96+
97+
it('refuses { tags: [...] } with the INVALID_FILTER / 400 envelope', () => {
98+
const err = captureRefusal(() => convertFiltersToAST({ tags: ['a', 'b'] }));
99+
// A bare `Error` classifies as a network fault in the list error panel
100+
// (objectui#3066); the data API's own code and status are what make it
101+
// render as "the filter is malformed".
102+
expect(err.code).toBe('INVALID_FILTER');
103+
expect(err.httpStatus).toBe(400);
104+
expect(err.name).toBe('FilterOperatorError');
105+
});
106+
107+
it('names the field, prints the comparand, and prescribes $in / $nin', () => {
108+
const err = captureRefusal(() => convertFiltersToAST({ tags: ['a', 'b'] }));
109+
// The first sentence is the contract a reader acts on without opening the
110+
// source: which field, what value.
111+
expect(err.message).toMatch(
112+
/^\[ObjectUI\] The filter on field 'tags' carries a bare ARRAY as its equality comparand: \["a","b"\]\./,
113+
);
114+
// The door that works, spelled for THIS field — and its negation.
115+
expect(err.message).toContain('{ tags: { $in: [...] } }');
116+
expect(err.message).toContain('{ tags: { $nin: [...] } }');
117+
// Says out loud that it was not rewritten to membership, and why, so a
118+
// reader who wants `in` knows that door exists and is a separate decision.
119+
expect(err.message).toMatch(/NOT read as membership/);
120+
expect(err.message).toContain('objectui#8530');
121+
// Not the sibling diagnostics: this is neither an unknown operator nor a
122+
// combinator problem, and it must not be reported as one.
123+
expect(err.message).not.toMatch(/Unknown filter operator/);
124+
expect(err.message).not.toMatch(/combinator/);
125+
});
126+
127+
it('prints the comparand it was given, not a placeholder', () => {
128+
const err = captureRefusal(() => convertFiltersToAST({ owner_id: [42, null, 'x'] }));
129+
expect(err.message).toContain("field 'owner_id'");
130+
expect(err.message).toContain('[42,null,"x"]');
131+
});
132+
133+
it('refuses the empty array too — it is not "no constraint"', () => {
134+
// `['tags', '=', []]` is exactly as unanswerable as the two-member one, and
135+
// reading `[]` as TRUE would silently widen the result set — the one
136+
// failure direction this file exists to avoid.
137+
const err = captureRefusal(() => convertFiltersToAST({ tags: [] }));
138+
expect(err.code).toBe('INVALID_FILTER');
139+
expect(err.message).toContain('comparand: []');
140+
});
141+
142+
it('refuses the array wherever it sits: beside other fields and inside $and / $or', () => {
143+
// Beside a scalar condition — the array must not hide behind a sibling
144+
// that lowers fine.
145+
expect(captureRefusal(() => convertFiltersToAST({ status: 'active', tags: ['a'] })).message)
146+
.toContain("field 'tags'");
147+
// As a member condition of a combinator — children lower recursively, so
148+
// the refusal propagates from the child.
149+
expect(captureRefusal(
150+
() => convertFiltersToAST({ $or: [{ status: 'open' }, { tags: ['a'] }] }),
151+
).message).toContain("field 'tags'");
152+
expect(captureRefusal(
153+
() => convertFiltersToAST({ $and: [{ status: 'open' }, { tags: ['a', 'b'] }] }),
154+
).message).toContain("field 'tags'");
155+
});
156+
157+
it('is refused by the sink the same way — toFilterNode and mergeFilterNodes delegate', () => {
158+
// `toFilterNode` is the last hop before the wire for an OBJECT source, and
159+
// `mergeFilterNodes` is what every renderer calls; both route the object
160+
// through `convertFiltersToAST`, so the refusal reaches them unchanged.
161+
const viaSink = captureRefusal(() => toFilterNode({ tags: ['a', 'b'] }));
162+
expect(viaSink.code).toBe('INVALID_FILTER');
163+
const viaMerge = captureRefusal(() => mergeFilterNodes({ status: 'x' }, { tags: ['a'] }));
164+
expect(viaMerge.code).toBe('INVALID_FILTER');
165+
expect(viaMerge.message).toContain("field 'tags'");
166+
});
167+
});
168+
169+
// ---------------------------------------------------------------------------
170+
// 2. NON-regression — arrays that are LEGITIMATELY arrays keep lowering.
171+
// This is the axis that separates the fix from "throw on anything array-
172+
// shaped". Every case asserts the PRODUCED node and puts it through the
173+
// spec's own doors; none of them is "does not throw".
174+
// ---------------------------------------------------------------------------
175+
176+
describe('objectui#8530 — legitimate array positions are untouched', () => {
177+
it('$in still lowers to `in` with its member array intact', () => {
178+
const node = convertFiltersToAST({ status: { $in: ['active', 'pending'] } });
179+
expect(node).toEqual(['status', 'in', ['active', 'pending']]);
180+
expect(isFilterAST(node)).toBe(true);
181+
// Round trip through the spec's shape door: `$in` with an array member is
182+
// exactly what `assertListComparandShapes` accepts.
183+
expect(parseFilterAST(node)).toEqual({ status: { $in: ['active', 'pending'] } });
184+
});
185+
186+
it('$nin (and its $notin alias) still lower to `nin`', () => {
187+
expect(convertFiltersToAST({ status: { $nin: ['archived'] } }))
188+
.toEqual(['status', 'nin', ['archived']]);
189+
expect(convertFiltersToAST({ status: { $notin: ['archived', 'deleted'] } }))
190+
.toEqual(['status', 'nin', ['archived', 'deleted']]);
191+
expect(parseFilterAST(['status', 'nin', ['archived']])).toEqual({ status: { $nin: ['archived'] } });
192+
});
193+
194+
it('$between still lowers with its [min, max] pair', () => {
195+
const node = convertFiltersToAST({ age: { $between: [18, 65] } });
196+
expect(node).toEqual(['age', 'between', [18, 65]]);
197+
expect(isFilterAST(node)).toBe(true);
198+
expect(parseFilterAST(node)).toEqual({ age: { $between: [18, 65] } });
199+
});
200+
201+
it('$in / $nin members inside $and / $or still lower', () => {
202+
const node = convertFiltersToAST({
203+
$or: [{ status: { $in: ['open', 'blocked'] } }, { tags: { $nin: ['x'] } }],
204+
});
205+
expect(node).toEqual([
206+
'or',
207+
['status', 'in', ['open', 'blocked']],
208+
['tags', 'nin', ['x']],
209+
]);
210+
expect(isFilterAST(node)).toBe(true);
211+
});
212+
213+
it('$and / $or themselves — arrays OF conditions — still lower to groups', () => {
214+
// The combinator's VALUE is an array. The caricature ("throw on any array")
215+
// placed ahead of the combinator arm would refuse it as a field called
216+
// `$or` carrying an array comparand.
217+
const node = convertFiltersToAST({ $or: [{ status: 'open' }, { status: 'blocked' }] });
218+
expect(node).toEqual(['or', ['status', '=', 'open'], ['status', '=', 'blocked']]);
219+
expect(parseFilterAST(node)).toEqual({ $or: [{ status: 'open' }, { status: 'blocked' }] });
220+
const conj = convertFiltersToAST({ $and: [{ a: 1 }, { b: 2 }] });
221+
expect(conj).toEqual(['and', ['a', '=', 1], ['b', '=', 2]]);
222+
});
223+
224+
it('a stored ViewFilterRule whose operator is `in` / `between` keeps its array value', () => {
225+
// The card asked for this path to be checked before choosing: a saved view
226+
// rule legitimately carries an array on these operators and lowers through
227+
// `viewFilterRuleToNode`, not through the object arm. It must keep working.
228+
const inRule = toFilterNode([{ field: 'status', operator: 'in', value: ['a', 'b'] }]);
229+
expect(inRule).toEqual([['status', 'in', ['a', 'b']]]);
230+
expect(isFilterAST(inRule)).toBe(true);
231+
const betweenRule = toFilterNode([{ field: 'amount', operator: 'between', value: [1, 10] }]);
232+
expect(betweenRule).toEqual([['amount', 'between', [1, 10]]]);
233+
expect(isFilterAST(betweenRule)).toBe(true);
234+
});
235+
236+
it('an object source with $in merges beside a rule array under one `and`', () => {
237+
const merged = mergeFilterNodes(
238+
{ status: { $in: ['open', 'blocked'] } },
239+
[{ field: 'amount', operator: 'between', value: [1, 10] }],
240+
);
241+
expect(merged).toEqual([
242+
'and',
243+
['status', 'in', ['open', 'blocked']],
244+
[['amount', 'between', [1, 10]]],
245+
]);
246+
});
247+
248+
it('scalar equality is exactly what it was', () => {
249+
expect(convertFiltersToAST({ status: 'active' })).toEqual(['status', '=', 'active']);
250+
expect(convertFiltersToAST({ count: 0, ok: false })).toEqual([
251+
'and',
252+
['count', '=', 0],
253+
['ok', '=', false],
254+
]);
255+
});
256+
});

‎packages/core/src/utils/filter-converter.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,8 +216,10 @@ function falseIdentityLeaf(field: string, value: unknown[]): FilterNode {
216216
* convertFiltersToAST({ $or: [{ status: 'open' }, { status: 'blocked' }] })
217217
* // => ['or', ['status', '=', 'open'], ['status', '=', 'blocked']]
218218
*
219-
* @throws {FilterOperatorError} If an unknown operator is encountered, or if
220-
* `$not` is used — see the `$not` arm for why the AST cannot carry it.
219+
* @throws {FilterOperatorError} If an unknown operator is encountered, if
220+
* `$not` is used — see the `$not` arm for why the AST cannot carry it — or if a
221+
* field's value is a bare ARRAY (`{ tags: ['a', 'b'] }`) — see the array arm for
222+
* why that is refused rather than read as `$in`.
221223
*/
222224
export function convertFiltersToAST(filter: Record<string, any>): FilterNode | Record<string, any> {
223225
const conditions: FilterNode[] = [];
@@ -253,6 +255,46 @@ export function convertFiltersToAST(filter: Record<string, any>): FilterNode | R
253255
);
254256
}
255257

258+
// A bare ARRAY in comparand position is the third shape this file cannot
259+
// lower, after `$regex` and `$not` (objectui#8530). The equality `else`
260+
// below used to catch it and emit `[field, '=', [...]]` — an array in a
261+
// scalar-equality slot. The spec's own doors pass that node through
262+
// unjudged (`isFilterAST` is true and `parseFilterAST` hands back
263+
// `{ field: [...] }`; measured against @objectstack/spec 17.3.0, whose
264+
// `assertListComparandShapes` rules only on `$in` / `$nin` / `$between`),
265+
// so the refusal arrived two layers later: `@objectstack/driver-sql`
266+
// answers 400 INVALID_FILTER, and the in-memory matchers
267+
// (`@objectstack/formula`, `ValueDataSource` since objectui#8514) refuse
268+
// the node and exclude every row. Either way the author learned nothing at
269+
// lowering time. Refused HERE instead, where the field name and the
270+
// offending value are both still in hand.
271+
//
272+
// NOT lowered to `in`. `{ tags: ['a', 'b'] }` and `{ tags: { $in: ['a', 'b'] } }`
273+
// are different statements and the second is already spellable; rewriting
274+
// one into the other guesses at intent and silently changes which rows a
275+
// stored view returns — the lenient second contract objectui#8514 was
276+
// resolved against on this same data shape one layer down. A lowering to
277+
// `in` would be a deliberate, separately-argued change, not a fallback.
278+
//
279+
// `$in` / `$nin` / `$between` MEMBERS are legitimately arrays and are read
280+
// by the operator loop below, never here; `$and` / `$or` carry arrays of
281+
// conditions and were consumed by the combinator arm above.
282+
if (Array.isArray(value)) {
283+
throw new FilterOperatorError(
284+
`[ObjectUI] The filter on field '${field}' carries a bare ARRAY as its ` +
285+
`equality comparand: ${JSON.stringify(value)}. It cannot be lowered: the ` +
286+
`ObjectQL filter AST has no array-equality node, so the lowered node ` +
287+
`[${field}, '=', [...]] is refused by @objectstack/driver-sql (400 INVALID_FILTER) ` +
288+
`and matches no row in the in-memory matchers — it can never select anything. ` +
289+
`It is deliberately NOT read as membership here: { ${field}: [...] } and ` +
290+
`{ ${field}: { $in: [...] } } are different statements, and guessing the ` +
291+
`second from the first would silently change which rows a stored view ` +
292+
`returns (objectui#8530; the same ruling objectui#8514 applied one layer ` +
293+
`down). Spell membership as { ${field}: { $in: [...] } }, its negation as ` +
294+
`{ ${field}: { $nin: [...] } }, or a range as { ${field}: { $between: [min, max] } }.`
295+
);
296+
}
297+
256298
// Check if value is a complex operator object
257299
if (typeof value === 'object' && !Array.isArray(value)) {
258300
// Handle operator-based filters

‎packages/data-objectstack/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,13 @@ AST format**. This is what keeps it compatible with the ObjectStack Protocol
136136
| `$startswith` | `startswith` | `{ email: { $startswith: 'admin' } }` → `['email', 'startswith', 'admin']` |
137137
| `$between` | `between` | `{ age: { $between: [18, 65] } }` → `['age', 'between', [18, 65]]` |
138138

139+
A bare array as a field's value — `{ tags: ['a', 'b'] }` — is **refused** at
140+
lowering time with a `FilterOperatorError` (`INVALID_FILTER` / 400) naming the
141+
field and the comparand, not read as `$in` (objectui#8530): the ObjectQL AST
142+
has no array-equality node, so `['tags', '=', ['a', 'b']]` was answered by a
143+
`400` from the wire or an empty list from every in-memory matcher. Spell
144+
membership as `{ tags: { $in: ['a', 'b'] } }` (or `$nin` for its negation).
145+
139146
#### Complex Filter Examples
140147

141148
**Multiple conditions** are combined with `'and'`:

0 commit comments

Comments
 (0)