Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .changeset/36167-list-equality-site-rewrites.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
'@objectstack/formula': minor
'@objectstack/lint': minor
'@objectstack/service-automation': minor
'@objectstack/spec': minor
---

fix(formula): the `list-equality` refusal prescribes a rewrite that works where it is read, and a flow condition is judged only where the run binds a row of the typed object

Clause-②: yes (widening)
Metadata-protocol: added
Skills-docs: follow-up #36217

The two widenings. A flow condition in a flow that no record write or sweep starts (an API, scheduled or trigger-less flow) is no longer refused as `list-equality`, bare or `record.`: that run holds what its entrance handed it, so `labels == 'frontend'` can be correct code there. And `ExprSchemaHint` gains the optional key `filterCompiled`, which tells the validator that the site's source compiles to a query filter.

The rewrite the refusal prescribes now depends on the site, and is parenthesised whole so it can stand where the comparison stood (`A && (…)`):

- **A `record.` / `previous.` read evaluated as CEL** (a validation rule, a field rule, a formula, an action's `visible` / `disabled` / `pressed`, a hook condition):
- FROM `record.labels != null && "frontend" in record.labels`
- TO `(has(record.labels) && record.labels != null && "frontend" in record.labels)`
- `has()` answers on a sparse row or a null `previous`, where the old form faulted.
- For `!=` the TO form is `(!has(record.labels) || record.labels == null || !("frontend" in record.labels))`. The old `!=` form, with no parentheses, split under a leading `&&`.
- **A bare name at a flow condition:**
- FROM `labels == null || !("frontend" in labels)`
- TO `(labels == null || !("frontend" in labels))`
- For `==` the TO form is `(labels != null && "frontend" in labels)`.
- **A sharing rule `condition`**, which compiles to a query filter:
- FROM `record.labels != null && "frontend" in record.labels`, which does not lower (`in` needs a field on its left), so the rule was dropped as `sharing-rule-unlowerable-condition`.
- TO `(record.labels != null && record.labels.contains("frontend"))`, which lowers to a membership filter (`$contains`).
- For `!=` the TO form is `(record.labels == null || !record.labels.contains("frontend"))`.
- A number or boolean operand is passed as its text (`contains("3")`).

One-line fix: write the rewrite the refusal names.

`registerFlow`'s advisory pass now hands the validator `faultOutcome: 'run-fails'` on a record-triggered flow and on a time-relative sweep of the typed object, the same flows `os validate` declares it on. On those flows its logged type-mismatch lines now use the wording `os validate` prints. It still only logs and never throws.
57 changes: 53 additions & 4 deletions packages/formula/src/expression-refusal-codes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,12 +854,13 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
operator: '==',
operand: '"frontend"',
answer: 'false',
rewrite: 'record.labels != null && "frontend" in record.labels',
rewrite: '(has(record.labels) && record.labels != null && "frontend" in record.labels)',
},
message:
'list compared with a scalar — `record.labels` holds a list (a multi-value field), and `==` compares the whole ' +
'list with `"frontend"`, so the expression answers `false` on every row whatever the list holds: the condition ' +
'never changes. Test membership with `in`: write `record.labels != null && "frontend" in record.labels`. ' +
'never changes. Test membership with `in`: write ' +
'`(has(record.labels) && record.labels != null && "frontend" in record.labels)`. ' +
'To test whether the list is set, compare it with `null`.',
},
{
Expand All @@ -875,14 +876,62 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
operator: '!=',
operand: '"u1"',
answer: 'true',
rewrite: 'previous.owners == null || !("u1" in previous.owners)',
rewrite: '(!has(previous.owners) || previous.owners == null || !("u1" in previous.owners))',
},
message:
'list compared with a scalar — `previous.owners` holds a list (a multi-value field), and `!=` compares the whole ' +
'list with `"u1"`, so the expression answers `true` on every row whatever the list holds: the condition ' +
'never changes. Test membership with `in`: write `previous.owners == null || !("u1" in previous.owners)`. ' +
'never changes. Test membership with `in`: write ' +
'`(!has(previous.owners) || previous.owners == null || !("u1" in previous.owners))`. ' +
'To test whether the list is set, compare it with `null`.',
},
{
// A bare field name at a flattened site proven to bind the typed row.
produce: () =>
onlyError('predicate', "owners != 'u1'", {
scope: 'flattened',
faultOutcome: 'run-fails',
fields: ['owners'],
fieldTypes: { owners: 'user' },
multiValueFields: ['owners'],
}),
params: {
reference: 'owners',
operator: '!=',
operand: '"u1"',
answer: 'true',
rewrite: '(owners == null || !("u1" in owners))',
},
message:
'list compared with a scalar — `owners` holds a list (a multi-value field), and `!=` compares the whole ' +
'list with `"u1"`, so the expression answers `true` on every row whatever the list holds: the condition ' +
'never changes. Test membership with `in`: write `(owners == null || !("u1" in owners))`. ' +
'To test whether the list is set, compare it with `null`.',
},
{
// A source compiled to a query filter (a sharing rule's condition).
produce: () =>
onlyError('predicate', "record.labels == 'frontend'", {
scope: 'record',
filterCompiled: true,
fields: ['labels'],
fieldTypes: { labels: 'multiselect' },
}),
params: {
reference: 'record.labels',
operator: '==',
operand: '"frontend"',
answer: 'false',
rewrite: '(record.labels != null && record.labels.contains("frontend"))',
},
message:
'list compared with a scalar — `record.labels` holds a list (a multi-value field), and `==` compares the whole ' +
'list with `"frontend"`: as CEL it answers `false` on every row, and this condition compiles to a query ' +
'filter, where `==` against a list column is refused, so it never tests membership. Test membership with ' +
'`contains`, which compiles to a membership filter: write ' +
'`(record.labels != null && record.labels.contains("frontend"))`. To test whether the list is set, compare ' +
'it with `null`.',
},
],
'empty-expression': [
{
Expand Down
11 changes: 8 additions & 3 deletions packages/formula/src/expression-refusal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,14 @@ export interface ExpressionRefusalParams {
* or a `fieldTypes` type that is inherently multi) and a non-null scalar
* literal: CEL compares the whole list with the scalar, so the expression
* answers the same constant on every row. `reference` is the read as
* `<root>.<field>`, `operand` the literal as CEL prints it, `answer` the
* constant (`false` for `==`, `true` for `!=`), and `rewrite` the
* null-guarded membership test that replaces the comparison.
* `<root>.<field>` (`record['f']` renders `record.f`), or the bare
* `<field>` at a flattened (flow) site, `operand` the literal as CEL prints
* it, `answer` the constant CEL answers (`false` for `==`, `true` for
* `!=`), and `rewrite` the guarded membership test that replaces the
* comparison, parenthesised whole and spelled for the site: `has()`-guarded
* `in` for a `<root>.<field>` read, `!= null`-guarded `in` for a bare name,
* `.contains(…)` where the source compiles to a query filter
* (`ExprSchemaHint.filterCompiled`).
*/
'list-equality': {
readonly reference: string;
Expand Down
156 changes: 154 additions & 2 deletions packages/formula/src/validate-list-equality-36167.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import { describe, it, expect } from 'vitest';

import { celEngine } from './cel-engine';
import { compileCelToFilter } from './cel-to-filter';
import { matchesFilterCondition } from './matches-filter';
import { validateExpression, type ExprSchemaHint } from './validate';

const MULTI_TYPES = ['multiselect', 'checkboxes', 'tags'] as const;
Expand All @@ -31,6 +33,9 @@ function hintFor(type: string, multi = false, scope: 'record' | 'flattened' = 'r
fieldTypes: { f: type, name: 'text' },
...(multi ? { multiValueFields: ['f'] } : {}),
scope,
// A flattened site is judged only where the run is proven to bind a row
// of the typed object; the unproven case is pinned on its own below.
...(scope === 'flattened' ? { faultOutcome: 'run-fails' as const } : {}),
};
}

Expand Down Expand Up @@ -58,7 +63,7 @@ describe('the premise — on the evaluator, a list compared with a scalar is a c
expect(run("record.labels == 'frontend'", labels)).toEqual({ ok: true, value: false });
expect(run("record.labels != 'frontend'", labels)).toEqual({ ok: true, value: true });
});
it('CONTROL — the prescribed membership test answers per row', () => {
it('CONTROL — a membership test answers per row', () => {
const src = "record.labels != null && 'frontend' in record.labels";
expect(run(src, ['frontend', 'qa'])).toEqual({ ok: true, value: true });
expect(run(src, ['qa'])).toEqual({ ok: true, value: false });
Expand All @@ -80,7 +85,7 @@ describe('list-equality — refused on an inherently multi-value type', () => {
expect(e.code === 'list-equality' && e.params.answer).toBe(op === '==' ? 'false' : 'true');
expect(e.message).toContain(`\`${root}.f\``);
expect(e.message).toContain(' in ');
expect(e.message).toContain(op === '==' ? `in ${root}.f\`` : `!(`);
expect(e.message).toContain(op === '==' ? `in ${root}.f)\`` : `!(`);
});
}
}
Expand Down Expand Up @@ -220,6 +225,7 @@ describe('list-equality — a name a comprehension macro binds is an item of the
fieldTypes: { items: 'tags', labels: 'multiselect', owners: 'user' },
multiValueFields: ['owners'],
scope,
...(scope === 'flattened' ? { faultOutcome: 'run-fails' as const } : {}),
});
const refusedReferences = (source: string, scope: 'record' | 'flattened') =>
refusalsOf(source, hint(scope)).filter((e) => e.code === 'list-equality').map((e) => e.params.reference);
Expand Down Expand Up @@ -263,3 +269,149 @@ describe('list-equality — a name a comprehension macro binds is an item of the
expect(refusedReferences("record.items.exists(labels, labels == 'a')", 'record')).toEqual([]);
});
});

describe('list-equality — the prescribed rewrite tests membership where it is read', () => {
/** The one `list-equality` refusal of `source` under `hint`, and its prescribed rewrite. */
const rewriteOf = (source: string, hint: ExprSchemaHint): string => {
const errors = refusalsOf(source, hint).filter((e) => e.code === 'list-equality');
expect(errors).toHaveLength(1);
const [e] = errors;
if (e.code !== 'list-equality') throw new Error('unreachable');
expect(e.message).toContain(`write \`${e.params.rewrite}\``);
return e.params.rewrite;
};
/** Rows a list field can hold, and whether `'a'` is a member. */
const ROWS: readonly (readonly [string, Record<string, unknown>, boolean])[] = [
['[a, b]', { f: ['a', 'b'], name: 'x' }, true],
['[b]', { f: ['b'], name: 'x' }, false],
['[]', { f: [], name: 'x' }, false],
['null', { f: null, name: 'x' }, false],
['absent', { name: 'x' }, false],
];
const evaluate = (source: string, vars: Record<string, unknown>) =>
celEngine.evaluate({ dialect: 'cel', source }, vars);

describe('a `record.` / `previous.` read evaluated as CEL', () => {
it('pins the text: has()-guarded and parenthesised whole', () => {
expect(rewriteOf("record.f == 'a'", hintFor('tags'))).toBe(
'(has(record.f) && record.f != null && "a" in record.f)',
);
expect(rewriteOf("record.f != 'a'", hintFor('tags'))).toBe(
'(!has(record.f) || record.f == null || !("a" in record.f))',
);
});
for (const op of ['==', '!='] as const) {
for (const [label, row, member] of ROWS) {
it(`\`${op}\` on row ${label}: answers ${op === '==' ? member : !member}, and stands inside \`&&\` / \`||\``, () => {
const rewrite = rewriteOf(`record.f ${op} 'a'`, hintFor('tags'));
const want = op === '==' ? member : !member;
expect(evaluate(rewrite, { record: row })).toEqual({ ok: true, value: want });
// Parenthesised whole: a conjunct before it does not split it.
expect(evaluate(`record.name == 'x' && ${rewrite}`, { record: row })).toEqual({ ok: true, value: want });
expect(evaluate(`record.name == 'y' && ${rewrite}`, { record: row })).toEqual({ ok: true, value: false });
expect(evaluate(`false || ${rewrite}`, { record: row })).toEqual({ ok: true, value: want });
});
}
}
it('on `previous`, which is null on a create, answers without faulting', () => {
expect(evaluate(rewriteOf("previous.f == 'a'", hintFor('tags')), { previous: null })).toEqual({ ok: true, value: false });
expect(evaluate(rewriteOf("previous.f != 'a'", hintFor('tags')), { previous: null })).toEqual({ ok: true, value: true });
});
it('the rewrite itself is accepted at the site', () => {
for (const op of ['==', '!='] as const) {
const rewrite = rewriteOf(`record.f ${op} 'a'`, hintFor('tags'));
expect(validateExpression('predicate', rewrite, hintFor('tags')).ok).toBe(true);
}
});
});

describe('a bare name at a flattened site proven to bind the typed row', () => {
const flat = hintFor('tags', false, 'flattened');
it('pins the text: null-guarded and parenthesised whole', () => {
expect(rewriteOf("f == 'a'", flat)).toBe('(f != null && "a" in f)');
expect(rewriteOf("f != 'a'", flat)).toBe('(f == null || !("a" in f))');
});
// The run binds every declared field (null when empty), so no row lacks `f`.
for (const op of ['==', '!='] as const) {
for (const [label, row, member] of ROWS.filter(([label]) => label !== 'absent')) {
it(`\`${op}\` on row ${label}: answers ${op === '==' ? member : !member}, inside \`&&\` too`, () => {
const rewrite = rewriteOf(`f ${op} 'a'`, flat);
const want = op === '==' ? member : !member;
// `extra` binds the row's fields as top-level names, as a flow run does.
expect(evaluate(rewrite, { extra: row })).toEqual({ ok: true, value: want });
expect(evaluate(`name == 'x' && ${rewrite}`, { extra: row })).toEqual({ ok: true, value: want });
expect(evaluate(`name == 'y' && ${rewrite}`, { extra: row })).toEqual({ ok: true, value: false });
});
}
}
it('the rewrite itself is accepted at the site', () => {
for (const op of ['==', '!='] as const) {
expect(validateExpression('predicate', rewriteOf(`f ${op} 'a'`, flat), flat).ok).toBe(true);
}
});
});

describe('a source compiled to a query filter (`filterCompiled`: a sharing rule condition)', () => {
const filtered: ExprSchemaHint = { ...hintFor('tags'), filterCompiled: true };
const FIELDS = { f: { type: 'tags' }, name: { type: 'text' } } as const;
/** Lower `source` as the sharing-rule path does, then match it against `row`. */
const matches = (source: string, row: Record<string, unknown>): boolean => {
const lowered = compileCelToFilter(source);
if (!lowered.ok) throw new Error(`not lowered: ${lowered.reason} — ${lowered.detail}`);
return matchesFilterCondition(row, lowered.filter, { fields: FIELDS });
};
it('pins the text: `contains`, null-guarded, parenthesised whole', () => {
expect(rewriteOf("record.f == 'a'", filtered)).toBe('(record.f != null && record.f.contains("a"))');
expect(rewriteOf("record.f != 'a'", filtered)).toBe('(record.f == null || !record.f.contains("a"))');
});
it('a number literal is passed as its text (`$contains` compares text)', () => {
expect(rewriteOf('record.f == 3', filtered)).toBe('(record.f != null && record.f.contains("3"))');
});
it('the CEL `in` spelling does not lower: the reason the site gets its own', () => {
const lowered = compileCelToFilter('record.f != null && "a" in record.f');
expect(lowered.ok).toBe(false);
});
for (const op of ['==', '!='] as const) {
for (const [label, row, member] of ROWS) {
it(`\`${op}\` on row ${label}: the lowered filter matches ${op === '==' ? member : !member}, inside \`&&\` too`, () => {
const rewrite = rewriteOf(`record.f ${op} 'a'`, filtered);
const want = op === '==' ? member : !member;
expect(matches(rewrite, row)).toBe(want);
expect(matches(`record.name == 'x' && ${rewrite}`, row)).toBe(want);
expect(matches(`record.name == 'y' && ${rewrite}`, row)).toBe(false);
});
}
}
it('the rewrite itself is accepted at the site', () => {
for (const op of ['==', '!='] as const) {
expect(validateExpression('predicate', rewriteOf(`record.f ${op} 'a'`, filtered), filtered).ok).toBe(true);
}
});
it('CONTROL — without `filterCompiled` the same comparison gets the CEL spelling', () => {
expect(rewriteOf("record.f == 'a'", hintFor('tags'))).toContain(' in record.f');
});
});
});

describe('list-equality — a flattened site with no proven row binding gets no verdict', () => {
// An API, scheduled or trigger-less flow runs on what its entrance handed
// it: `record` / the bare names are not proven to be the typed object's
// fields, so `labels == 'frontend'` can be correct code there.
const unproven: ExprSchemaHint = { ...hintFor('tags', false, 'flattened') };
delete (unproven as { faultOutcome?: unknown }).faultOutcome;
for (const source of ["f == 'a'", "record.f == 'a'", "'a' != f", "previous.f != 'a'"]) {
it(`accepts \`${source}\` (no list-equality)`, () => {
expect(refusalsOf(source, unproven).filter((e) => e.code === 'list-equality')).toEqual([]);
});
}
it(`a faultOutcome other than 'run-fails' is no proof either`, () => {
for (const faultOutcome of ['fail-closed', 'fail-open'] as const) {
expect(refusalsOf("f == 'a'", { ...unproven, faultOutcome }).filter((e) => e.code === 'list-equality')).toEqual([]);
}
});
it('CONTROL — the same sources at a proven site are refused', () => {
for (const source of ["f == 'a'", "record.f == 'a'"]) {
expect(refusalsOf(source, hintFor('tags', false, 'flattened')).map((e) => e.code)).toContain('list-equality');
}
});
});
Loading
Loading