From d03836a0cf3ceec42360d8712022960d39d88c71 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:47:06 +0000 Subject: [PATCH 1/3] feat(driver-sql, driver-turso): compile the SharedRecordIds fixed-read leaf to an in-database subquery (ADR-0155 step 3) driver-sql's filter compiler and the Turso remote transport compile a SharedRecordIds leaf, as the $in comparand of a field, to its fixed inner read: field IN (SELECT record_id FROM sys_record_share WHERE object_name = ? AND recipient_type = ? AND recipient_id = ? [AND access_level IN (...)] AND record_id IS NOT NULL AND record_id <> ?), every value bound, with no tenant scope on the subquery (ADR-0155 1 ruled A) and the outer statement's wall untouched. Oracle omits the <> '' half, since it stores '' as NULL. Both faces declare fixedReadLeaves: ['SharedRecordIds'] in this commit: SqlDriver declares it, and TursoDriver inherits it in every mode now that its remote transport compiles the leaf with its own compiler. A leaf anywhere else is refused with ADR-0139 D3's envelope (INTERNAL_ERROR / 500), logged once per driver. The tenant chokepoint guard reads the new builder, so its absence of a tenant scope is recorded as an EXEMPT entry citing the ruling. The shared case-set gains the cross-organization nested witness (step 1's L2 N4): note n5 names d7, whose only grant is stamped org_b. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../driver-sql/src/fixed-read-leaf-compile.ts | 208 ++++++++++++++++++ packages/drivers/driver-sql/src/index.ts | 5 + .../src/sql-driver-filter-helpers.ts | 28 ++- .../src/sql-driver-internal-helpers.ts | 45 +++- packages/drivers/driver-sql/src/sql-driver.ts | 16 +- .../driver-turso/src/remote-transport.ts | 53 +++++ .../drivers/driver-turso/src/turso-driver.ts | 16 +- .../data/fixed-read-leaf-conformance.test.ts | 2 +- .../src/data/fixed-read-leaf-conformance.ts | 29 ++- scripts/check-tenant-chokepoint.mjs | 26 ++- 10 files changed, 408 insertions(+), 20 deletions(-) create mode 100644 packages/drivers/driver-sql/src/fixed-read-leaf-compile.ts diff --git a/packages/drivers/driver-sql/src/fixed-read-leaf-compile.ts b/packages/drivers/driver-sql/src/fixed-read-leaf-compile.ts new file mode 100644 index 00000000000..ea97d9f49ec --- /dev/null +++ b/packages/drivers/driver-sql/src/fixed-read-leaf-compile.ts @@ -0,0 +1,208 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 D2, D4] What `driver-sql`'s filter compiler and the Turso remote + * transport's compiler share for a FIXED-READ LEAF (`@objectstack/spec/data`'s + * `isFixedReadLeaf`: `SharedRecordIds` today): the walk that finds a leaf no + * compiler here compiles, and the predicates of the fixed inner read the leaf + * describes. Each compiler builds its own SQL from them, every value bound, + * ⛔ never spliced into the statement. + * + * ## Where a leaf compiles + * + * Only as the comparand of `$in` in a field's operator map, + * `{ field: { $in: leaf } }`: at any depth under `$and`, `$or` and `$not`, and + * inside the composed scope of a `ReadableIds` leaf. There it compiles to + * `field IN (SELECT column FROM table WHERE …)`, one statement, so `find`, + * `count` and `aggregate` agree by construction and a record matched by several + * rows of the table is one row (ADR-0155 D1: ⛔ no `EXISTS`, no correlated + * form, no join). + * + * Anywhere else (under another operator, as a field's bare value, as a list + * member, as a combinator's operand, as a node) the leaf is a composition + * fault, refused with ADR-0139 D3's envelope, `INTERNAL_ERROR` / 500 + * (`@objectstack/core`'s `refuseFixedReadLeafOnce`). ⛔ It is never read as an + * ordinary comparand. The engine's seam places every leaf (ADR-0155 D1, D4); + * this walk is the compiler's own floor under that seam, for a caller that + * reached the driver another way. + * + * ## The inner read + * + * {@link fixedInnerReadPredicates} turns the leaf's own description + * (`fixedInnerReadOf`) into predicates, so ⛔ no compiler restates a leaf's + * predicate by hand: + * + * - each `equals` entry as `column = ?`, each `memberOf` entry as + * `column IN (?, …)`; + * - the blank-id guard, `column IS NOT NULL AND column <> ''`, so a negation + * (`NOT (id IN (…))`) answers every row the set does not hold. On a dialect + * that stores the empty string as NULL (Oracle) `<> ''` is `<> NULL`, which + * is never true and would empty the set, so the half is omitted there: + * `IS NOT NULL` already excludes the empty id; + * - **no tenant scope** (`tenantScope: 'none'`, ADR-0155 ① ruled A): ⛔ the + * compiler applies none to the inner read. The outer statement's wall is + * untouched. + * + * `index.ts` re-exports this module for `@objectstack/driver-turso`. + */ + +import { describeFixedReadLeaf } from '@objectstack/core'; +import { fixedInnerReadOf, isComposedReadableIds, isFixedReadLeaf } from '@objectstack/spec/data'; +import type { FixedInnerRead, FixedReadLeaf } from '@objectstack/spec/data'; + +/** A fixed-read leaf the walk found where no compiler compiles one. */ +export interface MisplacedFixedReadLeaf { + /** Where it sits, as a path from the `where` root (`where.owner.$eq`). */ + readonly at: string; + /** The leaf itself, for `describeFixedReadLeaf`. */ + readonly leaf: unknown; +} + +/** Is `value` a plain object or a list: something a filter is built from and the walk descends into? */ +function isPlainContainer(value: unknown): value is Record | unknown[] { + if (value === null || typeof value !== 'object') return false; + if (Array.isArray(value)) return true; + const proto = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +/** + * [ADR-0155 D1] The first fixed-read leaf in `where` that sits anywhere but as + * the `$in` comparand of a field's operator map, or `null` when every leaf + * sits there (or there is none). + * + * The walk reads roles, not just keys: a NODE's keys are combinators and field + * names, an OPERATOR MAP's keys are operators, and only an operator map's `$in` + * holds a leaf. A composed `ReadableIds` leaf's scope is a node, walked with + * the same rules, and so is the scope of any value `scopeOf` answers for (a + * compiler's own resolved form of that leaf, such as the Turso remote + * transport's semi-join). A value that is neither a plain object nor a list (a + * `Date`, a buffer) holds no leaf. Cycles are cut on the current path. + */ +export function findMisplacedFixedReadLeaf( + where: unknown, + path = 'where', + scopeOf: (value: unknown) => { readonly scope: unknown } | null = () => null, +): MisplacedFixedReadLeaf | null { + const onPath = new Set(); + const descend = (value: object, walk: () => T): T | null => { + if (onPath.has(value)) return null; + onPath.add(value); + try { + return walk(); + } finally { + onPath.delete(value); + } + }; + /** Any value outside the two roles: a leaf here is misplaced, a composed `ReadableIds` scope is a node. */ + const visitValue = (value: unknown, at: string): MisplacedFixedReadLeaf | null => { + if (isFixedReadLeaf(value)) return { at, leaf: value }; + const nested = isComposedReadableIds(value) ? value : scopeOf(value); + if (nested !== null) return nested.scope === undefined ? null : visitNode(nested.scope, `${at}.scope`); + if (!isPlainContainer(value)) return null; + return descend(value, () => { + const entries: [string, unknown][] = Array.isArray(value) + ? value.map((item, i) => [`[${i}]`, item]) + : Object.keys(value).map((key) => [`.${key}`, value[key]]); + for (const [step, item] of entries) { + const found = visitValue(item, `${at}${step}`); + if (found) return found; + } + return null; + }); + }; + /** A filter node: `$and` / `$or` list members and `$not`'s operand are nodes, a field's value is an operator map. */ + const visitNode = (node: unknown, at: string): MisplacedFixedReadLeaf | null => { + if (isFixedReadLeaf(node) || !isPlainContainer(node) || Array.isArray(node)) return visitValue(node, at); + return descend(node, () => { + for (const key of Object.keys(node)) { + const value = node[key]; + const here = `${at}.${key}`; + let found: MisplacedFixedReadLeaf | null; + if ((key === '$and' || key === '$or') && Array.isArray(value)) { + found = null; + for (let i = 0; i < value.length && found === null; i++) found = visitNode(value[i], `${here}[${i}]`); + } else if (key === '$not') { + found = visitNode(value, here); + } else if (!key.startsWith('$') && !isFixedReadLeaf(value) && isPlainContainer(value) && !Array.isArray(value)) { + found = visitOperatorMap(value, here); + } else { + found = visitValue(value, here); + } + if (found) return found; + } + return null; + }); + }; + /** A field's operator map: its `$in` is the one place a leaf compiles. */ + const visitOperatorMap = (map: Record, at: string): MisplacedFixedReadLeaf | null => + descend(map, () => { + for (const op of Object.keys(map)) { + const comparand = map[op]; + if (op === '$in' && isFixedReadLeaf(comparand)) continue; + const found = visitValue(comparand, `${at}.${op}`); + if (found) return found; + } + return null; + }); + return visitNode(where, path); +} + +/** + * The refusal's message for a leaf {@link findMisplacedFixedReadLeaf} found: + * where it sits, what it is (by name and table, never its inputs: a recipient + * is a principal's id, and the message reaches logs), and the one position it + * compiles in. + */ +export function misplacedFixedReadLeafMessage(found: MisplacedFixedReadLeaf): string { + return `${describeFixedReadLeaf(found.at, found.leaf)}, where no filter compiler compiles one: a fixed-read leaf ` + + 'compiles only as the $in comparand of a field, the position the engine\'s seam places it in (ADR-0155 D1). ' + + 'The statement was NOT run, rather than read the leaf as an ordinary comparand. Place it as ' + + '{ id: { $in: leaf } }, directly or inside a composed ReadableIds scope.'; +} + +/** The predicates of a fixed inner read, in the order a compiler emits them. */ +export interface FixedInnerReadPredicates { + /** The one table the read is of. */ + readonly table: string; + /** The one column it projects, and the column the blank-id guard reads. */ + readonly column: string; + /** `column = value`, ANDed. */ + readonly equals: readonly (readonly [column: string, value: string])[]; + /** `column IN (values…)`, ANDed; every list is non-empty. */ + readonly memberOf: readonly (readonly [column: string, values: readonly string[]])[]; + /** + * Whether the blank-id guard carries its `<> ''` half. Always true but where + * the dialect stores the empty string as NULL, where `IS NOT NULL` is the + * whole guard. + */ + readonly notEmpty: boolean; +} + +/** + * [ADR-0155 D2, D4] The predicates of the fixed inner read `leaf` denotes, + * from its own description (`fixedInnerReadOf`). + * + * The description's tenant scope is a literal type: a leaf whose record ever + * rules a scope other than `'none'` widens it and stops this function from + * compiling until every compiler answers the new value. + * + * @param emptyStringIsNull the dialect stores `''` as NULL (Oracle). + * @throws TypeError when `leaf` is not a fixed-read leaf (`fixedInnerReadOf`). + */ +export function fixedInnerReadPredicates( + leaf: FixedReadLeaf, + { emptyStringIsNull }: { readonly emptyStringIsNull: boolean }, +): FixedInnerReadPredicates { + const read: FixedInnerRead = fixedInnerReadOf(leaf); + // ADR-0155 ① ruled A: no tenant scope on the inner read. A widened type fails here. + const tenantScope: 'none' = read.tenantScope; + void tenantScope; + return Object.freeze({ + table: read.table, + column: read.column, + equals: Object.freeze(Object.entries(read.equals)), + memberOf: Object.freeze(Object.entries(read.memberOf)), + notEmpty: !emptyStringIsNull, + }); +} diff --git a/packages/drivers/driver-sql/src/index.ts b/packages/drivers/driver-sql/src/index.ts index 720ac0767f9..119c4f94c64 100644 --- a/packages/drivers/driver-sql/src/index.ts +++ b/packages/drivers/driver-sql/src/index.ts @@ -23,6 +23,11 @@ export { recoverUnencodedJsonText } from './unencoded-json-text.js'; // face compiles SQL text with its own compiler, and must regroup by the same // rule the knex path does. export { FLAT_GROUP_MAX_MEMBERS, joinBalancedGroup } from './sql-driver-balanced-group.js'; +// [ADR-0155 D2, D4] Where a fixed-read leaf compiles and the predicates of its +// fixed inner read. Exported because the Turso remote face compiles the leaf +// with its own compiler, from the same walk and the same predicates. +export { findMisplacedFixedReadLeaf, fixedInnerReadPredicates, misplacedFixedReadLeafMessage } from './fixed-read-leaf-compile.js'; +export type { FixedInnerReadPredicates, MisplacedFixedReadLeaf } from './fixed-read-leaf-compile.js'; // [cloud#3652 D3] The declared-rename refusal the sync throws before any DDL, // and its renderer, so a host reporting a refused sync (the install door, `os // migrate apply`) reads the structured refusals rather than parsing the text; diff --git a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts index 21ac54f81c7..8dbf613e04b 100644 --- a/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-filter-helpers.ts @@ -39,12 +39,13 @@ * evaluation cycle. `index.ts` re-exports nothing from this module. */ -import { isComposedReadableIds, resolveFilterSubtreeProvenance } from '@objectstack/spec/data'; +import { isComposedReadableIds, isFixedReadLeaf, resolveFilterSubtreeProvenance } from '@objectstack/spec/data'; import type { DriverOptions, ValueShapeFieldDef } from '@objectstack/spec/data'; -import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAsNumber, refuseReadableIdsOnce, temporalStorageForm } from '@objectstack/core'; +import { JSON_COLUMN_INCOMPATIBLE_OPERATORS, findMisplacedReadableIds, presentAsNumber, refuseFixedReadLeafOnce, refuseReadableIdsOnce, temporalStorageForm } from '@objectstack/core'; import type { JsonColumnFieldClass } from '@objectstack/core'; import { StorageNameMapping } from '@objectstack/spec/system'; import { emitBalancedGroup } from './sql-driver-balanced-group.js'; +import { findMisplacedFixedReadLeaf, misplacedFixedReadLeafMessage } from './fixed-read-leaf-compile.js'; import { presentStoredBoolean, sqliteBooleanBinding } from './sql-driver-sqlite-serialisation.js'; import type { Knex } from 'knex'; import { @@ -101,6 +102,8 @@ export interface FilterHelpersHost { readonly dateFieldsOnInstantColumn: SqlDriver['dateFieldsOnInstantColumn']; readonly datetimeFields: SqlDriver['datetimeFields']; filterColumnExpr: SqlDriver['filterColumnExpr']; + readonly fixedReadLeafRefusalLog: SqlDriver['fixedReadLeafRefusalLog']; + fixedReadLeafSubquery: SqlDriver['fixedReadLeafSubquery']; isJsonColumn: SqlDriver['isJsonColumn']; readonly isMssql: SqlDriver['isMssql']; readonly isMysql: SqlDriver['isMysql']; @@ -524,13 +527,20 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#applyFilters`; the method's docblock there is its contract. */ - static applyFilters(this: Pick, builder: Knex.QueryBuilder, filters: any, options?: DriverOptions) { + static applyFilters(this: Pick, builder: Knex.QueryBuilder, filters: any, options?: DriverOptions) { // [ADR-0139 D3] A `ReadableIds` leaf this compiler will not evaluate — an // UNCOMPOSED one anywhere, a composed one outside a `$in` comparand — is // refused before anything compiles: INTERNAL_ERROR / 500, logged at // `error` once per driver. ⛔ Never evaluated as "no restriction". const misplaced = findMisplacedReadableIds(filters, true); if (misplaced) throw refuseReadableIdsOnce(this.readableIdsDriverName, misplaced, this.logger, this.readableIdsRefusalLog); + // [ADR-0155 D1, D4] Likewise a fixed-read leaf anywhere but as a field's + // `$in` comparand, the one position `applyFilterCondition` compiles it in: + // the same envelope, logged once per driver on its own flag. + const misplacedLeaf = findMisplacedFixedReadLeaf(filters); + if (misplacedLeaf) { + throw refuseFixedReadLeafOnce(this.readableIdsDriverName, misplacedFixedReadLeafMessage(misplacedLeaf), this.logger, this.fixedReadLeafRefusalLog); + } try { this.compileFilters(builder, filters, options); } catch (err) { @@ -697,7 +707,7 @@ export class FilterHelpersFacet { } /** The body of `SqlDriver#applyFilterCondition`; the method's docblock there is its contract. */ - static applyFilterCondition(this: Pick, + static applyFilterCondition(this: Pick, builder: Knex.QueryBuilder, condition: any, logicalOp: 'and' | 'or' = 'and', @@ -845,6 +855,16 @@ export class FilterHelpersFacet { (builder as any)[mIn](field, this.readableIdsSubquery(opValue, options)); continue; } + // [ADR-0155 D2, D4] A fixed-read leaf, the other non-list a `$in` may + // hold, compiles to its fixed inner read in the list's own position, + // `field IN (SELECT …)` (`SqlDriver#fixedReadLeafSubquery`), under the + // outer statement's own wall and nothing else. `applyFilters` refused + // it at every other position. + if (rawOp === '$in' && isFixedReadLeaf(opValue)) { + const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn'; + (builder as any)[mIn](field, this.fixedReadLeafSubquery(opValue)); + continue; + } // #5222 — a `{ $field }` that is the WHOLE comparand of a scalar // comparison compiles to a same-table column-to-column comparison // (or refuses inside the emitter, with the specific boundary named). diff --git a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts index e56395c706e..317be8d95ab 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -5,7 +5,9 @@ * `getKnex`, `getBuilder`, `resolveTenantField`, `isMultiTenantMode`, * `applyTenantScope`, `readableIdsSubquery`, `injectTenantOnInsert`, * `auditMissingTenant` moved out of `sql-driver.ts` whole (split - * by #29598 and #30249). + * by #29598 and #30249). `fixedReadLeafSubquery` (ADR-0155 D2) was written + * here, a private method's body with its docblock, beside the subquery it + * mirrors. * * A MOVE, not a redesign. {@link InternalHelpersFacet} is a stateless facet of `SqlDriver` * (ruling 6624345766): each static method of it is the body of the `SqlDriver` @@ -30,12 +32,13 @@ * evaluation cycle. `index.ts` re-exports nothing from this module. */ -import type { ComposedReadableIds, DriverOptions } from '@objectstack/spec/data'; +import type { ComposedReadableIds, DriverOptions, FixedReadLeaf } from '@objectstack/spec/data'; import { StorageNameMapping } from '@objectstack/spec/system'; import { resolveTenancyPosture } from '@objectstack/types'; import { postureEnforcesWall } from '@objectstack/spec/security'; import type { Knex } from 'knex'; import type { SqlDriver } from './sql-driver.js'; +import { fixedInnerReadPredicates } from './fixed-read-leaf-compile.js'; /** * The `SqlDriver` members the bodies of {@link InternalHelpersFacet} read — every one of @@ -49,6 +52,7 @@ export interface InternalHelpersHost { applyTenantScope: SqlDriver['applyTenantScope']; getBuilder: SqlDriver['getBuilder']; isMultiTenantMode: SqlDriver['isMultiTenantMode']; + readonly isOracle: SqlDriver['isOracle']; readonly knex: SqlDriver['knex']; readonly logger: SqlDriver['logger']; readonly physicalSchemaByObject: SqlDriver['physicalSchemaByObject']; @@ -141,6 +145,43 @@ export class InternalHelpersFacet { return sub; } + /** + * The body of `SqlDriver#fixedReadLeafSubquery`, a private method, with its + * docblock: [ADR-0155 D2, D4] the subquery a fixed-read leaf compiles to, + * which the `$in` arm of `applyFilterCondition` embeds as `field IN (…)`: + * + * ```sql + * SELECT record_id FROM sys_record_share + * WHERE object_name = ? AND recipient_type = ? AND recipient_id = ? + * [AND access_level IN (?, …)] -- the write form (③ ruled A) + * AND record_id IS NOT NULL AND record_id <> '' + * ``` + * + * The table, the column and every predicate are the leaf's own description + * (`fixedInnerReadPredicates`), every value bound. On Oracle, which stores + * `''` as NULL, the guard is `IS NOT NULL` alone. + * + * - **No tenant scope (ADR-0155 ① ruled A).** ⛔ No `applyTenantScope` on + * this builder: today's read of the table carries none, and the subquery + * carries none either. `scripts/check-tenant-chokepoint.mjs` records the + * absence as an exemption citing that ruling. The OUTER statement's wall is + * untouched: it is applied to the outer builder as on every read. + * - **Same datasource.** The table is resolved by `getBuilder`, on this + * driver, as a read of it is; the engine's seam refuses an object bound to + * another datasource before any driver is called. + * - **One statement.** No transaction of its own (it is part of the outer + * statement), no cap, no ordering, ⛔ no `EXISTS`, no correlation, no join. + */ + static fixedReadLeafSubquery(this: Pick, leaf: FixedReadLeaf): Knex.QueryBuilder { + const read = fixedInnerReadPredicates(leaf, { emptyStringIsNull: this.isOracle }); + const inner = this.getBuilder(read.table).select(read.column); + for (const [column, value] of read.equals) inner.where(column, value); + for (const [column, values] of read.memberOf) inner.whereIn(column, [...values]); + inner.whereNotNull(read.column); + if (read.notEmpty) inner.where(read.column, '<>', ''); + return inner; + } + /** The body of `SqlDriver#injectTenantOnInsert`; the method's docblock there is its contract. */ static injectTenantOnInsert(this: Pick, object: string, row: Record, options?: DriverOptions): void { const tenantId = options?.tenantId; diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 85a046fc367..0298fbdebb5 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -7,7 +7,7 @@ * Supports PostgreSQL, MySQL, SQLite, and other SQL databases. */ -import type { DateGranularityValue, DriverOptions, FilterCondition, SchemaMode } from '@objectstack/spec/data'; +import type { DateGranularityValue, DriverOptions, FilterCondition, FixedReadLeaf, SchemaMode } from '@objectstack/spec/data'; // The ONE introspection contract (ADR-0015 / `ISchemaDiffService`). This // driver's introspection types are DERIVED from these rather than // re-declared next to them — see the `Introspection Types` region below. @@ -413,6 +413,10 @@ export class SqlDriver implements IDataDriver { // here. Every dialect; `SqliteWasmDriver` and `TursoDriver` inherit it // (Turso's remote transport compiles the leaf with its own compiler). readableIdsLeaf: true, + // [ADR-0155 D4] The filter compiler compiles a `SharedRecordIds` leaf to its + // fixed inner read as one subquery (`applyFilterCondition`), every dialect; + // TursoDriver's remote transport compiles it with its own compiler. + fixedReadLeaves: ['SharedRecordIds' as const], }; } @@ -764,6 +768,8 @@ export class SqlDriver implements IDataDriver { * `driver-turso`), so the operator reading the line looks in the right place. */ protected readonly readableIdsDriverName: string = 'driver-sql'; + /** [ADR-0155 D4] Whether this instance has logged its fixed-read leaf refusal (once per driver). */ + protected readonly fixedReadLeafRefusalLog = { logged: false }; /** * Optional logger sink for security-audit warnings. Tests inject a spy; @@ -6519,6 +6525,11 @@ export class SqlDriver implements IDataDriver { return InternalHelpersFacet.readableIdsSubquery.call(internalHelpersHost.of(this), leaf, options); } + private fixedReadLeafSubquery(leaf: FixedReadLeaf): Knex.QueryBuilder { + // [ADR-0155 D2] The body lives in `sql-driver-internal-helpers.ts`, its docblock with it. + return InternalHelpersFacet.fixedReadLeafSubquery.call(internalHelpersHost.of(this), leaf); + } + /** * Auto-inject the tenant column on insert rows when: * 1. `options.tenantId` is provided, AND @@ -9705,6 +9716,8 @@ export class SqlDriver implements IDataDriver { get dateFieldsOnInstantColumn() { return driver.dateFieldsOnInstantColumn; }, get datetimeFields() { return driver.datetimeFields; }, filterColumnExpr: (...a) => driver.filterColumnExpr(...a), + get fixedReadLeafRefusalLog() { return driver.fixedReadLeafRefusalLog; }, + fixedReadLeafSubquery: (...a) => driver.fixedReadLeafSubquery(...a), isJsonColumn: (...a) => driver.isJsonColumn(...a), get isMssql() { return driver.isMssql; }, get isMysql() { return driver.isMysql; }, @@ -9748,6 +9761,7 @@ export class SqlDriver implements IDataDriver { applyTenantScope: (...a) => driver.applyTenantScope(...a), get getBuilder() { return driver.getBuilder.bind(driver); }, isMultiTenantMode: (...a) => driver.isMultiTenantMode(...a), + get isOracle() { return driver.isOracle; }, get knex() { return driver.knex; }, get logger() { return driver.logger; }, get physicalSchemaByObject() { return driver.physicalSchemaByObject; }, diff --git a/packages/drivers/driver-turso/src/remote-transport.ts b/packages/drivers/driver-turso/src/remote-transport.ts index c260a83aa25..bfafe299e93 100644 --- a/packages/drivers/driver-turso/src/remote-transport.ts +++ b/packages/drivers/driver-turso/src/remote-transport.ts @@ -64,6 +64,12 @@ import { // local face (`SqlDriver.applyFilters`), `driver-memory` and `driver-mongodb`. import { findMisplacedReadableIds, readableIdsDriverRefusal } from '@objectstack/core'; import { isComposedReadableIds, type FilterCondition } from '@objectstack/spec/data'; +// [ADR-0155 D2, D4] The fixed-read leaf: where it compiles and the predicates of +// its fixed inner read, shared with the local face's compiler +// (`SqlDriver#fixedReadLeafSubquery`), and the refusal every evaluator answers. +import { fixedReadLeafRefusal } from '@objectstack/core'; +import { findMisplacedFixedReadLeaf, fixedInnerReadPredicates, misplacedFixedReadLeafMessage } from '@objectstack/driver-sql'; +import { isFixedReadLeaf, type FixedReadLeaf } from '@objectstack/spec/data'; // [#8413] What a `unique: true` FIELD becomes, from the one place that decides // it. `uniqueIndexesFromFields`' own contract is that it is "the ONLY place // field-level uniqueness becomes an index, so the create-table, alter-table, @@ -3140,6 +3146,40 @@ export class RemoteTransport { return { sql: `SELECT "id" FROM ${this.tableSql(join.table)}${where}`, args }; } + /** + * [ADR-0155 D2, D4] The fixed inner read a fixed-read leaf compiles to — the + * local face's `SqlDriver#fixedReadLeafSubquery`, compiled by this + * transport's compiler from the same predicates (`fixedInnerReadPredicates`): + * + * `SELECT "record_id" FROM "sys_record_share" WHERE "object_name" = ? AND + * "recipient_type" = ? AND "recipient_id" = ? [AND "access_level" IN (?, …)] + * AND "record_id" IS NOT NULL AND "record_id" <> ?` + * + * Every value bound. ⛔ No tenant scope (ADR-0155 ① ruled A): the driver + * hands over none for it, and the outer statement's scope is ANDed on by + * the door as on every statement. No cap, no ordering, no correlation. + */ + private fixedInnerReadSQL(leaf: FixedReadLeaf): { sql: string; args: unknown[] } { + const read = fixedInnerReadPredicates(leaf, { emptyStringIsNull: false }); + const column = this.aliasIdentifierSql(read.column); + const parts: string[] = []; + const args: unknown[] = []; + for (const [name, value] of read.equals) { + parts.push(`${this.aliasIdentifierSql(name)} = ?`); + args.push(value); + } + for (const [name, values] of read.memberOf) { + parts.push(`${this.aliasIdentifierSql(name)} IN (${values.map(() => '?').join(', ')})`); + args.push(...values); + } + parts.push(`${column} IS NOT NULL`); + if (read.notEmpty) { + parts.push(`${column} <> ?`); + args.push(''); + } + return { sql: `SELECT ${column} FROM ${this.tableSql(read.table)} WHERE ${parts.join(' AND ')}`, args }; + } + private buildWhereSQL( object: string, filters: any, @@ -3161,6 +3201,12 @@ export class RemoteTransport { // semi-join is not a leaf, so this answers `null` for every tree it hands over. const misplaced = findMisplacedReadableIds(filters, true); if (misplaced) throw readableIdsDriverRefusal('driver-turso', misplaced); + // [ADR-0155 D1, D4] Likewise a fixed-read leaf anywhere but as a field's + // `$in` comparand. A resolved semi-join's scope is a node like a composed + // leaf's; `TursoDriver` asks the same walk first, and logs. + const misplacedLeaf = findMisplacedFixedReadLeaf(filters, path, (value) => + isRemoteReadableIdsSemiJoin(value) ? value : null); + if (misplacedLeaf) throw fixedReadLeafRefusal('driver-turso', misplacedFixedReadLeafMessage(misplacedLeaf)); try { return this.compileWhereSQL(object, filters, path); } catch (err) { @@ -3538,6 +3584,13 @@ export class RemoteTransport { args.push(...sub.args); break; } + // [ADR-0155 D2, D4] A fixed-read leaf, in the list's own position. + if (isFixedReadLeaf(opValue)) { + const sub = this.fixedInnerReadSQL(opValue); + clauses.push(`${column} IN (${sub.sql})`); + args.push(...sub.args); + break; + } if (isComposedReadableIds(opValue)) { throw readableIdsDriverRefusal( 'driver-turso', diff --git a/packages/drivers/driver-turso/src/turso-driver.ts b/packages/drivers/driver-turso/src/turso-driver.ts index dc1feb404f6..43e310f0f8e 100644 --- a/packages/drivers/driver-turso/src/turso-driver.ts +++ b/packages/drivers/driver-turso/src/turso-driver.ts @@ -37,6 +37,8 @@ import { parseIndexDdl, planDeclaredRenames, latestPerDirectiveOf, + findMisplacedFixedReadLeaf, + misplacedFixedReadLeafMessage, type DeclaredRenameCarry, type DeclaredRenamePlan, type DriftOp, @@ -56,7 +58,7 @@ import { RemoteTransport, remoteReadableIdsSemiJoin, type RemoteTenantScope } fr import { planRelaxedColumnDefinition } from './remote-relax-not-null.js'; // [ADR-0139 D3] The walk, the rewrite and the refusal for a `ReadableIds` leaf — // shared with the local face this class inherits, `driver-memory` and `driver-mongodb`. -import { findMisplacedReadableIds, refuseReadableIdsOnce, replaceComposedReadableIds } from '@objectstack/core'; +import { findMisplacedReadableIds, refuseFixedReadLeafOnce, refuseReadableIdsOnce, replaceComposedReadableIds } from '@objectstack/core'; import { backfillRemoteCanonicalColumns, type RemoteBackfillClient, @@ -1962,6 +1964,10 @@ export class TursoDriver extends SqlDriver { // on the engine's `find()` + in-memory path, which answers it; local and // embedded-replica modes run SqlDriver's own compile and inherit `true`. ...(this.transportMode === 'remote' ? { aggregationFilter: false } : {}), + + // [ADR-0155 D4] `fixedReadLeaves` is inherited in every mode: local and + // embedded-replica modes run SqlDriver's compile, and remote mode's + // transport compiles the leaf with its own (`fixedInnerReadSQL`). }; } @@ -3506,6 +3512,14 @@ export class TursoDriver extends SqlDriver { private toRemoteWhere(object: string, where: unknown, options: DriverOptions | undefined): unknown { const misplaced = findMisplacedReadableIds(where, true); if (misplaced) throw refuseReadableIdsOnce(this.readableIdsDriverName, misplaced, this.logger, this.readableIdsRefusalLog); + // [ADR-0155 D1, D4] A fixed-read leaf anywhere but as a field's `$in` + // comparand, refused as the local face's `applyFilters` refuses it. One + // that is placed passes through by reference (`replaceComposedReadableIds` + // and `toRemoteFilter` copy around it), and the transport compiles it. + const misplacedLeaf = findMisplacedFixedReadLeaf(where); + if (misplacedLeaf) { + throw refuseFixedReadLeafOnce(this.readableIdsDriverName, misplacedFixedReadLeafMessage(misplacedLeaf), this.logger, this.fixedReadLeafRefusalLog); + } const resolved = replaceComposedReadableIds(where, (leaf) => remoteReadableIdsSemiJoin({ object: leaf.object, table: this.remoteTableFor(leaf.object, 'ReadableIds'), diff --git a/packages/spec/src/data/fixed-read-leaf-conformance.test.ts b/packages/spec/src/data/fixed-read-leaf-conformance.test.ts index bb38d67c783..7c3a3ce5e87 100644 --- a/packages/spec/src/data/fixed-read-leaf-conformance.test.ts +++ b/packages/spec/src/data/fixed-read-leaf-conformance.test.ts @@ -271,7 +271,7 @@ describe('SHARED_RECORD_IDS_CASE_SET — each wrong reading of the leaf fails th expect(failing('inner-read-walled')).toEqual( set.cases.filter((c) => c.requiresUnwalledInnerRead === true).map((c) => c.name), ); - expect(failing('inner-read-walled')).toHaveLength(1); + expect(failing('inner-read-walled')).toHaveLength(2); }); it('a join in place of the semi-join fails: a record with two grant rows is answered twice', () => { diff --git a/packages/spec/src/data/fixed-read-leaf-conformance.ts b/packages/spec/src/data/fixed-read-leaf-conformance.ts index 4e4789b9cbc..8c4bf05e3c6 100644 --- a/packages/spec/src/data/fixed-read-leaf-conformance.ts +++ b/packages/spec/src/data/fixed-read-leaf-conformance.ts @@ -224,7 +224,8 @@ const DOC_ROWS: readonly FixedReadLeafRow[] = frozenRows([ * - `g6` is a group's grant whose id happens to be `u1` (`recipient_type` * fixed to `'user'`); * - `g7` grants `d7`, a doc in `org_a`, on a row stamped `org_b`: it counts, - * because the inner read carries no tenant scope (① ruled A); + * because the inner read carries no tenant scope (① ruled A), directly and + * through the note `n5` in the nested position; * - `g8` grants `d8`, a doc in `org_b`: under a tenant read in `org_a` the * OUTER wall drops it, as it does today; * - `g9` and `g10` carry a NULL and an empty `record_id` (the blank-id guard). @@ -244,12 +245,17 @@ const GRANT_ROWS: readonly FixedReadLeafRow[] = frozenRows([ { id: 'g10', object_name: DOC, recipient_type: 'user', recipient_id: 'u1', record_id: '', access_level: LEVEL_EDIT, organization_id: 'org_a' }, ]); -/** Four notes, the nested position's rows. `n4` names no doc. */ +/** + * Five notes, the nested position's rows. `n4` names no doc; `n5` names `d7`, + * whose only grant is stamped in another organization, so the nested position + * crosses an organization too. + */ const NOTE_ROWS: readonly FixedReadLeafRow[] = frozenRows([ { id: 'n1', record_id: 'd1', organization_id: 'org_a' }, { id: 'n2', record_id: 'd3', organization_id: 'org_a' }, { id: 'n3', record_id: 'd4', organization_id: 'org_a' }, { id: 'n4', record_id: null, organization_id: 'org_a' }, + { id: 'n5', record_id: 'd7', organization_id: 'org_a' }, ]); const read = (recipient: string) => SharedRecordIds.read(DOC, recipient); @@ -381,10 +387,23 @@ const SHARED_RECORD_IDS_CASES: readonly FixedReadLeafMatchesCase[] = Object.free object: NOTE, where: () => ({ record_id: { $in: ReadableIds.compose(ReadableIds.of(DOC), readScope('u1')) } }), holdsLeaf: true, - expected: ['n1', 'n2'], + expected: ['n1', 'n2', 'n5'], note: 'ADR-0155 D4: the scope the engine composes for a ReadableIds leaf is the parent\'s read filter, which ' - + 'carries this leaf for a sharing-scoped parent. n1\'s doc is shared, n2\'s is owned, n3\'s is neither ' - + 'and n4 names none. A driver that evaluates the inner leaf as no restriction returns n3 too.', + + 'carries this leaf for a sharing-scoped parent. n1\'s and n5\'s docs are shared, n2\'s is owned, n3\'s is ' + + 'neither and n4 names none. A driver that evaluates the inner leaf as no restriction returns n3 too.', + }, + { + name: 'nested, under a tenant: the inner read stays unwalled inside the parent\'s walled subquery', + verdict: 'matches', + object: NOTE, + where: () => ({ record_id: { $in: ReadableIds.compose(ReadableIds.of(DOC), readScope('u1')) } }), + options: { tenantId: 'org_a' }, + requiresUnwalledInnerRead: true, + holdsLeaf: true, + expected: ['n1', 'n2', 'n5'], + note: 'ADR-0155 ① ruled A, in the nested position: the composed scope\'s subquery takes the outer read\'s ' + + 'tenant wall on the doc (ADR-0139 D3), and the leaf inside it takes none, so n5 counts through d7, whose ' + + 'only grant is stamped org_b. An inner read walled with the driver\'s tenant scope drops n5.', }, ]); diff --git a/scripts/check-tenant-chokepoint.mjs b/scripts/check-tenant-chokepoint.mjs index f11270294ed..d980d88cfe8 100644 --- a/scripts/check-tenant-chokepoint.mjs +++ b/scripts/check-tenant-chokepoint.mjs @@ -311,12 +311,25 @@ const TENANT_PREDICATE_FLOOR = 3; /** * `'::::'` -> reason a reader can check. * - * Empty by design. #6792 closed the last three unscoped read doors, so this - * starts from zero rather than from a ratchet. A new entry needs a reason, - * not a name — and "the layer above catches it" is not one: the chokepoint's - * own contract is what this asserts. + * #6792 closed the last three unscoped read doors, so this started from zero + * rather than from a ratchet. A new entry needs a reason, not a name — and + * "the layer above catches it" is not one: the chokepoint's own contract is + * what this asserts. One entry, a decision recorded rather than a door left + * open: + * + * - `fixedReadLeafSubquery`'s `inner` is the fixed inner read a + * `SharedRecordIds` leaf compiles to, a SUBQUERY embedded as + * `id IN (SELECT record_id FROM sys_record_share …)` in a statement whose + * outer builder IS scoped; it never escapes as a read of its own. ADR-0155 + * D2 rules that it carries no tenant scope (① ruled A, ruling 6942854600 on + * #33787) and that the driver card records that absence here. */ -const EXEMPT = Object.create(null); +const EXEMPT = Object.assign(Object.create(null), { + 'packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts::fixedReadLeafSubquery::inner': + 'ADR-0155 D2, ① ruled A (ruling 6942854600 on #33787): the fixed inner read of a SharedRecordIds leaf carries ' + + 'no tenant scope, as today\'s read of sys_record_share carries none; it is a subquery of a statement whose ' + + 'outer builder applyTenantScope walls, never a read door of its own', +}); const BUILDER_FACTORY = 'getBuilder'; const SCOPE_CALL = 'applyTenantScope'; @@ -1324,7 +1337,8 @@ decision and needs a superseding ADR first.`); console.log( `✓ check:tenant-chokepoint: ${discovered} ${BUILDER_FACTORY}() binding(s) across ${scannedFiles} ` + - 'file(s); every read builder routes through applyTenantScope(), every unscoped one is an insert; ' + + 'file(s); every read builder routes through applyTenantScope(), every unscoped one is an insert or ' + + `one of ${Object.keys(EXEMPT).length} EXEMPT entr(ies) with its reason; ` + 'no IS NULL arm on a tenant column (ADR-0131 D8).', ); } From 9a099c3d2185545c884facf47618d8041a5d0a53 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:55:01 +0000 Subject: [PATCH 2/3] test(driver-sql, driver-turso): pin the SharedRecordIds compile per dialect and on both Turso faces (ADR-0155 step 3) The shared case-set runs on every live dialect cell and on both Turso faces, find and count; the predicate update's two statements (the prior-row find and updateMany, same AST) each answer the write-form cases' rows, and each reads the grants as they stand when it runs. A record whose id is the empty string witnesses the <> '' half of the blank-id guard (step 1's L2 N4). O2: the leaf answers today's list's rows for case and padding variants, and for an INTEGER federated key on SQLite. The compiled statement is pinned on SQLite, PostgreSQL, MySQL, SQL Server and Oracle; refusals assert code and status. Also: a changeset, and ADR anchors for the three files whose behaviour ADR-0155 decides. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .../35872-shared-record-ids-sql-compile.md | 19 + ...driver-fixed-read-leaf-conformance.test.ts | 389 ++++++++++++++++++ .../src/sql-driver-internal-helpers.ts | 4 +- .../turso-fixed-read-leaf-conformance.test.ts | 273 ++++++++++++ ...-sql__src__fixed-read-leaf-compile.ts.json | 7 + ...__src__sql-driver-internal-helpers.ts.json | 8 + ...river-turso__src__remote-transport.ts.json | 8 + 7 files changed, 707 insertions(+), 1 deletion(-) create mode 100644 .changeset/35872-shared-record-ids-sql-compile.md create mode 100644 packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts create mode 100644 packages/drivers/driver-turso/src/turso-fixed-read-leaf-conformance.test.ts create mode 100644 scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-compile.ts.json create mode 100644 scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-internal-helpers.ts.json create mode 100644 scripts/adr-anchors/packages__drivers__driver-turso__src__remote-transport.ts.json diff --git a/.changeset/35872-shared-record-ids-sql-compile.md b/.changeset/35872-shared-record-ids-sql-compile.md new file mode 100644 index 00000000000..c87e4bb62bd --- /dev/null +++ b/.changeset/35872-shared-record-ids-sql-compile.md @@ -0,0 +1,19 @@ +--- +'@objectstack/driver-sql': patch +'@objectstack/driver-turso': patch +'@objectstack/spec': patch +--- + +feat(driver-sql, driver-turso): the SQL drivers compile the `SharedRecordIds` fixed-read leaf to a subquery (ADR-0155, step 3 of 6) + +Clause-②: yes +Metadata-protocol: none + +No visible change on its own: nothing on main writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step. + +- **The compile** (`@objectstack/driver-sql`). A `SharedRecordIds` leaf in a field's `$in` compiles to one subquery in the list's own position: `id IN (SELECT record_id FROM sys_record_share WHERE object_name = ? AND recipient_type = 'user' AND recipient_id = ? AND record_id IS NOT NULL AND record_id <> '')`. The write form adds `AND access_level IN (…)` inside the subquery. Every value is bound. The subquery carries no tenant scope (ADR-0155 ① ruled A), and the outer statement's tenant wall is unchanged. It covers every read verb and `updateMany`, on SQLite, PostgreSQL, MySQL, SQL Server and Oracle. On Oracle the `<> ''` half is left out, because Oracle stores `''` as NULL. `SqliteWasmDriver` and Turso's local mode inherit the compile. +- **The remote transport** (`@objectstack/driver-turso`). Turso's remote mode compiles the same subquery with its own compiler, from the same predicates. +- **The declaration.** `SqlDriver.supports.fixedReadLeaves` is `['SharedRecordIds']`, and `TursoDriver` inherits it in every mode. The engine's seam now hands the leaf to these drivers instead of refusing it. +- **The refusal.** A leaf anywhere other than a field's `$in` comparand is refused before any statement runs, with `INTERNAL_ERROR` / 500, and logged at `error` once per driver. +- **New exports** (`@objectstack/driver-sql`). `findMisplacedFixedReadLeaf`, `fixedInnerReadPredicates` and `misplacedFixedReadLeafMessage` are the walk, the predicates and the refusal text the two compilers share. +- **The shared case-set** (`@objectstack/spec`). `SHARED_RECORD_IDS_CASE_SET` gains a note (`n5`) on a doc whose only grant is stamped in another organization, and a nested case read under a tenant. Together they witness, in the nested position, that the inner read carries no tenant scope. diff --git a/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts b/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts new file mode 100644 index 00000000000..a30c8e511f5 --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-fixed-read-leaf-conformance.test.ts @@ -0,0 +1,389 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 plan step 3] `driver-sql` compiles the `SharedRecordIds` + * fixed-read leaf to its fixed inner read, `field IN (SELECT record_id FROM + * sys_record_share WHERE … AND record_id IS NOT NULL AND record_id <> '')`, + * with no tenant scope on the subquery (① ruled A), on reads and on the + * predicate-update path (③ ruled A), and refuses a misplaced leaf with + * ADR-0139 D3's envelope. + * + * Every live dialect cell runs: + * + * - **the shared case-set** (`SHARED_RECORD_IDS_CASE_SET.cases`, + * `@objectstack/spec/data`), `find` and `count`, no per-driver hand copy; + * - **the predicate update's two statements**: the engine's prior-row read, + * `driver.find(object, ast, preOpts)`, and the write, + * `driver.updateMany(object, ast, data, opts)` (`engine-update.ts`), each + * evaluating the share arm for itself (ADR-0155, Consequences, Freshness); + * - **N4 (step 1's L2)**: the `<> ''` half of the blank-id guard, witnessed by + * a record whose id is the empty string, which no registration door writes + * and so the shared fixture cannot hold; + * - **O2**: the comparison is the outer column's against `record_id` under the + * dialect's own collation, exactly as today's list binds it, so the leaf and + * the list answer the same rows for case and padding variants too; + * - the declaration, the absence of a tenant scope in the statement, the + * bindings, and the refusals with `code` and `status`. + * + * MSSQL and Oracle are pinned by the compiled statement (no server here). + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import type { Knex } from 'knex'; +import { + READABLE_IDS_REFUSAL, + ReadableIds, + SHARED_RECORD_IDS_CASE_SET, + SharedRecordIds, + isSharedRecordIds, + lowerFilterCondition, + type FilterCondition, + type FixedReadLeafRow, +} from '@objectstack/spec/data'; +import { SqlDriver, type SqlDriverConfig } from './sql-driver.js'; +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; + +const set = SHARED_RECORD_IDS_CASE_SET; +const seamed = (where: unknown): any => lowerFilterCondition(where, { isDatetimeColumn: () => false }); + +const DOC = 'srid_doc'; +const GRANTS = 'sys_record_share'; +/** O2's object: ids that a case- or padding-insensitive collation would confuse with a grant's spelling. */ +const O2 = 'srid_o2'; +const TABLES = [DOC, GRANTS, 'srid_note', O2]; + +const rowsOf = (object: string): readonly FixedReadLeafRow[] => set.tables.find((t) => t.object === object)!.rows; +const fieldsOf = (rows: readonly FixedReadLeafRow[]): Record => + Object.fromEntries([...new Set(rows.flatMap((r) => Object.keys(r)))].filter((k) => k !== 'id').map((k) => [k, { type: 'text' }])); +const sortedIds = (rows: any[]): string[] => rows.map((r) => String(r.id)).sort(); + +/** Does `where` hold a WRITE-form leaf (one that carries `accessLevels`), at any depth? */ +const holdsWriteForm = (node: unknown): boolean => { + if (isSharedRecordIds(node)) return node.accessLevels !== undefined; + if (node === null || typeof node !== 'object') return false; + return (Array.isArray(node) ? node : Object.values(node)).some(holdsWriteForm); +}; + +const O2_ROWS = [ + { id: 'k1', organization_id: 'org_a' }, + { id: 'k2', organization_id: 'org_a' }, + { id: 'k3', organization_id: 'org_a' }, +]; +/** A grant per spelling: a case variant, a trailing space, and the exact id. */ +const O2_GRANTS = [ + { id: 'o2g1', object_name: O2, recipient_type: 'user', recipient_id: 'u9', record_id: 'K1', access_level: 'lvl_read', organization_id: 'org_a' }, + { id: 'o2g2', object_name: O2, recipient_type: 'user', recipient_id: 'u9', record_id: 'k2 ', access_level: 'lvl_read', organization_id: 'org_a' }, + { id: 'o2g3', object_name: O2, recipient_type: 'user', recipient_id: 'u9', record_id: 'k3', access_level: 'lvl_read', organization_id: 'org_a' }, +]; + +async function seedDocs(driver: SqlDriver): Promise { + const knex: Knex = (driver as any).knex; + await knex(DOC).del(); + await knex(DOC).insert(rowsOf(DOC).map((r) => ({ ...r }))); +} + +function declareFixedReadLeafSweep(cell: DialectCell): void { + describe(`[ADR-0155 step 3] driver-sql — SharedRecordIds conformance (${cell.label})`, () => { + let driver: SqlDriver; + let knex: Knex; + + beforeAll(async () => { + driver = new SqlDriver(cell.config()); + knex = (driver as any).knex; + for (const t of TABLES) await driver.execute(`drop table if exists ${t}`).catch(() => {}); + await driver.initObjects([ + ...set.tables.map((t) => ({ name: t.object, fields: fieldsOf(t.rows) })), + { name: O2, fields: fieldsOf(O2_ROWS) }, + ] as any); + for (const t of set.tables) await knex(t.object).insert(t.rows.map((r) => ({ ...r }))); + await knex(O2).insert(O2_ROWS); + await knex(GRANTS).insert(O2_GRANTS); + }, 60_000); + + afterAll(async () => { + for (const t of TABLES) await driver?.execute(`drop table if exists ${t}`).catch(() => {}); + await driver?.disconnect?.(); + }); + + it('declares the leaf it compiles: supports.fixedReadLeaves is exactly [SharedRecordIds]', () => { + expect(driver.supports.fixedReadLeaves).toEqual(['SharedRecordIds']); + }); + + describe('shared conformance cases (find, and count with the same where)', () => { + for (const c of set.cases) { + it(c.name, async () => { + const rows = await driver.find(c.object, { where: seamed(c.where()) }, c.options); + expect(sortedIds(rows), c.note).toEqual([...c.expected]); + // One statement: `count` answers the same population as `find`. + expect(await driver.count(c.object, { where: seamed(c.where()) }, c.options), c.note).toBe(c.expected.length); + }); + } + + it('aggregate agrees with find: the leaf is one statement on every read verb', async () => { + const out = await driver.aggregate( + DOC, + { where: seamed({ id: { $in: SharedRecordIds.read(DOC, 'u1') } }), aggregations: [{ function: 'count', alias: 'n' }] }, + { tenantId: 'org_a' }, + ); + expect(Number((out[0] as any).n)).toBe(3); + }); + }); + + describe('the predicate update\'s two statements (③ ruled A)', () => { + const writeCases = set.cases.filter((c) => holdsWriteForm(c.where())); + + it('the case-set carries write-form cases to run', () => { + expect(writeCases.length).toBeGreaterThanOrEqual(2); + }); + + for (const c of writeCases) { + it(`${c.name}: the prior-row read and the write each answer the case's rows`, async () => { + await seedDocs(driver); + const where = seamed(c.where()); + // The engine's prior-row read: driver.find(object, ast, preOpts). + expect(sortedIds(await driver.find(c.object, { where }, c.options))).toEqual([...c.expected]); + // The write: driver.updateMany(object, ast, data, opts), the same AST. + const touched = await driver.updateMany(c.object, { where }, { label: 'touched' }, c.options); + expect(touched).toBe(c.expected.length); + expect(sortedIds(await knex(c.object).where('label', 'touched').select('id'))).toEqual([...c.expected]); + await seedDocs(driver); + }); + } + + it('under a tenant: the write is walled on the outer statement and the inner read stays unwalled', async () => { + await seedDocs(driver); + const where = seamed({ id: { $in: SharedRecordIds.write(DOC, 'u1', ['lvl_edit', 'lvl_full']) } }); + expect(sortedIds(await driver.find(DOC, { where }, { tenantId: 'org_a' }))).toEqual(['d2', 'd7']); + expect(await driver.updateMany(DOC, { where }, { label: 'touched' }, { tenantId: 'org_a' })).toBe(2); + // d7 through g7, stamped org_b (no tenant scope on the inner read); d8 in org_b, outside the outer wall. + expect(sortedIds(await knex(DOC).where('label', 'touched').select('id'))).toEqual(['d2', 'd7']); + await seedDocs(driver); + }); + + it('freshness: each statement reads the grants as they stand when it runs', async () => { + await seedDocs(driver); + const where = () => seamed({ id: { $in: SharedRecordIds.write(DOC, 'u1', ['lvl_edit', 'lvl_full']) } }); + expect(sortedIds(await driver.find(DOC, { where: where() }))).toEqual(['d2', 'd7', 'd8']); + // A grant lands between the prior-row read and the write; another is revoked. + await knex(GRANTS).insert({ id: 'g_fresh', object_name: DOC, recipient_type: 'user', recipient_id: 'u1', record_id: 'd1', access_level: 'lvl_edit', organization_id: 'org_a' }); + await knex(GRANTS).where('id', 'g8').del(); + try { + expect(await driver.updateMany(DOC, { where: where() }, { label: 'touched' })).toBe(3); + expect(sortedIds(await knex(DOC).where('label', 'touched').select('id'))).toEqual(['d1', 'd2', 'd7']); + } finally { + await knex(GRANTS).where('id', 'g_fresh').del(); + await knex(GRANTS).insert(rowsOf(GRANTS).filter((r) => r.id === 'g8').map((r) => ({ ...r }))); + await seedDocs(driver); + } + }); + }); + + describe('N4: the `<> \'\'` half of the blank-id guard', () => { + // A record whose id is the empty string: g10 grants it to u1 by its + // `record_id`, so only the `<> ''` half keeps it out of the set. + beforeAll(async () => { + await knex(DOC).insert({ id: '', owner: 'u2', label: 'keep', organization_id: 'org_a' }); + }); + afterAll(async () => { + await knex(DOC).where('id', '').del(); + }); + + it('the empty id names no record: the leaf does not admit it', async () => { + const rows = await driver.find(DOC, { where: seamed({ id: { $in: SharedRecordIds.read(DOC, 'u1') } }) }); + expect(sortedIds(rows)).toEqual(['d1', 'd2', 'd7', 'd8']); + expect(await driver.count(DOC, { where: seamed({ id: { $in: SharedRecordIds.read(DOC, 'u1') } }) })).toBe(4); + }); + + it('and the negation answers it: not shared', async () => { + const rows = await driver.find(DOC, { where: seamed({ $not: { id: { $in: SharedRecordIds.read(DOC, 'u1') } } }) }); + expect(sortedIds(rows)).toEqual(['', 'd3', 'd4', 'd5', 'd6', 'd9']); + }); + + it('the write path keeps it out too', async () => { + const where = seamed({ id: { $in: SharedRecordIds.write(DOC, 'u1', ['lvl_edit', 'lvl_full']) } }); + try { + expect(await driver.updateMany(DOC, { where }, { label: 'touched' })).toBe(3); + expect(await knex(DOC).where('id', '').first()).toMatchObject({ label: 'keep' }); + } finally { + await knex(DOC).where('label', 'touched').update({ label: 'keep' }); + await knex(DOC).where('id', 'd7').update({ label: 'drop' }); + } + }); + }); + + describe('O2: the comparison, type and collation are today\'s list\'s', () => { + const leaf = () => seamed({ id: { $in: SharedRecordIds.read(O2, 'u9') } }); + const list = () => seamed({ id: { $in: O2_GRANTS.map((g) => g.record_id) } }); + + it('the leaf answers the rows today\'s list of the same grants answers, under this dialect\'s collation', async () => { + const viaList = sortedIds(await driver.find(O2, { where: list() })); + expect(sortedIds(await driver.find(O2, { where: leaf() }))).toEqual(viaList); + expect(await driver.count(O2, { where: leaf() })).toBe(viaList.length); + }); + + if (cell.id === 'sqlite' || cell.id === 'pg') { + it('a deterministic, unpadded collation: only the exact spelling matches, as in the list', async () => { + expect(sortedIds(await driver.find(O2, { where: leaf() }))).toEqual(['k3']); + }); + } + + if (cell.id === 'sqlite') { + // D-0's other type: a federated table keyed by INTEGER. SQLite applies + // the column's numeric affinity to `record_id` in the subquery as it does + // to each bound member of the list, so '07' names 7 both ways. + it('an INTEGER outer key answers the rows today\'s list answers', async () => { + const EXT = 'srid_o2_int'; + await driver.execute(`drop table if exists ${EXT}`).catch(() => {}); + await driver.execute(`create table ${EXT} (id integer primary key, label text)`); + const grants = [ + { id: 'o2i1', object_name: EXT, recipient_type: 'user', recipient_id: 'u9', record_id: '42', access_level: 'lvl_read', organization_id: 'org_a' }, + { id: 'o2i2', object_name: EXT, recipient_type: 'user', recipient_id: 'u9', record_id: '07', access_level: 'lvl_read', organization_id: 'org_a' }, + ]; + try { + await knex(EXT).insert([{ id: 7, label: 'a' }, { id: 42, label: 'b' }, { id: 43, label: 'c' }]); + await knex(GRANTS).insert(grants); + driver.registerExternalObject({ name: EXT, fields: { label: { type: 'text' } } }); + const viaList = await driver.find(EXT, { where: seamed({ id: { $in: grants.map((g) => g.record_id) } }) }); + const viaLeaf = await driver.find(EXT, { where: seamed({ id: { $in: SharedRecordIds.read(EXT, 'u9') } }) }); + expect(sortedIds(viaLeaf)).toEqual(sortedIds(viaList)); + expect(sortedIds(viaLeaf)).toEqual(['42', '7']); + } finally { + await knex(GRANTS).whereIn('id', grants.map((g) => g.id)).del(); + await driver.execute(`drop table if exists ${EXT}`).catch(() => {}); + } + }); + } + }); + + describe('the statement', () => { + it('carries the outer tenant wall once and none inside the subquery, and binds the leaf\'s inputs only', async () => { + const seen: { sql: string; bindings: readonly unknown[] }[] = []; + const onQuery = (q: { sql: string; bindings?: readonly unknown[] }) => { + if (q.sql.includes('sys_record_share')) seen.push({ sql: q.sql, bindings: q.bindings ?? [] }); + }; + knex.on('query', onQuery); + try { + await driver.find(DOC, { where: seamed({ id: { $in: SharedRecordIds.read(DOC, 'u1') } }) }, { tenantId: 'org_a' }); + } finally { + knex.removeListener('query', onQuery); + } + expect(seen).toHaveLength(1); + const { sql, bindings } = seen[0]; + const inner = sql.slice(sql.toLowerCase().indexOf('(select')); + expect(sql.match(/organization_id/g)).toHaveLength(1); + expect(inner).not.toMatch(/organization_id/); + expect(inner.toLowerCase()).toMatch(/is not null and .record_id. <> /); + expect(bindings).toEqual(expect.arrayContaining([DOC, 'user', 'u1', '', 'org_a'])); + // No per-id parameter, whatever the grants hold: the inner read's four and the wall's one. + expect(bindings).toHaveLength(5); + }); + }); + + describe('refusals: a leaf anywhere but a field\'s $in comparand', () => { + const leaf = () => SharedRecordIds.read(DOC, 'u1'); + const misplaced: [string, () => unknown][] = [ + ['as a field\'s bare value', () => ({ id: leaf() })], + ['under $nin', () => ({ id: { $nin: leaf() } })], + ['under $eq', () => ({ id: { $eq: leaf() } })], + ['as a member of a $in list', () => ({ id: { $in: [leaf()] } })], + ['as a $and member', () => ({ $and: [leaf()] })], + ['as $not\'s operand', () => ({ $not: leaf() })], + ['misplaced inside a composed ReadableIds scope', () => ({ record_id: { $in: ReadableIds.compose(ReadableIds.of(DOC), { owner: leaf() }) } })], + ]; + for (const [name, where] of misplaced) { + it(`${name}: INTERNAL_ERROR / 500 on find, count and updateMany, no row written`, async () => { + const object = name.includes('ReadableIds') ? 'srid_note' : DOC; + const w = where() as FilterCondition; + await expect(driver.find(object, { where: w })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + await expect(driver.count(object, { where: w })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + await expect(driver.updateMany(object, { where: w }, { label: 'touched' })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + expect(Number((await knex(DOC).where('label', 'touched').count({ n: '*' }))[0].n)).toBe(0); + }); + } + + it('the refusal names the position and the leaf, never its recipient', async () => { + const err = await driver.find(DOC, { where: { id: { $nin: leaf() } } as any }).catch((e) => e); + expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect(err.message).toContain('[driver-sql] where.id.$nin holds a SharedRecordIds leaf'); + expect(err.message).not.toContain('u1'); + }); + + it('is logged at error once per driver, and every refusal reaches the caller', async () => { + const fresh = new SqlDriver(cell.config()); + const error = vi.spyOn((fresh as any).logger, 'error'); + for (let i = 0; i < 2; i++) { + await expect(fresh.find(DOC, { where: { id: { $nin: leaf() } } as any })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + } + expect(error).toHaveBeenCalledTimes(1); + await fresh.disconnect?.(); + }); + }); + }); +} + +for (const cell of DIALECT_CELLS) declareDialectCell(cell, 'SharedRecordIds conformance', declareFixedReadLeafSweep); + +// ── The compiled statement, on every dialect driver-sql ships ─────────────── + +class CompileProbe extends SqlDriver { + compileWhere(where: FilterCondition): { sql: string; bindings: readonly unknown[] } { + const builder: Knex.QueryBuilder = this.getKnex()(DOC); + this.applyFilters(builder, where); + const native = builder.toSQL().toNative(); + return { sql: native.sql, bindings: native.bindings }; + } +} + +const COMPILE_CONFIGS: Record = { + sqlite: { client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as SqlDriverConfig, + pg: { client: 'pg', connection: {} } as unknown as SqlDriverConfig, + mysql: { client: 'mysql2', connection: {} } as unknown as SqlDriverConfig, + mssql: { client: 'mssql', connection: {}, schemaMode: 'external' } as unknown as SqlDriverConfig, + oracle: { + client: 'oracledb', + connection: { user: 'nobody', password: 'unused', connectString: '127.0.0.1:1/NONE' }, + schemaMode: 'external', + } as unknown as SqlDriverConfig, +}; + +/** What each dialect compiles `{ id: { $in: } }` and the write form to. Never dialled. */ +const COMPILED: Record = { + sqlite: { + read: 'select * from `srid_doc` where `id` in (select `record_id` from `sys_record_share` where `object_name` = ? and `recipient_type` = ? and `recipient_id` = ? and `record_id` is not null and `record_id` <> ?)', + write: 'select * from `srid_doc` where `id` in (select `record_id` from `sys_record_share` where `object_name` = ? and `recipient_type` = ? and `recipient_id` = ? and `access_level` in (?, ?) and `record_id` is not null and `record_id` <> ?)', + }, + pg: { + read: 'select * from "srid_doc" where "id" in (select "record_id" from "sys_record_share" where "object_name" = $1 and "recipient_type" = $2 and "recipient_id" = $3 and "record_id" is not null and "record_id" <> $4)', + write: 'select * from "srid_doc" where "id" in (select "record_id" from "sys_record_share" where "object_name" = $1 and "recipient_type" = $2 and "recipient_id" = $3 and "access_level" in ($4, $5) and "record_id" is not null and "record_id" <> $6)', + }, + mysql: { + read: 'select * from `srid_doc` where `id` in (select `record_id` from `sys_record_share` where `object_name` = ? and `recipient_type` = ? and `recipient_id` = ? and `record_id` is not null and `record_id` <> ?)', + write: 'select * from `srid_doc` where `id` in (select `record_id` from `sys_record_share` where `object_name` = ? and `recipient_type` = ? and `recipient_id` = ? and `access_level` in (?, ?) and `record_id` is not null and `record_id` <> ?)', + }, + mssql: { + read: 'select * from [srid_doc] where [id] in (select [record_id] from [sys_record_share] where [object_name] = @p0 and [recipient_type] = @p1 and [recipient_id] = @p2 and [record_id] is not null and [record_id] <> @p3)', + write: 'select * from [srid_doc] where [id] in (select [record_id] from [sys_record_share] where [object_name] = @p0 and [recipient_type] = @p1 and [recipient_id] = @p2 and [access_level] in (@p3, @p4) and [record_id] is not null and [record_id] <> @p5)', + }, + // Oracle stores '' as NULL, so `<> ''` would be `<> NULL`, true for no row: `IS NOT NULL` is the whole guard. + oracle: { + read: 'select * from "srid_doc" where "id" in (select "record_id" from "sys_record_share" where "object_name" = :1 and "recipient_type" = :2 and "recipient_id" = :3 and "record_id" is not null)', + write: 'select * from "srid_doc" where "id" in (select "record_id" from "sys_record_share" where "object_name" = :1 and "recipient_type" = :2 and "recipient_id" = :3 and "access_level" in (:4, :5) and "record_id" is not null)', + }, +}; + +describe('[ADR-0155 step 3] the compiled fixed inner read, per dialect (no server)', () => { + for (const [dialect, config] of Object.entries(COMPILE_CONFIGS)) { + it(`${dialect}: one subquery in the list's position, every value bound, no tenant scope inside it`, () => { + const probe = new CompileProbe(config); + expect(probe.supports.fixedReadLeaves).toEqual(['SharedRecordIds']); + const read = probe.compileWhere({ id: { $in: SharedRecordIds.read(DOC, 'u1') } } as unknown as FilterCondition); + expect(read.sql).toBe(COMPILED[dialect].read); + expect(read.bindings).toEqual(dialect === 'oracle' ? [DOC, 'user', 'u1'] : [DOC, 'user', 'u1', '']); + const write = probe.compileWhere({ id: { $in: SharedRecordIds.write(DOC, 'u1', ['lvl_edit', 'lvl_full']) } } as unknown as FilterCondition); + expect(write.sql).toBe(COMPILED[dialect].write); + expect(write.bindings).toEqual( + dialect === 'oracle' ? [DOC, 'user', 'u1', 'lvl_edit', 'lvl_full'] : [DOC, 'user', 'u1', 'lvl_edit', 'lvl_full', ''], + ); + }); + } +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts index 317be8d95ab..bd8d9c663c2 100644 --- a/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts +++ b/packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts @@ -165,7 +165,9 @@ export class InternalHelpersFacet { * this builder: today's read of the table carries none, and the subquery * carries none either. `scripts/check-tenant-chokepoint.mjs` records the * absence as an exemption citing that ruling. The OUTER statement's wall is - * untouched: it is applied to the outer builder as on every read. + * untouched: it is applied to the outer builder as on every read. Unlike + * `readableIdsSubquery` above, which IS walled (ADR-0139 D3): the two + * differ on purpose. * - **Same datasource.** The table is resolved by `getBuilder`, on this * driver, as a read of it is; the engine's seam refuses an object bound to * another datasource before any driver is called. diff --git a/packages/drivers/driver-turso/src/turso-fixed-read-leaf-conformance.test.ts b/packages/drivers/driver-turso/src/turso-fixed-read-leaf-conformance.test.ts new file mode 100644 index 00000000000..7de36045e6a --- /dev/null +++ b/packages/drivers/driver-turso/src/turso-fixed-read-leaf-conformance.test.ts @@ -0,0 +1,273 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0155 plan step 3] `TursoDriver` compiles the `SharedRecordIds` + * fixed-read leaf on BOTH faces, and refuses a misplaced one with ADR-0139 + * D3's envelope: + * + * - **local** inherits `SqlDriver`'s compile (`fixedReadLeafSubquery`); + * - **remote** is an independent compiler: `TursoDriver.toRemoteWhere` passes + * a placed leaf through by reference and `RemoteTransport.fixedInnerReadSQL` + * compiles the subquery from the same predicates + * (`fixedInnerReadPredicates`, `@objectstack/driver-sql`). + * + * Each face declares the leaf (`supports.fixedReadLeaves`, inherited), and + * runs the shared case-set (`SHARED_RECORD_IDS_CASE_SET.cases`), the predicate + * update's two statements (the prior-row `find` and `updateMany`, ③ ruled A), + * the `<> ''` witness of the blank-id guard (step 1's L2 N4), and the + * refusals. The remote face also pins the statement it sends. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { + READABLE_IDS_REFUSAL, + ReadableIds, + SHARED_RECORD_IDS_CASE_SET, + SharedRecordIds, + isSharedRecordIds, + lowerFilterCondition, + type FilterCondition, + type FixedReadLeafRow, +} from '@objectstack/spec/data'; +import { TursoDriver } from './turso-driver.js'; +import { remoteReadableIdsSemiJoin } from './remote-transport.js'; +import { makeLibsqlSqliteStub, type LibsqlSqliteStub } from './libsql-sqlite-stub.testkit.js'; + +const set = SHARED_RECORD_IDS_CASE_SET; +const seamed = (where: unknown): any => lowerFilterCondition(where, { isDatetimeColumn: () => false }); + +const DOC = 'srid_doc'; +const GRANTS = 'sys_record_share'; +const WRITE_LEVELS = ['lvl_edit', 'lvl_full']; + +const rowsOf = (object: string): readonly FixedReadLeafRow[] => set.tables.find((t) => t.object === object)!.rows; +const objectOf = (object: string, rows: readonly FixedReadLeafRow[]) => ({ + name: object, + fields: Object.fromEntries( + [...new Set(rows.flatMap((r) => Object.keys(r)))].filter((k) => k !== 'id').map((k) => [k, { type: 'string' }]), + ), +}); +const sortedIds = (rows: Array>): string[] => rows.map((r) => String(r.id)).sort(); +const holdsWriteForm = (node: unknown): boolean => { + if (isSharedRecordIds(node)) return node.accessLevels !== undefined; + if (node === null || typeof node !== 'object') return false; + return (Array.isArray(node) ? node : Object.values(node)).some(holdsWriteForm); +}; + +type Face = 'local' | 'remote'; + +function declareFace(face: Face): void { + describe(`[ADR-0155 step 3] TursoDriver — SharedRecordIds conformance (${face} face)`, () => { + let driver: TursoDriver; + let stub: LibsqlSqliteStub | undefined; + /** A raw statement on the face's own database, outside the driver's doors. */ + let raw: (sql: string, ...args: unknown[]) => Promise; + + const seedDocs = async () => { + await raw(`delete from ${DOC}`); + for (const r of rowsOf(DOC)) { + await raw(`insert into ${DOC} (id, owner, label, organization_id) values (?, ?, ?, ?)`, r.id, r.owner, r.label, r.organization_id); + } + }; + const touched = async () => (await raw(`select id from ${DOC} where label = 'touched'`)).map((r) => String(r.id)).sort(); + + beforeAll(async () => { + const objects = set.tables.map((t) => objectOf(t.object, t.rows)); + if (face === 'remote') { + stub = makeLibsqlSqliteStub(); + driver = new TursoDriver({ url: 'libsql://shared-record-ids.turso.io', client: stub as never }); + await driver.connect(); + expect(driver.transportMode).toBe('remote'); + for (const obj of objects) await driver.syncSchema(obj.name, obj); + raw = async (sql, ...args) => { + const statement = stub!.raw.prepare(sql); + if (statement.reader) return statement.all(...args); + statement.run(...args); + return []; + }; + } else { + driver = new TursoDriver({ url: ':memory:' }); + expect(driver.transportMode).toBe('local'); + await driver.initObjects(objects as any); + const knex = (driver as any).knex; + raw = async (sql, ...args) => { + const out = await knex.raw(sql, args); + return Array.isArray(out) ? out : (out?.rows ?? []); + }; + } + for (const t of set.tables) { + for (const r of t.rows) { + const cols = Object.keys(r); + await raw(`insert into ${t.object} (${cols.join(', ')}) values (${cols.map(() => '?').join(', ')})`, ...cols.map((c) => r[c])); + } + } + }, 60_000); + + afterAll(async () => { + await driver?.disconnect(); + stub?.close(); + }); + + it('declares the leaf it compiles, inherited from SqlDriver: supports.fixedReadLeaves is [SharedRecordIds]', () => { + expect(driver.supports.fixedReadLeaves).toEqual(['SharedRecordIds']); + }); + + describe('shared conformance cases (find, and count with the same where)', () => { + for (const c of set.cases) { + it(c.name, async () => { + const rows = await driver.find(c.object, { where: seamed(c.where()) }, c.options); + expect(sortedIds(rows), c.note).toEqual([...c.expected]); + expect(await driver.count(c.object, { where: seamed(c.where()) }, c.options), c.note).toBe(c.expected.length); + }); + } + }); + + describe('the predicate update\'s two statements (③ ruled A)', () => { + const writeCases = set.cases.filter((c) => holdsWriteForm(c.where())); + + it('the case-set carries write-form cases to run', () => { + expect(writeCases.length).toBeGreaterThanOrEqual(2); + }); + + for (const c of writeCases) { + it(`${c.name}: the prior-row read and the write each answer the case's rows`, async () => { + await seedDocs(); + const where = seamed(c.where()); + expect(sortedIds(await driver.find(c.object, { where }, c.options))).toEqual([...c.expected]); + await driver.updateMany(c.object, { where }, { label: 'touched' }, c.options); + expect(await touched()).toEqual([...c.expected]); + await seedDocs(); + }); + } + + it('under a tenant: the outer statement is walled and the inner read is not', async () => { + await seedDocs(); + const where = seamed({ id: { $in: SharedRecordIds.write(DOC, 'u1', WRITE_LEVELS) } }); + expect(sortedIds(await driver.find(DOC, { where }, { tenantId: 'org_a' }))).toEqual(['d2', 'd7']); + await driver.updateMany(DOC, { where }, { label: 'touched' }, { tenantId: 'org_a' }); + expect(await touched()).toEqual(['d2', 'd7']); + await seedDocs(); + }); + }); + + describe('N4: the `<> \'\'` half of the blank-id guard', () => { + beforeAll(async () => { + await raw(`insert into ${DOC} (id, owner, label, organization_id) values ('', 'u2', 'keep', 'org_a')`); + }); + afterAll(async () => { + await raw(`delete from ${DOC} where id = ''`); + }); + + it('the empty id names no record: the leaf does not admit it, and the negation does', async () => { + const leaf = () => SharedRecordIds.read(DOC, 'u1'); + expect(sortedIds(await driver.find(DOC, { where: seamed({ id: { $in: leaf() } }) }))).toEqual(['d1', 'd2', 'd7', 'd8']); + expect(sortedIds(await driver.find(DOC, { where: seamed({ $not: { id: { $in: leaf() } } }) }))).toEqual( + ['', 'd3', 'd4', 'd5', 'd6', 'd9'], + ); + }); + }); + + if (face === 'remote') { + it('the statement the transport sends: one subquery, bound inputs, the tenant scope outside it only', async () => { + const sent: { sql: string; args: unknown[] }[] = []; + const execute = stub!.execute.bind(stub); + const spy = vi.spyOn(stub!, 'execute').mockImplementation(async (stmt: any) => { + if (typeof stmt === 'object' && String(stmt.sql).includes(GRANTS)) sent.push({ sql: stmt.sql, args: [...(stmt.args ?? [])] }); + return execute(stmt); + }); + try { + await driver.find(DOC, { where: seamed({ id: { $in: SharedRecordIds.write(DOC, 'u1', WRITE_LEVELS) } }) }, { tenantId: 'org_a' }); + } finally { + spy.mockRestore(); + } + expect(sent).toHaveLength(1); + const subquery = + '"id" IN (SELECT "record_id" FROM "sys_record_share" WHERE "object_name" = ? AND "recipient_type" = ? ' + + 'AND "recipient_id" = ? AND "access_level" IN (?, ?) AND "record_id" IS NOT NULL AND "record_id" <> ?)'; + // The subquery carries no organization predicate; the outer statement carries its one. + expect(sent[0].sql).toContain(subquery); + expect(sent[0].sql.match(/organization_id/g)).toHaveLength(1); + expect(sent[0].args).toEqual(expect.arrayContaining([DOC, 'user', 'u1', 'lvl_edit', 'lvl_full', '', 'org_a'])); + }); + } + + describe('refusals: a leaf anywhere but a field\'s $in comparand', () => { + const leaf = () => SharedRecordIds.read(DOC, 'u1'); + const misplaced: [string, string, () => unknown][] = [ + ['under $nin', DOC, () => ({ id: { $nin: leaf() } })], + ['as a member of a $in list', DOC, () => ({ id: { $in: [leaf()] } })], + ['as $not\'s operand', DOC, () => ({ $not: leaf() })], + ['misplaced inside a composed ReadableIds scope', 'srid_note', () => ({ record_id: { $in: ReadableIds.compose(ReadableIds.of(DOC), { owner: leaf() }) } })], + ]; + for (const [name, object, where] of misplaced) { + it(`${name}: INTERNAL_ERROR / 500 on find, count and updateMany`, async () => { + const w = where() as FilterCondition; + await expect(driver.find(object, { where: w })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + await expect(driver.count(object, { where: w })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + await expect(driver.updateMany(object, { where: w }, { label: 'touched' })).rejects.toMatchObject(READABLE_IDS_REFUSAL); + expect(await touched()).toEqual([]); + }); + } + + it('names the position and the leaf, never its recipient', async () => { + const err = await driver.find(DOC, { where: { id: { $nin: leaf() } } as any }).catch((e) => e); + expect(err).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect(err.message).toContain('[driver-turso] where.id.$nin holds a SharedRecordIds leaf'); + expect(err.message).not.toContain('u1'); + }); + }); + }); +} + +declareFace('local'); +declareFace('remote'); + +describe('[ADR-0155 step 3] the refusal is logged at error once per driver', () => { + for (const face of ['local', 'remote'] as const) { + it(`${face} face`, async () => { + const stub = face === 'remote' ? makeLibsqlSqliteStub() : undefined; + const driver = face === 'remote' + ? new TursoDriver({ url: 'libsql://refusal-log.turso.io', client: stub as never }) + : new TursoDriver({ url: ':memory:' }); + await driver.connect(); + const doc = objectOf(DOC, rowsOf(DOC)); + if (face === 'remote') await driver.syncSchema(doc.name, doc); + else await driver.initObjects([doc] as any); + const error = vi.spyOn((driver as any).logger, 'error'); + for (let i = 0; i < 2; i++) { + await expect(driver.find(DOC, { where: { id: { $nin: SharedRecordIds.read(DOC, 'u1') } } as any })).rejects.toMatchObject( + READABLE_IDS_REFUSAL, + ); + } + expect(error).toHaveBeenCalledTimes(1); + await driver.disconnect(); + stub?.close(); + }); + } +}); + +describe('[ADR-0155 step 3] RemoteTransport driven standalone refuses a misplaced leaf before compiling', () => { + it('buildWhereSQL answers the envelope, not a compiled statement', async () => { + const stub = makeLibsqlSqliteStub(); + const driver = new TursoDriver({ url: 'libsql://standalone.turso.io', client: stub as never }); + await driver.connect(); + const transport = (driver as any).remoteTransport; + expect(() => transport.buildWhereSQL(DOC, { id: { $eq: SharedRecordIds.read(DOC, 'u1') } })).toThrow( + expect.objectContaining(READABLE_IDS_REFUSAL), + ); + // A placed leaf compiles, directly and inside a resolved semi-join's scope, + // which the walk reads as a node (a composed scope the driver resolved). + expect(transport.buildWhereSQL(DOC, { id: { $in: SharedRecordIds.read(DOC, 'u1') } }).whereClauses).toMatch(/^"id" IN \(SELECT "record_id"/); + const semiJoin = remoteReadableIdsSemiJoin({ object: DOC, table: DOC, scope: { id: { $in: SharedRecordIds.read(DOC, 'u1') } }, tenant: undefined }); + expect(transport.buildWhereSQL('srid_note', { record_id: { $in: semiJoin } }).whereClauses).toBe( + '"record_id" IN (SELECT "id" FROM "srid_doc" WHERE ("id" IN (SELECT "record_id" FROM "sys_record_share" WHERE ' + + '"object_name" = ? AND "recipient_type" = ? AND "recipient_id" = ? AND "record_id" IS NOT NULL AND "record_id" <> ?)))', + ); + const misplacedInScope = remoteReadableIdsSemiJoin({ object: DOC, table: DOC, scope: { owner: SharedRecordIds.read(DOC, 'u1') } as any, tenant: undefined }); + expect(() => transport.buildWhereSQL('srid_note', { record_id: { $in: misplacedInScope } })).toThrow( + expect.objectContaining(READABLE_IDS_REFUSAL), + ); + await driver.disconnect(); + stub.close(); + }); +}); diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-compile.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-compile.ts.json new file mode 100644 index 00000000000..38c4c04de59 --- /dev/null +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__fixed-read-leaf-compile.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/drivers/driver-sql/src/fixed-read-leaf-compile.ts", + "adrs": [ + "ADR-0155" + ], + "invariant": "ADR-0155 D1, D4: a fixed-read leaf compiles only as the `$in` comparand of a field's operator map; every other position is refused with INTERNAL_ERROR / 500, never read as an ordinary comparand. The inner read's predicates come from the leaf's own description (`fixedInnerReadOf`), so no compiler restates them, and its tenant scope is the literal `'none'` (① ruled A): a widened type stops this module compiling until every compiler answers it." +} diff --git a/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-internal-helpers.ts.json b/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-internal-helpers.ts.json new file mode 100644 index 00000000000..18e3e622a49 --- /dev/null +++ b/scripts/adr-anchors/packages__drivers__driver-sql__src__sql-driver-internal-helpers.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/drivers/driver-sql/src/sql-driver-internal-helpers.ts", + "adrs": [ + "ADR-0139", + "ADR-0155" + ], + "invariant": "ADR-0155 D2, ① ruled A: `fixedReadLeafSubquery` builds the fixed inner read of a `SharedRecordIds` leaf with NO `applyTenantScope` — today's read of `sys_record_share` carries no tenant scope, so the subquery carries none (the outer statement's wall stands, applied to the outer builder), and `scripts/check-tenant-chokepoint.mjs` records the absence as its one EXEMPT entry. Its neighbour `readableIdsSubquery` IS walled (ADR-0139 D3): the two subqueries differ on purpose, and adding the wall to the first narrows the shared set ADR-0155 D-0 keeps equal to today's list. On Oracle the blank-id guard is `IS NOT NULL` alone, because `<> ''` is `<> NULL` there and would empty the set." +} diff --git a/scripts/adr-anchors/packages__drivers__driver-turso__src__remote-transport.ts.json b/scripts/adr-anchors/packages__drivers__driver-turso__src__remote-transport.ts.json new file mode 100644 index 00000000000..187463af011 --- /dev/null +++ b/scripts/adr-anchors/packages__drivers__driver-turso__src__remote-transport.ts.json @@ -0,0 +1,8 @@ +{ + "file": "packages/drivers/driver-turso/src/remote-transport.ts", + "adrs": [ + "ADR-0139", + "ADR-0155" + ], + "invariant": "ADR-0155 D2, D4: `fixedInnerReadSQL` is the remote twin of `SqlDriver#fixedReadLeafSubquery`, compiled from the same predicates (`fixedInnerReadPredicates`, `@objectstack/driver-sql`), every value bound and with no tenant scope (① ruled A); `TursoDriver` declares `fixedReadLeaves` in remote mode only because this compiles it. A resolved `ReadableIds` semi-join (ADR-0139 D3) carries the tenant wall the driver handed over; the fixed inner read carries none." +} From 71324295d471099c8ab8926e1b44ddace72ce7ae Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:53:25 +0000 Subject: [PATCH 3/3] docs(changeset): name the open PostgreSQL non-text key case of the SharedRecordIds compile (ADR-0155 step 3) The changeset said the compile covers every dialect without saying that on PostgreSQL an object whose id column is not text fails the subquery with DATABASE_ERROR 42883. It now says so, says the case is open on its own decision card (ADR-0155 D-0) and settled before the sharing plugin writes the leaf, and says which dialects ran live and which are pinned at compile shape. Claude-Session: https://claude.ai/code/session_01L9qibyXo4gSy8DJPNz4ANz Co-authored-by: Claude --- .changeset/35872-shared-record-ids-sql-compile.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/35872-shared-record-ids-sql-compile.md b/.changeset/35872-shared-record-ids-sql-compile.md index c87e4bb62bd..91b16b6b50b 100644 --- a/.changeset/35872-shared-record-ids-sql-compile.md +++ b/.changeset/35872-shared-record-ids-sql-compile.md @@ -11,7 +11,7 @@ Metadata-protocol: none No visible change on its own: nothing on main writes a `SharedRecordIds` leaf yet. The sharing plugin starts writing it at ADR-0155's last step. -- **The compile** (`@objectstack/driver-sql`). A `SharedRecordIds` leaf in a field's `$in` compiles to one subquery in the list's own position: `id IN (SELECT record_id FROM sys_record_share WHERE object_name = ? AND recipient_type = 'user' AND recipient_id = ? AND record_id IS NOT NULL AND record_id <> '')`. The write form adds `AND access_level IN (…)` inside the subquery. Every value is bound. The subquery carries no tenant scope (ADR-0155 ① ruled A), and the outer statement's tenant wall is unchanged. It covers every read verb and `updateMany`, on SQLite, PostgreSQL, MySQL, SQL Server and Oracle. On Oracle the `<> ''` half is left out, because Oracle stores `''` as NULL. `SqliteWasmDriver` and Turso's local mode inherit the compile. +- **The compile** (`@objectstack/driver-sql`). A `SharedRecordIds` leaf in a field's `$in` compiles to one subquery in the list's own position: `id IN (SELECT record_id FROM sys_record_share WHERE object_name = ? AND recipient_type = 'user' AND recipient_id = ? AND record_id IS NOT NULL AND record_id <> '')`. The write form adds `AND access_level IN (…)` inside the subquery. Every value is bound. The subquery carries no tenant scope (ADR-0155 ① ruled A), and the outer statement's tenant wall is unchanged. It compiles on every read verb and on `updateMany`, for SQLite, PostgreSQL, MySQL, SQL Server and Oracle. SQLite and PostgreSQL were run live for this release. MySQL, SQL Server and Oracle are pinned at compile shape, and MySQL also runs live in CI's Temporal Conformance job. On PostgreSQL, an object whose `id` column is not text (an integer- or uuid-keyed federated table) fails the compiled subquery with `DATABASE_ERROR` (42883) instead of answering its rows. That case is open on #35906 (ADR-0155 D-0) and is settled before the sharing plugin writes the leaf. On Oracle the `<> ''` half is left out, because Oracle stores `''` as NULL. `SqliteWasmDriver` and Turso's local mode inherit the compile. - **The remote transport** (`@objectstack/driver-turso`). Turso's remote mode compiles the same subquery with its own compiler, from the same predicates. - **The declaration.** `SqlDriver.supports.fixedReadLeaves` is `['SharedRecordIds']`, and `TursoDriver` inherits it in every mode. The engine's seam now hands the leaf to these drivers instead of refusing it. - **The refusal.** A leaf anywhere other than a field's `$in` comparand is refused before any statement runs, with `INTERNAL_ERROR` / 500, and logged at `error` once per driver.