diff --git a/.changeset/37386-sort-door-reads-projection-predicate.md b/.changeset/37386-sort-door-reads-projection-predicate.md new file mode 100644 index 00000000000..8a5a01d7926 --- /dev/null +++ b/.changeset/37386-sort-door-reads-projection-predicate.md @@ -0,0 +1,14 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +refactor(metadata-protocol): the Data API's sort door judges a computed field type by the predicate the sortability projection reads + +Clause-②: no +Metadata-protocol: none + +`GET /data/:object?sort=` and every other sort that reaches `findData` refuse an order by a field whose type is computed on read (`400 INVALID_SORT`). The door decided "computed on read" from a set of its own, `formula` alone. The sortability projection served on `GET /meta/object/:name` (`resolveObjectSortability`, `reason: 'virtual-type'`) decided the same thing from `@objectstack/spec/data`'s `isVirtualSearchField`. The door now reads that predicate too, as its filter and search checks already did, so one place answers which field types have no column to order by. + +Nothing changes for a caller: both sets held `formula` and nothing else, so every sort is accepted or refused as before, with the same code, status and message. What changes is what happens when a computed type is added: it is added in the spec's `SEARCH_VIRTUAL_TYPES`, and the Data API door, the projection, the list header and the Sort picker follow together. Before, a type added to one set alone left the grid offering a sort the Data API refused, or the Data API refusing a computed type in the words it uses for a field that declares `sortable: false`. + +What to do: nothing. diff --git a/docs/adr/0160-record-scoped-ai-inquiry.md b/docs/adr/0160-record-scoped-ai-inquiry.md index caa8a050063..66467dcda3c 100644 --- a/docs/adr/0160-record-scoped-ai-inquiry.md +++ b/docs/adr/0160-record-scoped-ai-inquiry.md @@ -1,6 +1,6 @@ # ADR-0160: Record-scoped AI inquiry — a context pack is its own metadata type, read as the caller and served by one tool; conversation focus, the `ask_ai` action type, the skill `context` key, the citation shape -**Status**: Accepted — merged 2026-11-24 (PR [objectstack#37115](https://github.com/objectstack-ai/objectstack/pull/37115)); amended 2026-11-25 and 2026-11-26 (see **Amended** below). Written 2026-11-24 for objectstack#36997 (epic objectstack#36996) on the maintainer's acceptance of the epic's decision list that day, verbatim as the epic records it: 「需要拍板的事项 都同意」. It stands on cloud ADR-0119 (Accepted 2026-11-24), which rules this mechanism open source ([Provenance](#provenance)). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema, no code, no changeset, and no anchor under `scripts/adr-anchors/`; every mechanism below is cut as a card after the merge ([Implementation split](#implementation-split-after-acceptance)). +**Status**: Accepted — merged 2026-11-24 (PR [objectstack#37115](https://github.com/objectstack-ai/objectstack/pull/37115)); amended 2026-11-25, 2026-11-26 and 2026-11-27 (see **Amended** below). Written 2026-11-24 for objectstack#36997 (epic objectstack#36996) on the maintainer's acceptance of the epic's decision list that day, verbatim as the epic records it: 「需要拍板的事项 都同意」. It stands on cloud ADR-0119 (Accepted 2026-11-24), which rules this mechanism open source ([Provenance](#provenance)). `docs/adr/**` is Tier H (Prime Directive #14): this record becomes **Accepted** by an authorized approval or the maintainer's merge of the PR that carries it, and is in force from that merge. **This record declares; it implements nothing** — no schema, no code, no changeset, and no anchor under `scripts/adr-anchors/`; every mechanism below is cut as a card after the merge ([Implementation split](#implementation-split-after-acceptance)). - **Date**: 2026-11-24 - **Amended**: 2026-11-25, by the maintainer's word, verbatim: 「同意你的建议」. The maintainer was answering two independent analyses of this record, written in the maintainer's session on 2026-11-25 for [objectstack#36996](https://github.com/objectstack-ai/objectstack/issues/36996). One weighed points 1, 2 and 10 of [Points that go past the card's words](#points-that-go-past-the-cards-words), which this record said needed the maintainer's explicit acceptance. The other reviewed the six cards cut from the [Implementation split](#implementation-split-after-acceptance). The amendment records the following: @@ -37,6 +37,16 @@ - **`anchor` and `outlineFrom` are exclusive.** A call that names both is refused before any gate is judged and any record is read. See [D4](#d4), "Definition". - The text's own settlement is point 24 of [Points that go past the card's words](#points-that-go-past-the-cards-words). - Nothing else changes. +- **Amended**: 2026-11-27, a fifth time, to bring the text level with `main` in the places below. This amendment is card [objectstack#37386](https://github.com/objectstack-ai/objectstack/issues/37386). It follows PR [objectstack#37354](https://github.com/objectstack-ai/objectstack/pull/37354), which built row 11 for card objectstack#37203, and the review of the fourth amendment's PR objectstack#37573 (record 7194836142, nits N1–N3). It rests on no ruling of its own: it writes down what `main` does, and it is accepted with the approval or the merge of the PR that carries it. Its readings of the tree were taken on `main` at `7e638ba7`. It records the following: + - **An `orderBy` field the child does not offer as a sort is an author defect.** Validation reports it as `ai-context-sort-field-unsortable`, and the tool leaves the section out and states nothing. See [D1](#d1), "Author defects are reported on author surfaces". The text's own settlement is the note this amendment adds to point 20 of [Points that go past the card's words](#points-that-go-past-the-cards-words). + - **The tool's input row lists every alias, and says that none is accepted.** The schema names seven other spellings, for `objectName`, `recordId`, `context` and `anchor`. A call that uses one is refused, and the refusal names the declared key. The row also says that `outlineFrom` is an integer, 0 or more. See [D4](#d4), "Definition". + - **The `outlineFrom` refusal lists one more reason**: a `body` that names a field that is not a long-text field, or that the root does not have. See [D3](#d3), "Outline pages". + - **Point 24 names its one exception**: a heading too long for any page to list is issued no anchor. + - Nothing else changes. +- **Amended**: 2026-11-27, a sixth time, by the maintainer's ruling on card [objectstack#37486](https://github.com/objectstack-ai/objectstack/issues/37486) (record 7208943876). The maintainer chose option B of that card's decision analysis (7207825366), whose text reads, verbatim: 「B 采用修复」「只在确有资料被隐藏时才提示;设计文档先改一句并写明这个信号(需审批人批准),再合入写好的修复。看到提示就能确定确有其物。」 This amendment rides the PR of card objectstack#37386 with the fifth, and it comes before the code. PR [objectstack#37751](https://github.com/objectstack-ai/objectstack/pull/37751) builds it, was read there at `cb1a47e9`, and waits for this text. Until that PR merges, `main` reads nothing of such a child, and tells every caller of a pack that names an object the stack does not define that some material is not visible. It records the following: + - **A left-out child's published definition is asked one question**: whether the stack defines the object at all. A `related` object the stack does not define then states nothing, as [D1](#d1) says of an author defect. See [D3](#d3), "Object level". + - **What the statement signals.** It now means that something the stack defines is hidden from this caller, so a caller who knows the pack's names can infer that such an object exists. The field-level rule of [D3](#d3) already makes this trade for fields. The record tools are not changed: a name the caller typed is still answered alike whether the object is hidden or does not exist (Context, "What a refusal names"). + - Nothing else changes. - **Decided by**: the maintainer, 2026-11-24, verbatim and untranslated, as epic [objectstack#36996](https://github.com/objectstack-ai/objectstack/issues/36996) records them: 「先立专题 ① 记录范围 AI 问询 ;⑤ 应用技能进入应用内 AI ,M0 那几项知识服务缺陷 也立专题,目前开发的策略是按专题派」 and 「需要拍板的事项 都同意」. The six rulings the epic sets over every child are quoted in [Provenance](#provenance); ⛔ none of them is re-opened here. - **Card**: [objectstack#36997](https://github.com/objectstack-ai/objectstack/issues/36997). It lists ten items; D1–D9 decide items 1–9 in the card's order and [Not decided here](#not-decided-here) carries item 10. - **Builds on**: [ADR-0005](./0005-metadata-customization-overlay.md) (its ai row: a behavioural contract takes no environment overlay), [ADR-0011](./0011-actions-as-ai-tools.md) (an action reaches AI only through its `ai` exposure block), [ADR-0049](./0049-no-unenforced-security-properties.md) (enforce or remove), [ADR-0088](./0088-metadata-kind-admission-and-retirement.md) (the kind admission test), [ADR-0090](./0090-permission-model-v2-concept-convergence.md) D10 (the agent ceiling over reads), [ADR-0106](./0106-metadata-plane-fls-object-schema-masking.md) (the caller's served schema), [ADR-0112](./0112-error-code-vocabulary-and-ledger.md) (the error envelope and its catalogue), [ADR-0149](./0149-ai-answers-business-questions-through-the-dataset-semantic-layer.md) D2 and M1 (one definition, one executor, every transport; guidance sentences belong to the executor), [ADR-0159](./0159-forms-are-their-own-metadata-type-public-forms-are-form-items-view-is-lists-only.md) (the latest kind admission; the form of D1). @@ -159,7 +169,7 @@ The link filter stays the service's: `where` is joined to it with `$and`, so no **Registration (proposal, row 5 lands it).** One entry on each surface listed in Context. The registry row takes the `skill` row's flags, for the `skill` row's reason: a file loader (`**/*.ai-context.ts`, `**/*.ai-context.yml`), `supportsOverlay: true`, `allowRuntimeCreate: true`, `allowEnvironmentOverlay: false` (ADR-0005's ai row), `domain: 'ai'`; collection key `aiContexts`; a liveness row per key; a `KIND_COVERAGE` row with an example pack. -**Author defects are reported on author surfaces.** A pack that names an object or field that does not exist, a `related` entry with no reference field to the root, a `where` or `orderBy` that names a field the child does not have, or a `body.field` that is not a long-text field is reported by metadata validation at save and by `os validate`. An operator outside `where`'s admitted set, or a comparand that is a whole `{…}` placeholder, is refused at parse, before any of this. ADR-0149 D2 is the precedent: a dataset member no caller could be served is reported on an author surface, and the tool answer says nothing about it ([D3](#d3)). +**Author defects are reported on author surfaces.** A pack that names an object or field that does not exist, a `related` entry with no reference field to the root, a `where` or `orderBy` that names a field the child does not have, or a `body.field` that is not a long-text field is reported by metadata validation at save and by `os validate`. So is an `orderBy` that names a field the child has and does not offer as a sort (fifth amendment, 2026-11-27): one the child's sortability projection answers `sortable: false` for (`packages/spec/src/api/sortability.zod.ts#resolveObjectSortability`), which on `main` at `7e638ba7` is a `formula` field or a field whose author declared `sortable: false`. Its rule id is `ai-context-sort-field-unsortable` (`packages/lint/src/validate-ai-context.ts#AI_CONTEXT_SORT_FIELD_UNSORTABLE`). Both MCP doors refuse an order by such a field with `INVALID_SORT`, which would refuse the whole call. So the tool judges the field before the query, on the published definition, and leaves that `related` section out of every caller's answer with nothing stated. An operator outside `where`'s admitted set, or a comparand that is a whole `{…}` placeholder, is refused at parse, before any of this. ADR-0149 D2 is the precedent: a dataset member no caller could be served is reported on an author surface, and the tool answer says nothing about it ([D3](#d3)). **Advisory reports (amended 2026-11-25, point 1's third condition).** Two configurations are legal but leave a call to fail at run time. Validation reports each one as an advisory warning, never an error: @@ -203,7 +213,7 @@ The render service takes a pack, a record id and the caller, and returns the pac **Object level (amended 2026-11-25).** The objects are judged in steps 1 and 3, by the gates the record tools put before the same read. This record adds no gate and skips none. What a refusal does depends on whom it refuses. - **A refusal that applies to everyone refuses the whole call.** The door serves a `related` child to nobody — the system-object refusal, or API exposure turned off — or a gate refuses a surviving lookup's target. The call is refused in the record tools' envelope, and no partial pack is returned. This is an author defect: it shows on the first test call, whoever makes it. This is the #35145 rule (`packages/mcp/src/mcp-relation-reads.ts`) applied to a pack. -- **A `related` child that this caller is not served is left out.** This is the object-level visibility of ADR-0106's 2026-11-11 amendment. Nothing of the child is read, its definition included. Its section is not named. The notes carry the one statement of the field-level rule below: some of the material this pack covers is not visible to the caller. The child is judged before projection, as before, so projection never reads it. The pack still answers with the sections the caller may read. The reason: object permissions are configured per deployment, while a pack is authored and shipped with an application. A deployment that narrows one role's object access should shorten that role's pack, not switch it off. A refusal would also tell the caller nothing a statement does not. +- **A `related` child that this caller is not served is left out.** This is the object-level visibility of ADR-0106's 2026-11-11 amendment. Nothing of the child is read except its published definition, which is asked once, for whether the stack defines the object at all (sixth amendment, 2026-11-27): a name the published definitions lack is an author defect ([D1](#d1)), left out with no statement for every caller. The published definition is the same for every caller, so whether the statement fires depends on this caller's served schema alone, and nothing of the definition is carried. The statement therefore now means that something the stack defines is hidden from this caller, so a caller who knows the pack's names can infer that such an object exists. That is the trade the field-level rule below already makes for fields, where the statement fires only for an entry the published definition has. Its section is not named. The notes carry the one statement of the field-level rule below: some of the material this pack covers is not visible to the caller. The child is judged before projection, as before, so projection never reads it. The pack still answers with the sections the caller may read. The reason: object permissions are configured per deployment, while a pack is authored and shipped with an application. A deployment that narrows one role's object access should shorten that role's pack, not switch it off. A refusal would also tell the caller nothing a statement does not. The root object's gates are unchanged ([D4](#d4), "Order of judgement"). A root the caller is not served answers as `get_record` answers. The refusal names the refused object only when the caller's served schema shows it, and every such refusal carries one code ([D4](#d4), "The naming bound"). Where the record tools do not refuse, the pack does not either: a lookup whose target the caller may not read is left unexpanded by the engine, and the row-level rule below renders it. @@ -233,7 +243,7 @@ This is how ruling 2's sentence — "A field hidden from the caller reads 'not v - **What a walk covers.** Within one state of the body, every heading is listed on exactly one page, with its anchor, so following `outlineNext` from the first page lists them all. The one exception is a heading whose entry alone passes the body bound. No page lists it and no anchor is issued for it; the cut statement counts it. - **One state of the body.** `outlineFrom` is a position in the page order of the body as the call reads it, and the tool keeps nothing between calls. If the body is edited between two page calls, the later call answers the page at that position of the body as it then is, or is refused as below where that body has nothing left to list from it. The walk can then skip a heading or list one twice, and nothing in the answer says so. The anchors on each page are still current: they are derived from the body that call read. - **The notes, on every page.** Every page carries the statement that the body is given as an outline. Every page that does not list all of the body's headings carries the cut statement: how many headings the page lists, how many it does not, and the `outlineFrom` of the next page, or that no later page lists more. That statement carries counts and a position, never an anchor: a note never carries record text, and an anchor is derived from heading text. That is why the cursor is a position. -- **A page that does not exist.** An `outlineFrom` above 0 with no heading left to list from it is refused, never answered with the first page. The refusal is one answer whatever the reason, with the code an `anchor` that does not resolve gets (`RESOURCE_NOT_FOUND`, 404): a position past the last heading a page lists, a body carried whole or cut without an outline, a pack with no `body`, a body the caller's projection dropped, or a body withheld from the caller. So `outlineFrom`, like `anchor`, cannot show that a pack has a body the caller's schema hides. `outlineFrom` 0 is the first page. +- **A page that does not exist.** An `outlineFrom` above 0 with no heading left to list from it is refused, never answered with the first page. The refusal is one answer whatever the reason, with the code an `anchor` that does not resolve gets (`RESOURCE_NOT_FOUND`, 404): a position past the last heading a page lists, a body carried whole or cut without an outline, a pack with no `body`, a pack whose `body` names a field that is not a long-text field or that the root does not have (an author defect, [D1](#d1); fifth amendment, 2026-11-27), a body the caller's projection dropped, or a body withheld from the caller. So `outlineFrom`, like `anchor`, cannot show that a pack has a body the caller's schema hides. `outlineFrom` 0 is the first page. **The bound on carried text (amended 2026-11-25).** A related list's columns may include long-text fields, and their values are carried as served, within one bound. Text the pack carries counts toward one total bound: the body, and every long-text value in the related lists' cells. @@ -258,7 +268,7 @@ The framing sentence covers the data member only, so it does not undo a note. Sp **Definition.** Input and output are zod in `@objectstack/spec`, in a new module beside the dataset tools' module, projected to JSON Schema the way `packages/spec/src/ai/dataset-tools.zod.ts#getDatasetToolJsonSchemas` does. This follows the dataset tools' form, not the knowledge tool's. -- Input, strict: `{ objectName: string, recordId: string, context?: string, anchor?: string, outlineFrom?: integer }`, with the record tools' aliases for the first two. `anchor` reads one section of the body and `outlineFrom` lists one page of its outline ([D3](#d3), "Outline pages"; fourth amendment, 2026-11-26), so a call names at most one of them. A call that names both is refused `VALIDATION_ERROR` (400) in step 1 of the order below, before any gate is judged and any record is read. +- Input, strict: `{ objectName: string, recordId: string, context?: string, anchor?: string, outlineFrom?: integer }`. `outlineFrom` is an integer, 0 or more; a negative or fractional one is refused at parse. The schema also names seven aliases, each a spelling a caller may reach for in place of a declared key (`packages/spec/src/ai/record-context-tools.zod.ts#GetRecordContextInputSchema`; fifth amendment, 2026-11-27): `object` and `table` for `objectName`, and `id` and `record_id` for `recordId`, which are the record tools' aliases; `pack` and `contextName` for `context`; and `section` for `anchor`. An alias is not accepted. The input is strict, so a call that uses one is refused at parse like any unknown key, and the refusal names the declared key to write. `anchor` reads one section of the body and `outlineFrom` lists one page of its outline ([D3](#d3), "Outline pages"; fourth amendment, 2026-11-26), so a call names at most one of them. A call that names both is refused `VALIDATION_ERROR` (400) in step 1 of the order below, before any gate is judged and any record is read. - Output: the D3 envelope, with its three parts — the data member, the notes and the framing sentence. The data member holds the pack header (`name`, `label`), the record (`object`, `id`, display name), the field entries, the related lists and the body or its outline. An outline page that leaves headings for a later page carries `outlineNext` on the body: the `outlineFrom` of the next page (fourth amendment, 2026-11-26). **Order of judgement.** The steps run in this order, and no later step changes an earlier answer: @@ -392,7 +402,7 @@ Each is this record's settlement, taken from the tree's precedent. Points 1, 2 a 17. **A whole `{token}` comparand is refused at parse** (D1), beside the `$now` anchor: `{today}`, `{now}`, `{current_user_id}`, `{record_id}`, and any token the platform does not know. The data engine would resolve such a string at call time. The pack's selection would then read the clock or the caller, and an unknown token or `{record_id}` would fail every caller's call. The alternative not taken is a list of admitted tokens; placeholders resolved at call time are later work. 18. **`orderBy` is `{ field, order }[]`** (D1), the tree's sort node. The direction is spelled `order`, and that schema refuses `direction` by name. With no `orderBy` the read names no order, because the data engine adds none. 19. **A `where` or `orderBy` field the caller cannot query on drops the section** (D3), stated and never named. The card says "hidden". "Cannot query on" is every field outside the security service's `getQueryableFields` answer: besides the hidden field, it takes in the field the schema shows and field-level security withholds, the field served masked, and the others D3 lists. Under the narrower rule those callers would get a whole-call refusal from the engine's guard, where this record says a field-level rule omits and states. -20. **A `where` or `orderBy` field the published definition lacks leaves the section out** (D1, D3). It is an author defect, reported at save and by `os validate`, and the answer states nothing. The alternative not taken is to run the filter without that condition, which would carry rows the author excluded. +20. **A `where` or `orderBy` field the published definition lacks leaves the section out** (D1, D3). It is an author defect, reported at save and by `os validate`, and the answer states nothing. The alternative not taken is to run the filter without that condition, which would carry rows the author excluded. *Fifth amendment, 2026-11-27:* an `orderBy` field the child has and does not offer as a sort leaves the section out the same way (D1). It is judged after a field the definition lacks and before the caller's own fields, so the answer is the same for every caller. PR objectstack#37354 settled it, and this record's words had stopped at the field the definition lacks. The alternatives not taken are the MCP doors' own answer, an `INVALID_SORT` that refuses the whole call for every caller, and reading the list with that field taken out of its order. 21. **A list cut at its own `limit` is a stated cut** (D3), like a list cut at the cap, so the model knows that more rows matched than it was given. 22. **The cap on an outline's entries is named** (D3, "The body"). This point is not about `related` and is not from the maintainer's word. The seat's review of PR objectstack#37222 (card objectstack#37178), nit N5, asked this record to name that cap as a further constant of the service and a further stated cut. The record sets no number. @@ -402,7 +412,7 @@ Each is this record's settlement, taken from the tree's precedent. Points 1, 2 a **The fourth amendment's point (2026-11-26).** The fourth amendment records what PR objectstack#37484 shipped and rests on no ruling of its own. So its text is this record's settlement, accepted with the PR that carries the amendment, and it is listed as one point. -24. **A long outline is paged on the same tool, by a position** (D3, D4). `outlineFrom` joins `anchor` on `get_record_context`, as point 4 keeps a section read on that tool, and a call that names both is refused. The cursor is a position in the body's page order and not an anchor, because the note that says where to continue may carry no record text. So a walk holds for one state of the body, and an edit between two page calls is not signalled. The alternative that PR weighed and did not take is one answer that lists every omitted heading's anchor compactly: for a large enough body it passes the same bound and needs a cut of its own. +24. **A long outline is paged on the same tool, by a position** (D3, D4). `outlineFrom` joins `anchor` on `get_record_context`, as point 4 keeps a section read on that tool, and a call that names both is refused. The cursor is a position in the body's page order and not an anchor, because the note that says where to continue may carry no record text. So a walk holds for one state of the body, and an edit between two page calls is not signalled. One kind of heading stays outside every walk (fifth amendment, 2026-11-27): a heading whose entry alone passes the body bound is listed on no page and issued no anchor, so the outline gives no way to read its section by itself. The cut statement counts such headings. A body whose headings are all that long has no outline to cut: it is carried up to the bound and marked truncated, as a long body with no headings is. The alternative that PR weighed and did not take is one answer that lists every omitted heading's anchor compactly: for a large enough body it passes the same bound and needs a cut of its own. ## Implementation split (after acceptance) diff --git a/packages/metadata-protocol/src/protocol-query-validation.ts b/packages/metadata-protocol/src/protocol-query-validation.ts index 69c71bdf5cd..b7e0ffe20d1 100644 --- a/packages/metadata-protocol/src/protocol-query-validation.ts +++ b/packages/metadata-protocol/src/protocol-query-validation.ts @@ -94,42 +94,6 @@ const AGGREGATION_FUNCTIONS: ReadonlySet = new Set(AggregationFunction.o const DATE_GRANULARITIES: ReadonlySet = new Set(DateGranularity.options); -/** - * [#6994] Field types whose value NO driver materialises, so no driver can - * ORDER BY them. - * - * `formula` is the whole set today, and deliberately not a synonym for - * "computed": the three computed types diverge exactly here. - * - * | type | column | sortable | - * |---|---|---| - * | `formula` | none — `SqlDriver.createColumn` returns early; `driver-turso`'s transport skips it with the same `Virtual — no column` note | **no** | - * | `summary` | an engine-maintained numeric column — `table.decimal` on tables created since #16318, `table.float` on earlier ones | yes (measured #6924: `orderBy desc` -> E D C B A over 5 4 3 2 1) | - * | `autonumber` | `table.string`, engine-assigned | yes | - * - * So the spec's own `COMPUTED_VALUE_TYPES` (`formula`/`summary`/`autonumber`) - * is the WRITE contract — "never client-written" — and is the wrong set to - * gate a sort with: it would refuse the two types that sort correctly. - * - * This is a local set rather than a shared spec constant because the same fact - * is currently spelled in five places, none of them in `packages/spec`: - * `driver-sql`'s `fieldHasColumn` and `createColumn`, `driver-turso`'s - * `remote-transport`, `objectql`'s `planFormulaProjection` and - * `search-companion`, and `plugin-audit`'s `VIRTUAL_FIELD_TYPES`. - * Consolidating them is a cross-package change and is filed separately; adding - * a sixth local spelling here — with that ledger written down — keeps this fix - * inside one package rather than opening a spec-wide edit for one string. - * - * One deliberate divergence from `fieldHasColumn`: that helper short-circuits - * on `multiple` (a `multiple` field is a JSON column whatever its type), so it - * would answer "has a column" for a `multiple` formula. This set does not, - * because the questions differ — `fieldHasColumn` asks whether DDL emits a - * column, this asks whether there is a persisted VALUE to order by, and a - * formula's value is computed on read and never written, so that JSON column - * is always empty. Ordering by it degrades exactly as the bare case does. - */ -const UNMATERIALIZED_SORT_TYPES: ReadonlySet = new Set(['formula']); - /** * [#4254] An aggregation-axis value (`groupBy` / `aggregations`) whose SHAPE * the spec's `QueryAST` cannot read — a non-array, an entry that names no @@ -615,8 +579,8 @@ export function assertSortFieldsExist( // [#6994] The third verdict on this axis: a name that is a REAL, // non-dotted field of this object and still cannot be ordered by, - // because its TYPE materialises no column ({@link - // UNMATERIALIZED_SORT_TYPES} — `formula`, today the whole set). + // because its TYPE materialises no column ({@link isVirtualSearchField} + // / `SEARCH_VIRTUAL_TYPES` — `formula`, today the whole set). // // This is the shape the doc comment above already describes and this // gate already let through: being in `gate.known` is what carried it @@ -641,9 +605,25 @@ export function assertSortFieldsExist( // therefore unchanged verdict-for-verdict, and a dotted path whose head // is a formula field keeps the dotted answer (it is wrong about the // shape too, and the shape is what the caller wrote). - const unmaterialized = names.filter( - (f) => UNMATERIALIZED_SORT_TYPES.has(String(gate.fields[f]?.type ?? '')), - ); + // + // ONE SOURCE — judged by {@link isVirtualSearchField}, the + // `@objectstack/spec/data` predicate the served sortability projection + // reads for its `virtual-type` verdict ({@link resolveObjectSortability}) + // and the filter and search axes of this file read too. This door used + // to carry a set of its own for the same fact (`UNMATERIALIZED_SORT_TYPES`, + // `formula` alone, retired here): two one-member sets that agreed only + // while neither grew. A type added to this door's alone is a sort the + // grid offers and this door refuses; one added to the spec's alone is + // refused by the fourth verdict below, worded as an author's + // `sortable: false`. `protocol.sort-door-projection-agreement-37386.test.ts` + // holds this verdict to the projection for every `FieldType`. + // + // The predicate is the STORAGE fact, and deliberately not the spec's + // `COMPUTED_VALUE_TYPES` (`formula` / `summary` / `autonumber`), which is + // the WRITE contract: `summary` and `autonumber` have stored columns and + // sort correctly (`SEARCH_VIRTUAL_TYPES`' docblock, and the projection's + // "Considered and deliberately NOT members"). + const unmaterialized = names.filter((f) => isVirtualSearchField(gate.fields[f])); if (unmaterialized.length === 0) { assertSortFieldsAreOffered(gate.schema, object, names, param); return; diff --git a/packages/metadata-protocol/src/protocol.sort-door-projection-agreement-37386.test.ts b/packages/metadata-protocol/src/protocol.sort-door-projection-agreement-37386.test.ts new file mode 100644 index 00000000000..99633d083bd --- /dev/null +++ b/packages/metadata-protocol/src/protocol.sort-door-projection-agreement-37386.test.ts @@ -0,0 +1,118 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Data API's sort door and the served sortability projection answer one + * question — is this field's TYPE computed on read, with no column to order + * by — from one source, `isVirtualSearchField` (`@objectstack/spec/data`). + * + * The door (`assertSortFieldsExist`, third verdict) used to judge it by a set + * of its own, `formula` alone, while the projection + * (`resolveObjectSortability`, `reason: 'virtual-type'`) read the spec's. Two + * one-member sets agree only while neither grows: + * + * - a type added to the door's alone is a sort the grid offers (the + * projection still says `sortable: true`) and the Data API refuses; + * - a type added to the spec's alone is still refused, by the door's FOURTH + * verdict, which reads the projection and words every refusal as an + * author's `sortable: false` — the wrong reason for a computed type. + * + * So this file does not copy a verdict table. For EVERY member of the spec's + * `FieldType` it asks the projection, then holds the door to that answer, and + * it tells the door's third verdict from its fourth without reading a + * sentence: the third names the computed fields alone, the fourth names every + * field the projection calls unsortable. Sorting by the field under test AND + * by a companion that declares `sortable: false` therefore answers + * + * third verdict → `fields: []` + * fourth verdict → `fields: []` (type not computed) + * `fields: [, ]` (the two parted) + * + * and the third row is what the old local set answers the day the spec's set + * grows without it. + */ + +import { describe, it, expect, vi } from 'vitest'; +// `./protocol.js` reaches `@objectstack/lint` only through a dynamic import; paid +// here at module scope so the first load lands during collection, not inside a +// clocked window (`pnpm check:test-source-alias`). +import '@objectstack/lint'; +import { resolveObjectSortability } from '@objectstack/spec/api'; +import { FieldType } from '@objectstack/spec/data'; +import { ObjectStackProtocolImplementation } from './protocol.js'; + +const OBJECT = 'sort_agreement_37386'; + +/** Every field type the spec knows, as the enum lists them. */ +const FIELD_TYPES: readonly string[] = FieldType.options; + +const fieldOf = (type: string) => `f_${type}`; + +/** A stored column whose author declared it unsortable: the door's fourth verdict, by construction. */ +const COMPANION = 'declared_unsortable'; + +const DEFINITION = { + name: OBJECT, + fields: { + ...Object.fromEntries(FIELD_TYPES.map((type) => [fieldOf(type), { name: fieldOf(type), type }])), + [COMPANION]: { name: COMPANION, type: 'text', sortable: false }, + }, +}; + +/** The projection's verdicts over the same definition the door's registry serves. */ +const PROJECTION = resolveObjectSortability(DEFINITION).fields; + +const computedByProjection = (type: string) => PROJECTION[fieldOf(type)]?.reason === 'virtual-type'; + +function makeProtocol() { + const find = vi.fn(async () => []); + const engine = { registry: { getObject: (name: string) => (name === OBJECT ? DEFINITION : undefined) }, find }; + return { protocol: new ObjectStackProtocolImplementation(engine as any), find }; +} + +/** What the door answers a sort by `fields`: the refusal it threw, or the `orderBy` it handed the engine. */ +async function sortBy(fields: readonly string[]) { + const { protocol, find } = makeProtocol(); + const orderBy = fields.map((field) => ({ field, order: 'asc' as const })); + try { + await protocol.findData({ object: OBJECT, query: { orderBy } }); + } catch (err) { + const refusal = err as { code?: unknown; status?: unknown; field?: unknown; fields?: unknown }; + return { refused: { code: refusal.code, status: refusal.status, field: refusal.field, fields: refusal.fields }, reads: find.mock.calls.length }; + } + const options = (find.mock.calls[0] as unknown[] | undefined)?.[1] as { orderBy?: unknown } | undefined; + return { applied: options?.orderBy, reads: find.mock.calls.length }; +} + +describe('the sort door and the sortability projection agree on which field types are computed (#37386)', () => { + it('the table is not empty on either side: the spec knows a computed type and a stored one', () => { + // Without both, every row below would agree about nothing. + expect(FIELD_TYPES.filter(computedByProjection), 'field types the projection calls virtual').not.toEqual([]); + expect(FIELD_TYPES.filter((type) => !computedByProjection(type)), 'field types the projection calls stored').not.toEqual([]); + // The companion is the fourth verdict's, whatever the field beside it. + expect(PROJECTION[COMPANION]).toEqual({ sortable: false, reason: 'author-declared' }); + }); + + it.each(FIELD_TYPES)('a sort by a `%s` field alone is refused exactly when the projection calls it unsortable', async (type) => { + const answer = await sortBy([fieldOf(type)]); + if (PROJECTION[fieldOf(type)]?.sortable === false) { + expect(answer).toEqual({ + refused: { code: 'INVALID_SORT', status: 400, field: fieldOf(type), fields: [fieldOf(type)] }, + reads: 0, + }); + } else { + // CONTROL — what the grid may offer, the Data API performs. + expect(answer).toEqual({ applied: [{ field: fieldOf(type), order: 'asc' }], reads: 1 }); + } + }); + + it.each(FIELD_TYPES)('a `%s` field gets the computed-type verdict exactly when the projection says `virtual-type`', async (type) => { + const answer = await sortBy([fieldOf(type), COMPANION]); + // The third verdict names the computed field alone and outranks the + // fourth; with no computed field the fourth names the companion alone. + const named = computedByProjection(type) ? fieldOf(type) : COMPANION; + expect(answer).toEqual({ + refused: { code: 'INVALID_SORT', status: 400, field: named, fields: [named] }, + reads: 0, + }); + }); +});