diff --git a/.changeset/32607-two-enabled-row-holders.md b/.changeset/32607-two-enabled-row-holders.md new file mode 100644 index 00000000000..6ad85e1d04b --- /dev/null +++ b/.changeset/32607-two-enabled-row-holders.md @@ -0,0 +1,27 @@ +--- +'@objectstack/metadata-protocol': minor +'@objectstack/rest': patch +'@objectstack/runtime': patch +--- + +fix(metadata-protocol)!: a name two enabled packages hold only as stored rows is refused by the plain read, never served by save order (ADR-0150 D3, #32607) + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — no skill and no doc teaches what the read naming no package answers for a name only stored rows of several packages hold (`skills/**` and `content/docs/**` grepped: the `ambiguous-in-environment` mentions are about flow, queue and permission-set references, not `/meta` reads); the refusal's own sentence names the `?package=` remedy. + + + +**BREAKING** answer narrowing at the `/meta` bare item reads: a name that two or more enabled packages hold only as stored rows, and that no package ships in code, answers 409 `RESOURCE_CONFLICT` naming each of them, where the plain read and `/published` served one of the rows. `/layers` already refused it. + +The row-aware served-holder judgment that a disabled holder brings in (#32354) now also judges, on the item read, a name with no disabled holder. The holders are judged at one grain, the packages the item's active stored rows are bound to at the member the read addresses, as the read itself binds them, and never united with the registry's holders of the name (with no shipper the registry knows a row-only name through one bare slot, the row written or hydrated last). Two or more of them are refused as the by-name read refuses two package holders (`ambiguous-in-environment`). One holder reads as before. It applies to a type the registry reads by package, when no enabled package ships the name in code at any member, and when no package-less row or environment item of the name is stored. + +**Every moved answer, before → after.** Both transports (`RestServer` and the runtime `HttpDispatcher`), both registration orders, both save orders, and on the runtime dispatcher before and after a reboot. First-party count 0: no first-party app saves one name into two packages' stored rows. + +Narrowing: + +- Bare `GET /meta/:type/:name`: 200 with the row saved first → 409 `RESOURCE_CONFLICT` naming each holder, with `details.candidates`. +- Bare `GET /meta/:type/:name/published`: 200 with a row (on `RestServer` the row saved first; on the runtime dispatcher the same package in every save order) → 409 `RESOURCE_CONFLICT` naming each holder. +- The execution face (`getMetaItemForExecution`) of the same name: the row saved first → the same refusal. + +**Not moved.** Bare `GET /meta/:type/:name/layers` keeps its 409 `RESOURCE_CONFLICT`, the package-less writes' own refusal naming the same holders with its `?package=` prescription (#28337), on both transports: each transport's layered chain (`RestServer`'s and the runtime `HttpDispatcher`'s) reads the plain read first to find a disabled owner, and now leaves that read's refusal of row holders, and only that refusal (the protocol marks it), to the package-less refusal step, rethrowing every other refusal as before (two code holders, with or without a stored row each, and two row holders beside a disabled one, keep the plain read's refusal). `?package=` naming either holder serves that holder's row. A name one package holds as a stored row is served as before. A row the reads decline (a shipped flow name's undeclared row, a sealed managed name's row) and a row of a customization pair of another package the rows or the registry name make no holder here, as they make none beside a disabled holder (#32354), so they never turn one holder into a refusal: a package's row beside its pair's undeclared row is one holder in either save order, and no door names the pair. A dependent's added member over a base that holds the name only as a stored row (`email_template`: the base's `en-US` row, the dependent's `fr-FR` row) is the dependent's alone at that member (#28802): the plain read, `/layers` and the execution face at `fr-FR` keep serving the dependent's row. A name an enabled package ships in code at any member (for a bundled type such as `email_template`, a base shipping `en-US` beside another package's `fr-FR` row: the package-less `fr-FR` read keeps its answer), or one with a package-less row or an environment item, is judged as before. The paired customization addresses (`?package=HOLDER.custom`), which after a reboot follow the registry's one bare slot, are unchanged here (#32662 carries them). diff --git a/.changeset/32607-two-row-holders-semantic-entry.md b/.changeset/32607-two-row-holders-semantic-entry.md new file mode 100644 index 00000000000..6b94944bf89 --- /dev/null +++ b/.changeset/32607-two-row-holders-semantic-entry.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +docs(spec): the protocol upgrade guide names the bare item read #32607 narrows: a name two or more enabled packages hold only as stored rows, which no package ships in code, is refused naming each holder instead of served by save order + +Clause-②: no +Metadata-protocol: none + +The semantic entry `two-row-holders-bare-read-refused` (`packages/spec/src/migrations/entries/semantic/18.two-row-holders-bare-read-refused.ts`) registers the narrowing `.changeset/32607-two-enabled-row-holders.md` declares (ADR-0087, `adr-0087: registered`). There is no automatic rewrite, because which package's row a caller meant is a judgement about that caller. The remedy it names is the exact read (`?package=`), which serves each holder's row. It adds no key and no export. diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index 63ac6038632..531444d2b10 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -45,6 +45,7 @@ import { resolveBundleMemberSelector } from './protocol-bundle-members.js'; import { installedManifestsOfEngine } from './installed-manifests.js'; import { pairsOf } from '@objectstack/metadata-core'; import { disabledExactAddressHolder } from './protocol-exact-qualifier.js'; +import type { PrereadActiveRows } from './protocol-meta-item-reads.js'; import { isActionWithheldByDisabledPackage, isItemOfDisabledPackage, @@ -131,11 +132,12 @@ export function servedHolderAddressOf(registry: any, type: string, name: string) * was the last one written or hydrated; the rows themselves name every * package that holds the name ({@link packagelessAddress}'s candidates). * - * Asked only when a package is disabled, of a type the registry reads by - * package, when an enabled package ships no code item of the name (otherwise - * the shipped item is the name's, ADR-0048 §3.3, and a row of another package - * never stands in for it: {@link servedHolderAddressOf} and - * `packagelessContentPackage` judge it), and when no package-less row and no + * Asked only when a package is disabled ([#32607] or when the item face + * asks, below), of a type the registry reads by package, when an enabled + * package ships no code item of the name (otherwise the shipped item is the + * name's, ADR-0048 §3.3, and a row of another package never stands in for + * it: {@link servedHolderAddressOf} and `packagelessContentPackage` judge + * it), and when no package-less row and no * environment item is stored (a customization of no one holder, judged as * before). Then the holders are the registry's served holders and the * packages the active rows are bound to, less every disabled package: @@ -145,7 +147,17 @@ export function servedHolderAddressOf(registry: any, type: string, name: string) * - two or more → `{ kind: 'refused' }`, the by-name read's own refusal * (`ambiguous-in-environment`), naming only the served holders (epic ruling * on #32354, Q2): a disabled package is never named; - * - none, or no disabled package among them → `undefined`, the read as it was. + * - none → `undefined`, the read as it was. + * + * [#32607] With no disabled package among the holders, and only when + * `options.refuseWithoutDisabled` asks (the item face, {@link + * readMetaItemFace}), two or more are refused the same way, naming each: the + * plain read served the row saved first while `/layers` refused naming both. + * That arm is {@link storedRowHoldersRefusal}, which judges the holders at + * the rows' grain alone. + * Otherwise, and for one holder, `undefined` (the read already reads there). + * The layered reads keep their own refusal for that case, the one the + * package-less writes give (#28337). * * [#32354 contract review S4] A row the reads decline * ({@link ObjectStackProtocolImplementation.declinesStoredRow}: a shipped flow @@ -170,14 +182,16 @@ export function servedHolderAddressOf(registry: any, type: string, name: string) export async function servedRowHolderOf( host: ServedRowHost, type: string, name: string, member?: string, + options: { readonly refuseWithoutDisabled?: boolean } = {}, ): Promise<{ kind: 'served'; packageId: string } | { kind: 'refused'; error: PackageScopedNameRefusedError } | undefined> { const registry: any = host.engine?.registry; if (typeof registry?.readsByPackage !== 'function' || registry.readsByPackage(type) !== true) return undefined; if (typeof registry.packageScopedHoldersOf !== 'function' || typeof registry.isPackageDisabled !== 'function') return undefined; const disabled = (id: string): boolean => registry.isPackageDisabled(id) === true; - // No disabled package at all: no read moves, and no row is read for it. - // The predicate `isPackageDisabled` reads, asked of each installed record. - if (typeof registry.getAllPackages === 'function' + // No disabled package at all, and no refusal asked of that case: no read + // moves, and no row is read for it. The predicate `isPackageDisabled` + // reads, asked of each installed record. + if (options.refuseWithoutDisabled !== true && typeof registry.getAllPackages === 'function' && !(registry.getAllPackages() as ReadonlyArray<{ enabled?: unknown; status?: unknown } | undefined>) .some((pkg) => pkg?.enabled === false || pkg?.status === 'disabled')) { return undefined; @@ -199,7 +213,8 @@ export async function servedRowHolderOf( const rows = await host.packagelessAddress(type, name, member, 'active', activeRows); if (rows.unbound) return undefined; const every: readonly string[] = registry.packageScopedHoldersOf(type, name, null, { includeDisabledPackages: true }) ?? []; - if (![...every, ...rows.candidates].some(disabled)) return undefined; + const anyDisabled = [...every, ...rows.candidates].some(disabled); + if (!anyDisabled) return options.refuseWithoutDisabled === true ? storedRowHoldersRefusal(host, type, name, member, every, activeRows, rows.candidates) : undefined; const installed = installedManifestsOfEngine(host.engine); const pairRow = (row: { package_id?: unknown }): boolean => typeof row.package_id === 'string' && every.some((holder) => pairsOf(holder, installed).includes(row.package_id as string)); @@ -220,6 +235,73 @@ export async function servedRowHolderOf( return { kind: 'refused', error: new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }) }; } +/** + * [#32607] The marker {@link storedRowHoldersRefusal} sets on its refusal, a + * registered symbol (so every copy of this package reads the same key, and + * no envelope serializes it). The layered chains' owner step in `RestServer` + * and the runtime dispatcher reads it by the same `Symbol.for` key (neither + * depends on this package at run time): it hands over to the package-less + * refusal step only the refusal this judgment made, and rethrows every other + * (contract review S1). + */ +const STORED_ROW_HOLDERS_REFUSAL: unique symbol = Symbol.for('objectstack.metadata-protocol.storedRowHoldersRefusal') as never; + +/** + * [#32607] The item face's judgment of a name with no disabled holder + * ({@link servedRowHolderOf} with `refuseWithoutDisabled`): two or more + * packages holding it only as stored rows are refused naming each, where the + * plain read served the row saved first. `undefined` leaves the read as it + * was. + * + * Only a name no enabled package ships, at any member: a shipped name keeps + * the read's own content judgment, which counts the shipper + * (`packagelessContentPackage` over the name's shipped artifacts), so there is + * no save order to guess there (a bundled type's base shipping one locale + * beside another package's row of another). + * + * [contract review M1, M2] The holders are judged at ONE grain: the packages + * the item's active rows are bound to at the member, as the read itself + * binds them ({@link packagelessAddress}), and never united with the + * registry's holders of the name. With no shipper the registry knows a + * row-only name through one bare slot, the row written or hydrated last, at + * the name's grain, so the union followed save order (a customization pair + * named as a holder when its row was the slot's entry) and counted a holder + * of another member (a base's `en-US` row against a dependent's added + * `fr-FR`). Excluded, as beside a disabled holder: a row the reads decline + * ({@link ObjectStackProtocolImplementation.declinesStoredRow}) and a row of a + * customization pair of another package the rows or the registry name + * (`pairsOf`), which is that package's customization, never a holder of its + * own. An unbound package-less row among them leaves the read as it was. + */ +async function storedRowHoldersRefusal( + host: ServedRowHost, + type: string, name: string, member: string | undefined, + every: readonly string[], + activeRows: Awaited>, + bound: readonly string[], +): Promise<{ kind: 'refused'; error: PackageScopedNameRefusedError } | undefined> { + const registry: any = host.engine?.registry; + if ([...shippingPackageIds(host.shippedArtifactsOf(type, name))].some((id) => registry.isPackageDisabled(id) !== true)) return undefined; + const installed = installedManifestsOfEngine(host.engine); + const known = [...new Set([...every, ...bound])]; + const pairOfAnother = (row: { package_id?: unknown }): boolean => typeof row.package_id === 'string' + && known.some((holder) => holder !== row.package_id && pairsOf(holder, installed).includes(row.package_id as string)); + const holding = await host.packagelessAddress(type, name, member, 'active', activeRows.filter((row) => + !host.declinesStoredRow(type, name, row) && !pairOfAnother(row))); + if (holding.unbound || holding.candidates.length < 2) return undefined; + const base = { + status: 'refused' as const, + reason: 'ambiguous-in-environment' as const, + type: type as PackageScopedResolvableType, + name, + callerPackageId: null, + candidates: [...holding.candidates].sort().map((packageId) => ({ kind: 'package' as const, packageId })), + }; + const error = new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); + Object.defineProperty(error, STORED_ROW_HOLDERS_REFUSAL, { value: true }); + return { kind: 'refused', error }; +} + /** * [#32183, #32354] The judgment of the address a read naming no package takes * for a name a disabled package also holds: the registry's served holder @@ -228,14 +310,18 @@ export async function servedRowHolderOf( * holders; `undefined` leaves the read as it was. Answered, never thrown: the * plain read throws the refusal ({@link servedAddressOf}); the layered read * only re-addresses, and leaves the refusal to its door (contract review S1). + * `options` as on {@link servedRowHolderOf}: only the item face asks it, so + * [#32607] two enabled row holders of a name nobody ships are refused there + * alone. */ export async function servedAddressJudgment( host: ServedRowHost, type: string, name: string, member?: string, + options: { readonly refuseWithoutDisabled?: boolean } = {}, ): Promise<{ kind: 'served'; packageId: string } | { kind: 'refused'; error: PackageScopedNameRefusedError } | undefined> { const registryAddress = servedHolderAddressOf(host.engine?.registry, type, name); if (registryAddress !== undefined) return { kind: 'served', packageId: registryAddress }; - return servedRowHolderOf(host, type, name, member); + return servedRowHolderOf(host, type, name, member, options); } /** @@ -246,8 +332,9 @@ export async function servedAddressJudgment( export async function servedAddressOf( host: ServedRowHost, type: string, name: string, member?: string, + options: { readonly refuseWithoutDisabled?: boolean } = {}, ): Promise { - const judged = await servedAddressJudgment(host, type, name, member); + const judged = await servedAddressJudgment(host, type, name, member, options); if (judged?.kind === 'refused') throw judged.error; return judged?.packageId; } @@ -292,10 +379,28 @@ export async function readMetaItemFace( // [contract review N1] The member selector resolved once, as the layered // read resolves it: a malformed one is the read's own 400, never a 409 // judged at a member nobody named. + // [#32607] …and refuses two enabled row holders of a name nobody ships. + // The rows that judgment reads are read on the face's key and handed to + // the read below, which takes them instead of reading them again + // (#24371: the item's active rows, one read). + let activeRows: PrereadActiveRows | undefined; + const host = this; + const judgeHost: ServedRowHost = { + get engine() { return host.engine; }, + packagelessAddress: (...a) => this.packagelessAddress(...a), + shippedArtifactsOf: (...a) => this.shippedArtifactsOf(...a), + declinesStoredRow: (...a) => this.declinesStoredRow(...a), + rethrowUnlessMetadataStoreUnprovisioned: (...a) => this.rethrowUnlessMetadataStoreUnprovisioned(...a), + readItemActiveRows: async (type, name) => { + const rows = await this.readItemActiveRows(type, name, true); + activeRows = { type, name, rows }; + return rows; + }, + }; const servedAddress = request.packageId ? undefined - : await servedAddressOf(this, request.type, request.name, resolveBundleMemberSelector(request.type, request.member)); - const answer = await this.readMetaItem(servedAddress === undefined ? request : { ...request, packageId: servedAddress }, { face }); + : await servedAddressOf(judgeHost, request.type, request.name, resolveBundleMemberSelector(request.type, request.member), { refuseWithoutDisabled: true }); + const answer = await this.readMetaItem(servedAddress === undefined ? request : { ...request, packageId: servedAddress }, { face, ...(activeRows !== undefined ? { activeRows } : {}) }); // [#28877] The served read of an `action` also withholds one that launches // into a disabled package, as the served list does. const withheldAction = request.type === 'action' && face === 'served' diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index dc322c5bff6..d86520616fa 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -505,10 +505,21 @@ export async function getMetaItemForExecution(host: Pick, request: { type: string, name: string, packageId?: string, state?: 'active' | 'draft', previewDrafts?: boolean, member?: string, - }, opts: { face?: 'served' | 'execution' } = {}) { + }, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. request = canonicalizeMetaRequestType(request); // [#23183] ADR-0048 §3.1: the app read keyed by PACKAGE ID, resolved @@ -725,7 +736,12 @@ export async function readMetaItem(host: Pick { + const THIRD_PKG = 'app.third_demo'; + const label = (pkg: string) => (pkg === OTHER_PKG ? 'healthy row' : 'third row'); + const save = (host: ReturnType, name: string, pkg: string) => host.protocol.saveMetaItem({ + type: 'dashboard', name, packageId: pkg, item: { name, label: label(pkg), widgets: [] }, + }); + const ORDERS = [['healthy registered first', [OTHER_PKG, THIRD_PKG]], ['third registered first', [THIRD_PKG, OTHER_PKG]]] as const; + + it.each(ORDERS.flatMap(([order, packages]) => [ + [`${order}, the healthy row saved first`, packages, [OTHER_PKG, THIRD_PKG]], + [`${order}, the third row saved first`, packages, [THIRD_PKG, OTHER_PKG]], + ] as const))('%s: the plain read, /layers, /published and the execution face refuse naming both', async (_label, packages, saved) => { + const host = setup(); + for (const pkg of packages) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + for (const pkg of saved) await save(host, 'two_rows_dash', pkg); + const read = await host.plain('dashboard', 'two_rows_dash'); + expect([read.status, read.body?.code], JSON.stringify(read.body)).toEqual([409, 'RESOURCE_CONFLICT']); + expect([...(read.body?.details?.candidates ?? [])].map((c: any) => c.packageId).sort(), JSON.stringify(read.body)) + .toEqual([OTHER_PKG, THIRD_PKG].sort()); + // `/published` answers the plain read's refusal; `/layers` keeps the package-less writes' own (#28337). Both name both holders and serve no row. + for (const answer of [await host.layers('dashboard', 'two_rows_dash'), await host.published('dashboard', 'two_rows_dash')]) { + expect(answer.status, JSON.stringify(answer.body)).toBe(409); + for (const pkg of [OTHER_PKG, THIRD_PKG]) expect(JSON.stringify(answer.body)).toContain(pkg); + expect(JSON.stringify(answer.body)).not.toMatch(/(healthy|third) row/); + } + await expect(host.protocol.getMetaItemForExecution({ type: 'dashboard', name: 'two_rows_dash' })) + .rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', httpStatus: 409 }); + for (const pkg of [OTHER_PKG, THIRD_PKG]) { + const exact = await host.plainWith('dashboard', 'two_rows_dash', { package: pkg }); + expect([exact.status, exact.body?.item?.label], JSON.stringify(exact.body)).toEqual([200, label(pkg)]); + } + }, 60_000); + + // [#32607, A1] The layered chain's owner step reads the plain read first; its refusal of two row holders is + // left to step 1c (the writes' own refusal, #28337), and every other refusal of it is answered as before. + const WRITES_SENTENCE = 'Name the package this layered read is for'; + const messageOf = (body: any): string => String(body?.error?.message ?? body?.message ?? body?.error ?? ''); + + it.each(ORDERS)('%s, A1 CONTROL: /layers of a name two packages ship in code keeps the plain read\'s refusal', async (_order, packages) => { + const host = setup(); + for (const pkg of packages) { + host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + host.registry.registerItem('dashboard', { name: 'two_code_dash', label: `${label(pkg)} code`, widgets: [] } as any, 'name', pkg); + } + const read = await host.plain('dashboard', 'two_code_dash'); + const layers = await host.layers('dashboard', 'two_code_dash'); + expect([read.status, layers.status], JSON.stringify([read.body, layers.body])).toEqual([409, 409]); + expect(messageOf(layers.body), JSON.stringify(layers.body)).toBe(messageOf(read.body)); + expect(messageOf(layers.body)).not.toContain(WRITES_SENTENCE); + }, 60_000); + + // [contract review S1] Only the row judgment's own refusal is handed over: a name two packages ship in code, + // each with its own bound row, keeps the plain read's refusal (the registry's) on `/layers`, as on `main`. + it.each(ORDERS)('%s, A1 CONTROL (S1): /layers of a name two packages ship in code, each with its own stored row, keeps the plain read\'s refusal', async (_order, packages) => { + const host = setup(); + for (const pkg of packages) { + host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + host.registry.registerItem('dashboard', { name: 's1_dash', label: `${label(pkg)} code`, widgets: [] } as any, 'name', pkg); + await (host.protocol as any).engine.insert('sys_metadata', { + type: 'dashboard', name: 's1_dash', package_id: pkg, state: 'active', scope: 'platform', strategy: 'merge', version: 1, + metadata: JSON.stringify({ name: 's1_dash', label: label(pkg), widgets: [] }), + }); + } + const read = await host.plain('dashboard', 's1_dash'); + const layers = await host.layers('dashboard', 's1_dash'); + expect([read.status, layers.status], JSON.stringify([read.body, layers.body])).toEqual([409, 409]); + expect(messageOf(layers.body), JSON.stringify(layers.body)).toBe(messageOf(read.body)); + expect(messageOf(layers.body)).not.toContain(WRITES_SENTENCE); + }, 60_000); + + it.each(ORDERS)('%s, A1 CONTROL: /layers of two served row holders beside a disabled one keeps the plain read\'s refusal (#32354 Q2)', async (_order, packages) => { + const host = setup(); + for (const pkg of [...packages, PKG]) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + for (const pkg of [PKG, ...packages]) await save(host, 'q2_rows_dash', pkg); + host.registry.disablePackage(PKG); + const read = await host.plain('dashboard', 'q2_rows_dash'); + const layers = await host.layers('dashboard', 'q2_rows_dash'); + expect([read.status, layers.status], JSON.stringify([read.body, layers.body])).toEqual([409, 409]); + expect(messageOf(layers.body), JSON.stringify(layers.body)).toBe(messageOf(read.body)); + expect(messageOf(layers.body)).not.toContain(WRITES_SENTENCE); + expect(JSON.stringify(layers.body)).not.toContain(PKG); + }, 60_000); + + it.each(ORDERS)('%s, A1: /layers of two enabled row holders answers the package-less writes\' refusal, not the plain read\'s', async (_order, packages) => { + const host = setup(); + for (const pkg of packages) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + for (const pkg of packages) await save(host, 'a1_rows_dash', pkg); + const read = await host.plain('dashboard', 'a1_rows_dash'); + const layers = await host.layers('dashboard', 'a1_rows_dash'); + expect([read.status, layers.status], JSON.stringify([read.body, layers.body])).toEqual([409, 409]); + expect(messageOf(layers.body).startsWith(WRITES_SENTENCE), JSON.stringify(layers.body)).toBe(true); + for (const pkg of packages) expect(messageOf(layers.body)).toContain(pkg); + }, 60_000); + + it.each(ORDERS)('%s, CONTROL: one row holder is served on every bare door as before', async (_order, packages) => { + const host = setup(); + for (const pkg of packages) host.registry.installPackage({ id: pkg, name: pkg, version: '1.0.0' } as any, 'code'); + await save(host, 'one_row_dash', OTHER_PKG); + const read = await host.plain('dashboard', 'one_row_dash'); + expect([read.status, read.body?.item?.label, read.body?.packageId], JSON.stringify(read.body)).toEqual([200, 'healthy row', OTHER_PKG]); + const layers = await host.layers('dashboard', 'one_row_dash'); + expect([layers.status, layers.body?.effective?.label], JSON.stringify(layers.body)).toEqual([200, 'healthy row']); + const published = await host.published('dashboard', 'one_row_dash'); + expect([published.status, published.body?.label], JSON.stringify(published.body)).toEqual([200, 'healthy row']); + const executed: any = await host.protocol.getMetaItemForExecution({ type: 'dashboard', name: 'one_row_dash' }); + expect(executed?.item?.label).toBe('healthy row'); + }, 60_000); +}); + /** * [ruling record 6787890900] An object the caller may not read is answered on * every object door exactly as a name with nothing behind it — decided BEFORE diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index a13a416f975..0ab04da2045 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -3732,7 +3732,23 @@ export class RestServer { ...(member !== undefined ? { member } : {}), ...(environmentId ? { environmentId } : {}), }; - const envelope = await p.getMetaItem(itemRequest) as { item?: unknown; packageId?: unknown } | undefined; + let envelope: { item?: unknown; packageId?: unknown } | undefined; + try { + envelope = await p.getMetaItem(itemRequest) as typeof envelope; + } catch (error) { + // [#32607] The plain read's refusal of a name several + // packages hold only as stored rows is step 1c's to answer: + // the package-less writes' own refusal (#28337). Only that + // refusal, which the protocol marks under the registered + // key below (`protocol-meta-item-face.ts`); every other + // error is rethrown (contract review S1). + if (!packageId && (error as Record | null)?.[Symbol.for('objectstack.metadata-protocol.storedRowHoldersRefusal')] === true + && typeof p.packagelessLayeredReadRefusal === 'function' + && await p.packagelessLayeredReadRefusal({ type, name, ...(member !== undefined ? { member } : {}) }) !== undefined) { + return false; + } + throw error; + } return envelope?.item == null && registry.isPackageDisabled(envelope?.packageId) === true; }, ...(typeof p.packagelessLayeredReadRefusal === 'function' diff --git a/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts b/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts index ba2ba0592cf..0663e767e43 100644 --- a/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts +++ b/packages/runtime/src/domains/meta-disabled-holder-served-stack.test.ts @@ -333,3 +333,243 @@ describe.each([ } }, 120_000); }); + +// --------------------------------------------------------------------------- +// [#32607, ADR-0150 D3] With NO package disabled, a name two enabled packages +// hold only as stored rows (no package ships it) is refused on every bare door +// naming both, by the row-aware served-holder judgment above, so the answer +// follows no save order; each exact address serves its own row, and one row +// holder is served as before. +// +// Measured on the #32183 head plus #32354's work (step 0 of #32607): the plain +// read and `/published` served one row (the plain read the row saved first, +// `/published` on this dispatcher the same package in every order), while +// `/layers` refused 409 naming both, before and after a reboot. `/layers` keeps +// that refusal, the package-less writes' own (#28337). +// --------------------------------------------------------------------------- + +describe.each([ + { regOrder: 'E registered first', registered: [ROW_E, ROW_F] }, + { regOrder: 'F registered first', registered: [ROW_F, ROW_E] }, +])('[#32607] two enabled row holders and no shipper, $regOrder', ({ registered }) => { + const roots: string[] = []; + afterAll(() => { for (const dir of roots) rmSync(dir, { recursive: true, force: true }); }); + const freshFile = () => { + const dir = mkdtempSync(join(tmpdir(), 'os-meta-two-rows-db-')); + roots.push(dir); + return join(dir, 'meta.sqlite'); + }; + const down = async (booted: Booted) => { + if (booted.kernel.getState() === 'running') await booted.kernel.shutdown(); + roots.push(booted.root); + }; + const expectRefusedNamingBoth = async (booted: Booted, name: string) => { + const read = await get(booted.kernel, `/meta/dashboard/${name}`); + expect([read.status, codeOf(read.body)], JSON.stringify(read.body)).toEqual([409, 'RESOURCE_CONFLICT']); + expect([...(read.body?.error?.details?.candidates ?? [])].map((c: any) => c.packageId).sort(), JSON.stringify(read.body)) + .toEqual([ROW_E, ROW_F].sort()); + // `/published` answers the plain read's refusal; `/layers` keeps the package-less writes' own (#28337). Both name both holders and serve no row. + for (const door of ['layers', 'published']) { + const answer = await get(booted.kernel, `/meta/dashboard/${name}/${door}`); + expect([answer.status, codeOf(answer.body), door], JSON.stringify(answer.body)).toEqual([409, 'RESOURCE_CONFLICT', door]); + for (const id of [ROW_E, ROW_F]) expect(JSON.stringify(answer.body)).toContain(id); + expect(JSON.stringify(answer.body)).not.toMatch(/(enabled|third) row/); + // [#32607, A1] The dispatcher's layered chain leaves the plain read's refusal to step 1c too: `/layers` + // leads with the writes' sentence, `/published` does not. + const message = String(answer.body?.error?.message ?? ''); + expect([door, message.startsWith('Name the package this layered read is for')], message).toEqual([door, door === 'layers']); + } + // The execution face takes the same refusal. + const protocol: any = booted.kernel.getService('protocol'); + await expect(protocol.getMetaItemForExecution({ type: 'dashboard', name })) + .rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', httpStatus: 409 }); + // Each exact address serves its own row. + for (const id of [ROW_E, ROW_F]) { + const exact = await get(booted.kernel, `/meta/dashboard/${name}`, { package: id }); + expect([exact.status, unwrap(exact.body)?.item?.label], JSON.stringify(exact.body)).toEqual([200, `${rowTag(id)} row`]); + } + }; + + it.each([ + { saveOrder: 'E saved first', saved: [ROW_E, ROW_F] }, + { saveOrder: 'F saved first', saved: [ROW_F, ROW_E] }, + ])('$saveOrder: the plain read, /layers, /published and the execution face refuse naming both, before and after a reboot', async ({ saved }) => { + const file = freshFile(); + let booted = await bootRowKernel(registered, file); + try { + for (const id of saved) await layStoredRow(booted.engine, 'two_rows_dash', id, `${rowTag(id)} row`); + await expectRefusedNamingBoth(booted, 'two_rows_dash'); + } finally { + await down(booted); + } + booted = await bootRowKernel(registered, file); + try { + await expectRefusedNamingBoth(booted, 'two_rows_dash'); + } finally { + await down(booted); + } + }, 120_000); + + it('CONTROL: one row holder is served on every bare door as before, before and after a reboot', async () => { + const file = freshFile(); + let booted = await bootRowKernel(registered, file); + const expectServed = async (b: Booted) => { + const read = await get(b.kernel, '/meta/dashboard/one_row_dash'); + expect([read.status, unwrap(read.body)?.item?.label, unwrap(read.body)?.packageId], JSON.stringify(read.body)).toEqual([200, 'enabled row', ROW_E]); + const layers = await get(b.kernel, '/meta/dashboard/one_row_dash/layers'); + expect([layers.status, unwrap(layers.body)?.effective?.label], JSON.stringify(layers.body)).toEqual([200, 'enabled row']); + const published = await get(b.kernel, '/meta/dashboard/one_row_dash/published'); + expect([published.status, unwrap(published.body)?.label], JSON.stringify(published.body)).toEqual([200, 'enabled row']); + const executed = await (b.kernel.getService('protocol') as any).getMetaItemForExecution({ type: 'dashboard', name: 'one_row_dash' }); + expect(executed?.item?.label).toBe('enabled row'); + }; + try { + await layStoredRow(booted.engine, 'one_row_dash', ROW_E, 'enabled row'); + await expectServed(booted); + } finally { + await down(booted); + } + booted = await bootRowKernel(registered, file); + try { + await expectServed(booted); + } finally { + await down(booted); + } + }, 120_000); +}); + +// --------------------------------------------------------------------------- +// [#32607 contract review M1, M2, n1] The no-disabled arm judges a name's +// holders at the rows' grain alone, never united with the registry's one bare +// slot. M1: a package's row and its customization pair's undeclared row are +// one holder, whichever was saved (and so hydrated) last; the pair is never +// named. M2: a dependent's added member over a base that holds the name only +// as a stored row is the dependent's alone at that member (#28802); the +// base's row of another member is no second holder there, and `/layers` does +// not move. Both save orders, before and after a reboot. Measured on this +// branch before the fix (1ab9370442): M1 refused 409 naming the base and its +// pair in one save order; M2 refused 409 naming the base and the dependent. +// On `main` 89d7bef033 neither refuses, and both answer as below. +// --------------------------------------------------------------------------- + +// A bundled type's non-canonical member carries its `bundle_member` key column, as the save door writes it. +const layRow = (engine: ObjectQL, type: string, name: string, packageId: string, metadata: Record) => engine.insert('sys_metadata', { + type, name, namespace: 'default', package_id: packageId, scope: 'platform', strategy: 'merge', state: 'active', version: 1, + ...(type === 'email_template' && metadata.locale !== 'en-US' ? { bundle_member: metadata.locale } : {}), + metadata: JSON.stringify({ name, ...metadata }), +}, { context: { isSystem: true } } as any); + +async function bootManifests(manifests: readonly Record[], file: string): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const root = mkdtempSync(join(tmpdir(), 'os-meta-row-grain-')); + const engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }) as any, true); + await kernel.use(new MetadataPlugin({ watch: false, rootDir: root })); + await kernel.use(new ObjectQLPlugin({ ql: engine })); + const host: Plugin = { + name: 'qa.row-grain-host', + dependencies: ['com.objectstack.engine.objectql'], + init: async (ctx: PluginContext) => { + for (const manifest of manifests) await ctx.getService('manifest').register(manifest); + }, + }; + await kernel.use(host); + await kernel.bootstrap(); + await engine.syncSchemas(); + return { kernel, engine, root }; +} + +describe('[#32607 M1, M2] the no-disabled arm judges holders at the rows\' grain', () => { + const roots: string[] = []; + afterAll(() => { for (const dir of roots) rmSync(dir, { recursive: true, force: true }); }); + const freshFile = () => { + const dir = mkdtempSync(join(tmpdir(), 'os-meta-row-grain-db-')); + roots.push(dir); + return join(dir, 'meta.sqlite'); + }; + const down = async (booted: Booted) => { + if (booted.kernel.getState() === 'running') await booted.kernel.shutdown(); + roots.push(booted.root); + }; + const appManifest = (id: string, extra: Record = {}) => ({ + id, name: id.split('.').pop(), namespace: id.split('.').pop()!.replace(/[^a-z]/g, ''), version: '1.0.0', type: 'app', objects: [], ...extra, + }); + + // M1: X (an id that derives a pair: no underscore) and X's pair, each storing an undeclared row; nobody ships the name. + const X = 'com.qa.rowpairbase'; + const PAIR = `${X}.custom`; + it('M1: a package\'s row and its pair\'s undeclared row are one holder in both save orders, before and after a reboot: no door refuses or names the pair', async () => { + const answers: string[] = []; + for (const saved of [[X, PAIR], [PAIR, X]]) { + const file = freshFile(); + const manifests = [appManifest(X), appManifest(PAIR, { dependencies: { [X]: '*' } })]; + let booted = await bootManifests(manifests, file); + const observe = async (b: Booted, leg: string) => { + const read = await get(b.kernel, '/meta/dashboard/pair_rows_dash'); + const published = await get(b.kernel, '/meta/dashboard/pair_rows_dash/published'); + const where = `${saved.join(' then ')} saved, ${leg}`; + expect([read.status, published.status, where], JSON.stringify([read.body, published.body])).toEqual([200, 200, where]); + for (const answer of [read, published]) expect(JSON.stringify(answer.body ?? null)).not.toContain('RESOURCE_CONFLICT'); + const executed = await (b.kernel.getService('protocol') as any).getMetaItemForExecution({ type: 'dashboard', name: 'pair_rows_dash' }); + answers.push(JSON.stringify([unwrap(read.body)?.item?.label, unwrap(published.body)?.label, executed?.item?.label])); + }; + try { + for (const id of saved) await layRow(booted.engine, 'dashboard', 'pair_rows_dash', id, { label: id === X ? 'base row' : 'pair row', widgets: [] }); + await observe(booted, 'before a reboot'); + } finally { + await down(booted); + } + booted = await bootManifests(manifests, file); + try { + await observe(booted, 'after a reboot'); + } finally { + await down(booted); + } + } + // Each save order answers the same before and after a reboot. Which + // row it serves still follows the save order (the row saved first), + // exactly as on `main` 89d7bef033: that is the plain read's own pick + // between a base's row and its pair's undeclared row, not this + // judgment's, and it is carried separately. + expect([answers[0] === answers[1], answers[2] === answers[3]], answers.join(' | ')).toEqual([true, true]); + }, 240_000); + + // M2 (n1: a bundled type at a member other than the canonical one): base A stores `en-US`, dependent D stores `fr-FR`. + const A = 'com.qa.mailrowbase'; + const D = 'com.qa.mailrowaddon'; + const template = (locale: string, subject: string) => ({ label: subject, locale, subject, bodyHtml: `

${subject}

` }); + it.each([ + { order: 'A saved first', saved: [A, D] }, + { order: 'D saved first', saved: [D, A] }, + ])('M2, $order: the dependent\'s added `fr-FR` over a row-held base is served as the dependent\'s on the plain read, /layers and the execution face, before and after a reboot', async ({ saved }) => { + const file = freshFile(); + const manifests = [appManifest(A), appManifest(D, { dependencies: { [A]: '*' } })]; + let booted = await bootManifests(manifests, file); + const observe = async (b: Booted) => { + const read = await get(b.kernel, '/meta/email_template/rowmail', { member: 'fr-FR' }); + expect([read.status, unwrap(read.body)?.item?.subject, unwrap(read.body)?.packageId], JSON.stringify(read.body)).toEqual([200, 'addon fr', D]); + const layers = await get(b.kernel, '/meta/email_template/rowmail/layers', { member: 'fr-FR' }); + expect([layers.status, unwrap(layers.body)?.effective?.subject], JSON.stringify(layers.body)).toEqual([200, 'addon fr']); + // `/published` takes no member selector (400 VALIDATION_ERROR): it reads the canonical member only. + const executed = await (b.kernel.getService('protocol') as any).getMetaItemForExecution({ type: 'email_template', name: 'rowmail', member: 'fr-FR' }); + expect(executed?.item?.subject).toBe('addon fr'); + // CONTROL: the base's own `en-US` stays the base's. + const en = await get(b.kernel, '/meta/email_template/rowmail', { member: 'en-US' }); + expect([en.status, unwrap(en.body)?.item?.subject], JSON.stringify(en.body)).toEqual([200, 'base en']); + }; + try { + for (const id of saved) { + await layRow(booted.engine, 'email_template', 'rowmail', id, id === A ? template('en-US', 'base en') : template('fr-FR', 'addon fr')); + } + await observe(booted); + } finally { + await down(booted); + } + booted = await bootManifests(manifests, file); + try { + await observe(booted); + } finally { + await down(booted); + } + }, 240_000); +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 43a154f5200..0b9a90160da 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -590,9 +590,26 @@ function metaItemReadGateSources( const registry = (await deps.getObjectQL(context))?.registry; if (typeof (registry as { isPackageDisabled?: unknown } | undefined)?.isPackageDisabled !== 'function') return false; // [#32076] At the member the layers were read at (`MetaItemReadGateSources.isItemOfDisabledPackage`). - const envelope = await protocol.getMetaItem({ - type, name, ...(packageId ? { packageId } : {}), ...(member !== undefined ? { member } : {}), - }); + let envelope: Awaited>>; + try { + envelope = await protocol.getMetaItem({ + type, name, ...(packageId ? { packageId } : {}), ...(member !== undefined ? { member } : {}), + }); + } catch (error) { + // [#32607] The plain read's refusal of a name several packages + // hold only as stored rows is step 1c's to answer: the + // package-less writes' own refusal (#28337), as `RestServer`'s + // owner step leaves it. Only that refusal, which the protocol + // marks under the registered key below + // (`protocol-meta-item-face.ts`); every other error is + // rethrown (contract review S1). + if (!packageId && (error as Record | null)?.[Symbol.for('objectstack.metadata-protocol.storedRowHoldersRefusal')] === true + && typeof protocol.packagelessLayeredReadRefusal === 'function' + && await protocol.packagelessLayeredReadRefusal({ type, name, ...(member !== undefined ? { member } : {}) }) !== undefined) { + return false; + } + throw error; + } return envelope?.item == null && isServiceItemOfDisabledPackage(registry, { _packageId: envelope?.packageId }); }, ...(typeof protocol?.packagelessLayeredReadRefusal === 'function' diff --git a/packages/spec/src/migrations/entries/semantic/18.two-row-holders-bare-read-refused.ts b/packages/spec/src/migrations/entries/semantic/18.two-row-holders-bare-read-refused.ts new file mode 100644 index 00000000000..716f5d234be --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.two-row-holders-bare-read-refused.ts @@ -0,0 +1,35 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A narrowing of the bare item read, not of any key: ADR-0150 D3 (#32607) has +// the read that names no package refuse a name two or more enabled packages +// hold only as stored rows (no package ships it in code), where it served the +// row saved first (red line 2: ambiguity is reported, never guessed). No key +// is added, removed or re-shaped and no stored row changes shape, so no +// tombstone and no D2 conversion: which package's row a reader meant is the +// reader's judgement. No relevance question: the move turns on which packages' +// stored rows hold a name, which no question over one stack can name. +export const entry: SemanticMigration = { + id: 'two-row-holders-bare-read-refused', + surface: + 'The read of a metadata item that names no package (GET /api/v1/meta/TYPE/NAME, ' + + 'GET /api/v1/meta/TYPE/NAME/published, and the execution read of the same name) for a name that two or more ' + + 'enabled packages hold only as stored rows, which no installed package ships in code, of a type the registry ' + + 'reads by package', + replacement: + 'Name the package: GET /api/v1/meta/TYPE/NAME?package=PACKAGE serves that package\'s row. The refusal ' + + '(409 RESOURCE_CONFLICT, reason ambiguous-in-environment) names each holder in details.candidates.', + reason: + 'The read naming no package took the row saved first, so the same name answered a different package\'s item ' + + 'depending on save order, while GET /api/v1/meta/TYPE/NAME/layers already refused it naming both holders. ' + + 'The read now judges the name\'s holders (the registry\'s holders and the packages its active stored rows ' + + 'are bound to) and refuses two or more as the by-name read refuses two package holders. One holder is served ' + + 'as before. There is no mechanical rewrite: which package\'s row a caller meant is a judgement about that ' + + 'caller.', + acceptanceCriteria: + 'For every name two or more enabled packages hold only as stored rows: every caller that reads it without ' + + '?package= reads it with ?package=PACKAGE naming the package it means, and that read answers that package\'s ' + + 'row; GET /api/v1/meta/TYPE/NAME without ?package= answers 409 RESOURCE_CONFLICT naming each holder in ' + + 'details.candidates, never a row.', +};