From b46f3325e651803ed2d8cf82bb462a9adaef6314 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 18:47:19 +0000 Subject: [PATCH 1/2] fix(objectql,metadata-protocol)!: a stored row bound to a package lives in that package's own registry slot (ADR-0150 D3/D4) The registry kept one bare slot per name for a stored row, so the row saved or hydrated last took it. Each row bound to a package (its own, or its .custom pair's by the pair-row rule) of a type the registry reads by package now registers in that package's overlay slot, beside the code artifact's composite entry, which it never overwrites. - each package's exact read and registry item answer its own row in every registration, save and row order, before and after a restart, on the writer and on its peers; - a pair address of a name held only as stored rows answers its base's row; - the read naming no package of a package's row beside its pair's undeclared row serves the package's own row in both orders; - the read naming no package of an action two packages hold only as stored rows refuses 409 naming both after a restart, as every other type already did (the narrowing); - a bundle member two packages hold only as stored rows is no clash, as when one slot held one of them. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cy1y7UNVbT2QAdmgdn --- ...red-row-own-package-slot-semantic-entry.md | 10 + .../33127-stored-row-own-package-slot.md | 24 ++ .../src/protocol-exact-qualifier.ts | 28 +- .../src/protocol-meta-item-face.ts | 15 +- .../src/protocol-meta-item-reads.ts | 8 +- .../src/protocol-registry-hydration.ts | 55 +++- .../protocol.register-item-call-sites.test.ts | 9 +- .../protocol-cluster-signal-package.test.ts | 51 ++++ .../src/protocol-flow-custom-override.test.ts | 14 +- packages/objectql/src/registry.ts | 251 ++++++++++++++++-- .../webhook-stored-row-boot-hydration.test.ts | 139 ++++++++++ .../meta-disabled-holder-served-stack.test.ts | 133 +++++++++- .../18.stored-row-own-package-slot.ts | 38 +++ 13 files changed, 735 insertions(+), 40 deletions(-) create mode 100644 .changeset/33127-stored-row-own-package-slot-semantic-entry.md create mode 100644 .changeset/33127-stored-row-own-package-slot.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.stored-row-own-package-slot.ts diff --git a/.changeset/33127-stored-row-own-package-slot-semantic-entry.md b/.changeset/33127-stored-row-own-package-slot-semantic-entry.md new file mode 100644 index 00000000000..1b4d350949f --- /dev/null +++ b/.changeset/33127-stored-row-own-package-slot-semantic-entry.md @@ -0,0 +1,10 @@ +--- +'@objectstack/spec': patch +--- + +docs(spec): the protocol upgrade guide names what each package's address answers when two packages each hold a stored row of one name: that package's own row, in every save order, before and after a restart (ADR-0150 D3/D4) + +Clause-②: no +Metadata-protocol: none + +The semantic entry `stored-row-own-package-slot` (`packages/spec/src/migrations/entries/semantic/18.stored-row-own-package-slot.ts`) registers the narrowing `.changeset/33127-stored-row-own-package-slot.md` declares (ADR-0087, `adr-0087: registered`): no automatic rewrite, since every stored row keeps its shape and its binding. It adds no key and no export. diff --git a/.changeset/33127-stored-row-own-package-slot.md b/.changeset/33127-stored-row-own-package-slot.md new file mode 100644 index 00000000000..87a4096f6d6 --- /dev/null +++ b/.changeset/33127-stored-row-own-package-slot.md @@ -0,0 +1,24 @@ +--- +'@objectstack/objectql': minor +'@objectstack/metadata-protocol': minor +--- + +fix(objectql,metadata-protocol)!: a stored row bound to a package lives in that package's own registry slot, so each package's address serves its own row in every save order, before and after a restart (ADR-0150 D3/D4) + +Clause-②: yes (narrowing) — one served answer goes away: an action that two packages hold only as stored rows was served by the read naming no package after a restart (the row hydrated last); it now refuses `409 RESOURCE_CONFLICT` naming both, as every other type the registry reads by package already did (#32607). The widening is on `SchemaRegistry`, exported from `@objectstack/objectql`: `registerItem` takes an optional fifth argument `{ storedRowPackage }`, and one new public method `removePackageOverlaySlots(type, name, member, select)`; and four reads that answered a shipped item, a 404 or a 409 now answer the address's own stored row (below). +Metadata-protocol: semantic +Skills-docs: none — `skills/**` and `content/docs/**` teach no reading of a name two packages each store a row of (grepped `?package=`, `.custom`, `409`: the hits are the pair's save door, a flow's secret refusal and a permission grant), so no taught sentence moves; the read naming no package keeps its `409` and its `?package=` remedy. + + + +**BREAKING** for a reader of an action that two packages hold only as stored rows, by the read naming no package (`GET /api/v1/meta/action/NAME`), after a restart: it refused before the restart and served the row hydrated last after it; it now refuses `409 RESOURCE_CONFLICT` naming both packages, before and after. The fix: read each package's action by its package (`?package=ID`). + +The registry kept ONE slot per name for a stored row (`registerItem` with no package), so the row saved or hydrated last took it. Each stored row of a type the registry reads by package (action, tool, agent, skill, webhook, api, email template, picklist, mapping, dataset; flow and permission keep their own slot rules) that is bound to a package — its own, or its `.custom` pair's by the pair-row rule — now lives in that package's own overlay slot, beside the package's code artifact, which it never overwrites. + +- **#33127 — two packages ship a name and each stores its own row.** At boot (`loadMetaFromDb`) the row hydrated last took the name's slot: that package's registry item and `?package=` read answered its row, the other package's answered its shipped item, which package by row order (tool, webhook, agent, skill measured). Each package now answers its own row in every registration and row order; the read naming no package still refuses `409` naming both. +- **#32663 — the writer's registry item.** After alpha then beta saved a row of one name, both replicas' registry items answered `[null, beta's row]` at the two packages (the mirror in the other order) while the exact reads, row-served, answered each package's own row. The registry now agrees with the exact reads on the writer and on the peer (action, tool, email template). A `dashboard` is converged by name, unchanged. +- **#32662 — a pair address of a name held only as stored rows.** `?package=ID.custom` answered `404` for both packages before a restart and, after it, `200` for the row hydrated last and `409` naming one package for the other (dashboard, tool, action). Each pair address now answers its base package's row, before and after. +- **#32662 scope note (b).** A package's row beside its own pair's undeclared row: the read naming no package served the pair's row when it was saved first while `/published` served the package's own row. Both now serve the package's own row in either order. +- **#32900.** A module's locale member stored in its App's pair (declaring the module) beside a package-less row of the same locale: the module's registry item at that locale followed the row order. It now answers the module's own pair row in both orders; the install and seal answers are unchanged. + +Unchanged, pinned as CONTROLs: a name one package holds (its row in its slot, its exact read and its read naming no package); two packages with one stored row (the other keeps its shipped item); a package-less row (it keeps the bare slot); the read naming no package of a two-holder name (`409` naming both). diff --git a/packages/metadata-protocol/src/protocol-exact-qualifier.ts b/packages/metadata-protocol/src/protocol-exact-qualifier.ts index 8f14e88f213..5eda31f6b80 100644 --- a/packages/metadata-protocol/src/protocol-exact-qualifier.ts +++ b/packages/metadata-protocol/src/protocol-exact-qualifier.ts @@ -119,6 +119,13 @@ export interface ExactQualifierAddress { * when only a stored row bound to the package carries it. */ readonly registryHolders: readonly string[]; + /** + * [#32662, ADR-0150 D3] The one base a customization pair's address was + * admitted at through that base's stored row, when the registry holds the + * name for no base it pairs and the pair stores no row of its own: the + * package whose stored content the address serves. Absent otherwise. + */ + readonly storedRowBase?: string; } /** The engine's registry, as the reads below probe it. */ @@ -278,8 +285,9 @@ function refusal( * `getEnvironmentScopedItem`, `getPackageScopedItem`). */ export async function admitExactQualifier( - host: Pick, + host: Pick, request: { type: string; name: string; packageId?: string; member?: string }, + options: { readonly storedRowBases?: boolean } = {}, ): Promise { const packageId = request.packageId; if (!packageId || !isPackageScopedType(request.type)) return undefined; @@ -321,6 +329,24 @@ export async function admitExactQualifier( } } + // [#32662, ADR-0150 D3, red line 2] A pair address of a name its bases + // hold only as stored rows is judged from the rows' bindings, as the read + // naming no package judges such a name ({@link servedRowHolderOf}), never + // from the registry alone: a type the registry keeps one bare slot per + // name for (`dashboard`) holds the row hydrated last, so after a reboot + // the later saver's pair address answered its row and the earlier one's + // was refused naming only the other. Admitted at every base whose row is + // stored, one base read for its content ({@link ExactQualifierAddress.storedRowBase}); + // two are refused naming both by {@link exactQualifierItem}, as two + // registry bases are. Asked by the plain item read (`options.storedRowBases`). + if (options.storedRowBases === true) { + const bindings = (await host.packagelessAddress(request.type, request.name, request.member, 'active')).candidates; + const rowBases = bindings.filter((binding) => binding !== packageId && pairsOf(binding, installed).includes(packageId)); + if (rowBases.length > 0) { + return { packageId, registryHolders: rowBases, ...(rowBases.length === 1 ? { storedRowBase: rowBases[0] } : {}) }; + } + } + const candidates: PackageScopedHolder[] = holders.map((holder) => ({ kind: 'package' as const, packageId: holder })); if (registry.getEnvironmentScopedItem(request.type, request.name, request.member) !== undefined) { candidates.push({ kind: 'environment' }); diff --git a/packages/metadata-protocol/src/protocol-meta-item-face.ts b/packages/metadata-protocol/src/protocol-meta-item-face.ts index 531444d2b10..f16b88fdba2 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-face.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-face.ts @@ -279,7 +279,7 @@ async function storedRowHoldersRefusal( every: readonly string[], activeRows: Awaited>, bound: readonly string[], -): Promise<{ kind: 'refused'; error: PackageScopedNameRefusedError } | undefined> { +): Promise<{ kind: 'served'; packageId: string } | { 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); @@ -288,7 +288,18 @@ async function storedRowHoldersRefusal( && 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; + if (holding.unbound) return undefined; + // [#32662 scope note (b), ADR-0150 D3] One holder whose rows are its own + // and its customization pair's: the read is that holder's, at its address, + // as `/published` reads it, so the layer served is its own row in both + // save orders. Read as it was, it served the row stored first. + if (holding.candidates.length === 1) { + const [holder] = holding.candidates; + const ownAndPair = bound.length > 1 && bound.includes(holder) + && bound.every((id) => id === holder || pairsOf(holder, installed).includes(id)); + return ownAndPair ? { kind: 'served', packageId: holder } : undefined; + } + if (holding.candidates.length < 2) return undefined; const base = { status: 'refused' as const, reason: 'ambiguous-in-environment' as const, diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index d86520616fa..ca66612b20d 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -604,7 +604,7 @@ export async function readMetaItem(host: Pick isPairOf(bound, holder, installed)); } +/** + * [#33127, ADR-0150 D4 "registry overlay slot (ADR-0005)"] Whether a stored row + * of `canonicalType` bound to a package registers into that package's overlay + * slot (`SchemaRegistry#registerItem`'s `storedRowPackage`) instead of the + * name's one bare slot: the types the metadata service stores per `(package, + * name)` ({@link PACKAGE_SLOTTED_STORE_TYPES}), so the registry keeps one entry + * per stored row as the store keeps one row per package. With one bare slot, + * two packages' rows of a name (or a package's row beside its pair's, or a + * pair's row beside the package-less row of one member) kept only the row + * registered last: the other package's exact read and its registry item + * answered its shipped item, or nothing, by save or hydration order. + * + * ⛔ Not a `flow`: the name's one bare slot keeps the shipping package's + * declared override over any other row ({@link incomingTakesStoredFlowSlot}, + * #28717), which the boot pull reads. ⛔ Not a `permission`: a stored fork of + * a shipped permission set keeps the disposition of its own maintainer ruling + * (see {@link judgesRowHolder}). A package-less row keeps the bare slot. + */ +function takesPackageOverlaySlot(canonicalType: string): boolean { + return PACKAGE_SLOTTED_STORE_TYPES.has(canonicalType) && canonicalType !== 'flow' && canonicalType !== 'permission'; +} + /** {@link pairRowEnvelopeHolder}'s answer for a row that is not a customization pair's row of a two-holder name. */ const NOT_A_PAIR_ROW = Symbol('not-a-pair-row'); @@ -898,13 +921,19 @@ export class ProtocolRegistryHydrationFacet { if (typeof owner === 'string' && owner !== '') shippers.add(owner); if (!incomingTakesStoredFlowSlot(held, registered, shippers, installedManifestsOf(registry))) return true; } - registry.registerItem(type, registered, 'name' as any); + // [#33127, ADR-0150 D4] A row bound to a package takes that package's + // overlay slot ({@link takesPackageOverlaySlot}), so each stored row of + // the name keeps its own entry and each package's exact read serves its + // own, in every save and hydration order. + const rowPackage = boundPackageOf(options.packageId); + const overlaySlot = rowPackage !== undefined && takesPackageOverlaySlot(canonicalType); + registry.registerItem(type, registered, 'name' as any, undefined, overlaySlot ? { storedRowPackage: rowPackage } : undefined); // [#32820] A package-less row wearing the envelope of the one holder // served now is recorded, so an enable serving a second holder builds // it again ({@link healSoleHolderEnvelopes}); any other registration - // of the key forgets it. + // of the key forgets it. [#33127] A package overlay slot is another key. const member = bundleMemberOf(type, data); - recordSoleHolderEnvelope(registry, envelopeKey(type, rowName, member), + if (!overlaySlot) recordSoleHolderEnvelope(registry, envelopeKey(type, rowName, member), !options.packageId && typeof envelopePackage === 'string' && envelope && HEALED_OVERLAY_TYPES.has(canonicalType) ? { host, type, canonicalType, name: rowName, member, data, holder: envelopePackage, registered } : undefined); @@ -1754,8 +1783,17 @@ export class ProtocolRegistryHydrationFacet { registry.removeObjectOverlay(name); } - let healed = false; - if (typeof registry.removeRuntimeShadow === 'function') { + // [#33127, ADR-0150 D4] A removed row bound to a package sat in that + // package's overlay slot (`SchemaRegistry#removePackageOverlaySlots`, + // the types {@link takesPackageOverlaySlot} names): that slot is + // retired, and tier 1 does not touch the bare slot, which holds the + // package-less row, still stored. The walk then stops where tier 1 + // stops, where a packaged artifact of the name is served. + const removedBinding = packageId === HEAL_BINDING_UNKNOWN ? undefined : boundPackageOf(packageId); + const slotRetired = removedBinding !== undefined && typeof registry.removePackageOverlaySlots === 'function' + && registry.removePackageOverlaySlots(singular, name, memberKey, (id: string) => id === removedBinding).length > 0; + let healed = slotRetired && host.isArtifactBacked(singular, name); + if (!slotRetired && typeof registry.removeRuntimeShadow === 'function') { healed = registry.removeRuntimeShadow(singular, name, memberKey); if (type !== singular) { healed = registry.removeRuntimeShadow(type, name, memberKey) || healed; @@ -1815,6 +1853,13 @@ export class ProtocolRegistryHydrationFacet { const remainingRows = canonical === 'object' && host.isUnservedSealedOverlay(canonical, name) ? [] : storedRows ?? []; + // [#33127] A caller that does not know the removed row's binding (a + // peer on a signal naming no package): every package overlay slot + // whose package no remaining row is bound to is the removed row's. + if (packageId === HEAL_BINDING_UNKNOWN && storedRows != null && typeof registry.removePackageOverlaySlots === 'function') { + const bindings = new Set(remainingRows.map((row) => boundPackageOf(row.package_id))); + registry.removePackageOverlaySlots(singular, name, memberKey, (id: string) => !bindings.has(id)); + } if (remainingRows.length > 0) { if (canonical === 'object' && !host.isArtifactBacked(canonical, name)) { const bindings = new Set(remainingRows.map((row) => boundPackageOf(row.package_id) ?? 'sys_metadata')); diff --git a/packages/metadata-protocol/src/protocol.register-item-call-sites.test.ts b/packages/metadata-protocol/src/protocol.register-item-call-sites.test.ts index 8e39f8a1999..c495c9dcc84 100644 --- a/packages/metadata-protocol/src/protocol.register-item-call-sites.test.ts +++ b/packages/metadata-protocol/src/protocol.register-item-call-sites.test.ts @@ -127,12 +127,17 @@ const SITES: ReadonlyArray { + const read = async (protocol: any, type: string, packageId?: string) => { + try { + return (await protocol.getMetaItem({ type, name: NAME, ...(packageId ? { packageId } : {}) }))?.item?.label; + } catch (e) { + const err = e as { code?: string; status?: number }; + return `${err.status} ${err.code}`; + } + }; + for (const type of ['action', 'tool', 'email_template']) { + for (const saved of [[ALPHA, BETA], [BETA, ALPHA]] as const) { + it(`${type} (${saved[0] === ALPHA ? 'alpha' : 'beta'} saved first): alpha's and beta's slots are their own rows on both replicas, and the exact reads agree`, async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const c = makeCluster(type); + const body = (label: string) => (type === 'tool' ? { name: NAME, label, description: label, parameters: { type: 'object', properties: {} } } : bodyOf(type, label)); + for (const id of saved) { + const res = await c.a.protocol.saveMetaItem({ type, name: NAME, packageId: id, item: body(`row-${id.split('.').pop()}`) }); + expect(res.success).toBe(true); + await settle(); + } + // FROM (main): both replicas `[null, last, last]` at the two slots. + expect(c.a.serves().slice(0, 2), 'the writer').toEqual(['row-alpha', 'row-beta']); + expect(c.b.serves(), 'the peer').toEqual(c.a.serves()); + expect([await read(c.a.protocol, type, ALPHA), await read(c.a.protocol, type, BETA)]).toEqual(['row-alpha', 'row-beta']); + // The read naming no package refuses (#32607). For `action` + // this is a move: on main the last-hydrated row answered it 200. + expect(await read(c.a.protocol, type)).toBe('409 RESOURCE_CONFLICT'); + }); + } + } + it('CONTROL — one package\'s row of a name: its slot, its exact read and the read naming no package, on both replicas, as before', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const c = makeCluster('tool'); + const res = await c.a.protocol.saveMetaItem({ type: 'tool', name: NAME, packageId: BETA, item: { name: NAME, label: 'row-beta', description: 'row-beta', parameters: { type: 'object', properties: {} } } }); + expect(res.success).toBe(true); + await settle(); + expect([c.a.serves(), c.b.serves()]).toEqual([[null, 'row-beta', 'row-beta'], [null, 'row-beta', 'row-beta']]); + expect([await read(c.a.protocol, 'tool', BETA), await read(c.a.protocol, 'tool')]).toEqual(['row-beta', 'row-beta']); + }); +}); diff --git a/packages/objectql/src/protocol-flow-custom-override.test.ts b/packages/objectql/src/protocol-flow-custom-override.test.ts index 5b476b6db74..fc8152e0f52 100644 --- a/packages/objectql/src/protocol-flow-custom-override.test.ts +++ b/packages/objectql/src/protocol-flow-custom-override.test.ts @@ -1152,15 +1152,15 @@ describe('[#33131] two packages ship one action name, one declares an override: } // [#33131 contract review S1] Both holders overridden. Every read face serves each holder's own override, - // in both registration orders and both save orders. The registry's package-scoped item cannot yet: it keeps - // ONE bare slot per name (`overlaySlotBinding`), so the holder whose override was published LAST is served - // there and the other holder's slot answers its own SHIPPED action — never the other package's override - // (FROM `main`: alpha's registry item could read `OVR-B`). Carried on the card, not fixed here: the fix is - // the registry's slot model, not this hydrator. + // in both registration orders and both save orders. [#33127] So does the registry's package-scoped item now: + // each pair's declared override lives in its pair's own package overlay slot, bound to the holder it + // declares. FROM (#33131's head, the carried face): the registry kept ONE bare slot per name, so the holder + // whose override was published LAST was served there and the other holder's slot answered its own SHIPPED + // action. for (const order of [[ALPHA, BETA], [BETA, ALPHA]] as const) { for (const saves of [[ALPHA, BETA], [BETA, ALPHA]] as const) { const [savedFirst, savedLast] = saves; - it(`${nsOf(order[0])} registered first, ${nsOf(savedFirst)} saved first, both overridden: each read face serves its own override; the registry item serves the last-saved holder's override and the first-saved holder's own shipped action (carried)`, async () => { + it(`${nsOf(order[0])} registered first, ${nsOf(savedFirst)} saved first, both overridden: each read face and each holder's registry item serves its own override`, async () => { const { engine, protocol } = await bootHolders(order, saves); for (const face of ['served', 'execution'] as const) { expect(await entries(protocol, face), face).toEqual([`${ALPHA}:OVR-A`, `${BETA}:OVR-B`]); @@ -1172,7 +1172,7 @@ describe('[#33131] two packages ship one action name, one declares an override: } const registry = engine.registry as any; expect(registry.getPackageScopedItem('action', SHARED_ACTION, savedLast)?.label, 'the last-saved holder').toBe(labelOf(savedLast)); - expect(registry.getPackageScopedItem('action', SHARED_ACTION, savedFirst)?.label, 'the first-saved holder: its own shipped action, never the other override').toBe(`SHIPPED-${nsOf(savedFirst)}`); + expect(registry.getPackageScopedItem('action', SHARED_ACTION, savedFirst)?.label, 'the first-saved holder: its own override, never the other one').toBe(labelOf(savedFirst)); }); } } diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 85ef55a712f..4c92587de4b 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -3724,6 +3724,53 @@ function bundleBaseKey(key: string): string { /** One member of an i18n bundle, as stored. */ type BundleEntry = { key: string; item: any }; +/** + * [#33127, ADR-0150 D4 "registry overlay slot (ADR-0005)"] The mark that opens + * and separates a package overlay slot's storage key: the slot of the stored + * row of `(type, name[, member])` bound to one package, beside the bare slot + * (a package-less row) and the composite slots (code artifacts). A NUL never + * occurs in a package id or a name, so no reader of the other two key forms + * mistakes this one for its own: it is never a bare key (`name`, `name@member`) + * and never ends `:name` ({@link bundleBaseKey}, {@link collectBundle}, the + * composite scans), so it adds no holder and is no artifact. + */ +const OVERLAY_SLOT_MARK = '\u0000'; + +/** `com.acme.alpha` + `auth.welcome@zh-CN` → the package overlay slot key of that member. */ +function overlaySlotKey(packageId: string, bareKey: string): string { + return `${OVERLAY_SLOT_MARK}${packageId}${OVERLAY_SLOT_MARK}${bareKey}`; +} + +/** The package and the bare key of a package overlay slot key, or `undefined` for any other key. */ +function parseOverlaySlotKey(key: string): { packageId: string; bareKey: string } | undefined { + if (!key.startsWith(OVERLAY_SLOT_MARK)) return undefined; + const sep = key.indexOf(OVERLAY_SLOT_MARK, 1); + return sep < 0 ? undefined : { packageId: key.slice(1, sep), bareKey: key.slice(sep + 1) }; +} + +/** + * [#33127] The package overlay slots of `(name)` in `collection`, every member + * of a bundled type (`disc`), in the store's order: the stored rows bound to a + * package, one slot per row package. + */ +function overlaySlotEntriesOf(collection: Map, name: string, disc?: { field: string; canonical: string }): BundleEntry[] { + const out: BundleEntry[] = []; + for (const [key, item] of collection) { + const slot = parseOverlaySlotKey(key); + if (slot === undefined) continue; + if ((disc ? bundleBaseKey(slot.bareKey) : slot.bareKey) === name) out.push({ key, item }); + } + return out; +} + +/** The package a bare-slot or package overlay slot entry's stored row is bound to: the slot's package, else the entry's stamp. */ +function storedRowPackageOf(entry: BundleEntry): string | undefined { + const slot = parseOverlaySlotKey(entry.key); + if (slot !== undefined) return slot.packageId; + const stamped = (entry.item as { _packageId?: unknown } | null | undefined)?._packageId; + return typeof stamped === 'string' && stamped !== '' && stamped !== 'sys_metadata' ? stamped : undefined; +} + /** * [#32408, contract review F2, delta review N1] What a door's registration * brings to a bundled name: the package and the members it adds to its @@ -6657,11 +6704,27 @@ export class SchemaRegistry { private boundServedActions(): any[] { const collection = this.metadata.get('action'); if (!collection) return []; + // [#33127, ADR-0150 D4] A stored row in a package overlay slot shadows the + // composite entry of the package it customizes (its envelope's), as the + // bare slot shadows every composite of its name; of two rows customizing + // one package, the one its read serves ({@link rankedForPackage}). + const overlaysOf = new Map(); + for (const [key, item] of collection) { + if (parseOverlaySlotKey(key) === undefined) continue; + const holder = storedRowPackageOf({ key: '', item }) ?? parseOverlaySlotKey(key)!.packageId; + const group = `${holder}:${String((item as any)?.name)}`; + overlaysOf.set(group, [...(overlaysOf.get(group) ?? []), { key, item }]); + } + const servedOverlays = new Set(); + for (const [group, entries] of overlaysOf) { + servedOverlays.add(this.rankedForPackage(entries, group.slice(0, group.lastIndexOf(':')))[0].key); + } const out: any[] = []; for (const [key, action] of collection) { if (!action || typeof action !== 'object' || typeof (action as any).name !== 'string') continue; const name: string = (action as any).name; if (key !== name && collection.has(name)) continue; + if (parseOverlaySlotKey(key) !== undefined ? !servedOverlays.has(key) : overlaysOf.has(key)) continue; if (isObjectLessActionKey(standaloneActionOwnerKey(action))) continue; // [#28877] …and so is an action that launches into a disabled package. if (this.isActionWithheldByDisabledPackage(action)) continue; @@ -8446,8 +8509,20 @@ export class SchemaRegistry { /** * Universal Register Method for non-object metadata. - */ - registerItem(type: string, item: T, keyField: keyof T = 'name' as keyof T, packageId?: string) { + * + * @param options.storedRowPackage - [#33127, ADR-0150 D4] For a registration + * with no `packageId` (a stored `sys_metadata` row, the ADR-0005 overlay): + * the package the row is bound to (its `package_id` column). The row then + * takes that package's overlay slot ({@link overlaySlotKey}) instead of the + * name's one bare slot, so two packages' rows of one name, and a package's + * row beside its pair's or beside the package-less row, each keep their own + * entry, whatever order they are registered in. Judged as the bare slot is + * (it is an overlay, never a package's declaration), and read by every + * overlay-slot reader ({@link bareSlotEntriesOf}) and by {@link getItem}'s + * overlay tier. Ignored with a `packageId`. + */ + registerItem(type: string, item: T, keyField: keyof T = 'name' as keyof T, packageId?: string, + options?: { storedRowPackage?: string }) { this.noteItemType(type); if (!this.metadata.has(type)) { this.metadata.set(type, new Map()); @@ -8650,7 +8725,13 @@ export class SchemaRegistry { // The bare (overlay) slot for this item — see the artifact-vs-DB warning below. const bareKey = withDisc(baseName); // Use composite key (packageId:name) when packageId is provided - const storageKey = packageId ? withDisc(`${packageId}:${baseName}`) : bareKey; + // [#33127] …and a stored row bound to a package its package's overlay slot. + const rowPackage = !packageId && typeof options?.storedRowPackage === 'string' && options.storedRowPackage !== '' + ? options.storedRowPackage + : undefined; + const storageKey = packageId + ? withDisc(`${packageId}:${baseName}`) + : rowPackage !== undefined ? overlaySlotKey(rowPackage, bareKey) : bareKey; if (collection.has(storageKey)) { this.log(`[Registry] Overwriting ${type}: ${storageKey}`); @@ -8770,7 +8851,9 @@ export class SchemaRegistry { // the TRANSITION (a bare slot that was empty is now taken), not the state, // so the read-side hydration and the write-through, which re-register the // same overlay on later reads and writes, stay silent. - if (!packageId && !collection.has(bareKey)) { + // [#33127] A package overlay slot marks the same transition for its own + // key: the first row of its package to shadow the name. + if (!packageId && !collection.has(storageKey) && (rowPackage === undefined || !collection.has(bareKey))) { let shadowed: any; for (const [key, existing] of collection) { if (key !== bareKey && key.endsWith(`:${bareKey}`) && isCodeArtifactBody(existing)) { @@ -8855,8 +8938,23 @@ export class SchemaRegistry { // group if it exists, else the first composite group in insertion order), // so this does not start deleting a second package's same-named item. const disc = ITEM_KEY_DISCRIMINATORS[type]; + // [#33127] With no bare entry, the package overlay slots the overlay tier of + // {@link getItem} reads first are the item's entries (one package's). + const overlayGroup = (entries: BundleEntry[]): BundleEntry[] => { + const first = this.orderedOverlayTier(type, collection, name, entries)[0]; + const pkg = first === undefined ? undefined : parseOverlaySlotKey(first.key)?.packageId; + return entries.filter(({ key }) => parseOverlaySlotKey(key)?.packageId === pkg); + }; if (disc) { const { bare, local, other } = collectBundle(collection, name, disc); + const overlays = bare.length > 0 ? [] : overlayGroup(overlaySlotEntriesOf(collection, name, disc)); + if (overlays.length > 0) { + for (const { key } of overlays) { + collection.delete(key); + this.log(`[Registry] Unregistered ${type}: ${key}`); + } + return; + } const group = bare.length > 0 ? bare : [...local, ...other]; if (group.length === 0) { console.warn(`[Registry] Attempted to unregister non-existent ${type}: ${name}`); @@ -8876,6 +8974,12 @@ export class SchemaRegistry { this.log(`[Registry] Unregistered ${type}: ${name}`); return; } + const [overlay] = overlayGroup(overlaySlotEntriesOf(collection, name)); + if (overlay !== undefined) { + collection.delete(overlay.key); + this.log(`[Registry] Unregistered ${type}: ${overlay.key}`); + return; + } // Scan composite keys for (const key of collection.keys()) { if (key.endsWith(`:${name}`)) { @@ -9174,9 +9278,11 @@ export class SchemaRegistry { // all still answers its first member, as it always did. A named `member` // answers that member, in the same tier order, or nothing. const disc = ITEM_KEY_DISCRIMINATORS[type]; + // [#33127] The package overlay slots join the overlay tier, after the bare slot. if (disc) { const { bare, local, other } = collectBundle(collection, name, disc, currentPackageId); - const tiers = [...bare, ...local, ...other]; + const overlays = this.orderedOverlayTier(type, collection, name, overlaySlotEntriesOf(collection, name, disc), currentPackageId); + const tiers = [...bare, ...overlays, ...local, ...other]; if (member !== undefined) return (entriesOfMember(tiers, disc, member)[0]?.item as T) ?? undefined; return ((entriesOfMember(tiers, disc, disc.canonical)[0] ?? tiers[0])?.item as T) ?? undefined; } @@ -9190,6 +9296,13 @@ export class SchemaRegistry { // not package) and resolves to the single overlay row. const direct = collection.get(name); if (direct) return direct as T; + // [#33127, ADR-0150 D4] …and with no package-less row, a stored row bound + // to a package (its package overlay slot): the caller's package's first, + // else in the holders' order ({@link orderedOverlayTier}), never in the + // order the rows were registered. One stored row reads as it did in the + // bare slot. + const overlays = overlaySlotEntriesOf(collection, name); + if (overlays.length > 0) return this.orderedOverlayTier(type, collection, name, overlays, currentPackageId)[0].item as T; // Prefer-local: resolve within the caller's package first. if (currentPackageId) { @@ -9271,6 +9384,12 @@ export class SchemaRegistry { if (paired !== NOT_A_PAIR_ROW_OF_A_HOLDER) return paired; const base = customizationBasePackageId(stamped); if (base !== null && composite.has(base)) return base; + // [#33127] …or whose base holds it as its own stored row (its package + // overlay slot): the pair's row customizes that base's item, as beside a + // composite slot, and is never a holder of its own. One bare slot never + // held both rows; the package overlay slots keep each. + if (base !== null && overlaySlotEntriesOf(collection, name, ITEM_KEY_DISCRIMINATORS[type]) + .some(({ key }) => parseOverlaySlotKey(key)?.packageId === base)) return base; return stamped; } @@ -9455,12 +9574,14 @@ export class SchemaRegistry { } const memberOf = (item: unknown) => discriminatorValue(item, disc.field) || disc.canonical; const membersOf = new Map>(); + const codeMembersOf = new Map>(); for (const id of new Set([...composite, ...bound.keys()])) { const { local } = collectBundle(collection, name, disc, id); membersOf.set(id, new Set([...local.map((e) => e.item), ...(bound.get(id) ?? [])].map(memberOf))); + codeMembersOf.set(id, new Set(local.map((e) => memberOf(e.item)))); } const rowMember = memberOf(row); - return owners.filter((id) => membersOf.get(id)!.has(rowMember) || !this.isBundleAddition(id, membersOf)); + return owners.filter((id) => membersOf.get(id)!.has(rowMember) || !this.isBundleAddition(id, membersOf, codeMembersOf)); } /** @@ -9538,8 +9659,12 @@ export class SchemaRegistry { const disc = ITEM_KEY_DISCRIMINATORS[type]; if (!disc || holders.size < 2) return served([...holders]); const membersOf = new Map>(); - for (const id of holders) membersOf.set(id, this.bundleMembersHeldBy(type, collection, name, id, compositeSet, disc)); - return served([...holders].filter((id) => id === callerPackageId || !this.isBundleAddition(id, membersOf))); + const codeMembersOf = new Map>(); + for (const id of holders) { + membersOf.set(id, this.bundleMembersHeldBy(type, collection, name, id, compositeSet, disc)); + codeMembersOf.set(id, new Set(collectBundle(collection, name, disc, id).local.map((e) => discriminatorValue(e.item, disc.field) || disc.canonical))); + } + return served([...holders].filter((id) => id === callerPackageId || !this.isBundleAddition(id, membersOf, codeMembersOf))); } /** @@ -9594,13 +9719,21 @@ export class SchemaRegistry { * dependency closure (the save door's walk), `packageId` is not in that * holder's, and none of `packageId`'s members is one that holder holds. */ - private isBundleAddition(packageId: string, membersOf: ReadonlyMap>): boolean { + private isBundleAddition(packageId: string, membersOf: ReadonlyMap>, + codeMembersOf?: ReadonlyMap>): boolean { const own = membersOf.get(packageId)!; const reach = new Set(packageDependencyClosure(packageId, this)?.dependencies ?? []); + // [#33127] With `codeMembersOf`, a member both packages hold only as + // stored rows is no clash: the registry used to keep ONE row per member, + // so one of the two was never counted and the base held the name, in + // either row order. The package overlay slots keep both rows; this keeps + // that judgment. A member either package ships in code still clashes. + const clashes = (base: string, m: string): boolean => codeMembersOf === undefined + || codeMembersOf.get(packageId)?.has(m) === true || codeMembersOf.get(base)?.has(m) === true; for (const [base, baseMembers] of membersOf) { if (base === packageId || !reach.has(base)) continue; if (packageDependencyClosure(base, this)?.dependencies.includes(packageId)) continue; - if ([...own].some((m) => baseMembers.has(m))) continue; + if ([...own].some((m) => baseMembers.has(m) && clashes(base, m))) continue; return true; } return false; @@ -9630,9 +9763,10 @@ export class SchemaRegistry { const collection = this.metadata.get(type); if (!collection) return undefined; const holders = new Set(this.compositeHoldersOf(collection, name)); - const bound = this.bareSlotEntriesOf(type, collection, name) + // [#33127] Every stored row bound to it, in the order its stored-row read serves them ({@link rankedForPackage}). + const bound = this.rankedForPackage(this.bareSlotEntriesOf(type, collection, name) .filter(({ item }) => this.overlaySlotBinding(type, item, name, collection, holders) === packageId - && !pairRowDeclaresAnotherHolder(item, packageId, holders)); + && !pairRowDeclaresAnotherHolder(item, packageId, holders)), packageId); const disc = ITEM_KEY_DISCRIMINATORS[type]; if (disc) { const { local } = collectBundle(collection, name, disc, packageId); @@ -9767,11 +9901,98 @@ export class SchemaRegistry { if (resolution.status === 'refused') throw new PackageScopedNameRefusedError(resolution); } - /** The bare-slot entries of `(type, name)`: one, or a bundle's members, canonical first. */ + /** + * The bare-slot entries of `(type, name)`: one, or a bundle's members, canonical first. + * [#33127, ADR-0150 D4] …then its package overlay slots ({@link overlaySlotKey}): every + * stored row of the name, each bound to its package, read as the bare slot's entry is. + */ private bareSlotEntriesOf(type: string, collection: Map, name: string): BundleEntry[] { const disc = ITEM_KEY_DISCRIMINATORS[type]; - if (disc) return collectBundle(collection, name, disc).bare; - return collection.has(name) ? [{ key: name, item: collection.get(name) }] : []; + const bare = disc + ? collectBundle(collection, name, disc).bare + : collection.has(name) ? [{ key: name, item: collection.get(name) }] : []; + return [...bare, ...overlaySlotEntriesOf(collection, name, disc)]; + } + + /** + * [#33127, ADR-0150 D4] `entries`, the stored rows that bind to `packageId` + * ({@link overlaySlotBinding}), in the order the stored-row read serves them + * for that package (`servedOverlayRowCandidates`, metadata-protocol): the + * declared override of its customization pair (a row of another package + * whose `overrides.package` names it), then its own row, then the + * package-less row, then any other row bound to it (a pair's undeclared + * row). Ties keep the store's order. So the item the registry answers for a + * package does not follow the order its rows were registered in. + */ + private rankedForPackage(entries: readonly BundleEntry[], packageId: string): BundleEntry[] { + const rank = (entry: BundleEntry): number => { + const rowPackage = storedRowPackageOf(entry); + if (rowPackage === packageId) return 1; + if (rowPackage === undefined) return 2; + return declaredOverrideBase(entry.item) === packageId ? 0 : 3; + }; + return entries.map((entry, index) => ({ entry, index, rank: rank(entry) })) + .sort((a, b) => a.rank - b.rank || a.index - b.index) + .map(({ entry }) => entry); + } + + /** + * [#33127, ADR-0150 D4] Retire the package overlay slots of `(type, name)` + * whose package `select` picks ({@link registerItem}'s `storedRowPackage`): + * one bundle member's (`member`, its discriminator value) or, with none + * named, every member's. The heal of a removed stored row + * (`restoreArtifactRegistryView`, metadata-protocol) retires the removed + * row's own slot, and only it: another package's row and the package-less + * row keep their entries. A slot holds a stored row by construction, never + * a packaged artifact. Touches no bare and no composite slot. + * + * @returns the packages whose slot was retired. + */ + removePackageOverlaySlots(type: string, name: string, member: string | undefined, select: (packageId: string) => boolean): string[] { + const collection = this.metadata.get(type); + if (!collection) return []; + const disc = ITEM_KEY_DISCRIMINATORS[type]; + const slots = overlaySlotEntriesOf(collection, name, disc); + const removed = new Set(); + for (const { key } of disc && member !== undefined ? entriesOfMember(slots, disc, member) : slots) { + const packageId = parseOverlaySlotKey(key)!.packageId; + if (!select(packageId)) continue; + this.noteItem(type, key); + collection.delete(key); + removed.add(packageId); + this.log(`[Registry] Removed package overlay slot ${type}: ${name} of ${packageId} (its stored row is gone)`); + } + if (removed.size > 0 && (type === 'picklist' || type === 'action')) this.invalidateAll(); + return [...removed]; + } + + /** + * [#33127] The overlay tier of a read naming no package ({@link getItem}), + * when the bare slot is empty and package overlay slots hold rows of the + * name: the rows of `preferred` first ({@link rankedForPackage}), then each + * other package's, holder by holder in the item store's order (the code + * holders, as the composite fallback reads them), then by package id. Never + * the order the rows were registered in. + */ + private orderedOverlayTier(type: string, collection: Map, name: string, entries: readonly BundleEntry[], + preferred?: string): BundleEntry[] { + if (entries.length <= 1) return [...entries]; + const composite = new Set(this.compositeHoldersOf(collection, name)); + const byHolder = new Map(); + for (const entry of entries) { + const bound = this.overlaySlotBinding(type, entry.item, name, collection, composite); + const holder = typeof bound === 'string' ? bound : `${OVERLAY_SLOT_MARK}${storedRowPackageOf(entry) ?? ''}`; + byHolder.set(holder, [...(byHolder.get(holder) ?? []), entry]); + } + const order = [...composite]; + const holders = [...byHolder.keys()].sort((a, b) => { + if (a === preferred || b === preferred) return a === preferred ? -1 : 1; + const ia = order.indexOf(a); + const ib = order.indexOf(b); + if (ia !== ib) return ia === -1 ? 1 : ib === -1 ? -1 : ia - ib; + return a < b ? -1 : a > b ? 1 : 0; + }); + return holders.flatMap((holder) => this.rankedForPackage(byHolder.get(holder)!, holder)); } /** diff --git a/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts b/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts index 310e63aae50..1b2295743d0 100644 --- a/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts +++ b/packages/objectql/src/webhook-stored-row-boot-hydration.test.ts @@ -341,3 +341,142 @@ describe('a stored row of a two-holder name at boot, beyond the webhook (#32692) expect((registry.getPackageScopedItem('tool', N, A) as { label?: string } | undefined)?.label).toBe('row:alpha-custom'); }); }); + +/** + * [#33127] Two holders of a name, each with its own stored row. Before this + * change the registry kept ONE bare slot per name for a stored row, so the row + * hydrated last took it: the other holder's slot and exact read answered its + * shipped item, which holder by row order. Each row bound to a + * holder now lives in that holder's own overlay slot, beside the holder's + * code artifact, so every order answers the same. The read naming no package + * still refuses 409 naming both holders (#32607). Every registration order, + * every row order. + */ +describe('[#33127] two holders, each with its own stored row: each row is its own holder\'s, in every order', () => { + const N = 'shared_thing'; + const TYPES = ['tool', 'webhook', 'agent', 'skill'] as const; + const nsOf = (id: string) => id.split('.').pop()!; + const body = (type: string, label: string) => type === 'webhook' + ? { name: N, label, object: 'showcase_task', triggers: ['create'], url: `https://hooks.example/${label}` } + : { name: N, label, description: label }; + let warn: ReturnType; + beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); }); + afterEach(() => { warn.mockRestore(); }); + + /** Boot `type` with `order` each shipping the name, then a stored row of each of `rowOwners`, in that order. */ + async function boot(type: string, order: readonly string[], rowOwners: readonly string[]) { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const id of order) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: nsOf(id) } as never, 'code'); + registry.registerItem(type, body(type, `shipped-${nsOf(id)}`), 'name' as never, id); + } + const stored = rowOwners.map((id, i) => ({ + id: `row_${i}`, type, name: N, organization_id: null, package_id: id, state: 'active', metadata: JSON.stringify(body(type, `row-${nsOf(id)}`)), + })); + const engine: any = { + async find(table: string, opts?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + const where = opts?.where ?? {}; + const found = stored.filter((r) => Object.entries(where).every(([k, v]) => v === undefined || typeof v === 'object' || (r as any)[k] === v)); + return typeof opts?.limit === 'number' ? found.slice(0, opts.limit) : found; + }, + async findOne(object: string, query?: EngineFindOneQueryInput) { + assertEngineFindOnePredicate(object, query); + return null; + }, + registry, + }; + const protocol = new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_prod'); + const load = await protocol.loadMetaFromDb(); + const slot = (id: string) => (registry.getPackageScopedItem(type, N, id) as { label?: string } | undefined)?.label; + const read = async (packageId?: string) => { + try { + return ((await protocol.getMetaItem({ type, name: N, ...(packageId ? { packageId } : {}) } as never)) as { item?: { label?: string } })?.item?.label; + } catch (e) { + const err = e as { code?: string; status?: number; refusal?: { candidates?: Array<{ packageId?: string }> } }; + return { code: err.code, status: err.status, candidates: (err.refusal?.candidates ?? []).map((c) => c.packageId).sort() }; + } + }; + return { load, registry, slot, read }; + } + + for (const type of TYPES) { + for (const order of [[A, B], [B, A]] as const) { + for (const rowOwners of [[A, B], [B, A]] as const) { + it(`${type} (${nsOf(order[0])} registered first, ${nsOf(rowOwners[0])}'s row stored first): each holder's slot and exact read is its own row; the read naming no package refuses 409 naming both`, async () => { + // FROM (measured on main): the row hydrated last took the + // name's one bare slot, so only its holder answered its + // row; the other holder's slot and exact read answered + // its shipped item, which holder by row order. + const { load, slot, read } = await boot(type, order, rowOwners); + expect(load).toMatchObject({ loaded: 2, errors: 0 }); + expect([slot(A), slot(B)], 'the registry slots').toEqual(['row-alpha', 'row-beta']); + expect([await read(A), await read(B)], 'the exact reads').toEqual(['row-alpha', 'row-beta']); + expect(await read(), 'the read naming no package').toEqual({ code: 'RESOURCE_CONFLICT', status: 409, candidates: [A, B] }); + }); + } + it(`CONTROL — ${type} (${nsOf(order[0])} registered first): one holder's row leaves the other holder its shipped item, as before`, async () => { + const { slot, read } = await boot(type, order, [B]); + expect([slot(A), slot(B)]).toEqual(['shipped-alpha', 'row-beta']); + expect([await read(A), await read(B)]).toEqual(['shipped-alpha', 'row-beta']); + }); + } + it(`CONTROL — ${type}, one holder: its own row is its slot, its exact read and its read naming no package, as before`, async () => { + const { slot, read } = await boot(type, [A], [A]); + expect([slot(A), await read(A), await read()]).toEqual(['row-alpha', 'row-alpha', 'row-alpha']); + }); + } +}); + +/** + * [#32900] A module's locale member at boot: X ships `welcome` in en-US and + * depends on the App; the App's pair stores X's de-DE override (declaring X), + * and a package-less de-DE row of the same name is stored too. X's de-DE slot + * followed the row order (the package-less row took the one bare slot when it + * hydrated last). It now answers X's own pair row in both orders. + */ +describe('[#32900] a module\'s locale member beside a package-less row of the same locale at boot', () => { + const APP = 'com.acme.suite'; + const X = 'com.acme.suitex'; + const PAIR = `${APP}.custom`; + const tpl = (label: string, locale: string, extra: object = {}) => ({ name: 'welcome', label, subject: label, bodyHtml: label, locale, ...extra }); + let warn: ReturnType; + beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); }); + afterEach(() => { warn.mockRestore(); }); + + async function boot(rowOrder: ReadonlyArray<'pair' | 'env'>) { + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + registry.installPackage({ id: APP, name: APP, version: '1.0.0', type: 'app', namespace: 'suite' } as never, 'code'); + registry.installPackage({ id: PAIR, name: PAIR, version: '1.0.0', type: 'app', namespace: 'suite_custom' } as never, 'code'); + registry.installPackage({ id: X, name: X, version: '1.0.0', type: 'module', namespace: 'suitex', dependencies: { [APP]: '^1.0.0' } } as never, 'code'); + registry.registerItem('email_template', tpl('suitex', 'en-US'), 'name' as never, X); + const rows: Record[] = rowOrder.map((k, i) => k === 'pair' + ? { id: `r${i}`, type: 'email_template', name: 'welcome', bundle_member: 'de-DE', organization_id: null, package_id: PAIR, state: 'active', metadata: JSON.stringify(tpl('pair', 'de-DE', { overrides: { package: X } })) } + : { id: `r${i}`, type: 'email_template', name: 'welcome', bundle_member: 'de-DE', organization_id: null, package_id: null, state: 'active', metadata: JSON.stringify(tpl('env', 'de-DE')) }); + const engine: any = { + async find(table: string, opts?: { where?: Record }) { + if (table !== 'sys_metadata') return []; + return rows.filter((r) => Object.entries(opts?.where ?? {}).every(([k, v]) => v === undefined || typeof v === 'object' || (r[k] ?? null) === v)); + }, + async findOne(object: string, query?: EngineFindOneQueryInput) { + assertEngineFindOnePredicate(object, query); + return null; + }, + registry, + }; + await new ObjectStackProtocolImplementation(engine, () => new Map(), 'env_prod').loadMetaFromDb(); + return (registry.getPackageScopedItem('email_template', 'welcome', X, 'de-DE') as { label?: string } | undefined)?.label ?? null; + } + + for (const rowOrder of [['pair', 'env'], ['env', 'pair']] as const) { + it(`${rowOrder[0]} row stored first: X's de-DE slot is its own pair row`, async () => { + // FROM: the row hydrated last ('env' in the first order) answered X's slot. + expect(await boot(rowOrder)).toBe('pair'); + }); + } + it('CONTROL — the pair row alone and the package-less row alone keep their readings', async () => { + expect([await boot(['pair']), await boot(['env'])]).toEqual(['pair', 'env']); + }); +}); 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 0663e767e43..e74e76fc6cb 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 @@ -526,12 +526,13 @@ describe('[#32607 M1, M2] the no-disabled arm judges holders at the rows\' grain 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. + // Each save order answers the same before and after a reboot. + // [#32662 scope note (b)] …and the same row in both save orders: the + // base's own row, on the plain read, `/published` and the execution + // face. FROM (`main` d4fbb4dbb6): the plain read served the row saved + // first, so with the pair's saved first it served the pair's row. expect([answers[0] === answers[1], answers[2] === answers[3]], answers.join(' | ')).toEqual([true, true]); + expect(answers, answers.join(' | ')).toEqual(Array(4).fill(JSON.stringify(['base row', 'base row', 'base row']))); }, 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`. @@ -573,3 +574,125 @@ describe('[#32607 M1, M2] the no-disabled arm judges holders at the rows\' grain } }, 240_000); }); + +// --------------------------------------------------------------------------- +// [#33127, #32662, ADR-0150 D3/D4] Each exact address serves its own stored +// row, in every save order, before and after a reboot. The registry kept ONE +// bare slot per name for a stored row bound to a package, so the row hydrated +// last took it. Measured on `main` d4fbb4dbb6 through these doors: +// - #33127, both packages ship a `tool` and each stores its own row: after a +// reboot `?package=` answered its own row only for the holder whose row +// hydrated last; the other answered its shipped item. +// - #32662, two packages hold a name only as stored rows: `?package=.custom` +// (each one's customization pair address) answered 404 for both before a +// reboot; after it, 200 for the row hydrated last and 409 naming one side +// for the other. +// - #32662 scope note (b), a package's row beside its own pair's undeclared +// row: the plain read served the pair's row when it was saved first, while +// `/published` served the package's own row. +// Throughout, the read naming no package of a two-holder name refuses 409 +// naming both (#32607): unchanged. +// --------------------------------------------------------------------------- +describe('[#33127, #32662] each exact address serves its own stored row, before and after a reboot', () => { + const roots: string[] = []; + afterAll(() => { for (const dir of roots) rmSync(dir, { recursive: true, force: true }); }); + const freshFile = () => { + const dir = mkdtempSync(join(tmpdir(), 'os-meta-own-slot-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 short = (id: string) => id.split('.').pop()!; + const P = 'com.qa.ownslotalpha'; + const Q = 'com.qa.ownslotbeta'; + const bodyOf = (type: string, label: string): Record => + type === 'tool' ? { label, description: label, parameters: { type: 'object', properties: {} } } : { label, widgets: [] }; + const manifestOf = (id: string, ships: readonly string[] = []) => ({ + id, name: short(id), namespace: short(id), version: '1.0.0', type: 'app', objects: [], + ...(ships.includes('tool') ? { tools: [{ name: 'shared_tool', ...bodyOf('tool', `shipped-${short(id)}`) }] } : {}), + }); + /** `200