diff --git a/.changeset/37810-engine-sort-door-reads-virtual-predicate.md b/.changeset/37810-engine-sort-door-reads-virtual-predicate.md new file mode 100644 index 00000000000..7aae6784251 --- /dev/null +++ b/.changeset/37810-engine-sort-door-reads-virtual-predicate.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': patch +--- + +refactor(objectql): the engine's own sort door judges a computed field type by the spec's predicate, as the Data API's door does + +Clause-②: no +Metadata-protocol: none + +`ObjectQL.find` and `ObjectQL.findOne` refuse an order by a field whose type is computed on read (`400 INVALID_SORT`), for callers that reach the engine directly, such as hooks and flows. The engine decided "computed on read" from a `formula` literal of its own. The Data API's sort door and the sortability projection served on `GET /meta/object/:name` decide it from `@objectstack/spec/data`'s `isVirtualSearchField`. The engine door now reads that predicate too. + +Nothing changes for a caller: the spec's set holds `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 to the spec's `SEARCH_VIRTUAL_TYPES`: an in-process `find` is refused together with the Data API, instead of sending the order to a driver that has no column for it and returning the rows unsorted. + +What to do: nothing. diff --git a/packages/drivers/driver-sql/src/sql-driver-external-unprovisioned-sort-anchor.test.ts b/packages/drivers/driver-sql/src/sql-driver-external-unprovisioned-sort-anchor.test.ts index d913169e45d..2a4f9e03f32 100644 --- a/packages/drivers/driver-sql/src/sql-driver-external-unprovisioned-sort-anchor.test.ts +++ b/packages/drivers/driver-sql/src/sql-driver-external-unprovisioned-sort-anchor.test.ts @@ -44,12 +44,13 @@ // // - `assertSortFieldsExist` (`@objectstack/metadata-protocol`, `protocol.ts`, // #6994) — the REST ingress. Precedence `unknown` > `dotted` > -// unmaterializable; the third verdict filters `UNMATERIALIZED_SORT_TYPES`, -// which is `formula` alone. An injected anchor IS in `gate.known` (the -// registry injected it into the served schema) and is undotted. +// unmaterializable; the third verdict filters by `isVirtualSearchField` +// (`@objectstack/spec/data`, `SEARCH_VIRTUAL_TYPES`), which is `formula` +// alone. An injected anchor IS in `gate.known` (the registry injected it +// into the served schema) and is undotted. // - `assertOrderByIsMaterializable` (`@objectstack/objectql`, `engine.ts`, // #7095) — the engine's own boundary, for callers that never pass ingress: -// `schema.fields[f]?.type === 'formula'`, the same narrowing. +// the same `isVirtualSearchField`, the same narrowing. // // Both live in packages that sit ABOVE this one in the dependency graph // (`driver-sql` depends on `spec`/`core`/`types` only), so this file cannot @@ -255,9 +256,10 @@ describe('SORT over an unprovisioned injected anchor on a federated object (prem it("ANCHORS ARE NOT 'formula' — the type both SORT doors narrow on", () => { // Why both doors let this ORDER BY through, asserted from the spec's own - // injected definitions. `UNMATERIALIZED_SORT_TYPES` (metadata-protocol) and - // the engine's `=== 'formula'` are unreachable from this package; this is - // the same fact from the side this package CAN see. If an anchor ever + // injected definitions. The two doors (metadata-protocol's and the + // engine's) are unreachable from this package, and both judge by + // `isVirtualSearchField`, `formula` alone today; this is the same fact + // from the side this package CAN see. If an anchor ever // becomes a `formula`, the doors refuse it and this file's premise is gone. for (const anchor of ANCHORS) { const type = String((ANCHOR_DEFS as any)[anchor]?.type ?? ''); diff --git a/packages/lint/src/validate-sortable-fields.ts b/packages/lint/src/validate-sortable-fields.ts index 3350a4421af..a72c28a5a3a 100644 --- a/packages/lint/src/validate-sortable-fields.ts +++ b/packages/lint/src/validate-sortable-fields.ts @@ -101,9 +101,11 @@ * gating a sort with it would refuse the two types that sort CORRECTLY: * `summary` is a `table.float` maintained by the engine and `autonumber` a * `table.string` the engine assigns. The distinction is pinned by name in the - * engine's own conformance suite and restated in `protocol.ts`'s - * `UNMATERIALIZED_SORT_TYPES` note; widening here would produce the false - * finding that makes authors stop trusting the linter (ADR-0072 D1). + * engine's own conformance suite and restated at both runtime sort doors, + * which read `isVirtualSearchField` too (the "ONE SOURCE" notes on + * `assertSortFieldsExist`'s third verdict and `assertOrderByIsMaterializable`); + * widening here would produce the false finding that makes authors stop + * trusting the linter (ADR-0072 D1). * * ── Which sort positions are walked, and which were checked and are not ── * @@ -214,11 +216,11 @@ * carry since #8340. * * WHY THIS AXIS NEEDS ITS OWN AUTHORING ANSWER — neither runtime door refuses - * it. Both key on `formula` ALONE (`UNMATERIALIZED_SORT_TYPES`): the ingress - * gate's third verdict (`assertSortFieldsExist`, #6994) and the engine's - * (`assertOrderByIsMaterializable`, #7095). An injected anchor is a `datetime` - * or `lookup`, it IS in `gate.known` (the registry injected it into the served - * schema), and it is undotted — so it passes all three verdicts and reaches + * it. Both key on the computed type ALONE (`isVirtualSearchField`, `formula` + * today): the ingress gate's third verdict (`assertSortFieldsExist`, #6994) + * and the engine's (`assertOrderByIsMaterializable`, #7095). An injected + * anchor is a `datetime` or `lookup`, it IS in `gate.known` (the registry + * injected it into the served schema), and it is undotted — so it passes all three verdicts and reaches * the driver. Measured (#10474) with a real `SqlDriver` over better-sqlite3, * the object declared exactly as `examples/app-showcase` declares it, against * a remote `customers` table carrying `[id, name, email, region, diff --git a/packages/objectql/src/engine-sort-door-agreement.test.ts b/packages/objectql/src/engine-sort-door-agreement.test.ts new file mode 100644 index 00000000000..00d9fd3582e --- /dev/null +++ b/packages/objectql/src/engine-sort-door-agreement.test.ts @@ -0,0 +1,117 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The engine's own sort door and the Data API's sort door 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 engine door, `assertOrderByIsMaterializable`, guards a caller that + * reaches `ObjectQL.find` / `findOne` directly (a hook, a flow). + * - The Data API door, `assertSortFieldsExist`'s third verdict + * (`@objectstack/metadata-protocol`), guards everything reaching `findData`. + * + * The engine door used to test a `'formula'` literal of its own while the + * Data API door read the spec's set. Both held `formula` alone, so they agreed + * only while the spec's set did not grow. The day it grows without the engine, + * the Data API refuses the new type and an in-process `find` sends the ORDER BY + * to a driver with no column for it, which drops the sort and answers success. + * + * So this file copies no verdict table. For EVERY member of the spec's + * `FieldType` it asks both doors and holds them to each other. It tells the + * Data API door's third verdict from its fourth (an author's + * `sortable: false`, read through the projection) without reading a sentence: + * the sort names the field under test AND a companion that declares + * `sortable: false`, and the third verdict names the computed field alone, + * where the fourth names the companion. The engine door does not judge + * `sortable: false` at all, so the companion never moves its answer. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { FieldType } from '@objectstack/spec/data'; +import { assertOrderByIsMaterializable } from './engine-top-level.js'; + +const OBJECT = 'engine_sort_agreement'; + +/** 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 Data API 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 }, + }, +}; + +const orderByOf = (type: string) => [ + { field: fieldOf(type), order: 'asc' as const }, + { field: COMPANION, order: 'asc' as const }, +]; + +type Refusal = { code?: unknown; status?: unknown; field?: unknown; fields?: unknown }; +const envelopeOf = (err: unknown) => { + const r = err as Refusal; + return { code: r.code, status: r.status, field: r.field, fields: r.fields }; +}; + +/** The engine door's answer: the refusal it threw, or null when it lets the sort through. */ +function engineDoor(type: string) { + try { + assertOrderByIsMaterializable(OBJECT, 'find', DEFINITION, orderByOf(type)); + } catch (err) { + return envelopeOf(err); + } + return null; +} + +/** The Data API door's answer to the same sort, over the same definition. */ +async function dataApiDoor(type: string) { + const find = vi.fn(async () => []); + const engine = { registry: { getObject: (name: string) => (name === OBJECT ? DEFINITION : undefined) }, find }; + const protocol = new ObjectStackProtocolImplementation(engine as any); + try { + await protocol.findData({ object: OBJECT, query: { orderBy: orderByOf(type) } }); + } catch (err) { + return envelopeOf(err); + } + return null; +} + +/** The computed-type verdict, as an envelope: what both doors answer for a computed field. */ +const computedVerdict = (type: string) => ({ + code: 'INVALID_SORT', status: 400, field: fieldOf(type), fields: [fieldOf(type)], +}); + +const engineCallsComputed = (type: string) => engineDoor(type) !== null; + +describe('the engine sort door and the Data API sort door agree on which field types are computed', () => { + it('the table is not empty on either side: the engine door refuses some types and lets others through', () => { + // Without both, every row below would agree about nothing. + expect(FIELD_TYPES.filter(engineCallsComputed), 'field types the engine door refuses').not.toEqual([]); + expect(FIELD_TYPES.filter((type) => !engineCallsComputed(type)), 'field types the engine door lets through') + .not.toEqual([]); + }); + + it.each(FIELD_TYPES)('a `%s` field: the engine door refuses it exactly when the Data API door calls it computed', async (type) => { + const engine = engineDoor(type); + const dataApi = await dataApiDoor(type); + // The Data API door always refuses this sort (the companion is unsortable); + // the verdict that fires says which side of the question the type is on. + const dataApiCallsComputed = JSON.stringify(dataApi?.fields) === JSON.stringify([fieldOf(type)]); + expect({ type, engineCallsComputed: engine !== null }).toEqual({ type, engineCallsComputed: dataApiCallsComputed }); + if (dataApiCallsComputed) { + // One wire envelope on both doors for the one condition. + expect(engine).toEqual(computedVerdict(type)); + expect(dataApi).toEqual(computedVerdict(type)); + } else { + // CONTROL: the Data API refused for the companion, by its fourth verdict. + expect(dataApi).toEqual({ code: 'INVALID_SORT', status: 400, field: COMPANION, fields: [COMPANION] }); + } + }); +}); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 51660e8dd0f..a2e7b0b37ef 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -11,7 +11,7 @@ // re-exports, by name, every declaration here it exported before, so every // importer of `./engine.js` reads what it read. -import { AUDIT_PROVENANCE_FIELDS, ENGINE_UPDATE_UPSERT_REMOVED, FILE_REFERENCE_TYPES, FullTextSearchSchema, QUERY_CURSOR_REMOVED, QUERY_DISTINCT_REMOVED, REFERENCE_VALUE_TYPES, RPC_QUERY_ALIAS_SLOTS, VALID_AST_OPERATORS, foldQueryAliasSlots, isFilterAST, isMultiValueField, lowerFilterCondition, normalizeFilterComparandTypes, parseFilterAST, percentScaleOf, readAutonumberCounter, referenceCarrierOf, referenceTargetOf, resolveInjectedColumnProvenance } from '@objectstack/spec/data'; +import { AUDIT_PROVENANCE_FIELDS, ENGINE_UPDATE_UPSERT_REMOVED, FILE_REFERENCE_TYPES, FullTextSearchSchema, QUERY_CURSOR_REMOVED, QUERY_DISTINCT_REMOVED, REFERENCE_VALUE_TYPES, RPC_QUERY_ALIAS_SLOTS, VALID_AST_OPERATORS, foldQueryAliasSlots, isFilterAST, isMultiValueField, isVirtualSearchField, lowerFilterCondition, normalizeFilterComparandTypes, parseFilterAST, percentScaleOf, readAutonumberCounter, referenceCarrierOf, referenceTargetOf, resolveInjectedColumnProvenance } from '@objectstack/spec/data'; import type { DroppedFieldsEvent, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryAliasSlot, RecycleBinClearedReference, ServiceObject } from '@objectstack/spec/data'; import type { EngineFilterJudgement, ISecurityService } from '@objectstack/spec/contracts'; import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js'; @@ -1861,6 +1861,32 @@ function withFileOwnerKey( * a dotted PROJECTION entry is refused since #7589 — * {@link assertProjectionHasNoDottedPaths}, directly below. * + * ONE SOURCE — "computed on read" is judged by `isVirtualSearchField` + * (`@objectstack/spec/data`, set `SEARCH_VIRTUAL_TYPES`), the predicate the + * Data API's sort door (`assertSortFieldsExist`, metadata-protocol) and the + * served sortability projection (`resolveObjectSortability`, `virtual-type`) + * read too, never a type literal of this door's own. A type added to the + * spec's set is then refused here and at the Data API together; a literal + * here would let an in-process `find` drop the sort the Data API refuses. + * `engine-sort-door-agreement.test.ts` holds the two doors together for + * every `FieldType`. It is the STORAGE fact, deliberately not the spec's + * `COMPUTED_VALUE_TYPES` (the write contract): `summary` and `autonumber` + * have stored columns and sort. + * + * THE OTHER SITES that spell the same fact with a `formula` literal of their + * own, read from the predicate by none of them yet. This list is their + * ledger (it moved here when the Data API door's local set was retired); + * changing one of them is its own card, and a type added to the spec's set + * needs each of them reworked first: + * - `driver-sql`: `fieldHasColumn` (`schema-drift.ts`) and + * `SqlDriver.createColumn` (`sql-driver.ts`), the DDL that gives a + * `formula` no column; + * - `driver-turso`: `remote-transport.ts`, which skips it with the same + * "Virtual — no column" note; + * - this package: {@link planFormulaProjection} above and + * `search-companion.ts`'s title-eligibility check; + * - `plugin-audit`: `VIRTUAL_FIELD_TYPES` (`audit-writers.ts`). + * * A registry-less host (`schema` undefined) returns early, exactly as the * ingress gate returns early when `resolveQueryFields` cannot answer: a door * that cannot see the field map must not invent a verdict about it. @@ -1876,7 +1902,7 @@ function assertOrderByIsMaterializable( const names = orderBy.map((node) => typeof node === 'string' ? node : String((node as any)?.field ?? '')); const unmaterialized = names.filter((f) => - f !== '' && !f.includes('.') && (schema.fields as any)[f]?.type === 'formula'); + f !== '' && !f.includes('.') && isVirtualSearchField((schema.fields as any)[f])); if (unmaterialized.length === 0) return; const first = unmaterialized[0]; const type = String((schema.fields as any)[first]?.type); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx index f94ea3c40c2..e354d293335 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.relationalSort.test.tsx @@ -105,8 +105,8 @@ describe('ListView sort picker — relational fields (objectui#3096)', () => { * objectui#4294 — the remedy the hint names has to be one the server will * actually sort by. It used to say "add a formula field holding it", and a * formula field is precisely the type the server refuses to order by - * (objectstack `UNMATERIALIZED_SORT_TYPES`, a hard 400 since - * objectstack#6994): an author who followed the hint landed on a refusal — + * (objectstack's sort doors judge it by `isVirtualSearchField` from + * `@objectstack/spec/data`, a hard 400 since objectstack#6994): an author who followed the hint landed on a refusal — * and, since #4243 withheld formula fields from the picker, on a field this * very panel does not offer. The wording now tracks the server's own * refusal-door hint (a STORED, denormalised field, written when the source diff --git a/ui/packages/plugin-list/src/__tests__/ListView.sortFieldFallback.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.sortFieldFallback.test.tsx index 6d14e0d7508..888e2627ac7 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.sortFieldFallback.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.sortFieldFallback.test.tsx @@ -184,10 +184,10 @@ describe('objectui#4243 part 1 — the sort picker no longer reuses `filterableF // deciding this: before the fix the unwhitelisted set already contained // every field, and `Total Amount` was offered here. // - // objectstack `packages/metadata-protocol/src/protocol.ts` - // `UNMATERIALIZED_SORT_TYPES` — a formula value is computed on read, no - // driver materialises a column for it, and since objectstack#6994 a sort - // naming one is a hard 400. + // objectstack's sort doors (`assertSortFieldsExist`, judged by + // `isVirtualSearchField` from `@objectstack/spec/data`) — a formula value + // is computed on read, no driver materialises a column for it, and since + // objectstack#6994 a sort naming one is a hard 400. await renderList({ sort: [{ field: 'name', order: 'asc' }] }); await openSortPanel();