Skip to content

Commit fa9d695

Browse files
fix(core): an unresolved { $record } lookup-filter comparand is refused by name before any driver sees it (#34330)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbCpddLFmKzR39wJWZpkRMCi)_ Fixes #34199 Clause-②: no Metadata-protocol: semantic Skills-docs: none — `git grep '$record'` finds no teaching of the `{ $record }` comparand under `skills/` or `content/docs/data-modeling/`; this PR adds nothing an author writes, and the teaching moves with the picker card (#34197), as PR #34078 recorded. ## 维护者速读 1. **改了什么**:服务端过滤器的占位符解析(`resolveFilterTokens`)遇到"作为字段比较值"的未解析 `{ $record: "路径" }` 时按名拒绝,返回 `INVALID_FILTER` / 400,消息写明字段、`$record` 路径和位置;藏在深层比较对象里的 `{ $record }` 不碰,对象写法和数组写法(`[字段, 操作符, 值]`)都和 main 一样放行。 2. **为什么改**:`$record` 只有编辑表单里的选择器能替换;以前它漏到驱动层,驱动用含糊的话拒绝(内存驱动说"不支持的操作符",SQL 驱动连字段都不说)。 3. **风险与回滚**:被拒的形状在内置驱动上以前就全部被拒;深层比较对象两种写法经 analytics 门与 `engine.find` 实测,本分支与 main 逐字相同(8 个用例)。回滚即撤销本 PR。 4. **先看**:`packages/core/src/utils/filter-tokens.ts`(`findRecordReferenceComparand` 的数组分支与位置规则、`resolveFilterTokens` 开头两行)、`packages/core/src/utils/filter-tokens.test.ts`(`[#34199]` describe 的拒绝表与 CONTROL 表)、`packages/spec/src/data/field.zod.ts`(合并冲突手工解决处:两段 describe 中 main 的选择器句子 + 本 PR 的服务端句子)。 5. **两分钟验证**:`pnpm --filter @objectstack/core exec vitest run src/utils/filter-tokens.test.ts`,预期 79 个用例全绿,其中 `[#34199]` 下 21 个。 6. **需要你做的**:无,席位落地。 ## What changes - **`resolveFilterTokens`** (`packages/core/src/utils/filter-tokens.ts`), the engine's one token pass (`engine-top-level.ts` `resolveWhereFilterTokens`, every read and write verb) and the analytics service's: before the fast path, `findRecordReferenceComparand` walks the filter's node grammar and refuses a `{ $record }` object (an own `$record` key, malformed or not) **only where it is a field's comparand**: the field's own value (the eq shorthand `{ f: { $record } }`) or the value of an operator on that field (`{ f: { $gt: { $record } } }`), under any `$and` / `$or` / `$not` nesting. `INVALID_FILTER` / 400; the message names the field, the `$record` path (echoed as JSON, bounded to 60 characters like the sibling comparand doors) and the position, e.g. `A { "$record": "account.cb_market" } comparand on field "cb_market" at filter.cb_market reached the server unresolved, and is refused rather than compared.` - **Not judged, exactly as on `main`:** a `{ $record }` inside a no-`$` object beneath a field (`{ attachment: { meta: { $record: 'x' } } }`: a deep-equality comparand or a nested-relation condition, which only the field's declaration tells apart and this field-agnostic resolver never reads), a member of an operator's list (`$in: ['NA', 'EU', { $record }]`), a `$` key in a node position that is not a combinator (`{ $record: 'x' }` at the root), and **a legacy `[field, op, value]` tuple**: an array whose first member is a string other than `and` / `or` (the split `parseFilterAST` lowers by) is a comparison whose third member is a comparand, so `['attachment', '=', { meta: { $record: 'x' } }]` comes back by reference like its object spelling. An `['and' | 'or', …]` array is walked from its second member; any other array as a list of nodes. (Round 3, L2 M2: round 2 walked the tuple's value as a node and refused this shape naming field `meta`; the analytics service hands the pass its `where` unlowered.) - The check is shallow and allocation-free (it never enters a comparand), and runs before `hasFilterToken`, so the refusal does not depend on a string token being present; a filter with no placeholder still comes back by reference. The resolver's own walk is byte-identical to `main`'s. - The field is the key the comparand sits under, so a column literally named `value` beside one named `field` is named `value`, and a list member is never read as a field name. - **Spec describes** (`packages/spec/src/data/field.zod.ts`, describe text only), worded to what holds on every path: the `value` describe says an unresolved `{ $record }` "is refused (INVALID_FILTER), never read as null"; the `lookupFilters` describe adds that it is refused "by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words" (round 3, L2 S2: `temporalComparandKind` answers for all three kinds). Round 4 merged main, whose picker change (PR #34253) rewrote both describes and dropped their `[PLANNED — not enforced]` tails; the merge keeps main's picker sentences whole and adds only this PR's server sentences (review#1 S3): the `value` describe appends "A { $record } that reaches a server unresolved is refused (INVALID_FILTER), never read as null.", and the `lookupFilters` describe replaces main's "refused, never read as null." with the by-name sentence above. This restates seat ruling 6900252552 §3 on #34009 ("An unresolved `$record` fails loudly (`INVALID_FILTER`) instead of returning wrong rows"); no schema shape, key or error code changes. Regenerated: `content/docs/references/{data/field,data/object,system/migration}.mdx`. - **`packages/spec/src/data/field.test.ts`**: the eq-shorthand pin's title and comment now name the engine's token pass as the refuser (claim surface amended by the area); its assertion is unchanged. - Changeset `.changeset/34199-record-reference-refused-by-name.md` (`@objectstack/core` and `@objectstack/spec`, minor, as `Metadata-protocol: semantic` requires). Round 3: the "no filter that answered rows now refuses" sentence now says why (the pass judges only a field's comparand, never a value inside one); the "Unchanged" row names both spellings of the deep comparand and their CONTROLs; the temporal carve-out names date, datetime and time. Round 4: the last paragraph says the `value` and `lookupFilters` describes state the server half, and their picker sentences are not changed by this entry (no PLANNED marker, no "does not resolve"). ## Tests - `packages/core/src/utils/filter-tokens.test.ts`, top-level describe `[#34199] resolveFilterTokens — an unresolved { $record } comparand refuses by name` (21 cases): - Refused, `INVALID_FILTER` / 400 naming the field, the `$record` path and the position (7 + 3): the eq shorthand, an operator comparand, an ordering comparand, inside `$or` beside a literal, under `$not`, beside a string token, a column named `value` beside one named `field`; an object node inside an `['or', …]` array (`filter[2].cb_market`); a 500-character `$record` value, echoed bounded; a malformed reference. - CONTROLs, returned by reference (8): inside a deep-equality comparand (`{ attachment: { meta: { $record: 'x' } } }`), inside a nested-relation condition, as an `$in` list member, at the root, as the third member of a tuple, and (round 3) **the deep comparand in the array spelling** `['attachment', '=', { meta: { $record: 'x' } }]`, the same tuple under an `and`-array, and inside a tuple of a legacy list of tuples. - CONTROLs (3): a token-free filter with nested objects comes back by reference; string tokens and the `$now` anchor resolve as before; a deep `{ $record }` beside a string token is resolved around and kept as written. - Driver pins, `packages/drivers/driver-sql/src/sql-driver-record-reference-refusal.test.ts` (SQLite in-process) and `packages/drivers/driver-memory/src/memory-record-reference-refusal.test.ts`: through the token seam the shorthand and the operator form are refused by name and the driver's `find` is never called; a caller that passes no seam is still refused by the driver itself; CONTROL: `{ attachment: { meta: { $record: 'x' } } }` comes through the seam by reference and the driver answers as before; CONTROL: an ordinary filter and `{current_user_id}` answer the same rows as before. Unchanged in round 3. - Ablation of the tuple rule (round 3, one-shot, `scripts/ablation-replace.mjs --delete` on the line `if (head !== 'and' && head !== 'or') return undefined;`; core's test imports the module from `src`, so no build sits between mutation and run): anchor x1 to x0, blob `244045f6cd22` to `ace6143a5a76`; core 3 failed / 76 passed, exactly the three new array-spelling CONTROLs, each with `UnresolvedRecordReferenceError: A { "$record": "x" } comparand on field "meta" at filter[2].meta` (and `filter[2][2].meta`, `filter[1][2][0].meta`); restored, blob == HEAD (`244045f6cd22`) and `git diff HEAD` empty. Round 2's ablation of the position rule stands as recorded there. ## Acceptance notes - **L2 M2, measured through the analytics door** (round 3, scratch harness, not committed: `AnalyticsServicePlugin` over a real `ObjectQL` engine on `SqliteWasmDriver`, ObjectQL face, `service.query` beside `engine.find`; three legs swapping only `filter-tokens.ts`, core rebuilt each time, restored and rebuilt after): the array spelling of the deep comparand, on a `json` and on a `file` column, answers **byte-identically on this head and on `main`** (`35c9a305f0`): on `json` the engine's no-operator-object door (`INVALID_FILTER` / 400, "puts an object with no operator key (keys "meta") … as the value of a json field"), on `file` the analytics normalizer's `Unsupported filter operator "meta" on field "doc"` (analytics) and the SQL driver's unbindable-comparand refusal (`engine.find`). Round 2's head answered the analytics array spelling with this pass's own refusal naming field `meta`: refused there too on these two column kinds, but by the wrong door, and on a column where `main` answers rows (L2's driver-memory reading) it would have been a narrowing. Not measured through analytics on driver-memory (service-analytics does not depend on it). A literal CONTROL (`['cb_market', '=', 'export']`) answered `["a"]` on every leg. - On the same harness the object-spelling eq shorthand is refused by name on this head through both doors, where `main` answered the analytics normalizer's and the SQL driver's generic sentences; the tuple spelling of a direct reference (`['cb_market', '=', { $record }]`) is refused by name through `engine.find` (which lowers first) and by the analytics normalizer's `Unsupported filter operator "$record"` through the analytics door, on this head and on `main` alike. - **Measured on `origin/main` 2243872 before the change** (round 1, scratch): driver-sql (SQLite) refused every comparand shape itself, `INVALID_FILTER` / 400 with the operator and field withheld, on `find`, `count`, `updateMany`, `deleteMany` and `aggregate`; driver-memory refused the shorthand on every verb. Through `engine.find` the operator form `{ f: { $eq: { $record } } }` (and the other five operators) is refused first by the comparand-type door, in its generic sentence, so the describe promises the by-name refusal only where the token pass is the door that meets it. - **Through the engine on driver-memory** (round 1, scratch), `{ attachment: { meta: { $record: 'x' } } }` over a `file` field answers 200 with `["d1"]` on `main` and on this branch, the driver receiving the filter unchanged. - H3 holds: no server path builds a `where` from `lookupFilters`, so no save or read path starts refusing. - A read-scope predicate carrying a refused shape stays fail-closed with `READ_SCOPE_COMPILE_FAILED` / 500 in the analytics read-scope compiler, which wraps whatever this pass throws; the message is withheld there as before. - The CONTROL for the array spelling is pinned at the pass, not through the analytics door: an analytics test file is outside the claim's file surface, and the pass is the only code this PR changes on that path (the head-versus-`main` legs above are byte-identical). ## Verification Round 4 readings at `4fe8f01a37`: merge `7969da81f8` (parents `16c765b371`, `cfcba53920` origin/main; `field.zod.ts` conflict resolved by hand per review#1 S3), regeneration `e3775ec5` (the three references re-derived from the merged source, equal to main's apart from this PR's two server sentences), changeset `4fe8f01a37`. Round 4 suites: core `filter-tokens.test.ts` 79 passed; spec `field.test.ts` 306 passed; core and spec typecheck exit 0; driver-memory pin 5 passed; driver-sql pin 6 passed; spec `check:generated` all 14 up to date after `gen:schema` + `gen:docs`; CI on `4fe8f01a`: 68 check-runs, 58 success, 10 skipped, 0 failure. The round-3 readings below were taken at `16c765b371`. <details><summary>Suites and generated artifacts (locked runs, VERDICT command-exit 0)</summary> - `@objectstack/core` `test`: 147 files / 3425 tests passed; `typecheck` exit 0. - `@objectstack/core` `src/utils/filter-tokens.test.ts`: 79 passed. - `@objectstack/driver-memory` `src/memory-record-reference-refusal.test.ts`: 5 passed. - `@objectstack/driver-sql` `src/sql-driver-record-reference-refusal.test.ts`: 6 passed. - `@objectstack/spec` `src/data/field.test.ts`: 306 passed. - `@objectstack/spec` `check:generated`: first run 1 of 14 stale (`content/docs/references/**`, the describe change); `--fix` regenerated the three references; re-check "All 14 generated artifacts are up to date". </details> <details><summary>Derived gate families (dispatch-gates at 16c765b)</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 116 commands (84 pnpm, 32 node) over the 10 changed paths. - Run record with each exit code captured before any pipe: 115 exit 0. `check:skill-examples` first exited 3 (PREREQUISITE NOT MET, `client-react` dist absent), then 0 once that dist was built. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET: it reads every package's `dist/`, and this worktree builds only the touched closures), recorded NOT-MEASURED; CI's `Lint & Repo Gates` carries it. - `--ran`: "116 derived famil(ies) accounted for — 115 run, 1 NOT-MEASURED (0 DERIVED from a recorded exit 3, 1 claimed)", exit 0. - The derivation warns the tree is at least 20 commits behind `origin/main`, with `scripts/check-skills-token-ratchet.mjs` and `scripts/pm/label-write.mjs` changed across that range; neither reads a path this PR changes. Round 4 merged `origin/main` `cfcba539`; this 116-family sweep was not re-run on the merge head, and CI `Lint & Repo Gates` is green on `4fe8f01a`. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5kgF3mo9f7LXuv5hac <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 27c0b20 commit fa9d695

10 files changed

Lines changed: 511 additions & 14 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/core': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
fix(core): an unresolved `{ $record }` lookup-filter comparand is refused by name before any driver sees it
7+
8+
Clause-②: no
9+
Metadata-protocol: semantic
10+
11+
A `lookupFilters` entry may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }`; only the record picker of the form editing that record can replace it with a value. When one reaches a server unresolved as a field's comparand (the field's own value, or the value of an operator on that field), the engine's token pass (`resolveFilterTokens`) now refuses it with `INVALID_FILTER` / 400, and the message names the field, the `$record` path and its position, for example:
12+
13+
`A { "$record": "account.cb_market" } comparand on field "cb_market" at filter.cb_market reached the server unresolved, and is refused rather than compared.`
14+
15+
- Before: the eq shorthand `{ cb_market: { $record: "account.cb_market" } }` reached the driver, which refused it in its own words: driver-memory as an unsupported operator `"$record"`, driver-sql with the operator and field withheld. Both were already `INVALID_FILTER` / 400 (driver-mongodb refuses an unknown operator the same way), so on the built-in drivers no filter that answered rows now refuses: the pass judges only a field's comparand, never a value inside one (see Unchanged).
16+
- Now: that shape is refused by name before any driver is asked, on every engine verb and in the analytics service, whether or not the filter also holds a string placeholder. On the engine's object path the other five operators (`{ valid_from: { $lte: { $record: "…" } } }`) and the eq shorthand on a date, datetime or time column are still refused one door earlier, in that door's own words, as before. The engine lowers a `[field, op, value]` array `where` before the pass, so there the array spelling is judged as its object form; the analytics service hands the pass its `where` unlowered, and the pass leaves a tuple to the doors that judged it before.
17+
- Unchanged: a `{ $record }` deeper inside a comparand is a deep-equality literal (or a nested-relation condition) and passes through as before, in either spelling: the object form `{ attachment: { meta: { $record: "x" } } }`, which driver-memory still compares whole, and the tuple `['attachment', '=', { meta: { $record: "x" } }]`, whose third member is a comparand, never a filter node. Both come back from the pass by reference (pinned as CONTROLs on `resolveFilterTokens`).
18+
19+
The `value` and `lookupFilters` describes now say what holds on the server: an unresolved `{ $record }` is refused with `INVALID_FILTER`, never read as null, and, in `lookupFilters`, by name on the eq shorthand of a column other than a date, datetime or time column. Their picker sentences (a record form sends the referenced value; every other picker host leaves the entry out) are not changed by this entry.

‎content/docs/references/data/field.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ const result = CurrencyConfigSchema.parse(data);
9393
| **descriptionField** | `string` | optional | Secondary field shown under the label in the quick-select popover. |
9494
| **lookupColumns** | `(string \| { field: string; label?: string; width?: string; type?: string })[]` | optional | Explicit columns for the record-picker table; auto-derived from the referenced object when omitted. |
9595
| **lookupPageSize** | `integer` | optional | Rows per page in the record-picker dialog (default 10). |
96-
| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused, never read as null. The picker narrows the choice only: a rule the save must enforce belongs on the server too. |
96+
| **lookupFilters** | `{ field: string; operator: Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>; value: any; orEmpty?: boolean }[]` | optional | Base filters restricting which records are selectable (e.g. only active). The structured, picker-honoured lookup filter. Each entry compares a column of the CANDIDATE record (`field`, on the referenced object) with `value`. A value may read the record being edited as `{ $record: "field" }` or `{ $record: "lookup_field.field" }` (at most one lookup hop). In a record form, whatever its layout, the picker sends that value in its place and re-queries whenever a referenced field changes; every other picker host leaves every `{ $record }` entry out: inline edit on a record page, a record page's header or related list, an action's parameter dialog, and a picker with no single record being edited (a bulk action over selected rows). The referenced fields are implied: do not list them in `dependsOn`, which also scopes the candidate query by equality (`dependsOn: ['quote_date']` adds `quote_date = …` to the query over the referenced object). While the value is empty or cannot be read (the hop's row or field does not come back, no object is named for the hop, or the host has no single-row reader), the entry is left out. A `{ $record }` is the whole value, never a member of an `in` / `notIn` list. `orEmpty: true` also matches a candidate whose column is null. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null: by name, naming the field and the path, when it arrives as the eq shorthand on a column other than a date, datetime or time column; any other operator, and eq on a date, datetime or time column, is refused earlier, in generic words. The picker narrows the choice only: a rule the save must enforce belongs on the server too. |
9797
| **dependsOn** | `(string \| { field: string; param?: string })[]` | optional | Declares that this field's available values depend on the value of other field(s) on the same record — the form gates the field until they are set and re-evaluates as they change. For `lookup`/`master_detail` it scopes the candidate query (string = same local/remote key; `{field,param}` when the remote filter key differs — the `{field,param}` form is lookup-only). For `select`/`multiselect`/`radio` the actual per-option rule lives in each option's `visibleWhen`; list the referenced fields here (string form) so the option list gates and refreshes with the parent. |
9898
| **allowCreate** | `boolean` | optional | Allow inline quick-create from the record picker: when no match exists the user can create a record from the typed text (optimistic dataSource.create with the display field). Best for simple objects whose only required field is the display field. |
9999
| **lookupAutofill** | `{ target: string; source: string; overwrite?: boolean }[]` | optional | Fields a pick in this lookup fills on the record being edited: each `{ target, source }` pair copies the picked record's `source` field (a field of the `reference` object) into this object's `target` field — e.g. `[{ target: 'unit_price', source: 'list_price' }]` on a quote line's product lookup. Read wherever this field is picked: the record form, and a line-item grid column over it. OVERWRITE RULE — the default, `overwrite` absent or false: a pick never replaces a value somebody wrote. The target is filled only while it is empty or still holds the value an earlier pick filled in; a value the user typed, or one the record already stored, stays. Only a pair that declares `overwrite: true` replaces the target on every pick, whatever it holds. Client-side only: it fills the form, and nothing on the write path reads it — the filled value is saved as an ordinary write, and an import or API write that sets the lookup fills nothing. Only on a single-value `lookup` / `master_detail`. Each target is a field of this object other than this one, written by its author — not `readonly`, not computed (`formula`, `summary`, `autonumber`, or an `expression`) — and named once. Each source is a field of the referenced object that the record carries (not `internal`) and whose value the target can hold; `os validate` / `os build` judge the source. In a line-item grid the column key `autofill` still governs only the same-named copy and is unchanged; a declared pair takes its target out of that copy. |
@@ -242,7 +242,7 @@ const result = CurrencyConfigSchema.parse(data);
242242
| :--- | :--- | :--- | :--- |
243243
| **field** | `string` | ✅ | |
244244
| **operator** | `Enum<'eq' \| 'ne' \| 'gt' \| 'lt' \| 'gte' \| 'lte' \| 'contains' \| 'in' \| 'notIn'>` | ✅ | |
245-
| **value** | `any` | ✅ | The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a `{ $now: true, addDays }` comparand for a date relative to today, or a `{ $record: "path" }` reference to the record being edited — a field of it, or one lookup hop ("account.cb_market"); a `{ $record }` value pairs only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced value in place of the reference; every other picker host leaves the entry out. |
245+
| **value** | `any` | ✅ | The comparand: a literal (an array for `in` / `notIn`), a date placeholder such as `{today}` or a `{ $now: true, addDays }` comparand for a date relative to today, or a `{ $record: "path" }` reference to the record being edited — a field of it, or one lookup hop ("account.cb_market"); a `{ $record }` value pairs only with eq, ne, gt, lt, gte or lte. In a record form, whatever its layout, the picker sends the referenced value in place of the reference; every other picker host leaves the entry out. A `{ $record }` that reaches a server unresolved is refused (INVALID_FILTER), never read as null. |
246246
| **orEmpty** | `boolean` | optional | TRUE: the entry also matches a candidate whose column is null — "valid from the quote date, or with no start date". Only with eq, ne, gt, lt, gte or lte. The picker sends the comparison or a null match on the same column. |
247247

248248
### Nested Shape: `Field.lookupAutofill[number]`

0 commit comments

Comments
 (0)