Skip to content

Commit cb5a975

Browse files
fix(formula): list-equality prescribes a rewrite that works at each site, and judges a flow condition only where the run binds the typed row (#36340)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbPgGMxS6cCEEprR4e3dQNe9)_ Fixes #36167 This is the card's last item: the builder half (#36185) and the validator half (#36207) are merged, and the remaining follow-ups have their own cards (#36217 skills text, #36218 review follow-ups, #36219 the as-you-type editor). Clause-②: yes (widening) Metadata-protocol: added Skills-docs: follow-up #36217 ## 维护者速读 - 作者把多值字段(多选、多人等)与单个值比较相等时,系统给出的改写建议现在在每个位置都能用:共享规则条件里也能用,且建议本身加了括号,不会被前面的条件拆开;由接口、定时或无触发方式启动的流程里,这种写法不再被误拒。 - 属于「表达式校验与作者护栏」:上一个已合并的拉取请求开始拒绝这种写法,复审发现它给的改写在共享规则里无法生效、部分写法会报错,还会误拒正确的流程条件。 - 若出错,作者看到的只是另一种改写建议,或某个流程条件不再被拦下;本改动可以整体撤回,不影响已存储的数据。 - 无 ## What changes Follow-up to #36207, which merged before its round-4 review findings were addressed. This PR covers four of them: r05 S1, r05 S2, r05 S4 / r06 N1, and r06 S1. **The prescribed rewrite is spelled for its site and parenthesised whole** (`listMembershipRewrite` in `packages/formula/src/validate.ts`). Each spelling below was measured on the site's own evaluator or filter compiler: | site | `==` rewrite | `!=` rewrite | |---|---|---| | a `record.` / `previous.` read evaluated as CEL (validation rule, field rule, formula, action `visible` / `disabled` / `pressed`, hook condition) | `(has(record.f) && record.f != null && "v" in record.f)` | `(!has(record.f) \|\| record.f == null \|\| !("v" in record.f))` | | a bare name at a flow condition (the run binds every declared field, `null` when empty) | `(f != null && "v" in f)` | `(f == null \|\| !("v" in f))` | | a sharing rule `condition`, compiled to a query filter (new `ExprSchemaHint.filterCompiled`, filled by the publish lint) | `(record.f != null && record.f.contains("v"))` | `(record.f == null \|\| !record.f.contains("v"))` | No single spelling works at every site, which is why the rewrite differs per site: - `"v" in record.f` does not lower to a filter. `compileCelToFilter` answers "`in` requires a field on the left (got literal)", so the sharing rule is dropped as `sharing-rule-unlowerable-condition`. - `has()` does not lower either ("unsupported operator call"). - On the CEL evaluator, `record.f.contains("v")` faults on a list, because there is no `list.contains` overload. - `record.f != null && "v" in record.f` faults on a row that lacks the key ("No such key"), which a sparse action row does. It also faults on a null `previous`, as on a create. The filter spelling lowers to `$and[{f:{$null:false}}, {f:{$contains:"v"}}]` and `$or[{f:{$null:true}}, {$not:{f:{$contains:"v"}}}]`. `$contains` on a JSON-stored (multi-value) column is membership in `matchesFilterCondition` and in driver-sql (`sql-driver-17590-json-column-membership.test.ts`). A number or boolean operand is passed as its text (`contains("3")`), since `$contains` compares text. The sharing-site message also says why `==` does not work there: the query filter refuses `$eq` against a list column. **A flattened (flow) site is judged only where the run binds a row of the typed object** (r06 S1). `checkListEquality` now returns early at a `'flattened'` site unless `faultOutcome` is `'run-fails'`. That outcome is declared only on a record-triggered flow, or on a time-relative sweep of the typed object: the lint's `faultOutcomeOf` ledger, `validate-expressions.ts` around line 1632. On any other flow (API, schedule, no trigger), the ledger's own row says the run "holds what its entrance handed it". `seedRunVariables` flattens whatever record that is. So an API flow whose request body carries a string `labels` runs `labels == 'frontend'` correctly, and #36207 refused it. The MCP tool already passes this outcome for `flow_condition` (its default `triggerKind` is `record_change`). `registerFlow`'s advisory pass now passes it on the same flows (`runBindsTypedRow`, which this PR moves above the hint). Side effect: on those flows, the pass's logged type-mismatch lines take the `run-fails` wording that `os validate` already prints. It still only logs and never throws. **Docblocks (r05 S4 / r06 N1).** - `ExprSchemaHint.multiValueFields` now names the forms actually judged: - `record.f` / `previous.f` and the bracket spelling; - the optional spellings, which are refused as `invalid-cel` first; - the bare name, only at a flattened site with `run-fails`, excluding `flowVariables` and `bareNamesUnproven`; - comprehension-bound names, which are never the field. - `ExpressionRefusalParams['list-equality']` now documents `reference` (the bracket spelling renders `record.f`; a bare name is the bare name) and the per-site `rewrite`. **Semantic entry** `cel-list-equality-refused` now has the per-site replacement text and the narrowed surface. The surface adds the sharing rule condition and limits flows to the proven-row ones. ## Tests - `packages/formula/src/validate-list-equality-36167.test.ts` - New describe, "the prescribed rewrite tests membership where it is read". For each site class it takes the rewrite out of the refusal itself, pins its text, and runs it: - **CEL member read:** evaluated on rows `[a,b]` / `[b]` / `[]` / `null` / absent, and with `previous = null`. Each is also checked inside `record.name == 'x' && …`, `record.name == 'y' && …` and `false || …`, which pins the parenthesisation. - **Bare name:** evaluated with the row bound as top-level names. - **Filter:** lowered with `compileCelToFilter` and matched with `matchesFilterCondition` (with the column declared `tags`), including inside `&&`. - Each rewrite validates clean at its own site. - The CEL `in` form is shown not to lower. - New describe, "a flattened site with no proven row binding gets no verdict": bare and `record.` reads, `fail-closed` / `fail-open`, plus a proven-site control. - `packages/formula/src/expression-refusal-codes.test.ts`: the two `list-equality` PINS carry the new rewrites. Two new pins cover the bare name at a proven flattened site and the `filterCompiled` site, with params and the whole message. - `packages/lint/src/validate-expressions.list-equality-36167.test.ts`: - action `visible` rewrites pinned, and each validates clean; - a flow condition's bare `!=` rewrite pinned in the parenthesised form and accepted inside `stage == 'qa' && …`; - CONTROLS: an API, a trigger-less autolaunched and a scheduled flow get no list-equality, bare or `record.`; - new describe, the sharing rule `condition`: refused with the `contains` rewrite, and that rewrite draws no finding from the expression lint or from `validateSharingRuleEnforceability` (it lowers); - CONTROL: the CEL `in` forms draw `sharing-rule-unlowerable-condition` there. - `packages/services/service-automation/src/list-equality-advisory-36167.test.ts`: - `makeFlow` now states its trigger (`record-after-update`); - parenthesised bare rewrite pinned and not reported itself; - CONTROLS: API, scheduled and trigger-less flows report nothing; - premise: the bare rewrites answer per row on `evaluateCondition`, including `false && (…)`. - Two fixtures fixed at `254d40cb` (they had never run; each stopped before the behaviour it pins): - the sharing-rule describe in the lint pin built its rule with a recipient type the spec does not have (`role`) and no rule `type`, so all three cases failed at the spec-validity guard. It now uses `type: 'criteria'` and a `team` recipient, as the other spec-valid sharing fixtures do; - the API-flow CONTROL in the service-automation pin carried no hook secret, so `registerFlow` refused the flow before the advisory pass ran. It now names a `secretRef` (ADR-0041). - `packages/mcp/src/mcp-validate-expression.list-equality-36167.test.ts`: the `flow_condition` rewrite is pinned and validates clean. CONTROL: `triggerKind` `api` / `schedule` / `none` get no list-equality. ## Acceptance notes - **Clause ② for this diff: `yes (widening)`.** Two things widen: - it adds the optional public key `ExprSchemaHint.filterCompiled`; - flow conditions on API / scheduled / trigger-less flows are accepted again, after #36207 refused them. Nothing in this diff refuses more. The changed rewrite text and the narrower flattened scope are not narrowings. `Metadata-protocol: added` because an accepted value is restored, so every package moved is `minor`. - The driver-sql leg of the filter rewrite is cited, not run here: `$contains` membership on a JSON column is pinned in `sql-driver-17590-json-column-membership.test.ts`, and `$not` is NULL-safe (#5146). This PR measures the lowering and `matchesFilterCondition`. - Decision node `config.condition` in the lint: only the start node's gate and edge / branch conditions carry the flow's outcome. An inert node condition already has its own `flow-inert-node-condition` finding, and gets no list-equality verdict. - L2 S1 carried by #36218 (scope !== 'record'); nits N1–N4 accepted. ## Verification Final head `254d40cb` (handover head `5a29954a` + `origin/main` merged at `2b570445` + the two fixture fixes). Every reading below is at that head. <details><summary>Package suites and pins</summary> - Build closure `--filter '@objectstack/lint^...' --filter '@objectstack/mcp^...' --filter '@objectstack/service-automation^...' --filter '@objectstack/scenarios^...' build`: lock VERDICT command-exit 0. Later a full `pnpm build --concurrency=2`: 120/120 tasks, VERDICT command-exit 0. - Pins: formula `validate-list-equality-36167` + `expression-refusal-codes` 250/250 (the 8 bare-name failures of the handover run are gone); lint `validate-expressions.list-equality-36167` 27/27 (3 failed before the fixture fix); mcp `mcp-validate-expression.list-equality-36167` 15/15; service-automation `list-equality-advisory-36167` 22/22 (1 failed before the fixture fix). - Full suites, one locked run, VERDICT command-exit 0: formula build + test 70 files / 2107 tests + typecheck exit 0; lint 225 files / 9434 tests + typecheck exit 0; mcp 83 files / 1467 tests + typecheck exit 0; service-automation 290 files / 4220 tests + typecheck exit 0; spec `src/migrations` 5 files / 198 tests. </details> <details><summary>Ablations (seven, each through ablation-replace WRAP mode under the lock)</summary> Each mutation was proven on disk (anchor 1 to 0, blob changed) and restored (blob equal to the HEAD blob, empty `git diff HEAD`). Every mutated module is read from source by its suite, so there is no dist leg. | ablation | file | pin result | |---|---|---| | delete the flattened proven-row early return | formula `validate.ts` | 5 failed / 245 passed (250) | | never take the `filterCompiled` spelling | formula `validate.ts` | 13 failed / 237 | | drop the outer parentheses of the `!=` member-read rewrite | formula `validate.ts` | 6 failed / 244 | | drop `has()` from the `==` member-read rewrite | formula `validate.ts` | 4 failed / 246 | | lint passes no `filterCompiled` at the sharing rule | lint `validate-expressions.ts` | 2 failed / 25 (27) | | service-automation always declares `run-fails` | `flow-registration-checks.ts` | 3 failed / 19 (22): the API, scheduled and trigger-less CONTROLS | | service-automation never declares `run-fails` | `flow-registration-checks.ts` | 5 failed / 17 (22) | </details> <details><summary>Derived gates</summary> - `dispatch-gates --commands` at `254d40cb`: 96 families. `dispatch-gates --ran` with recorded exit codes: 96 derived, 96 run, 0 NOT-MEASURED (a derived zero), every family exit 0. - Three needed a prerequisite first and were re-run: `check-plugin-teardown-shape --self-test` (exit 3 on the shallow clone until its pinned fixture commit was fetched, then exit 0); the cli `migrate-meta-engine-guidance` vitest (exit 1, MODULE_NOT_FOUND on an unbuilt `@objectstack/mcp` dist, then 3/3 after the full build); `check:dual-build-cjs-loads` (exit 3 PREREQUISITE NOT MET, then exit 0 after the full build: 124 require entry points across 72 packages load). - `check:type-check-debt` exit 0. `check:nul-bytes` OK. `overlap-check` VERDICT clean exit 0 against `origin/main` `2b570445` and #36333 (shares `validate.ts`, merges cleanly). - CI at `254d40cb`: all 69 check-runs completed, every one success or skipped (Check Changeset, PR-body guards, Governed Surface Queue Guard, every Lint and Type Check lane, Test Core 10/10 shards, Test UI 16/16, Build Core, Dogfood Regression Gate). - `test:repo` was not run locally (the diff touches no repo-project test); CI's Test Core ran it. </details> Dogfood battery: n/a (no `!` in the title, and `Clause-②: yes (widening)` has no `(narrowing)` arm). Two-minute check: `pnpm --filter @objectstack/formula exec vitest run src/validate-list-equality-36167.test.ts`. Expected: every test passes, including the "prescribed rewrite" and "no proven row" describes. Read first, by risk: 1. `packages/formula/src/validate.ts`: `listMembershipRewrite` and the early return in `checkListEquality`. 2. `packages/services/service-automation/src/flow-registration-checks.ts`: `faultOutcome` on the advisory hint. 3. `packages/lint/src/validate-expressions.ts`: the sharing-rule `check(…, true)`. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jVXKcrF3rr7ShYFZ9E <!-- signed: repo:objectstack#7 · zhuangjianguo · session_01QsR2jVXKcrF3rr7ShYFZ9E --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent ed33f8a commit cb5a975

11 files changed

Lines changed: 536 additions & 64 deletions
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/lint': minor
4+
'@objectstack/service-automation': minor
5+
'@objectstack/spec': minor
6+
---
7+
8+
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
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: added
12+
Skills-docs: follow-up #36217
13+
14+
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.
15+
16+
The rewrite the refusal prescribes now depends on the site, and is parenthesised whole so it can stand where the comparison stood (`A && (…)`):
17+
18+
- **A `record.` / `previous.` read evaluated as CEL** (a validation rule, a field rule, a formula, an action's `visible` / `disabled` / `pressed`, a hook condition):
19+
- FROM `record.labels != null && "frontend" in record.labels`
20+
- TO `(has(record.labels) && record.labels != null && "frontend" in record.labels)`
21+
- `has()` answers on a sparse row or a null `previous`, where the old form faulted.
22+
- 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 `&&`.
23+
- **A bare name at a flow condition:**
24+
- FROM `labels == null || !("frontend" in labels)`
25+
- TO `(labels == null || !("frontend" in labels))`
26+
- For `==` the TO form is `(labels != null && "frontend" in labels)`.
27+
- **A sharing rule `condition`**, which compiles to a query filter:
28+
- 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`.
29+
- TO `(record.labels != null && record.labels.contains("frontend"))`, which lowers to a membership filter (`$contains`).
30+
- For `!=` the TO form is `(record.labels == null || !record.labels.contains("frontend"))`.
31+
- A number or boolean operand is passed as its text (`contains("3")`).
32+
33+
One-line fix: write the rewrite the refusal names.
34+
35+
`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.

‎packages/formula/src/expression-refusal-codes.test.ts‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -854,12 +854,13 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
854854
operator: '==',
855855
operand: '"frontend"',
856856
answer: 'false',
857-
rewrite: 'record.labels != null && "frontend" in record.labels',
857+
rewrite: '(has(record.labels) && record.labels != null && "frontend" in record.labels)',
858858
},
859859
message:
860860
'list compared with a scalar — `record.labels` holds a list (a multi-value field), and `==` compares the whole ' +
861861
'list with `"frontend"`, so the expression answers `false` on every row whatever the list holds: the condition ' +
862-
'never changes. Test membership with `in`: write `record.labels != null && "frontend" in record.labels`. ' +
862+
'never changes. Test membership with `in`: write ' +
863+
'`(has(record.labels) && record.labels != null && "frontend" in record.labels)`. ' +
863864
'To test whether the list is set, compare it with `null`.',
864865
},
865866
{
@@ -875,14 +876,62 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
875876
operator: '!=',
876877
operand: '"u1"',
877878
answer: 'true',
878-
rewrite: 'previous.owners == null || !("u1" in previous.owners)',
879+
rewrite: '(!has(previous.owners) || previous.owners == null || !("u1" in previous.owners))',
879880
},
880881
message:
881882
'list compared with a scalar — `previous.owners` holds a list (a multi-value field), and `!=` compares the whole ' +
882883
'list with `"u1"`, so the expression answers `true` on every row whatever the list holds: the condition ' +
883-
'never changes. Test membership with `in`: write `previous.owners == null || !("u1" in previous.owners)`. ' +
884+
'never changes. Test membership with `in`: write ' +
885+
'`(!has(previous.owners) || previous.owners == null || !("u1" in previous.owners))`. ' +
884886
'To test whether the list is set, compare it with `null`.',
885887
},
888+
{
889+
// A bare field name at a flattened site proven to bind the typed row.
890+
produce: () =>
891+
onlyError('predicate', "owners != 'u1'", {
892+
scope: 'flattened',
893+
faultOutcome: 'run-fails',
894+
fields: ['owners'],
895+
fieldTypes: { owners: 'user' },
896+
multiValueFields: ['owners'],
897+
}),
898+
params: {
899+
reference: 'owners',
900+
operator: '!=',
901+
operand: '"u1"',
902+
answer: 'true',
903+
rewrite: '(owners == null || !("u1" in owners))',
904+
},
905+
message:
906+
'list compared with a scalar — `owners` holds a list (a multi-value field), and `!=` compares the whole ' +
907+
'list with `"u1"`, so the expression answers `true` on every row whatever the list holds: the condition ' +
908+
'never changes. Test membership with `in`: write `(owners == null || !("u1" in owners))`. ' +
909+
'To test whether the list is set, compare it with `null`.',
910+
},
911+
{
912+
// A source compiled to a query filter (a sharing rule's condition).
913+
produce: () =>
914+
onlyError('predicate', "record.labels == 'frontend'", {
915+
scope: 'record',
916+
filterCompiled: true,
917+
fields: ['labels'],
918+
fieldTypes: { labels: 'multiselect' },
919+
}),
920+
params: {
921+
reference: 'record.labels',
922+
operator: '==',
923+
operand: '"frontend"',
924+
answer: 'false',
925+
rewrite: '(record.labels != null && record.labels.contains("frontend"))',
926+
},
927+
message:
928+
'list compared with a scalar — `record.labels` holds a list (a multi-value field), and `==` compares the whole ' +
929+
'list with `"frontend"`: as CEL it answers `false` on every row, and this condition compiles to a query ' +
930+
'filter, where `==` against a list column is refused, so it never tests membership. Test membership with ' +
931+
'`contains`, which compiles to a membership filter: write ' +
932+
'`(record.labels != null && record.labels.contains("frontend"))`. To test whether the list is set, compare ' +
933+
'it with `null`.',
934+
},
886935
],
887936
'empty-expression': [
888937
{

‎packages/formula/src/expression-refusal.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -329,9 +329,14 @@ export interface ExpressionRefusalParams {
329329
* or a `fieldTypes` type that is inherently multi) and a non-null scalar
330330
* literal: CEL compares the whole list with the scalar, so the expression
331331
* answers the same constant on every row. `reference` is the read as
332-
* `<root>.<field>`, `operand` the literal as CEL prints it, `answer` the
333-
* constant (`false` for `==`, `true` for `!=`), and `rewrite` the
334-
* null-guarded membership test that replaces the comparison.
332+
* `<root>.<field>` (`record['f']` renders `record.f`), or the bare
333+
* `<field>` at a flattened (flow) site, `operand` the literal as CEL prints
334+
* it, `answer` the constant CEL answers (`false` for `==`, `true` for
335+
* `!=`), and `rewrite` the guarded membership test that replaces the
336+
* comparison, parenthesised whole and spelled for the site: `has()`-guarded
337+
* `in` for a `<root>.<field>` read, `!= null`-guarded `in` for a bare name,
338+
* `.contains(…)` where the source compiles to a query filter
339+
* (`ExprSchemaHint.filterCompiled`).
335340
*/
336341
'list-equality': {
337342
readonly reference: string;

‎packages/formula/src/validate-list-equality-36167.test.ts‎

Lines changed: 154 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
import { describe, it, expect } from 'vitest';
1919

2020
import { celEngine } from './cel-engine';
21+
import { compileCelToFilter } from './cel-to-filter';
22+
import { matchesFilterCondition } from './matches-filter';
2123
import { validateExpression, type ExprSchemaHint } from './validate';
2224

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

@@ -58,7 +63,7 @@ describe('the premise — on the evaluator, a list compared with a scalar is a c
5863
expect(run("record.labels == 'frontend'", labels)).toEqual({ ok: true, value: false });
5964
expect(run("record.labels != 'frontend'", labels)).toEqual({ ok: true, value: true });
6065
});
61-
it('CONTROL — the prescribed membership test answers per row', () => {
66+
it('CONTROL — a membership test answers per row', () => {
6267
const src = "record.labels != null && 'frontend' in record.labels";
6368
expect(run(src, ['frontend', 'qa'])).toEqual({ ok: true, value: true });
6469
expect(run(src, ['qa'])).toEqual({ ok: true, value: false });
@@ -80,7 +85,7 @@ describe('list-equality — refused on an inherently multi-value type', () => {
8085
expect(e.code === 'list-equality' && e.params.answer).toBe(op === '==' ? 'false' : 'true');
8186
expect(e.message).toContain(`\`${root}.f\``);
8287
expect(e.message).toContain(' in ');
83-
expect(e.message).toContain(op === '==' ? `in ${root}.f\`` : `!(`);
88+
expect(e.message).toContain(op === '==' ? `in ${root}.f)\`` : `!(`);
8489
});
8590
}
8691
}
@@ -220,6 +225,7 @@ describe('list-equality — a name a comprehension macro binds is an item of the
220225
fieldTypes: { items: 'tags', labels: 'multiselect', owners: 'user' },
221226
multiValueFields: ['owners'],
222227
scope,
228+
...(scope === 'flattened' ? { faultOutcome: 'run-fails' as const } : {}),
223229
});
224230
const refusedReferences = (source: string, scope: 'record' | 'flattened') =>
225231
refusalsOf(source, hint(scope)).filter((e) => e.code === 'list-equality').map((e) => e.params.reference);
@@ -263,3 +269,149 @@ describe('list-equality — a name a comprehension macro binds is an item of the
263269
expect(refusedReferences("record.items.exists(labels, labels == 'a')", 'record')).toEqual([]);
264270
});
265271
});
272+
273+
describe('list-equality — the prescribed rewrite tests membership where it is read', () => {
274+
/** The one `list-equality` refusal of `source` under `hint`, and its prescribed rewrite. */
275+
const rewriteOf = (source: string, hint: ExprSchemaHint): string => {
276+
const errors = refusalsOf(source, hint).filter((e) => e.code === 'list-equality');
277+
expect(errors).toHaveLength(1);
278+
const [e] = errors;
279+
if (e.code !== 'list-equality') throw new Error('unreachable');
280+
expect(e.message).toContain(`write \`${e.params.rewrite}\``);
281+
return e.params.rewrite;
282+
};
283+
/** Rows a list field can hold, and whether `'a'` is a member. */
284+
const ROWS: readonly (readonly [string, Record<string, unknown>, boolean])[] = [
285+
['[a, b]', { f: ['a', 'b'], name: 'x' }, true],
286+
['[b]', { f: ['b'], name: 'x' }, false],
287+
['[]', { f: [], name: 'x' }, false],
288+
['null', { f: null, name: 'x' }, false],
289+
['absent', { name: 'x' }, false],
290+
];
291+
const evaluate = (source: string, vars: Record<string, unknown>) =>
292+
celEngine.evaluate({ dialect: 'cel', source }, vars);
293+
294+
describe('a `record.` / `previous.` read evaluated as CEL', () => {
295+
it('pins the text: has()-guarded and parenthesised whole', () => {
296+
expect(rewriteOf("record.f == 'a'", hintFor('tags'))).toBe(
297+
'(has(record.f) && record.f != null && "a" in record.f)',
298+
);
299+
expect(rewriteOf("record.f != 'a'", hintFor('tags'))).toBe(
300+
'(!has(record.f) || record.f == null || !("a" in record.f))',
301+
);
302+
});
303+
for (const op of ['==', '!='] as const) {
304+
for (const [label, row, member] of ROWS) {
305+
it(`\`${op}\` on row ${label}: answers ${op === '==' ? member : !member}, and stands inside \`&&\` / \`||\``, () => {
306+
const rewrite = rewriteOf(`record.f ${op} 'a'`, hintFor('tags'));
307+
const want = op === '==' ? member : !member;
308+
expect(evaluate(rewrite, { record: row })).toEqual({ ok: true, value: want });
309+
// Parenthesised whole: a conjunct before it does not split it.
310+
expect(evaluate(`record.name == 'x' && ${rewrite}`, { record: row })).toEqual({ ok: true, value: want });
311+
expect(evaluate(`record.name == 'y' && ${rewrite}`, { record: row })).toEqual({ ok: true, value: false });
312+
expect(evaluate(`false || ${rewrite}`, { record: row })).toEqual({ ok: true, value: want });
313+
});
314+
}
315+
}
316+
it('on `previous`, which is null on a create, answers without faulting', () => {
317+
expect(evaluate(rewriteOf("previous.f == 'a'", hintFor('tags')), { previous: null })).toEqual({ ok: true, value: false });
318+
expect(evaluate(rewriteOf("previous.f != 'a'", hintFor('tags')), { previous: null })).toEqual({ ok: true, value: true });
319+
});
320+
it('the rewrite itself is accepted at the site', () => {
321+
for (const op of ['==', '!='] as const) {
322+
const rewrite = rewriteOf(`record.f ${op} 'a'`, hintFor('tags'));
323+
expect(validateExpression('predicate', rewrite, hintFor('tags')).ok).toBe(true);
324+
}
325+
});
326+
});
327+
328+
describe('a bare name at a flattened site proven to bind the typed row', () => {
329+
const flat = hintFor('tags', false, 'flattened');
330+
it('pins the text: null-guarded and parenthesised whole', () => {
331+
expect(rewriteOf("f == 'a'", flat)).toBe('(f != null && "a" in f)');
332+
expect(rewriteOf("f != 'a'", flat)).toBe('(f == null || !("a" in f))');
333+
});
334+
// The run binds every declared field (null when empty), so no row lacks `f`.
335+
for (const op of ['==', '!='] as const) {
336+
for (const [label, row, member] of ROWS.filter(([label]) => label !== 'absent')) {
337+
it(`\`${op}\` on row ${label}: answers ${op === '==' ? member : !member}, inside \`&&\` too`, () => {
338+
const rewrite = rewriteOf(`f ${op} 'a'`, flat);
339+
const want = op === '==' ? member : !member;
340+
// `extra` binds the row's fields as top-level names, as a flow run does.
341+
expect(evaluate(rewrite, { extra: row })).toEqual({ ok: true, value: want });
342+
expect(evaluate(`name == 'x' && ${rewrite}`, { extra: row })).toEqual({ ok: true, value: want });
343+
expect(evaluate(`name == 'y' && ${rewrite}`, { extra: row })).toEqual({ ok: true, value: false });
344+
});
345+
}
346+
}
347+
it('the rewrite itself is accepted at the site', () => {
348+
for (const op of ['==', '!='] as const) {
349+
expect(validateExpression('predicate', rewriteOf(`f ${op} 'a'`, flat), flat).ok).toBe(true);
350+
}
351+
});
352+
});
353+
354+
describe('a source compiled to a query filter (`filterCompiled`: a sharing rule condition)', () => {
355+
const filtered: ExprSchemaHint = { ...hintFor('tags'), filterCompiled: true };
356+
const FIELDS = { f: { type: 'tags' }, name: { type: 'text' } } as const;
357+
/** Lower `source` as the sharing-rule path does, then match it against `row`. */
358+
const matches = (source: string, row: Record<string, unknown>): boolean => {
359+
const lowered = compileCelToFilter(source);
360+
if (!lowered.ok) throw new Error(`not lowered: ${lowered.reason} — ${lowered.detail}`);
361+
return matchesFilterCondition(row, lowered.filter, { fields: FIELDS });
362+
};
363+
it('pins the text: `contains`, null-guarded, parenthesised whole', () => {
364+
expect(rewriteOf("record.f == 'a'", filtered)).toBe('(record.f != null && record.f.contains("a"))');
365+
expect(rewriteOf("record.f != 'a'", filtered)).toBe('(record.f == null || !record.f.contains("a"))');
366+
});
367+
it('a number literal is passed as its text (`$contains` compares text)', () => {
368+
expect(rewriteOf('record.f == 3', filtered)).toBe('(record.f != null && record.f.contains("3"))');
369+
});
370+
it('the CEL `in` spelling does not lower: the reason the site gets its own', () => {
371+
const lowered = compileCelToFilter('record.f != null && "a" in record.f');
372+
expect(lowered.ok).toBe(false);
373+
});
374+
for (const op of ['==', '!='] as const) {
375+
for (const [label, row, member] of ROWS) {
376+
it(`\`${op}\` on row ${label}: the lowered filter matches ${op === '==' ? member : !member}, inside \`&&\` too`, () => {
377+
const rewrite = rewriteOf(`record.f ${op} 'a'`, filtered);
378+
const want = op === '==' ? member : !member;
379+
expect(matches(rewrite, row)).toBe(want);
380+
expect(matches(`record.name == 'x' && ${rewrite}`, row)).toBe(want);
381+
expect(matches(`record.name == 'y' && ${rewrite}`, row)).toBe(false);
382+
});
383+
}
384+
}
385+
it('the rewrite itself is accepted at the site', () => {
386+
for (const op of ['==', '!='] as const) {
387+
expect(validateExpression('predicate', rewriteOf(`record.f ${op} 'a'`, filtered), filtered).ok).toBe(true);
388+
}
389+
});
390+
it('CONTROL — without `filterCompiled` the same comparison gets the CEL spelling', () => {
391+
expect(rewriteOf("record.f == 'a'", hintFor('tags'))).toContain(' in record.f');
392+
});
393+
});
394+
});
395+
396+
describe('list-equality — a flattened site with no proven row binding gets no verdict', () => {
397+
// An API, scheduled or trigger-less flow runs on what its entrance handed
398+
// it: `record` / the bare names are not proven to be the typed object's
399+
// fields, so `labels == 'frontend'` can be correct code there.
400+
const unproven: ExprSchemaHint = { ...hintFor('tags', false, 'flattened') };
401+
delete (unproven as { faultOutcome?: unknown }).faultOutcome;
402+
for (const source of ["f == 'a'", "record.f == 'a'", "'a' != f", "previous.f != 'a'"]) {
403+
it(`accepts \`${source}\` (no list-equality)`, () => {
404+
expect(refusalsOf(source, unproven).filter((e) => e.code === 'list-equality')).toEqual([]);
405+
});
406+
}
407+
it(`a faultOutcome other than 'run-fails' is no proof either`, () => {
408+
for (const faultOutcome of ['fail-closed', 'fail-open'] as const) {
409+
expect(refusalsOf("f == 'a'", { ...unproven, faultOutcome }).filter((e) => e.code === 'list-equality')).toEqual([]);
410+
}
411+
});
412+
it('CONTROL — the same sources at a proven site are refused', () => {
413+
for (const source of ["f == 'a'", "record.f == 'a'"]) {
414+
expect(refusalsOf(source, hintFor('tags', false, 'flattened')).map((e) => e.code)).toContain('list-equality');
415+
}
416+
});
417+
});

0 commit comments

Comments
 (0)