From 7cdd25a300e2984eacacceec0001e95ac5ed2142 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 17 Sep 2026 12:47:28 +0000 Subject: [PATCH] fix(objectql,driver-turso): the one-definition-of-multi-valued invariant reaches these two packages Maintainer ruling 2026-09-13 (decision batch #128 item 5, option 1'): there is ONE definition of "is this field multi-valued", `@objectstack/spec`'s `isMultiValueField`, and storage follows it. driver-sql was aligned by #17469 and `os generate migration` by #18199; these four sites read `field.multiple` raw, which answers `true` on types the predicate calls single-valued and `false` on the inherently-multi option types that carry no flag. - objectql: one local seam, `declaredMultiValued`, for the option-derived insert default, the referential-integrity dependents probe and the cascade-delete multi-value verdict; record-validator's select/radio gate is now the negation of its own multi-value branch's predicate. - driver-turso: `RemoteTransport.mapFieldTypeToSQL`'s short-circuit asks the predicate, so this driver's two transports stop declaring one field's column in two different storage classes. Comments that named the losing authority are rewritten rather than left standing. Claude-Session: https://claude.ai/code/session_01CqmCgU5RGDoJYhHUMVp2af Co-authored-by: Claude --- ...08-multi-value-invariant-objectql-turso.md | 55 +++++ .../driver-turso/src/remote-transport.ts | 25 ++- ...rso-remote-multi-value-column-type.test.ts | 205 ++++++++++++++++++ ...ne-cascade-delete-multivalue-probe.test.ts | 92 ++++++++ .../src/engine-select-option-default.test.ts | 38 +++- packages/objectql/src/engine.ts | 87 ++++++-- .../src/validation/record-validator.ts | 10 +- 7 files changed, 489 insertions(+), 23 deletions(-) create mode 100644 .changeset/18408-multi-value-invariant-objectql-turso.md create mode 100644 packages/drivers/driver-turso/src/turso-remote-multi-value-column-type.test.ts diff --git a/.changeset/18408-multi-value-invariant-objectql-turso.md b/.changeset/18408-multi-value-invariant-objectql-turso.md new file mode 100644 index 00000000000..c8a5c0aea4c --- /dev/null +++ b/.changeset/18408-multi-value-invariant-objectql-turso.md @@ -0,0 +1,55 @@ +--- +'@objectstack/objectql': patch +'@objectstack/driver-turso': patch +--- + +fix(objectql,driver-turso): "is this field multi-valued" is `isMultiValueField` here too — the `domain:engine` half of the one-definition ruling (#18408) + +Maintainer ruling, 2026-09-13 (decision batch #128 item 5, option 1′): there is +ONE definition of 「is this field multi-valued」, `@objectstack/spec`'s +`isMultiValueField`, and storage follows it. `driver-sql` was aligned by #17469 +and `os generate migration` by #18199. These four sites were the remainder: they +read `field.multiple` raw, which answers `true` on types the predicate calls +single-valued (`text`, `master_detail`, `tree`, `number`, …) and `false` on the +inherently-multi option types (`multiselect` / `checkboxes` / `tags`) that carry +no flag at all. + +**`@objectstack/driver-turso`** — `RemoteTransport.mapFieldTypeToSQL` short- +circuited its whole type switch on the raw flag, so a `{ type: 'number', +multiple: true }` field was declared `TEXT` in remote mode while the SAME +driver's local transport (`SqlDriver`, aligned since #17469) declared `float`: +one declaration, two storage classes, chosen by which URL the deployment +happens to hold. New columns for such a field are now declared by the field's +own type. Genuinely multi-valued fields (`lookup` / `select` / `file` / `image` +/ `user` flagged `multiple`, and the inherently-multi option types with or +without it) are unchanged — still the JSON-array `TEXT` column. + +**`@objectstack/objectql`** — three sites, all deciding the SHAPE of a stored +value: + +- the option-derived insert default (`resolveOptionDefault`) assembles an array + for a multi-valued field. A `multiselect` / `checkboxes` / `tags` field with an + option marked `default: true` and no `multiple` flag was defaulted to a bare + scalar, which this engine's own validator then refused as + `invalid_type_array` on the insert the default was resolved for; +- the referential-integrity dependents probe (`referenceProbeFilter`) composes + `$contains` for a multi-valued reference and bare equality for a scalar one. A + `master_detail` flagged `multiple` is outside `MULTI_CAPABLE_TYPES`, so every + aligned storage side builds it a scalar column — the probe now asks that column + the question it can answer, instead of a substring match repaired afterwards by + a second narrowing pass; +- the cascade-delete `multiValued` verdict, which that probe, the `set_null` + write shape and the required-FK escalation all read. + +**What a deployment feels.** Only declarations that are already off-spec move: +`FieldSchema` has refused `multiple` on a non-capable type since #17469 (ADR-0087 +semantic entry 18), so these shapes now reach the engine and the driver only +through doors that never run it — `registerExternalObject` / `initObjects` and a +driver's own unvalidated input. Existing columns are untouched: the remote +transport only ever declares types for columns it is creating. A deployment +holding one of these shapes should re-declare the field — drop the flag if the +value really is single, or move the field to a multi-capable type if it is not — +which is the same prescription entry 18 already carries. + +No export is added, removed or renamed in either package, and no authorable key +changes its name, type or optionality. diff --git a/packages/drivers/driver-turso/src/remote-transport.ts b/packages/drivers/driver-turso/src/remote-transport.ts index 73694d0a3db..4eae72c4cd8 100644 --- a/packages/drivers/driver-turso/src/remote-transport.ts +++ b/packages/drivers/driver-turso/src/remote-transport.ts @@ -15,6 +15,11 @@ import type { Client, InStatement, ResultSet } from '@libsql/client'; import { StandardErrorCode } from '@objectstack/spec/api'; import { FILTER_OPERATORS, LOGICAL_OPERATORS, RETIRED_FILTER_OPERATORS } from '@objectstack/spec/data'; +// [#18408] The ONE definition of "is this field multi-valued" (#17469, decision +// batch #128 item 5, option 1′) — the same predicate `SqlDriver` asks on this +// driver's local transport, so the two cannot declare one field's column +// differently. See {@link RemoteTransport.mapFieldTypeToSQL}. +import { isMultiValueField } from '@objectstack/spec/data'; // [#7872] The shared comparand-type door. `serializeComparand`'s allow-list and // `driver-sql`'s reached the identical six types twice independently — the // measured fact the door was ruled from — so the SET and the sentence the @@ -2432,9 +2437,25 @@ export class RemoteTransport { * edit its expectations to match new output. */ private mapFieldTypeToSQL(field: any): string { - if (field.multiple) return 'TEXT'; // JSON array stored as text - const type = field.type || 'string'; + // [#18408] The multi-value short-circuit — a JSON array stored as text. + // + // Was `if (field.multiple)`. Maintainer ruling 2026-09-13 (decision batch + // #128 item 5, option 1′): there is ONE definition of "is this field + // multi-valued", `@objectstack/spec`'s `isMultiValueField`, and storage + // follows it. The raw flag answered `true` on types that predicate calls + // single-valued, so this transport declared `TEXT` for a `number` / + // `integer` / `boolean` field carrying the flag while THIS SAME DRIVER's + // local transport — `SqlDriver`, aligned by #17469 — declared `float` / + // `boolean` for it: one declaration, two storage classes, chosen by which + // URL the deployment happens to hold. The flag is redundant rather than + // decisive on the inherently-multi option types, which the predicate + // answers `true` for with or without it. + // + // Resolved `type` first, so the one predicate and the switch below read the + // same type — the driver-internal `|| 'string'` default is applied once. + if (isMultiValueField({ type, multiple: field.multiple === true })) return 'TEXT'; + switch (type) { case 'string': case 'email': diff --git a/packages/drivers/driver-turso/src/turso-remote-multi-value-column-type.test.ts b/packages/drivers/driver-turso/src/turso-remote-multi-value-column-type.test.ts new file mode 100644 index 00000000000..5a2d2cf070b --- /dev/null +++ b/packages/drivers/driver-turso/src/turso-remote-multi-value-column-type.test.ts @@ -0,0 +1,205 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#18408] The remote transport's column builder asks the ONE definition of + * "is this field multi-valued" — `@objectstack/spec`'s `isMultiValueField` — + * and ⛔ not the raw `field.multiple` flag. + * + * ## The ruling this file pins + * + * Maintainer, 2026-09-13 (decision batch #128 item 5, option 1′): there is ONE + * definition of "multi-valued", `isMultiValueField`, and **storage follows it**. + * `driver-sql` was aligned by #17469 and `os generate migration` by #18199. + * `RemoteTransport.mapFieldTypeToSQL` was the remaining storage side reading the + * flag raw, and it short-circuits the whole type switch on it. + * + * ## The measured consequence, inside ONE driver + * + * `TursoDriver` is dual-transport: local/replica mode extends `SqlDriver` — + * aligned since #17469 — while remote mode spells its own column types here. So + * the same declaration reached two different storage classes depending on which + * URL the deployment happened to hold: + * + * ```text + * declared field local (SqlDriver, aligned #17469) remote (before #18408) + * ------------------------------------ --------------------------------- ---------------------- + * { type: 'number', multiple: true } float (REAL affinity) TEXT + * { type: 'boolean', multiple: true } boolean TEXT + * { type: 'lookup', multiple: true } TEXT (genuinely multi-valued) TEXT + * ``` + * + * The first two rows are the defect: the flag is INERT on a type outside + * `MULTI_CAPABLE_TYPES` ∪ `MULTI_OPTION_TYPES` — `FieldSchema` refuses it there + * at the authoring entrance, and every aligned storage side ignores it — so the + * remote transport was building a JSON-array column for a field nothing else in + * the platform calls multi-valued. The third row is the control: `lookup` IS + * multi-capable, the predicate answers `true`, and nothing about it moves. + * + * ## Reachability, stated so the pin is not over-graded + * + * `FieldSchema` refuses `multiple` on a non-capable type since #17469, so these + * declarations arrive only through doors that never run it — `syncSchema` / + * `initObjects` on a raw object definition, which is exactly what a driver test + * calls and what `registerExternalObject` does in production (#18199's bounding + * argument). Reachable, no longer authorable. + * + * ## ⛔ What to do when this file goes red + * + * It goes red when the remote transport stops asking the one predicate, or when + * the predicate's own type sets move under it. Both are decisions. ⛔ Never + * edit the expectations to match new output — `isMultiValueField` is the + * authority, and a disagreement means one side has to move, not that the pin + * has to be re-baselined. + * + * @see https://github.com/objectstack-ai/objectstack/issues/18408 (this alignment) + * @see https://github.com/objectstack-ai/objectstack/issues/17469 (the ruling) + * @see https://github.com/objectstack-ai/objectstack/issues/18199 (the CLI half) + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { isMultiValueField } from '@objectstack/spec/data'; +import { TursoDriver } from './turso-driver.js'; +import { makeLibsqlSqliteStub, type LibsqlSqliteStub } from './libsql-sqlite-stub.testkit.js'; + +const TABLE = 'multi_value_18408'; + +/** + * One column per verdict of the one predicate, plus the two controls. + * + * `v_number_multi` / `v_boolean_multi` carry the flag on a type the predicate + * calls SINGLE-valued; `v_lookup_multi` carries it on a multi-capable type; + * `v_multiselect` is inherently multi and carries NO flag — the direction a raw + * read gets wrong in the other sense; `v_text_multi` is the control for the + * alignment moving only what the predicate moves (a `text` column is TEXT on + * both sides of the change). + */ +const FIELDS = { + v_number_multi: { type: 'number', multiple: true }, + v_boolean_multi: { type: 'boolean', multiple: true }, + v_text_multi: { type: 'text', multiple: true }, + v_lookup_multi: { type: 'lookup', multiple: true }, + v_multiselect: { type: 'multiselect' }, +} as const; + +const DECLARED_COLUMNS = Object.keys(FIELDS); +const OBJECT = { name: TABLE, fields: { ...FIELDS } }; + +const catalogSql = (table: string) => `select name, type from pragma_table_info('${table}')`; + +const toTypeMap = (rows: Array<{ name: string; type: string }>): Record => + Object.fromEntries( + rows.filter((r) => DECLARED_COLUMNS.includes(r.name)).map((r) => [r.name, r.type]), + ); + +/** One row, one value per declared column — the §2 probe's whole input. */ +const ROW = { + id: 'row_18408', + v_number_multi: 12.5, + v_boolean_multi: true, + v_text_multi: 'abc', + v_lookup_multi: ['rec_1', 'rec_2'], + v_multiselect: ['a', 'b'], +}; + +const storageSql = (table: string) => + `select ${DECLARED_COLUMNS.map((c) => `typeof("${c}") as "t_${c}"`).join(', ')} from "${table}"`; + +/** `typeof(col)` per column — the storage class SQLite actually chose. */ +const storageClassOf = (rows: any[]): Record => + Object.fromEntries(DECLARED_COLUMNS.map((c) => [c, rows[0]?.[`t_${c}`]])); + +describe('[#18408] driver-turso remote — the multi-value short-circuit is the spec predicate', () => { + let remote: TursoDriver; + let stub: LibsqlSqliteStub; + let remoteTypes: Record; + + beforeAll(async () => { + stub = makeLibsqlSqliteStub(); + remote = new TursoDriver({ url: 'libsql://multi-value-18408.turso.io', client: stub as never }); + await remote.connect(); + expect(remote.transportMode).toBe('remote'); + await remote.syncSchema(TABLE, OBJECT); + remoteTypes = toTypeMap(stub.raw.prepare(catalogSql(TABLE)).all() as never); + await remote.create(TABLE, { ...ROW }); + }, 60_000); + + afterAll(async () => { + await remote.disconnect(); + stub?.close(); + }); + + // ─── §1 The site under test ────────────────────────────────────────────── + + it('THE SITE: the flag no longer short-circuits the type switch on a single-valued type', () => { + // Before #18408 every one of these five read `TEXT`, because + // `if (field.multiple) return 'TEXT'` ran before the switch and the four + // flagged declarations all carry the flag. Three of them are types the one + // definition calls single-valued. + expect(remoteTypes).toEqual({ + v_number_multi: 'REAL', + v_boolean_multi: 'INTEGER', + v_text_multi: 'TEXT', + v_lookup_multi: 'TEXT', + v_multiselect: 'TEXT', + }); + }); + + it('THE AUTHORITY: every column agrees with `isMultiValueField`, asked directly', () => { + // The pin above states the answers; this one states WHY they are the + // answers, against the predicate itself rather than a table reproduced by + // hand. A multi-valued field takes the JSON-array route (`TEXT`); a + // single-valued one takes the route its own type names. + const multiValued = DECLARED_COLUMNS.filter((c) => + isMultiValueField(FIELDS[c as keyof typeof FIELDS] as never), + ); + expect(multiValued.sort()).toEqual(['v_lookup_multi', 'v_multiselect']); + for (const c of multiValued) expect(remoteTypes[c], `${c} is multi-valued`).toBe('TEXT'); + // And the flag alone is not what decides it: FOUR columns carry + // `multiple: true` and only one of them is on that list, while a column + // that carries no flag at all IS on it. + const flagged = DECLARED_COLUMNS.filter( + (c) => (FIELDS[c as keyof typeof FIELDS] as { multiple?: boolean }).multiple === true, + ); + expect(flagged.sort()).toEqual([ + 'v_boolean_multi', 'v_lookup_multi', 'v_number_multi', 'v_text_multi', + ]); + }); + + // ─── §2 The consequence: one driver, one storage class ─────────────────── + + it('THE CONSEQUENCE: the two transports of this ONE driver land each value in the same storage class', async () => { + // Measured on the STORAGE CLASS of a written value, ⛔ not on the declared + // type string and ⛔ not on the affinity label derived from it. The two + // authors of DDL write different words for the same class by design + // (`float`/`REAL`, `boolean`/`INTEGER`), and one of those pairs does not + // even share an affinity label — `boolean` takes NUMERIC by SQLite's own + // rule while `INTEGER` takes INTEGER — yet both put 0/1 in an integer cell. + // That is the recorded cosmetic asymmetry (#12586 header), and asserting on + // labels would report it as this change's divergence. `typeof(col)` is the + // observable both #12738 and this file are actually about. + const local = new TursoDriver({ url: ':memory:' }); + try { + expect(local.transportMode).toBe('local'); + await local.initObjects([OBJECT]); + await local.create(TABLE, { ...ROW }, { bypassTenantAudit: true }); + const localStorage = storageClassOf((await local.execute(storageSql(TABLE))) as never); + const remoteStorage = storageClassOf(stub.raw.prepare(storageSql(TABLE)).all() as never); + + const divergent = DECLARED_COLUMNS.filter( + (c) => localStorage[c] !== remoteStorage[c], + ).map((c) => `${c}: local=${localStorage[c]} remote=${remoteStorage[c]}`); + + expect( + divergent, + 'Each declared field, compared by the storage class the value landed in on each transport. ' + + 'An EMPTY list is the #18408 post-state: one definition of multi-valued, so one storage ' + + 'class per declaration whichever transport built the column. Before #18408 this list held ' + + '`v_number_multi: local=real remote=text` — the flag bought a JSON-array column from the ' + + 'remote transport for a field the one definition calls single-valued. A NON-EMPTY list ' + + 'means one side moved: a decision, not a broken expectation.', + ).toEqual([]); + } finally { + await local.disconnect(); + } + }, 60_000); +}); diff --git a/packages/objectql/src/engine-cascade-delete-multivalue-probe.test.ts b/packages/objectql/src/engine-cascade-delete-multivalue-probe.test.ts index 26b8a3725f5..dab5d76df89 100644 --- a/packages/objectql/src/engine-cascade-delete-multivalue-probe.test.ts +++ b/packages/objectql/src/engine-cascade-delete-multivalue-probe.test.ts @@ -611,3 +611,95 @@ describe('[#9438] set_null on a multi-value reference removes the deleted member expect(stores.get('mv_acct')?.has('acc_a')).toBe(false); }); }); + +/** + * [#18408] WHICH relations are multi-valued is `isMultiValueField`, the one + * definition #17469 ruled — ⛔ not the raw `multiple` flag this probe read. + * + * `master_detail` is outside `MULTI_CAPABLE_TYPES`, so the flag on one buys a + * JSON array column from nobody: `driver-sql` (#17469) and `os generate + * migration` (#18199) both build it a SCALAR column. Reading the flag made the + * engine aim `$contains` — the membership spelling, lowered to `LIKE '%v%'` — + * at that scalar column, and then repair the superset it got back through a + * second narrowing pass. One relation, two definitions: the split the ruling + * closes. + * + * The fixture is registered through `registry.registerObject`, one of the doors + * that never runs `FieldSchema` — which is why the shape is still reachable + * after #17469 refused it at the authoring entrance (#18199's bounding + * argument), and the only way it can be exercised at all. + */ +describe('[#18408] the probe spelling follows the ONE multi-value definition, not the flag', () => { + /** `master_detail` + the flag: the one declaration where the two disagree. */ + const mdMulti: ServiceObject = { + name: 'mv_md_multi', + label: 'Master-detail (flagged)', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const }, + parent: { + name: 'parent', label: 'Parent', type: 'master_detail' as const, + reference: 'mv_acct', multiple: true, deleteBehavior: 'restrict' as const, + }, + }, + }; + + let engine: ObjectQL; + let stores: Map>>; + let probes: Array<{ object: string; where: unknown }>; + + beforeEach(async () => { + engine = new ObjectQL(); + const stub = makeJsonColumnDriver(); + stores = stub.stores; + probes = stub.probes; + engine.registerDriver(stub.driver, true); + await engine.init(); + // `mv_md_multi` is deliberately absent from `JSON_COLUMNS`: the double + // models the storage the one definition prescribes, so this relation's + // column is the scalar one every aligned storage side builds for it. + for (const o of [acct, zoo, mdMulti]) engine.registry.registerObject(o, OWNER_PACKAGE); + }); + + it('a flagged `master_detail` is probed with BARE EQUALITY — the flagged `lookup` beside it still gets `$contains`', async () => { + const a = await engine.insert('mv_acct', { id: 'acc_x', name: 'anything' }); + + await engine.delete('mv_acct', { where: { id: a.id } } as any); + + // The site under test. Before #18408 this read + // `{ parent: { $contains: 'acc_x' } }`. + expect(probes.find((p) => p.object === 'mv_md_multi')?.where).toEqual({ parent: 'acc_x' }); + // The control, in the same run and through the same seam: `lookup` IS + // multi-capable, so the flag is decisive there and the membership spelling + // is unchanged. A "fix" that simply stopped asking `$contains` reddens this + // line. + expect(probes.find((p) => p.object === 'mv_zoo')?.where) + .toEqual({ f_lookups: { $contains: 'acc_x' } }); + }); + + it('the relation is still GUARDED — a live dependent refuses the parent delete through its full envelope', async () => { + const a = await engine.insert('mv_acct', { id: 'acc_x', name: 'referenced' }); + // Stored the way the scalar column holds it: one id, not a set. + await engine.insert('mv_md_multi', { id: 'md1', parent: 'acc_x' }); + + const err: any = await engine.delete('mv_acct', { where: { id: a.id } } as any).catch((e) => e); + expect(err.code).toBe('DELETE_RESTRICTED'); + expect(err.status).toBe(409); + expect(err.dependentObject).toBe('mv_md_multi'); + expect(err.dependentCount).toBe(1); + expect(rows(stores, 'mv_acct')).toBe(1); + }); + + it('an id that is a PREFIX of another does not drag the other row into the refusal', async () => { + // What bare equality gives for free, and what the substring spelling had to + // be repaired into: `acc_1` must not be answered by the row holding + // `acc_10`. + await engine.insert('mv_acct', { id: 'acc_1', name: 'one' }); + await engine.insert('mv_acct', { id: 'acc_10', name: 'ten' }); + await engine.insert('mv_md_multi', { id: 'md10', parent: 'acc_10' }); + + await engine.delete('mv_acct', { where: { id: 'acc_1' } } as any); + + expect(stores.get('mv_acct')?.has('acc_1')).toBe(false); + expect(stores.get('mv_md_multi')?.has('md10')).toBe(true); + }); +}); diff --git a/packages/objectql/src/engine-select-option-default.test.ts b/packages/objectql/src/engine-select-option-default.test.ts index 2f379129637..55c693f71ab 100644 --- a/packages/objectql/src/engine-select-option-default.test.ts +++ b/packages/objectql/src/engine-select-option-default.test.ts @@ -21,7 +21,9 @@ * declaration (the precedence pin the ruling asks for by name); * - presence is the engine's own `dv == null` test, so `defaultValue: ''` is a * real default that wins; - * - `multiple: true` assembles an ARRAY, because that field stores one; + * - a MULTI-VALUED field assembles an ARRAY, because that field stores one — + * [#18408] multi-valued by `isMultiValueField`, the one definition #17469 + * ruled, ⛔ never a raw `field.multiple`; * - an option value is a plain LITERAL — never routed through the * `DEFAULT_VALUE_TOKENS` branches, which is why the fallback resolves in the * `defaultValue == null` arm rather than upstream of the token tests. @@ -294,6 +296,40 @@ describe('[#7246] the default follows the FIELD shape, not the option count', () expect(row.tags).toEqual(['important']); }); + it('[#18408] an inherently-multi type assembles an ARRAY with NO `multiple` flag — the shape is the TYPE\'s', async () => { + // The flag is REDUNDANT on `multiselect` / `checkboxes` / `tags` + // (`MULTI_OPTION_TYPES`): the field stores an array with or without it, and + // `isMultiValueField` — the one definition (#17469) — says so. Reading the + // raw flag here answered "single-valued" for this declaration and handed + // back the bare `'important'`, which `validateRecord`'s multi-value branch + // then refuses as `invalid_type_array` on the very insert the default was + // resolved for. Measured: this case threw `VALIDATION_ERROR` before #18408. + engine.registry.registerObject(multi('opt_inherent_multi', [ + { label: 'Important', value: 'important', default: true }, + { label: 'Quick', value: 'quick' }, + { label: 'Review', value: 'review', default: true }, + ], { type: 'multiselect' }) as any, 'test.issue18408'); + const row: any = await engine.insert('opt_inherent_multi', {}, sys); + expect(row.tags).toEqual(['important', 'review']); + }); + + it('[#18408] the flag on a type OUTSIDE both multi sets is inert — the default stays a scalar', async () => { + // The other direction of the same definition. `text` is neither + // multi-capable nor inherently-multi, so `FieldSchema` refuses the flag at + // the authoring entrance and every storage side (driver-sql #17469, `os + // generate migration` #18199, this driver's own column builder) declares a + // SCALAR column for it. A declaration that reaches the engine through a door + // that never runs `FieldSchema` used to be defaulted to `['important']` + // here — an array aimed at a varchar, and a value this engine's own + // validator refuses for a `text` field. + engine.registry.registerObject(multi('opt_flag_inert', [ + { label: 'Important', value: 'important', default: true }, + { label: 'Quick', value: 'quick' }, + ], { type: 'text', multiple: true }) as any, 'test.issue18408'); + const row: any = await engine.insert('opt_flag_inert', {}, sys); + expect(row.tags).toBe('important'); + }); + it('a SINGLE-valued field takes the FIRST marked option — one slot, declaration order decides', async () => { // Neither `Field.select` nor `SelectOptionSchema` dedupes the flag, so this // is reachable metadata. Refusing it would fail a spec-valid declaration at diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index edf4a5eec5c..235bdf25b98 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -26,7 +26,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; // engine is what `metadata-protocol.validateData` returns, so letting the two // drift would put a translation layer between a verdict and its contract. import type { ValidateDataIssue, ValidateDataResponse } from '@objectstack/spec/api'; -import { parseAutonumberFormat, renderAutonumber, resolveAutonumberFormat, readAutonumberCounter, missingFieldValues, isTenancyDisabled, FILE_REFERENCE_TYPES, REFERENCE_VALUE_TYPES, referenceTargetOf, isFileIdToken, RAW_FILE_VALUES_CONTEXT_KEY, isCurrentUserDefaultToken, isNowDefaultToken } from '@objectstack/spec/data'; +import { parseAutonumberFormat, renderAutonumber, resolveAutonumberFormat, readAutonumberCounter, missingFieldValues, isTenancyDisabled, FILE_REFERENCE_TYPES, REFERENCE_VALUE_TYPES, referenceTargetOf, isFileIdToken, RAW_FILE_VALUES_CONTEXT_KEY, isCurrentUserDefaultToken, isNowDefaultToken, isMultiValueField } from '@objectstack/spec/data'; // [#5158] Door 2's lowering sink — the SAME pair the protocol face (Door 1) // runs, so `FilterArray` has exactly one lowering in the product. import { @@ -1016,6 +1016,37 @@ function formulaRoundingScale(def: { scale?: unknown } | undefined): number | un return scale <= MAX_FORMULA_SCALE ? scale : undefined; } +/** + * [#18408] Is this field's value MULTI-VALUED — the one question, asked of the + * one predicate `@objectstack/spec` publishes, and the single local seam every + * site in this file goes through. + * + * Maintainer ruling 2026-09-13 (decision batch #128 item 5, option 1′): there + * is ONE definition of "is this field multi-valued", `isMultiValueField`, and + * storage follows it. The sites below used to read `field.multiple` raw, which + * answers `true` on types the spec predicate calls single-valued (`text`, + * `master_detail`, `tree` …) and `false` on the inherently-multi option types + * (`multiselect` / `checkboxes` / `tags`) that carry no flag at all. Both + * directions put this engine on a different list from the storage it writes + * through: `driver-sql` (#17469) and `os generate migration` (#18199) both ask + * the predicate now. + * + * Takes the field rather than a resolved type because — unlike driver-sql and + * the CLI generator — no caller in this file applies a type default of its own; + * a non-string `type` is answered `false` here, the same verdict those two + * reach through their `field.type || 'string'` resolution. + * + * ⛔ The predicate is called, never re-spelled. `MULTI_CAPABLE_TYPES` / + * `MULTI_OPTION_TYPES` membership written out at a site would be a second + * answer to a question the ruling gave exactly one. + */ +function declaredMultiValued(field: { type?: unknown; multiple?: unknown } | null | undefined): boolean { + return isMultiValueField({ + type: typeof field?.type === 'string' ? field.type : '', + multiple: field?.multiple === true, + }); +} + function planFormulaProjection( schema: any, requestedFields: string[] | undefined @@ -4715,12 +4746,19 @@ export class ObjectQL implements IObjectQLEngine { * two sides honest BY CONSTRUCTION: there is no field the lint calls * always-valued that this method leaves empty. * - * - **`multiple: true` assembles an ARRAY.** That field stores an - * Array/JSON (`FieldSchema.multiple`: "Stores as Array/JSON"), so the - * shape of its default follows the field, not the number of marked - * options — one marked option on a multi-select defaults to a - * one-element array, never a bare scalar that the driver would then store - * with the wrong shape. Refusing (throwing) was rejected: the metadata is + * - **A MULTI-VALUED field assembles an ARRAY.** That field stores an + * Array/JSON, so the shape of its default follows the field, not the + * number of marked options — one marked option on a multi-select defaults + * to a one-element array, never a bare scalar that the driver would then + * store with the wrong shape. [#18408] Multi-valued is + * {@link declaredMultiValued}, ⛔ not a raw `field.multiple`: the flag is + * inert on a type outside the two multi sets and redundant on a + * `multiselect` / `checkboxes` / `tags`, which stores an array with or + * without it — so reading the flag made this method disagree with the + * validator one frame later (`normalizeMultiValueFields` has asked the + * predicate all along) and with the column the driver builds. + * + * Refusing (throwing) was rejected: the metadata is * spec-valid, and a runtime throw on spec-valid input is a worse answer * than a well-defined value. Ignoring it was rejected too — it would * preserve, for multi-selects only, precisely the inertness this change @@ -4741,7 +4779,7 @@ export class ObjectQL implements IObjectQLEngine { * make the engine honour raw shapes lint calls nullable — the two would * disagree in the direction that produces a false "always-valued". */ - private resolveOptionDefault(field: { options?: unknown; multiple?: unknown }): unknown { + private resolveOptionDefault(field: { type?: unknown; options?: unknown; multiple?: unknown }): unknown { const options = field.options; if (!Array.isArray(options)) return undefined; const marked: unknown[] = []; @@ -4756,7 +4794,8 @@ export class ObjectQL implements IObjectQLEngine { marked.push(value); } if (marked.length === 0) return undefined; - return field.multiple === true ? marked : marked[0]; + // [#18408] Was `field.multiple === true`. See {@link declaredMultiValued}. + return declaredMultiValued(field) ? marked : marked[0]; } /** @@ -13122,10 +13161,16 @@ export class ObjectQL implements IObjectQLEngine { * field it is aimed at. * * A single-valued `lookup` / `master_detail` stores a scalar foreign key, and - * bare equality is the right question about it. A field declaring - * `multiple: true` stores an ARRAY — "Stores as Array/JSON" - * (`FieldSchema.multiple`) — and every SQL backend in this repo puts that - * array in a JSON TEXT column. Aiming bare equality at THAT column compares + * bare equality is the right question about it. A MULTI-VALUED reference + * field stores an ARRAY, and every SQL backend in this repo puts that array + * in a JSON TEXT column. [#18408] Which of the two a field is, is + * {@link declaredMultiValued} — the one predicate the storage side asks + * (#17469) — ⛔ never a raw `field.multiple`: `master_detail` and `tree` are + * outside `MULTI_CAPABLE_TYPES`, so the flag on one of those buys a JSON + * column from nobody, and aiming `$contains` at the scalar column the driver + * really built is the mirror image of the defect below. + * + * Aiming bare equality at a multi-valued column compares * the whole serialization (`["a","b"]`) against one id, which can never hold; * `driver-sql` refuses the spelling outright (`INVALID_FILTER` / 400, #7398), * and that refusal is correct and stays. Until this method existed the probe @@ -13162,10 +13207,11 @@ export class ObjectQL implements IObjectQLEngine { */ private referenceProbeFilter( fieldName: string, - fdef: { multiple?: unknown }, + fdef: { type?: unknown; multiple?: unknown }, id: string | number, ): Record { - if (fdef?.multiple !== true) return { [fieldName]: id }; + // [#18408] Was `fdef?.multiple !== true`. See {@link declaredMultiValued}. + if (!declaredMultiValued(fdef)) return { [fieldName]: id }; const raw = String(id); // The BODY of the JSON string form — `JSON.stringify('a"b')` is `"a\"b"`, // and the quotes are the serialization's, not the id's. @@ -13436,9 +13482,11 @@ export class ObjectQL implements IObjectQLEngine { * or `lookup` field referencing `object`, honor the field's `deleteBehavior`: * - `cascade` → delete the dependent rows (recursively, so grandchildren * are handled by each child's own delete), - * - `set_null` → clear the foreign key. On a `multiple: true` field the - * FK is a SET, so "clear" means remove the deleted MEMBER - * and keep the rest; an emptied set is written as `[]`, + * - `set_null` → clear the foreign key. On a MULTI-VALUED field + * ([#18408] {@link declaredMultiValued}, ⛔ not the raw + * flag) the FK is a SET, so "clear" means remove the + * deleted MEMBER and keep the rest; an emptied set is + * written as `[]`, * never `null` — the representation `FieldSchema` pins * (`packages/spec/src/data/field.zod.ts`, the `multiple` * doc block, #9447 maintainer ruling 2026-08-18), @@ -13599,7 +13647,8 @@ export class ObjectQL implements IObjectQLEngine { // [#9362] `multiValued` is declared here rather than at the probe // because the probe's filter spelling, the set_null write below and // — since #9688 — this escalation all turn on it. - const multiValued = fdef.multiple === true; + // [#18408] Was `fdef.multiple === true`. See {@link declaredMultiValued}. + const multiValued = declaredMultiValued(fdef); const requiredSetNull = behavior === 'set_null' && fdef.required === true; if (requiredSetNull && !multiValued) { behavior = 'restrict'; diff --git a/packages/objectql/src/validation/record-validator.ts b/packages/objectql/src/validation/record-validator.ts index 90e1d84642e..977962226cc 100644 --- a/packages/objectql/src/validation/record-validator.ts +++ b/packages/objectql/src/validation/record-validator.ts @@ -821,7 +821,15 @@ function validateOne( // disguise — it falls through to the multi-value branch below (#2552; // previously an array here was stringified to "a,b" and wrongly // rejected as invalid_option, while a scalar slipped straight through). - if ((t === 'select' || t === 'radio') && def.multiple !== true) { + // + // [#18408] The gate is the NEGATION of that branch's own predicate, ⛔ not a + // raw `def.multiple !== true`. The two are extensionally equal only while + // `select` and `radio` both sit in `MULTI_CAPABLE_TYPES` and in neither + // multi-option set — a membership `packages/spec` owns and may move. Spelling + // the complement as the flag would make this dispatch answer the multi-value + // question from two authorities that happen to agree today, which is the + // drift the one-definition ruling (#17469) closes. + if ((t === 'select' || t === 'radio') && !isMultiValueField(def)) { const allowed = optionValues(def.options); if (allowed.length > 0 && !allowed.includes(String(value))) { return fail('invalid_option', { allowed: allowed.join(', ') }, 'invalid_option', allowed);