diff --git a/.changeset/34348-environment-row-beside-two-shippers.md b/.changeset/34348-environment-row-beside-two-shippers.md new file mode 100644 index 00000000000..f208f042bef --- /dev/null +++ b/.changeset/34348-environment-row-beside-two-shippers.md @@ -0,0 +1,17 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/spec': patch +--- + +fix(metadata-protocol): the environment's own row of a name two enabled packages ship is what the reads naming no package serve, as the save naming no package edits it + +Clause-②: yes +Metadata-protocol: none + + + +Who sees it: an environment that stores its own (package-unbound) customization of a metadata item that two or more enabled packages ship, and reads it without naming a package. + +- **Before:** every read naming no package (`GET /api/v1/meta/TYPE/NAME`, `/layers`, `/published`, `/meta/TYPE/_env/NAME`, and the in-process item, layered and execution reads) answered `409 RESOURCE_CONFLICT` naming the shippers, while the save naming no package answered `200` and edited that row. An environment could change an item no read would show it. +- **Now:** those reads serve the environment's row, stating no package. `/layers` reports no code layer and the row as overlay and effective. After a save naming no package, every read serves the saved body. Reads and writes give the same answer (ruling 6942981052, option (b), narrowed by 7187668758 and 7405866869). +- **Unchanged:** with no such row the reads still refuse naming the enabled shippers; beside a stored row bound to a package (a shipper's own copy), where the save naming no package edits that package's row or refuses, the reads answer as before; `?package=PACKAGE` answers as before; a disabled shipper counts for nothing; a name the packages hold only as stored rows (no shipper) keeps its refusal on reads and saves alike; a sealed managed type's package-unbound row is still declined. diff --git a/packages/metadata-protocol/src/protocol-environment-row-beside-shippers.ts b/packages/metadata-protocol/src/protocol-environment-row-beside-shippers.ts new file mode 100644 index 00000000000..29d6c325eca --- /dev/null +++ b/packages/metadata-protocol/src/protocol-environment-row-beside-shippers.ts @@ -0,0 +1,113 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34348, ADR-0150 D3, ruling 6942981052 option (b) as narrowed by + * 7187668758 and 7405866869 and scoped by 7187358430] The environment's own item answers + * first: a package-unbound active row of a name two or more ENABLED packages + * ship in code is the environment's item, and the reads that name no package + * serve it, as the bare save already edits it. + * + * FROM (`main` 198301bd, measured before the change, both registration + * orders, both save orders, before and after a reboot, the runtime dispatcher + * and `RestServer`): the plain read, `/layers`, `/published`, `_env` and the + * execution read answered `409 RESOURCE_CONFLICT` naming both shippers + * (`ambiguous-in-environment`, PR #34355's refusal), while the bare save + * answered 200 and edited the package-unbound row. Reads and writes + * disagreed, and no read reached the row. + * + * Only that arrangement moves. Left as they were: + * - two shippers and no package-unbound row: the refusal naming both stands; + * - a row bound to a package beside the package-unbound one (a shipper's + * own copy or its pair's: the bare save edits that package's row, or + * refuses two): the reads stay as they were (contract review M1); + * - a disabled shipper counts for nothing (ruling 7187668758, 「我觉得停用就该 + * 全部消失」): one enabled shipper beside a disabled one is one holder, and + * a name only disabled packages hold stays hidden at every door (#37499); + * - a name the packages hold only as stored rows (no shipper): the bare save + * refuses there too, so reads and writes already agree (re-measure on the + * card's claim amendment 7404361429); + * - a package-unbound row the reads decline (a sealed managed type's, + * `declinesStoredRow`): it customizes nothing, so it is no environment item; + * - the strict draft read: its address is the draft save's. + */ + +import type { MetaItemFaceHost } from './protocol-meta-item-face.js'; +import { shippingPackageIds } from './protocol-environment-rows.js'; +import { ENVIRONMENT_READ_REFUSAL, type EnvironmentReadOutcome } from './protocol-enabled-holders.js'; +import type { PackageScopedNameRefusedError } from '@objectstack/core'; + +/** The protocol reads the judgment below takes, typed as the item face's. */ +export type EnvironmentRowHost = Pick; + +/** + * Whether the read of `(type, name)` naming no package serves the + * environment's own package-unbound row: a type the registry reads by + * package, a name two or more enabled packages ship in code at `member`, and + * at `member` an active package-unbound row the reads serve with no row bound + * to any package beside it, so the bare save addresses that row (contract + * review M1). A store that is not provisioned holds no row. + */ +export async function servesEnvironmentRowBesideShippers( + host: EnvironmentRowHost, + type: string, name: string, member?: string, +): Promise { + const registry: any = host.engine?.registry; + if (typeof registry?.readsByPackage !== 'function' || registry.readsByPackage(type) !== true) return false; + const disabled = (id: string): boolean => typeof registry.isPackageDisabled === 'function' && registry.isPackageDisabled(id) === true; + const enabledShippers = [...shippingPackageIds(host.shippedArtifactsOf(type, name, undefined, member))].filter((id) => !disabled(id)); + if (enabledShippers.length < 2) return false; + let activeRows: Awaited>; + try { + activeRows = await host.readItemActiveRows(type, name); + } catch (error) { + host.rethrowUnlessMetadataStoreUnprovisioned(error, 'sys_metadata'); + return false; + } + // [#34348 contract review M1] The rows the bare save addresses: every + // active row at `member` the reads serve, whatever its binding, as + // `packagelessAddress` judges them for the save. A row bound to any + // package beside the unbound one (a shipper's own copy, its customization + // pair's, a disabled package's) makes the save address that package or + // refuse, so the read is left as it was there. + const served = activeRows.filter((row) => !host.declinesStoredRow(type, name, row as never)); + const address = await host.packagelessAddress(type, name, member, 'active', served); + if (!address.unbound || address.candidates.length !== 0) return false; + // [#34348 contract review S1] The unbound rows at `member` are read at + // `package_id: null` by the content read: a row stored with the empty + // string is not, so it never makes the arrangement. + const atMember = await host.packagelessAddress(type, name, member, 'active', + served.filter((row) => (row as { package_id?: unknown }).package_id === '')); + return !atMember.unbound; +} + +/** + * [#34348] `_env` beside two or more enabled packages that ship the name. + * The admission (`admitEnvironmentQualifier`) reads the registry alone, and + * the registry keeps no environment item of such a name (the hydrator lays + * no package-unbound row into the bare slot of a name two packages hold), so + * it refuses `not-held-by-qualifier` naming the shippers, also where the + * environment's own row is stored and the read naming no package serves it. + * `refusal` is marked with the admission's `marker` (its + * `DISABLED_HOLDERS_ONLY_REFUSAL` key: the `_env` doors read it as "ask the + * read naming no package") and carries the judgment under + * {@link ENVIRONMENT_READ_REFUSAL}: when that read serves the environment's + * own item (no package states it: neither the envelope's `packageId` nor the + * item's `_packageId`), `_env` is admitted and answers it; otherwise the + * refusal stands, naming the shippers, as before. Returns `refusal`. + */ +export function withEnvironmentRowAdmission( + refusal: PackageScopedNameRefusedError, + marker: symbol, +): PackageScopedNameRefusedError { + const judge = (outcome: EnvironmentReadOutcome): PackageScopedNameRefusedError | undefined => { + if (outcome.error !== undefined) return refusal; + const served = outcome.answer as { item?: { _packageId?: unknown } | null; packageId?: unknown } | null | undefined; + if (served?.item == null) return refusal; + const stated = served.packageId ?? served.item._packageId; + return typeof stated === 'string' && stated !== '' ? refusal : undefined; + }; + Object.defineProperty(refusal, marker, { value: true }); + Object.defineProperty(refusal, ENVIRONMENT_READ_REFUSAL, { value: judge }); + return refusal; +} diff --git a/packages/metadata-protocol/src/protocol-exact-qualifier.ts b/packages/metadata-protocol/src/protocol-exact-qualifier.ts index afd3443ee3c..1642dbab41a 100644 --- a/packages/metadata-protocol/src/protocol-exact-qualifier.ts +++ b/packages/metadata-protocol/src/protocol-exact-qualifier.ts @@ -58,6 +58,7 @@ import { import { ENVIRONMENT_ADDRESS_SEGMENT, readNamespacePositionSegment } from '@objectstack/spec/kernel'; import { installedManifestsOfEngine } from './installed-manifests.js'; import { disabledHoldersOnlyRefusal } from './protocol-enabled-holders.js'; +import { withEnvironmentRowAdmission } from './protocol-environment-row-beside-shippers.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { bundleMemberDiscriminator } from './protocol-bundle-members.js'; import type { ProtocolHost } from './protocol-host.js'; @@ -1041,7 +1042,14 @@ export function admitEnvironmentQualifier( callerPackageId: null, candidates, }; - throw new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); + const refusal = new PackageScopedNameRefusedError({ ...base, message: packageScopedRefusalMessage(base) }); + // [#34348, ruling 6942981052 (b)] Two or more enabled holders: the read + // naming no package judges `_env`, which it admits where that read serves + // the environment's own package-unbound row ({@link withEnvironmentRowAdmission}). + if (served.length >= 2 && (registry as { readsByPackage?(type: string): boolean }).readsByPackage?.(request.type) === true) { + throw withEnvironmentRowAdmission(refusal, DISABLED_HOLDERS_ONLY_REFUSAL); + } + throw refusal; } /** @@ -1067,5 +1075,13 @@ export function admitEnvironmentQualifier( * registry has not read), never the disabled one; naming none, the door * admits `_env`, which answers as that read does. FROM (`main` * 8338d070): the refusal stood, naming the disabled package. + * + * [#34348 contract review N1] The mark also rides the refusal of a name two + * or more ENABLED packages hold, of a type the registry reads by package + * ({@link withEnvironmentRowAdmission}): it means "ask the read naming no + * package", not only "disabled holders alone". There that read never answers + * with no item (it serves the environment's own row or refuses naming the + * shippers), so the first step above is not reached; the second admits + * `_env` only where the read serves an item no package states. */ const DISABLED_HOLDERS_ONLY_REFUSAL: unique symbol = Symbol.for('objectstack.metadata-protocol.disabledHoldersOnlyRefusal') as never; diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index b8cd409664b..a873c996123 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -51,6 +51,7 @@ import { boundObjectOf } from '@objectstack/metadata/stored-item-package'; import { RELATED_LISTS_ARRANGEMENT_DECORATION, type RelatedListsArrangement } from '@objectstack/spec/data'; import { overlayMemberValue, overlayMemberWhere } from './migrations/overlay-index.js'; import { isServedOverrideRowOf } from './served-override.js'; +import { servesEnvironmentRowBesideShippers } from './protocol-environment-row-beside-shippers.js'; import { isActionWithheldByDisabledPackage, isItemOfDisabledPackage, @@ -963,14 +964,20 @@ export async function readMetaItemFace( // [#33210 (c)] …and a member only a dependent's addition holds, over a // base holding the name only as stored rows, is read at that base // ({@link rowHeldBaseAddressOf}), as it is when the base ships the name. - const servedAddress = request.packageId + // [#34348, ruling 6942981052 (b)] …and the environment's own + // package-unbound row of a name two or more enabled packages ship is + // what the read naming no package serves, as the bare save edits it + // ({@link servesEnvironmentRowBesideShippers}): no holder's address. + const environmentRow = !request.packageId && request.state !== 'draft' + && await servesEnvironmentRowBesideShippers(judgeHost, request.type, request.name, member); + const servedAddress = request.packageId || environmentRow ? undefined : await servedAddressOf(judgeHost, request.type, request.name, member, { refuseWithoutDisabled: true }) ?? (request.state === 'draft' ? undefined : await declaredMemberOverrideAddressOf(judgeHost, request.type, request.name, member) ?? await rowHeldBaseAddressOf(judgeHost, request.type, request.name, member)); - const answer = await this.readMetaItem(servedAddress === undefined ? request : { ...request, packageId: servedAddress }, { face, ...(activeRows !== undefined ? { activeRows } : {}) }); + const answer = await this.readMetaItem(servedAddress === undefined ? request : { ...request, packageId: servedAddress }, { face, ...(activeRows !== undefined ? { activeRows } : {}), ...(environmentRow ? { environmentRow: true } : {}) }); // [#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 ecce0fb16d9..b5075d3d073 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -797,7 +797,18 @@ export async function readMetaItem(host: Pick>, - }, opts: { face?: 'served' | 'execution'; activeRows?: PrereadActiveRows } = {}) { + }, opts: { + face?: 'served' | 'execution'; activeRows?: PrereadActiveRows; + /** + * [#34348] The item face judged the read naming no package to serve + * the environment's own package-unbound row beside two or more + * enabled shippers (`servesEnvironmentRowBesideShippers`): the + * package-scoped resolver's refusal of the shippers is not asked, the + * row is read at no package's address, and no shipper lends it an + * envelope. + */ + environmentRow?: boolean; + } = {}) { // #4432 — CANONICAL TYPE KEY. See {@link canonicalMetaType}. request = canonicalizeMetaRequestType(request); // [#23183] ADR-0048 §3.1: the app read keyed by PACKAGE ID, resolved @@ -878,7 +889,7 @@ export async function readMetaItem(host: Pick ({ ...CALLER }); + const body = { name, label, widgets: [] }; + const raw = new Request(`http://localhost/api/v1/meta/dashboard/${name}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + try { + const out: any = await dispatcher.dispatch('PUT', `/meta/dashboard/${name}`, body, {}, { request: raw } as any, '/api/v1'); + return { status: out.response?.status as number | undefined, body: out.response?.body }; + } catch (e) { + const thrown = resolveThrownHttpError(e); + return { status: thrown.status, body: { error: { code: thrown.code, message: String((e as Error)?.message ?? '') } } }; + } +} + +/** Every active stored row of the dashboard, as `binding:label`, sorted. */ +async function activeRowsOf(engine: ObjectQL, name: string): Promise { + const rows = (await engine.find('sys_metadata', { where: { type: 'dashboard', name, state: 'active' }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]; + return rows.map((row) => `${row.package_id ?? null}:${JSON.parse(String(row.metadata)).label}`).sort(); +} + // [type, name, plain read's label, code layer, overlay layer, /published label (undefined: 404)] const SPECIMENS = [ ['agent', 'helper', 'enabled code', 'enabled code', undefined, undefined], @@ -458,6 +479,16 @@ describe.each([ const answer = await get(b.kernel, `/meta/dashboard/three_rows_dash${door}`); expect(JSON.stringify(answer.body ?? null), door).not.toContain('package-less row'); } + // [#34348, ruling 7405866869 (flavor 2 = A)] CONTROL: the save + // naming no package refuses here too, naming both row holders, and + // writes nothing, so reads and writes give the same answer. The + // shipper shape (#34348's describe below) is the one that moved. + const before = await activeRowsOf(b.engine, 'three_rows_dash'); + const saved = await putBare(b.kernel, 'three_rows_dash', 'edited bare'); + expect([saved.status, codeOf(saved.body)], JSON.stringify(saved.body)).toEqual([409, 'RESOURCE_CONFLICT']); + for (const id of [ROW_E, ROW_F]) expect(JSON.stringify(saved.body), id).toContain(id); + expect(await activeRowsOf(b.engine, 'three_rows_dash')).toEqual(before); + expect(before).toHaveLength(3); }; let booted = await bootRowKernel(registered, file); try { @@ -1815,3 +1846,235 @@ describe('[#32605] the bare save of a name an enabled and a disabled package hol }); }); }); + +// --------------------------------------------------------------------------- +// [#34348, ADR-0150 D3, ruling 6942981052 option (b) as narrowed by +// 7187668758] The environment's own item answers first: a package-unbound +// row of a name two or more ENABLED packages ship in code is served by every +// read that names no package (the plain read, `/layers`, `/published`, `_env` +// and the execution read, on the runtime dispatcher and on `RestServer`), as +// the bare save edits it, so reads and writes agree. A disabled shipper +// counts for nothing. Both registration orders, before and after a reboot. +// +// FROM (`main` 198301bd, measured before the change): every one of those +// reads answered `409 RESOURCE_CONFLICT` naming both shippers while the bare +// save answered 200 and edited the row. The CONTROL: with no +// package-unbound row the bare doors still refuse naming both shippers. +// --------------------------------------------------------------------------- + +describe('[#34348] a package-unbound row beside two enabled shippers is the environment\'s own item, read as the bare save edits it', () => { + const SHIP_A = 'com.qa.env_ship_alpha'; + const SHIP_B = 'com.qa.env_ship_beta'; + const SHIP_C = 'com.qa.env_ship_gamma'; + // Two enabled shippers; the same two beside a third, disabled one; the CONTROL with no stored row. + const TWO = 'env_two_dash'; + const MIXED = 'env_mixed_dash'; + const NONE = 'env_none_dash'; + // [contract review M1, S1] CONTROLs: the unbound row beside a row bound to + // one shipper (X), to both (Y), and an unbound row stored with the empty + // string as its binding (E). + const BOUND_ONE = 'env_x_dash'; + const BOUND_BOTH = 'env_y_dash'; + const EMPTY_BINDING = 'env_e_dash'; + const shipperOf = (id: string) => ({ + id, name: id.split('.').pop(), namespace: id.split('.').pop()!.replace(/[^a-z]/g, ''), version: '1.0.0', type: 'app', objects: [], + dashboards: [...(id === SHIP_C ? [MIXED] : [TWO, MIXED, NONE, BOUND_ONE, BOUND_BOTH, EMPTY_BINDING])].map((name) => ({ name, label: `${id} code`, widgets: [] })), + }); + const roots: string[] = []; + afterAll(() => { for (const dir of roots) rmSync(dir, { recursive: true, force: true }); }); + + async function bootShippers(order: readonly string[], file: string): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const root = mkdtempSync(join(tmpdir(), 'os-meta-env-row-')); + roots.push(root); + const engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }); + engine.registerDriver(driver as any, true); + (engine as any).__qaKnex = (driver as any).knex; + await kernel.use(new MetadataPlugin({ watch: false, rootDir: root })); + await kernel.use(new ObjectQLPlugin({ ql: engine })); + const host: Plugin = { + name: 'qa.env-row-host', + dependencies: ['com.objectstack.engine.objectql'], + init: async (ctx: PluginContext) => { + for (const id of order) await ctx.getService('manifest').register(shipperOf(id)); + }, + }; + await kernel.use(host); + await kernel.bootstrap(); + await engine.syncSchemas(); + engine.registry.disablePackage(SHIP_C); + return { kernel, engine, root }; + } + + /** `RestServer`'s registered handler for `method path`, answered against a stub response. */ + function restDoor(kernel: ObjectKernel) { + const noop = () => {}; + const server = { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; + const rest: any = new RestServer(server as any, kernel.getService('protocol') as any, { api: { requireAuth: false } } as any); + rest.registerRoutes(); + rest.resolveExecCtx = async () => ({ ...CALLER }); + return async (method: string, path: string, params: Record, body?: unknown) => { + const route = rest.getRoutes().find((r: any) => r.method === method && r.path === `/api/v1/meta${path}`); + if (!route) throw new Error(`${method} /api/v1/meta${path} is not registered`); + const res: any = { statusCode: 200, body: undefined, headers: {} as Record }; + res.status = (code: number) => { res.statusCode = code; return res; }; + res.json = (payload: any) => { res.body = payload; return res; }; + res.send = () => res; + res.end = () => res; + res.header = (k: string, v: string) => { res.headers[k] = v; return res; }; + res.setHeader = () => {}; + res.write = () => true; + await route.handler({ method, path: `/api/v1/meta${path}`, params, headers: {}, query: {}, body }, res); + return { status: res.statusCode as number, body: res.body }; + }; + } + + /** Every read naming no package: `[door, status, served label or refusal code, the package it states]`. */ + async function bareReads(kernel: ObjectKernel, name: string) { + const rest = restDoor(kernel); + const at = { type: 'dashboard', name }; + const answers = [ + ['dispatcher plain', await get(kernel, `/meta/dashboard/${name}`)], + ['dispatcher /layers', await get(kernel, `/meta/dashboard/${name}/layers`)], + ['dispatcher /published', await get(kernel, `/meta/dashboard/${name}/published`)], + ['dispatcher _env', await get(kernel, `/meta/dashboard/_env/${name}`)], + ['rest plain', await rest('GET', '/:type/:name', at)], + ['rest /layers', await rest('GET', '/:type/:name/layers', at)], + ['rest /published', await rest('GET', '/:type/:name/published', at)], + ['rest _env', await rest('GET', '/:type/:ns/:name', { ...at, ns: '_env' })], + ] as const; + const read = answers.map(([door, answer]) => { + const body = unwrap(answer.body); + const served = door.endsWith('/layers') ? body?.effective : (body?.item ?? body); + return [door, answer.status, answer.status === 200 ? served?.label : codeOf(answer.body), answer.status === 200 ? body?.packageId ?? served?._packageId : undefined]; + }); + const executed = await (kernel.getService('protocol') as any).getMetaItemForExecution({ type: 'dashboard', name }).then( + (answer: any) => [200, answer?.item?.label, answer?.packageId ?? answer?.item?._packageId], + (error: any) => [error?.httpStatus, error?.code, undefined], + ); + return [...read, ['execution read', ...executed]]; + } + const servedEverywhere = (label: string) => [ + 'dispatcher plain', 'dispatcher /layers', 'dispatcher /published', 'dispatcher _env', + 'rest plain', 'rest /layers', 'rest /published', 'rest _env', 'execution read', + ].map((door) => [door, 200, label, undefined]); + const layersOf = async (kernel: ObjectKernel, name: string) => { + const layers = unwrap((await get(kernel, `/meta/dashboard/${name}/layers`)).body); + return [layers?.code ?? null, layers?.overlay?.label, layers?.effective?.label]; + }; + const storedRows = async (engine: ObjectQL, name: string) => ((await engine.find('sys_metadata', { where: { type: 'dashboard', name }, context: { isSystem: true } } satisfies EngineQueryOptions)) as any[]) + .map((row) => `${row.state}:${row.package_id ?? null}:${JSON.parse(String(row.metadata)).label}`).sort(); + + describe.each([ + { regOrder: 'registered A, B, C', order: [SHIP_A, SHIP_B, SHIP_C] }, + { regOrder: 'registered C, B, A', order: [SHIP_C, SHIP_B, SHIP_A] }, + ])('$regOrder (C disabled)', ({ order }) => { + it.each([ + { shippers: 'two enabled shippers', name: TWO }, + { shippers: 'two enabled shippers beside a disabled one', name: MIXED }, + ])('$shippers: every read naming no package serves the row, on both transports, before and after a reboot; the bare save edits it and every read serves the edit', async ({ name }) => { + const file = join(mkdtempSync(join(tmpdir(), 'os-meta-env-row-db-')), 'meta.sqlite'); + roots.push(join(file, '..')); + let booted = await bootShippers(order, file); + try { + await booted.engine.insert('sys_metadata', { + type: 'dashboard', name, namespace: 'default', package_id: null, scope: 'platform', strategy: 'merge', state: 'active', version: 1, + metadata: JSON.stringify({ name, label: 'environment row', widgets: [] }), + }, { context: { isSystem: true } } as any); + expect(await bareReads(booted.kernel, name)).toEqual(servedEverywhere('environment row')); + // No package's artifact is the environment item's code layer: the row is its overlay and effective layer. + expect(await layersOf(booted.kernel, name)).toEqual([null, 'environment row', 'environment row']); + } finally { + await booted.kernel.shutdown(); + } + booted = await bootShippers(order, file); + try { + expect(await bareReads(booted.kernel, name)).toEqual(servedEverywhere('environment row')); + // Reads and writes agree: the bare save on each transport edits that row, and every read serves the edit. + const saved = await restDoor(booted.kernel)('PUT', '/:type/:name', { type: 'dashboard', name }, { name, label: 'edited on rest', widgets: [] }); + expect(saved.status, JSON.stringify(saved.body)).toBe(200); + expect(await storedRows(booted.engine, name)).toEqual(['active:null:edited on rest']); + expect(await bareReads(booted.kernel, name)).toEqual(servedEverywhere('edited on rest')); + const dispatcher = new HttpDispatcher(booted.kernel as any, undefined, { enforceProjectMembership: false }); + (dispatcher as any).timedResolveExecutionContext = async () => ({ ...CALLER }); + const body = { name, label: 'edited on dispatcher', widgets: [] }; + const request = new Request(`http://localhost/api/v1/meta/dashboard/${name}`, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); + const out: any = await dispatcher.dispatch('PUT', `/meta/dashboard/${name}`, body, {}, { request } as any, '/api/v1'); + expect(out.response?.status, JSON.stringify(out.response?.body)).toBe(200); + expect(await storedRows(booted.engine, name)).toEqual(['active:null:edited on dispatcher']); + expect(await bareReads(booted.kernel, name)).toEqual(servedEverywhere('edited on dispatcher')); + // [contract review S2] The entry's remedy: the delete naming no package removes that row, and the + // reads refuse naming the enabled shippers again. + const removed = await restDoor(booted.kernel)('DELETE', '/:type/:name', { type: 'dashboard', name }); + expect(removed.status, JSON.stringify(removed.body)).toBe(200); + expect((await storedRows(booted.engine, name)).filter((row) => row.startsWith('active:'))).toEqual([]); + for (const [door, status, code] of await bareReads(booted.kernel, name)) expect([door, status, code]).toEqual([door, 409, 'RESOURCE_CONFLICT']); + } finally { + await booted.kernel.shutdown(); + } + }, 240_000); + + // [#34348 contract review M1, S1] Only the arrangement where the bare + // save addresses the environment's row moves. Beside a row bound to a + // shipper the save edits that package's row (one) or refuses (two), + // and a row stored with the empty string as its binding is not the row + // the content read finds at no package: no read naming no package + // serves the environment's row there, before and after a reboot. + it.each([ + { cell: 'X: the unbound row beside a row bound to one shipper', name: BOUND_ONE, rows: [[null, 'environment row'], [SHIP_A, 'A row']] }, + { cell: 'Y: the unbound row beside rows bound to both shippers', name: BOUND_BOTH, rows: [[null, 'environment row'], [SHIP_A, 'A row'], [SHIP_B, 'B row']] }, + { cell: 'E: an unbound row stored with an empty binding', name: EMPTY_BINDING, rows: [['', 'environment row']] }, + ] as const)('CONTROL, $cell: no read naming no package serves the environment\'s row, before and after a reboot', async ({ name, rows }) => { + const file = join(mkdtempSync(join(tmpdir(), 'os-meta-env-row-db-')), 'meta.sqlite'); + roots.push(join(file, '..')); + for (let boot = 0; boot < 2; boot += 1) { + const booted = await bootShippers(order, file); + try { + if (boot === 0) { + for (const [packageId, label] of rows) { + await booted.engine.insert('sys_metadata', { + type: 'dashboard', name, namespace: 'default', package_id: packageId, scope: 'platform', strategy: 'merge', state: 'active', version: 1, + metadata: JSON.stringify({ name, label, widgets: [] }), + }, { context: { isSystem: true } } as any); + } + // The engine stores an empty binding as null: write the empty string under it, as an older store holds it. + if (name === EMPTY_BINDING) { + await (booted.engine as any).__qaKnex('sys_metadata').where({ type: 'dashboard', name }).update({ package_id: '' }); + const raw = await (booted.engine as any).__qaKnex('sys_metadata').where({ type: 'dashboard', name }).select('package_id'); + expect(raw.map((row: any) => row.package_id)).toEqual(['']); + } + } + const answers = await bareReads(booted.kernel, name); + for (const [door, status, served, stated] of answers) { + expect([door, status === 200 && served === 'environment row' && stated === undefined], JSON.stringify(answers)).toEqual([door, false]); + } + if (name !== BOUND_ONE) { + for (const [door, status, code] of answers) expect([door, status, code], JSON.stringify(answers)).toEqual([door, 409, 'RESOURCE_CONFLICT']); + } + } finally { + await booted.kernel.shutdown(); + } + } + }, 240_000); + + it('CONTROL: with no package-unbound row, every read naming no package still refuses naming both enabled shippers, never the disabled one, before and after a reboot', async () => { + const file = join(mkdtempSync(join(tmpdir(), 'os-meta-env-row-db-')), 'meta.sqlite'); + roots.push(join(file, '..')); + for (let boot = 0; boot < 2; boot += 1) { + const booted = await bootShippers(order, file); + try { + for (const [door, status, code] of await bareReads(booted.kernel, NONE)) { + expect([door, status, code]).toEqual([door, 409, 'RESOURCE_CONFLICT']); + } + const read = await get(booted.kernel, `/meta/dashboard/${NONE}`); + expect([...(read.body?.error?.details?.candidates ?? [])].map((c: any) => c.packageId).sort(), JSON.stringify(read.body)) + .toEqual([SHIP_A, SHIP_B].sort()); + expect(await storedRows(booted.engine, NONE)).toEqual([]); + } finally { + await booted.kernel.shutdown(); + } + } + }, 240_000); + }); +}); diff --git a/packages/spec/src/migrations/entries/semantic/19.environment-row-beside-two-shippers-bare-read-served.ts b/packages/spec/src/migrations/entries/semantic/19.environment-row-beside-two-shippers-bare-read-served.ts new file mode 100644 index 00000000000..458061d0ecd --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.environment-row-beside-two-shippers-bare-read-served.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A widening of the reads that name no package, not of any key: ruling +// 6942981052 option (b) on #34348, narrowed by 7187668758 to two or more +// ENABLED holders, has the environment's own item answer first and reads and +// writes give the same answer. A package-unbound stored row of a name two or +// more enabled packages ship in code was refused by every such read (409 +// naming the shippers) while the save naming no package edited it (200); the +// reads now serve it. Only the shipper case moves: a name the packages hold +// only as stored rows keeps entry two-row-holders-bare-read-refused (its save +// refuses too, so reads and writes already agree there), and a disabled +// shipper counts for nothing. No key is added, removed or re-shaped and no +// stored row changes shape, so no tombstone and no D2 conversion. No +// relevance question: the move turns on which installed packages ship a name +// and which rows a deployment stores, which no question over one stack can +// name. +export const entry: SemanticMigration = { + id: 'environment-row-beside-two-shippers-bare-read-served', + surface: + 'The reads of a metadata item that name no package (GET /api/v1/meta/TYPE/NAME, ' + + 'GET /api/v1/meta/TYPE/NAME/layers, GET /api/v1/meta/TYPE/NAME/published, GET /api/v1/meta/TYPE/_env/NAME, and ' + + 'the in-process item, layered and execution reads with no packageId) of a type the registry reads by package, ' + + 'for a name two or more enabled packages ship in code while the environment stores a package-unbound active ' + + 'row of it that the reads serve, with no row bound to a package beside it at the same member (an overlay ' + + 'type\'s; a sealed managed type\'s package-unbound row is declined and stays refused)', + replacement: + 'Nothing to rewrite for a reader of the environment\'s row: every read that names no package now answers that ' + + 'row (200), as the save naming no package edits it. A caller that relied on the 409 RESOURCE_CONFLICT ' + + '(reason ambiguous-in-environment) to learn that two packages ship the name gets no package\'s item here: ' + + '?package=PACKAGE also answers 409 while that row is stored. Deleting the environment\'s row ' + + '(DELETE /api/v1/meta/TYPE/NAME naming no package, which removes that row) has the reads refuse naming the ' + + 'shippers again.', + reason: + 'The environment\'s own item answers first, and reads and writes give the same answer (ruling 6942981052, ' + + 'narrowed by 7187668758 and 7405866869). Beside two or more enabled shippers the save naming no package edited the ' + + 'environment\'s package-unbound row while every read naming no package refused 409 naming the shippers, ' + + 'and neither ?package= nor _env reached the row, so an environment could change an item no read would show. ' + + 'The reads now serve the row with no package\'s envelope: /layers reports no code layer, the row as overlay ' + + 'and effective. There is no mechanical rewrite: which item a caller meant is a judgement about that caller.', + acceptanceCriteria: + 'For every name two or more enabled packages ship while the environment stores a package-unbound row of it and ' + + 'no row bound to a package at the same member: ' + + 'GET /api/v1/meta/TYPE/NAME, /layers (code null, the row as overlay and effective), /published, ' + + 'GET /api/v1/meta/TYPE/_env/NAME and the in-process execution read each answer that row, stating no package, ' + + 'in both registration orders and after a restart, and after a save naming no package they answer the saved ' + + 'body. With no such row every read naming no package still answers 409 RESOURCE_CONFLICT naming the enabled ' + + 'shippers, and beside a row bound to a package every such read answers as it did before.', +}; diff --git a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts index 99955d6b3f3..cc9ca670cf7 100644 --- a/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts +++ b/packages/spec/src/migrations/semantic-relevance-coverage-38929.test.ts @@ -112,6 +112,10 @@ const STAYS_LISTED: Readonly