diff --git a/.changeset/33593-extension-follow-judged-as-served.md b/.changeset/33593-extension-follow-judged-as-served.md new file mode 100644 index 00000000000..1bf4cf58cd6 --- /dev/null +++ b/.changeset/33593-extension-follow-judged-as-served.md @@ -0,0 +1,28 @@ +--- +'@objectstack/objectql': minor +'@objectstack/metadata-protocol': minor +'@objectstack/spec': minor +--- + +feat(objectql)!: a record-mode amount an object extension adds is judged against its object as served, so a bad follow pair is refused at the run that completes it + +Clause-②: yes (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for an `objectExtensions` entry (or a stored `object_extension` item) that adds a record-mode amount (`currencyConfig.currencyMode: 'record'`, `currencyField: 'MASTER_DETAIL.CODE'`) whose parent field holds no ISO 4217 code, does not exist, or is reached through the extension's own new master_detail. The record-currency follow door (ADR-0144 D2 and D6, amended) asked an `extend` layer about its own roll-ups only and returned before the following-amount half, so such an amount was admitted and served; every write of it was then refused `ERR_CURRENCY_CODE_REQUIRED`, and the next no-change upgrade of the parent's owner was refused over the extension's field. Every object layer is now judged as its object served with the layer in its slot: the base, every enabled extension, and the incoming body. It is also BREAKING for a roll-up author: a published single save of an `object_extension` item that adds a `sum` / `avg` / `min` / `max` roll-up D6 refuses, or adds a record-mode amount a registered parent's such roll-up reads, is now refused 422 where it was stored (the last line below). + +The fix: name in the second segment of `currencyField` a field of the master_detail target that declares `valueDomain: 'iso_4217_currency'` (the refusal lists the candidates), or install the package that supplies that field before the extension, or in the same artifact. For a roll-up D6 refuses: roll up through the master_detail the amount follows (`summaryOperations.relationshipField`, on the parent it follows), use `function: 'count'`, or roll up a stored home-currency amount field of the child instead; the refusal says which applies. + +What moves (each line FROM → TO). The first four lines hold at the end of an install / upgrade / reload run, in the batch writer, and on a published single save of an `object_extension` item; the others name their askers: + +- an extension-only package adding an amount that follows a parent field holding no code, a missing field, or a field reached through its own new master_detail: FROM admitted (served) TO refused 422 `INVALID_METADATA`, naming the child object and the amount; nothing of the install stays. +- the other registration order, the extension registered first (no verdict while nothing owns the extended object) and the owner after it: the owner's install FROM admitted TO refused 422 over the extension's amount. +- an extension following a code field another extension supplies: refused when that supplier is not installed or is disabled; admitted when it is installed and enabled, or arrives in the same artifact. +- a parent upgrade that removes or de-codes a field an extension's amount follows: still refused 422; the sentence now names the extension's package and field. +- at the end of a run ONLY (an install, upgrade or reload): a no-change upgrade of the parent's owner, the child's owner or the extension's package over a pair a cold boot admitted, or an upgrade that only adds an unrelated code field to the parent: FROM refused 422 TO installed. A run is not refused over a pair it leaves as it found it (the pair is compared, not the refusal sentence: for a following amount, the object and field declaring it, the pointer, and the object the pointer's master_detail reaches; for a roll-up, the object and field declaring it and the child object and field it reads). An upgrade of the child's owner that re-points the master_detail onto another parent lacking the code makes a new pair and is still refused 422, as before. The same re-point upgrade of an extension package (its own master_detail, pointer string unchanged) moves FROM installed (`main` never asked an extension layer's following half) TO refused 422. +- on a published single save of an `object_extension` item and in the batch writer (a package publish, a duplicate, an import), which judge a layer against its slot left empty: re-publishing an UNCHANGED extension whose amount a cold boot admitted over a bad parent field: FROM saved (single save answered 200, the batch writer saved the row in its own result; the extension's following half was never asked) TO refused 422. An own object body re-published unchanged over such a pair was already refused there, and still is. +- a published single save of an `object_extension` item on a `/meta` face now also meets D6's roll-up door (`recordCurrencySummaryRefusal`), as the batch writer's extension row already did, in both directions: an extension adding a `sum` / `avg` / `min` / `max` roll-up of a child amount, or adding an amount a registered parent's such roll-up reads, where that child amount is declared `currencyMode: 'record'` (in each row's own currency, or following a parent's code but not read on that parent through the master_detail it follows): FROM stored and answered 200 (its registration then failed with a `console.warn` only) TO refused 422 `INVALID_METADATA`, nothing stored. + +Unchanged: the same amount in an own object body is refused 422, and so is a package that owns the parent and extends the child in one install; an extension of an object no package owns is no verdict; the cold boot is not asked. No stored-row migration or heal ships with this change. diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 84b15d11517..fac4bc4ea0e 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -85,6 +85,7 @@ import type { MutationProjectionOutcome } from './protocol-mutation-events.js'; import type { ProtocolHost } from './protocol-host.js'; import type { ObjectStackProtocolImplementation } from './protocol.js'; import { saveRegistryQuestion } from './registry-question.js'; +import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js'; import { BatchRowHealError, canJudgeBatchObjects, isBatchObjectType, readActiveBatchRow, settleBatchObjectRows, undoBatchRowWrite, undoOutcomeForLog, type WrittenBatchRow } from './batch-object-registration.js'; export class ProtocolSaveFacet { @@ -1253,6 +1254,23 @@ export class ProtocolSaveFacet { await host.saveWriteBinding(singularType, request, mode), ); if (extensionRefusal) throw extensionRefusal; + // [ADR-0144 D2 and D6, amended; #33593 ruling R1] …and, published + // on a face that makes the one body live at once, the follow door + // the same face asks of an `object` body: the extension judged as + // its object will be served, with this body in its package's + // slot. The registry answers no verdict for an object nothing + // serves yet, and none before the cold boot sealed it. + const registry = host.engine?.registry as { objectRegistrationRefusal?: (schema: unknown, packageId: string | undefined, ownership: string, options: { againstRegistry?: boolean }) => Error | null } | undefined; + if (singularType === OBJECT_EXTENSION_TYPE + && saveRegistryQuestion({ mode, writeFace: request.writeFace }) === 'against-registry' + && typeof registry?.objectRegistrationRefusal === 'function') { + const binding = await host.saveWriteBinding(singularType, request, mode); + if (binding) { + const { extend, priority: _priority, ...contribution } = registrableObjectExtension(request.item); + const followRefusal = registry.objectRegistrationRefusal({ ...contribution, name: extend }, binding, 'extend', { againstRegistry: true }); + if (followRefusal) throw followRefusal; + } + } } // [harden] …and a permission set whose NAME another owner already // holds, with `NAMESPACE_CONFLICT` / 422: a set's name is its diff --git a/packages/metadata-protocol/src/registry-question.ts b/packages/metadata-protocol/src/registry-question.ts index e85e7f1bd8b..c750414bb22 100644 --- a/packages/metadata-protocol/src/registry-question.ts +++ b/packages/metadata-protocol/src/registry-question.ts @@ -12,7 +12,11 @@ * makes one body live and relays the refusal to its author asks it; on a * sealed registry it then also asks the record-currency doors that read other * objects (D6's roll-up half, and the follow door), so a refused body is - * answered `422 INVALID_METADATA` and nothing is stored or promoted. + * answered `422 INVALID_METADATA` and nothing is stored or promoted. An + * `object_extension` item published on the same faces asks both + * record-currency doors too — D6's roll-up half (the roll-ups it adds, and a + * registered parent's roll-up over an amount it adds), and the follow door + * of the extension judged as its object will be served. * * The follow door is not that save's alone. `registerObject` never asks it — * a unit registers in an order a later member can still complete — so each @@ -27,8 +31,11 @@ * outermost run (`SchemaRegistry.restoringOnRefusal`). It calls neither * callee below, so it is no producer in * {@link REGISTRY_QUESTION_PRODUCERS}. - * An `extend` layer is asked only of its own roll-ups (the door's `partial` - * rule), by whichever asker registers it. + * An `extend` layer is judged like any other layer, by whichever asker + * registers it: as its object will be served, with every enabled extension + * and the layer in its slot, in both directions — the amounts and roll-ups + * the layer adds against their other ends, and the registered amounts and + * roll-ups whose other end is that object. * * Every other producer (a draft save, the batch writers, a package publish) * keeps the body-only question per row. A batch that makes object rows live diff --git a/packages/objectql/src/manifest-service-artifact-refusal-restores.test.ts b/packages/objectql/src/manifest-service-artifact-refusal-restores.test.ts index 6103c1c65c5..d7eba44427b 100644 --- a/packages/objectql/src/manifest-service-artifact-refusal-restores.test.ts +++ b/packages/objectql/src/manifest-service-artifact-refusal-restores.test.ts @@ -554,30 +554,22 @@ describe('a running install is asked the record-currency follow door once, at th expect(fieldOf(ql, 'suite_invoice', 'currency_code')?.valueDomain).toBe('iso_4217_currency'); }); - it('a package that holds only the parent is refused over a child another package holds, though its upgrade changes nothing in the pair', async () => { + it('[#33593 R7] a package that holds only the parent installs an upgrade that changes nothing in the pair, though a child another package holds follows a code it lacks', async () => { // The other package's child got in at a cold boot, which is not asked: it // follows `currency_code`, and the ledger's parent holds no such field. const { ql, manifest } = await bootWith([ledger(), billing([line('invoice.currency_code')])]); expect(followedBy(ql)).toBe('invoice.currency_code'); - // The ledger's next version re-registers the same parent. - const err = await refusal(() => manifest.register({ ...ledger(), version: '2.0.0' })); - - expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'amount' }); - expect(String(err?.message)).toContain("'suite_invoice' does not hold the code a registered amount follows"); - expect(String(err?.message)).toContain("'suite_invoice' declares no field 'currency_code'"); - expect(ql.registry.getPackage(LEDGER)?.manifest?.version).toBe('1.0.0'); - expect(ql.registry.getObjectOwner('suite_line')?.packageId).toBe(BILLING); - - // The correction is the child's holder's: once its amount follows nothing - // the parent lacks, the ledger's upgrade installs unchanged. - await manifest.register(billing([line()], '1.1.0')); + // The ledger's next version re-registers the same parent: the pair is as + // the upgrade found it, so the upgrade is not what breaks it. await manifest.register({ ...ledger(), version: '2.0.0' }); expect(ql.registry.getPackage(LEDGER)?.manifest?.version).toBe('2.0.0'); + expect(ql.registry.getObjectOwner('suite_line')?.packageId).toBe(BILLING); + expect(followedBy(ql)).toBe('invoice.currency_code'); }); - it('…and a package that holds only the child is refused over a `record` roll-up another package holds', async () => { + it('[#33593 R7] …and a package that holds only the child installs an unchanged child under a `record` roll-up another package holds', async () => { // At the cold boot the ledger's parent totals, in its own currency, an // amount of the other package's child that follows no record's currency. const { ql, manifest } = await bootWith([ @@ -587,16 +579,43 @@ describe('a running install is asked the record-currency follow door once, at th expect(fieldOf(ql, 'suite_invoice', 'subtotal')?.currencyConfig?.currencyMode).toBe('record'); // The child's package re-registers the same child. + await manifest.register(billing([line()], '1.1.0')); + + expect(ql.registry.getPackage(BILLING)?.manifest?.version).toBe('1.1.0'); + }); + + it('[#33593 R6] CONTROL: the child\'s upgrade that CHANGES the pair is still refused under that roll-up', async () => { + const { ql, manifest } = await bootWith([ + billing([line('invoice.currency_code')]), + { ...ledger(), objects: [invoice('currency_code', SUBTOTAL)] }, + ]); + + // 1.1.0 makes the amount follow nothing: the roll-up over it is now the upgrade's to answer for. const err = await refusal(() => manifest.register(billing([line()], '1.1.0'))); expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_invoice', fieldName: 'subtotal' }); expect(ql.registry.getPackage(BILLING)?.manifest?.version).toBe('1.0.0'); + expect(followedBy(ql)).toBe('invoice.currency_code'); + }); - // Here the refused package can supply what the other end names: an amount that follows the parent. - await manifest.register(billing([line('invoice.currency_code')], '1.1.0')); + it('[#33593 R6] CONTROL: the child\'s upgrade that re-points the pair onto ANOTHER parent lacking the code is refused, though the pointer reads the same', async () => { + // The cold boot admits the amount following `invoice.title` of + // `suite_invoice`, which holds no code; `suite_other` holds none either. + const { ql, manifest } = await bootWith([ + { ...ledger(), objects: [invoice(), object('suite_other')] }, + billing([line('invoice.title')]), + ]); - expect(ql.registry.getPackage(BILLING)?.manifest?.version).toBe('1.1.0'); - expect(followedBy(ql)).toBe('invoice.currency_code'); + // 1.1.0 changes only the master_detail's reference: the pointer is the + // same string, but the pair it makes is new, so the upgrade answers for it. + const repointed = line('invoice.title'); + (repointed.fields as Record).invoice = { type: 'master_detail', label: 'Invoice', reference: 'suite_other' }; + const err = await refusal(() => manifest.register(billing([repointed], '1.1.0'))); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'amount' }); + expect(String(err?.message)).toContain("'suite_other.title'"); + expect(ql.registry.getPackage(BILLING)?.manifest?.version).toBe('1.0.0'); + expect(fieldOf(ql, 'suite_line', 'invoice')?.reference).toBe('suite_invoice'); }); /** What the refusal adds when only the environment's own object of the name, served over the package's, earns it. */ @@ -727,3 +746,254 @@ describe('a reload is one registration run, asked the follow door once at its en expect(warn.mock.calls.filter((c) => c[0] === RELOAD_REFUSED)).toHaveLength(1); }); }); + +// ── [#33593 ruling A, amended] An `extend` layer's following amount, judged as the object is served ── +// +// Every object layer is judged as the served fold of its object — the base, +// every enabled extension and the incoming body — never as the bare body +// (R1). So an amount an extension-only package adds is refused at the run +// that adds it, as the same amount in an own body is; the owner registering +// under an extension that arrived first judges the extension's amounts with +// its own (R3); a parent upgrade that breaks an extension's amount is refused +// naming the extension's package (R6); and a run that leaves a pair as it +// found it is never refused over it (R7). + +const EXTENDER = 'com.probe.extender'; +const SUPPLIER = 'com.probe.supplier'; +/** A record-mode amount following `pointer`. */ +const follows = (pointer: string) => ({ type: 'currency', label: 'Extra', currencyConfig: { currencyMode: 'record', currencyField: pointer } }); +/** A package that only extends `suite_line` with `fields`. */ +const extender = (fields: Record, version = '1.0.0') => ({ + id: EXTENDER, name: 'extender', namespace: 'extender', version, type: 'module', + objectExtensions: [{ extend: 'suite_line', fields }], +}); +/** A package that only extends `suite_invoice` with an ISO 4217 code field. */ +const supplier = (version = '1.0.0') => ({ + id: SUPPLIER, name: 'supplier', namespace: 'supplier', version, type: 'module', + objectExtensions: [{ extend: 'suite_invoice', fields: { currency_code: CODE } }], +}); +const extraOf = (ql: ObjectQL) => fieldOf(ql, 'suite_line', 'ext_amount'); + +describe('[#33593] an extension\'s record-mode amount is judged against its object as served, at the end of the run', () => { + const BAD_EXTENSIONS: Array<{ label: string; fields: Record; says: string }> = [ + { label: 'a parent field holding no ISO 4217 code (R1)', fields: { ext_amount: follows('invoice.title') }, says: "'suite_invoice.title'" }, + { label: 'a parent field that does not exist (R1, R4)', fields: { ext_amount: follows('invoice.no_such_field') }, says: "declares no field 'no_such_field'" }, + { + label: 'a field reached through the extension\'s own new master_detail (R1)', + fields: { + inv2: { type: 'master_detail', label: 'Invoice 2', reference: 'suite_invoice' }, + ext_amount: follows('inv2.title'), + }, + says: "'suite_invoice.title'", + }, + ]; + for (const c of BAD_EXTENSIONS) { + it(`an extension-only install following ${c.label} is refused 422, and leaves nothing`, async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger('currency_code')); + await manifest.register(billing([line('invoice.currency_code')])); + + const err = await refusal(() => manifest.register(extender(c.fields), { source: 'marketplace' })); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(String(err?.message)).toContain(c.says); + expect(extraOf(ql)).toBeUndefined(); + expect(ql.registry.getPackage(EXTENDER)).toBeUndefined(); + }); + } + + it('CONTROL: the extension following the parent\'s code installs, and the served child carries it', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger('currency_code')); + await manifest.register(billing([line('invoice.currency_code')])); + + await manifest.register(extender({ ext_amount: follows('invoice.currency_code') }), { source: 'marketplace' }); + + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.currency_code'); + }); + + it('CONTROL: the same amount in an own body is refused the same way', async () => { + const { manifest } = await boot(); + await manifest.register(ledger('currency_code')); + + const err = await refusal(() => manifest.register(billing([ + object('suite_line', { fields: { + invoice: { type: 'master_detail', label: 'Invoice', reference: 'suite_invoice' }, + ext_amount: follows('invoice.title'), + } }), + ]))); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + }); + + it('CONTROL: a package that owns the parent and extends the child in one install is refused the same way', async () => { + const { ql, manifest } = await boot(); + await manifest.register(billing([line()])); + + const err = await refusal(() => manifest.register({ + ...ledger('currency_code'), + objectExtensions: [{ extend: 'suite_line', fields: { ext_amount: follows('invoice.title') } }], + })); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(ql.registry.getPackage(LEDGER)).toBeUndefined(); + }); + + it('R3: an extension that arrives before its object\'s owner is no verdict (R2), and the owner\'s install that completes the bad pair is refused', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger('currency_code')); + // `suite_line` is not registered yet: nothing serves it, so nothing is judged. + await manifest.register(extender({ ext_amount: follows('invoice.title') }), { source: 'marketplace' }); + expect(ql.registry.getPackage(EXTENDER)).toBeDefined(); + + const err = await refusal(() => manifest.register(billing([line('invoice.currency_code')]))); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(ql.registry.getPackage(BILLING)).toBeUndefined(); + expect(ql.registry.getObject('suite_line')).toBeUndefined(); + }); + + it('R3 CONTROL: …and the owner installs over an extension arrived first that follows the code', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger('currency_code')); + await manifest.register(extender({ ext_amount: follows('invoice.currency_code') }), { source: 'marketplace' }); + + await manifest.register(billing([line('invoice.currency_code')])); + + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.currency_code'); + }); + + it('R4: an extension that arrives before the parent\'s code field exists is refused; once the parent holds it, the same extension installs', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger()); + await manifest.register(billing([line()])); + + const err = await refusal(() => manifest.register(extender({ ext_amount: follows('invoice.currency_code') }))); + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(String(err?.message)).toContain("declares no field 'currency_code'"); + + await manifest.register({ ...ledger('currency_code'), version: '1.1.0' }); + await manifest.register(extender({ ext_amount: follows('invoice.currency_code') })); + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.currency_code'); + }); + + it('R5: a code field another extension supplies is read from the served parent: missing, the amount is refused; installed, it installs', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger()); + await manifest.register(billing([line()])); + + const err = await refusal(() => manifest.register(extender({ ext_amount: follows('invoice.currency_code') }))); + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + + await manifest.register(supplier()); + await manifest.register(extender({ ext_amount: follows('invoice.currency_code') })); + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.currency_code'); + }); + + it('R5: …a disabled supplier is no supplier: the amount is refused', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger()); + await manifest.register(billing([line()])); + await manifest.register(supplier()); + ql.registry.disablePackage(SUPPLIER); + expect(fieldOf(ql, 'suite_invoice', 'currency_code')).toBeUndefined(); + + const err = await refusal(() => manifest.register(extender({ ext_amount: follows('invoice.currency_code') }))); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + }); + + it('R5: …and the supplier and the amount in ONE artifact pass at the run end', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger()); + await manifest.register(billing([line()])); + + await manifest.register(artifact([ + core('1.0.0', { objectExtensions: [{ extend: 'suite_line', fields: { ext_amount: follows('invoice.currency_code') } }] }), + addon('1.0.0', { objectExtensions: [{ extend: 'suite_invoice', fields: { currency_code: CODE } }] }), + ])); + + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.currency_code'); + expect(fieldOf(ql, 'suite_invoice', 'currency_code')?.valueDomain).toBe('iso_4217_currency'); + }); + + it('R6: a parent upgrade that removes the code field an extension\'s amount follows is refused, naming the extension\'s package and field', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger('currency_code')); + await manifest.register(billing([line()])); + await manifest.register(extender({ ext_amount: follows('invoice.currency_code') })); + + const err = await refusal(() => manifest.register({ ...ledger(), version: '2.0.0' })); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(String(err?.message)).toContain(`'suite_line.ext_amount', which package '${EXTENDER}' adds to 'suite_line'`); + expect(ql.registry.getPackage(LEDGER)?.manifest?.version).toBe('1.0.0'); + expect(fieldOf(ql, 'suite_invoice', 'currency_code')?.valueDomain).toBe('iso_4217_currency'); + }); + + it('R6: …and so is one that de-codes it (the field stays, holding no ISO 4217 code)', async () => { + const { ql, manifest } = await boot(); + await manifest.register(ledger('currency_code')); + await manifest.register(billing([line()])); + await manifest.register(extender({ ext_amount: follows('invoice.currency_code') })); + + const err = await refusal(() => manifest.register({ + ...ledger(), version: '2.0.0', objects: [invoice(undefined, { currency_code: { type: 'text', label: 'Currency' } })], + })); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(String(err?.message)).toContain(`'${EXTENDER}'`); + expect(ql.registry.getPackage(LEDGER)?.manifest?.version).toBe('1.0.0'); + }); + + it('R7: a no-change upgrade of either owner is never refused over an extension\'s amount a cold boot admitted', async () => { + // The cold boot is not asked, so the bad extension is served. + const { ql, manifest } = await bootWith([ledger('currency_code'), billing([line()]), extender({ ext_amount: follows('invoice.title') })]); + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.title'); + + await manifest.register({ ...ledger('currency_code'), version: '1.0.1' }); + await manifest.register(billing([line()], '1.0.1')); + + expect(ql.registry.getPackage(LEDGER)?.manifest?.version).toBe('1.0.1'); + expect(ql.registry.getPackage(BILLING)?.manifest?.version).toBe('1.0.1'); + }); + + it('R7: …and so is the extension package\'s own no-change upgrade over the amount the cold boot admitted', async () => { + const { ql, manifest } = await bootWith([ledger('currency_code'), billing([line()]), extender({ ext_amount: follows('invoice.title') })]); + + await manifest.register(extender({ ext_amount: follows('invoice.title') }, '1.0.1')); + + expect(ql.registry.getPackage(EXTENDER)?.manifest?.version).toBe('1.0.1'); + expect(extraOf(ql)?.currencyConfig?.currencyField).toBe('invoice.title'); + }); + + it('R7: a parent upgrade that only adds an unrelated code field installs over a pair it leaves as it found it', async () => { + // The cold boot admits an amount following the parent's text field; the + // refusal sentence lists the parent's code fields, so it moves when the + // upgrade adds one, while the pair does not. + const { ql, manifest } = await bootWith([ledger(), billing([line('invoice.title')])]); + + await manifest.register({ ...ledger('cc'), version: '2.0.0' }); + + expect(ql.registry.getPackage(LEDGER)?.manifest?.version).toBe('2.0.0'); + expect(fieldOf(ql, 'suite_invoice', 'cc')?.valueDomain).toBe('iso_4217_currency'); + }); + + it('R6: an extension upgrade that re-points its own master_detail onto ANOTHER parent lacking the code is refused, though the pointer reads the same', async () => { + const viaInv2 = (reference: string) => ({ + inv2: { type: 'master_detail', label: 'Invoice 2', reference }, + ext_amount: follows('inv2.title'), + }); + const { ql, manifest } = await bootWith([ + { ...ledger(), objects: [invoice(), object('suite_other')] }, + billing([line()]), + extender(viaInv2('suite_invoice')), + ]); + + const err = await refusal(() => manifest.register(extender(viaInv2('suite_other'), '1.0.1'))); + + expect(err).toMatchObject({ ...FOLLOW_REFUSED, objectName: 'suite_line', fieldName: 'ext_amount' }); + expect(ql.registry.getPackage(EXTENDER)?.manifest?.version).toBe('1.0.0'); + expect(fieldOf(ql, 'suite_line', 'inv2')?.reference).toBe('suite_invoice'); + }); +}); diff --git a/packages/objectql/src/protocol-batch-object-registration.test.ts b/packages/objectql/src/protocol-batch-object-registration.test.ts index e2ea5c0183f..77b5e5938db 100644 --- a/packages/objectql/src/protocol-batch-object-registration.test.ts +++ b/packages/objectql/src/protocol-batch-object-registration.test.ts @@ -479,3 +479,124 @@ describe('migrateStoredMetadata: a rewrite the registry refuses is reported fail expect(after.fields.source_ref.reference).toBeUndefined(); }); }); + +// ── [#33593 ruling A, amended] An `extend` layer on single save and in the batch writer ── +// +// The two other askers of the follow door judge an extension as the run's end +// does: as its object is served with the extension in place (R1), in both +// registration orders (R3). +describe('[#33593] an extension\'s record-mode amount on a single save and in the batch writer', () => { + const P = 'com.qa.ledger'; + const X = 'com.qa.extender'; + const follows = (pointer: string) => ({ name: 'ext_amount', type: 'currency', label: 'Extra', currencyConfig: { currencyMode: 'record', currencyField: pointer } }); + /** The child, with no amount of its own. */ + const plainLine = (ns: string) => ({ + name: `${ns}_line`, label: 'Line', sharingModel: 'private', + fields: { + title: { name: 'title', type: 'text', label: 'Title' }, + invoice: { name: 'invoice', type: 'master_detail', reference: `${ns}_invoice`, label: 'Invoice' }, + }, + }); + const saveObject = (h: Harness, item: { name: string }) => + h.protocol.saveMetaItem({ type: 'object', name: item.name, packageId: P, item, writeFace: 'external-import' }); + const caught = async (run: () => Promise): Promise => { + try { + await run(); + } catch (e) { + return e; + } + return undefined; + }; + + it('single save: an object_extension whose amount follows a parent field holding no code is refused 422, and stores nothing', async () => { + const h = await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await h.protocol.installPackage({ manifest: { id: P, name: 'Ledger', type: 'app' } }); + await saveObject(h, invoice('ledger')); + await saveObject(h, plainLine('ledger')); + + const err = await caught(() => h.protocol.saveMetaItem({ + type: 'object_extension', name: 'ledger_line', packageId: P, mode: 'publish', writeFace: 'meta-envelope', + item: { extend: 'ledger_line', fields: { ext_amount: follows('invoice.title') } }, + })); + + expect(err).toMatchObject({ status: 422, code: 'INVALID_METADATA' }); + expect(registered(h, 'ledger_line')?.fields?.ext_amount).toBeUndefined(); + expect(activeRow(h, 'object_extension', 'ledger_line', P)).toBeUndefined(); + }); + + it('single save: an object_extension adding a `sum` roll-up of an amount in its rows\' own currency is refused 422 by D6\'s roll-up door, and stores nothing', async () => { + const h = await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await h.protocol.installPackage({ manifest: { id: P, name: 'Ledger', type: 'app' } }); + await saveObject(h, invoice('ledger')); + await saveObject(h, ownCurrencyLine('ledger')); + + const err = await caught(() => h.protocol.saveMetaItem({ + type: 'object_extension', name: 'ledger_invoice', packageId: P, mode: 'publish', writeFace: 'meta-envelope', + item: { extend: 'ledger_invoice', fields: { + own_total: { name: 'own_total', type: 'summary', label: 'Own total', summaryOperations: { object: 'ledger_own_line', field: 'amount', function: 'sum' } }, + } }, + })); + + expect(err).toMatchObject({ status: 422, code: 'INVALID_METADATA' }); + expect(registered(h, 'ledger_invoice')?.fields?.own_total).toBeUndefined(); + expect(activeRow(h, 'object_extension', 'ledger_invoice', P)).toBeUndefined(); + }); + + it('single save CONTROL: the same extension following the parent\'s code is saved and served', async () => { + const h = await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await h.protocol.installPackage({ manifest: { id: P, name: 'Ledger', type: 'app' } }); + await saveObject(h, invoice('ledger')); + await saveObject(h, plainLine('ledger')); + + await h.protocol.saveMetaItem({ + type: 'object_extension', name: 'ledger_line', packageId: P, mode: 'publish', writeFace: 'meta-envelope', + item: { extend: 'ledger_line', fields: { ext_amount: follows('invoice.currency_code') } }, + }); + + expect(registered(h, 'ledger_line')?.fields?.ext_amount?.currencyConfig?.currencyField).toBe('invoice.currency_code'); + }); + + it('single save, the other order: the owner saved under an extension registered first is refused over the extension\'s amount (R3)', async () => { + const h = await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + await h.protocol.installPackage({ manifest: { id: P, name: 'Ledger', type: 'app' } }); + await saveObject(h, invoice('ledger')); + // The extension registers while nothing serves `led_line`: no verdict (R2). + h.engine.registry.registerObject({ name: 'ledger_line', fields: { ext_amount: follows('invoice.title') } } as never, X, undefined, 'extend'); + + const refusal = h.engine.registry.objectRegistrationRefusal(plainLine('ledger') as never, P, 'own', { againstRegistry: true }); + + expect(refusal).toMatchObject({ name: 'RecordCurrencyFollowRefusedError', status: 422, code: 'INVALID_METADATA', objectName: 'ledger_line', fieldName: 'ext_amount' }); + }); + + it('batch writer: both registered rows of a bad pair are refused, whichever end is asked (R1, R3)', async () => { + const h = await boot(); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const registry = h.engine.registry; + registry.registerObject(invoice('ledger') as never, P, undefined, 'own'); + registry.registerObject(plainLine('ledger') as never, P, undefined, 'own'); + registry.registerObject({ name: 'ledger_line', fields: { ext_amount: follows('invoice.title') } } as never, X, undefined, 'extend'); + + // Asked as `batch-object-registration.ts` asks a registered row: the extension row, then the child row. + const asExtension = registry.objectRegistrationRefusal({ name: 'ledger_line', fields: { ext_amount: follows('invoice.title') } } as never, X, 'extend', { againstRegistry: true }); + const asOwner = registry.objectRegistrationRefusal(plainLine('ledger') as never, P, 'own', { againstRegistry: true }); + + for (const refusal of [asExtension, asOwner]) { + expect(refusal).toMatchObject({ name: 'RecordCurrencyFollowRefusedError', status: 422, code: 'INVALID_METADATA', objectName: 'ledger_line', fieldName: 'ext_amount' }); + } + }); + + it('batch writer CONTROL: a pair the extension completes against the parent\'s code is admitted from either end', async () => { + const h = await boot(); + const registry = h.engine.registry; + registry.registerObject(invoice('ledger') as never, P, undefined, 'own'); + registry.registerObject(plainLine('ledger') as never, P, undefined, 'own'); + registry.registerObject({ name: 'ledger_line', fields: { ext_amount: follows('invoice.currency_code') } } as never, X, undefined, 'extend'); + + expect(registry.objectRegistrationRefusal({ name: 'ledger_line', fields: { ext_amount: follows('invoice.currency_code') } } as never, X, 'extend', { againstRegistry: true })).toBeNull(); + expect(registry.objectRegistrationRefusal(plainLine('ledger') as never, P, 'own', { againstRegistry: true })).toBeNull(); + }); +}); diff --git a/packages/objectql/src/record-currency-aggregate-door.ts b/packages/objectql/src/record-currency-aggregate-door.ts index 89fc3f362cd..b6542b7f040 100644 --- a/packages/objectql/src/record-currency-aggregate-door.ts +++ b/packages/objectql/src/record-currency-aggregate-door.ts @@ -462,17 +462,19 @@ export interface RecordCurrencyFollowRegistryView { readonly lookup: (name: string) => ObjectLike | undefined; /** Every registered object, as served. */ readonly all: () => readonly ObjectLike[]; - /** The fields the registered `extend` contributions of `name` add, a disabled package's withheld as the served fold withholds them (they fold onto any base that registers). */ - readonly extensionFieldsOf: (name: string) => Record | undefined; - /** The incoming body is an `extend` contribution: its fields are not the object's whole field map. */ - readonly partial: boolean; + /** + * The package whose enabled `extend` contribution adds `field` to the + * served object `name`, or `undefined` when no extension does: a refusal of + * a parent's upgrade names the package whose field it breaks. + */ + readonly extensionPackageOf: (name: string, field: string) => string | undefined; } /** - * [ADR-0144 D2 and D6, amended] The refusal for an object about to register - * (or one of a unit just registered, asked with the whole unit in the view), - * or `undefined`. Two pairs, each judged at whichever registration completes - * it; a pair with an end not registered yet is no verdict: + * [ADR-0144 D2 and D6, amended] The refusal for an object layer about to + * register (or one of a unit just registered, asked with the whole unit in + * the view), or `undefined`. Two pairs, each judged at whichever registration + * completes it; a pair with an end not registered yet is no verdict: * * - (a) a record-mode amount whose `currencyField` is the path * `MASTER_DETAIL.CODE` (segment 1 is the spec object door's) and whose @@ -490,11 +492,24 @@ export interface RecordCurrencyFollowRegistryView { * following another record, is D6's ({@link recordCurrencySummaryRefusal}), * which refuses any such roll-up whatever it declares. * - * An `extend` body ({@link RecordCurrencyFollowRegistryView.partial}) holds - * only the fields it adds, so only its own roll-ups are judged; a parent known - * only through extensions is not registered, so it is no verdict, as - * `defineStack` skips it. The parent's fields at its own registration are its - * body with its registered extensions' fields under it. + * `served` is the layer's object AS SERVED with the layer in place: its base + * (`overlay ?? own`), every enabled extension, and the incoming layer filling + * its slot. Every layer is judged that way, an `extend` contribution included + * (seat ruling R1): a following amount an extension adds is judged against its + * parent as an own body's is, whichever registers first, and the owner + * registering under an extension that arrived before it judges the + * extension's amounts with its own (R3, R4). The parent is read as served, so + * a code field another extension supplies counts only while that extension is + * registered and enabled (R5). An object with no owner registered is not + * served, so the registry asks nothing of it (R2). + * + * `before` is the same object as it was served without the layer's change — + * with the layer the run replaced, or with nothing in the layer's slot — or + * `undefined` when there was no object to serve. A pair already refused there + * is not the layer's to answer for: a no-change upgrade of a parent is never + * refused over a pair it leaves as it found it (R7), while an upgrade that + * removes or de-codes a field a registered amount follows is, naming the + * package that adds the amount (R6). * * The registry asks this of a unit that is whole, and only once the cold boot * has ended (the AGENTS.md startup-registry rule): during the boot an `extend` @@ -519,44 +534,69 @@ export interface RecordCurrencyFollowRegistryView { * reload keeps the definitions that served. */ export function recordCurrencyFollowRefusal( - incoming: ObjectLike, + served: ObjectLike, view: RecordCurrencyFollowRegistryView, + before?: ObjectLike, ): RecordCurrencyFollowRefusedError | undefined { + let already: Set | undefined; + for (const [pair, refusal] of followRefusalsOf(served, view)) { + already ??= new Set(before === undefined ? [] : [...followRefusalsOf(before, view)].map(([key]) => key)); + if (!already.has(pair)) return refusal; + } + return undefined; +} + +/** + * One refused PAIR's identity across the two readings + * {@link recordCurrencyFollowRefusal} compares: the kind of pair, the object + * and field declaring it, and what it points at — never the sentence, which + * lists the parent's code fields and so moves when a run only adds one. A + * following amount's target names the OBJECT its master_detail reaches as + * well as the pointer: a run that re-points the pair's master_detail onto + * another parent makes a new pair, so it is that run's to answer for. + */ +function followPairKey(kind: 'follow' | 'rollup', object: string, field: string, target: string): string { + return `${kind}\u0000${object}\u0000${field}\u0000${target}`; +} + +/** Every refusal {@link recordCurrencyFollowRefusal} weighs for `incoming`, in the order it asks. */ +function* followRefusalsOf( + incoming: ObjectLike, + view: RecordCurrencyFollowRegistryView, +): Generator<[string, RecordCurrencyFollowRefusedError]> { const name = typeof incoming.name === 'string' ? incoming.name : undefined; const own = fieldsOf(incoming); - if (!name || !own) return undefined; + if (!name || !own) return; - // (c) at the parent: the incoming body's `record` roll-ups, over a child already registered (or itself). + // (c) at the parent: the object's `record` roll-ups, over a child already registered (or itself). for (const [summaryField, def] of Object.entries(own)) { const rollup = rawRollupOf(def); if (!rollup || !declaresRecordCurrency(def)) continue; - const childFields = rollup.child === name && !view.partial ? own : fieldsOf(view.lookup(rollup.child)); + const childFields = rollup.child === name ? own : fieldsOf(view.lookup(rollup.child)); const childDef = childFields && Object.prototype.hasOwnProperty.call(childFields, rollup.childField) ? childFields[rollup.childField] : undefined; if (childDef === undefined || recordCurrencyAggregandOf(childDef) !== undefined) continue; - return new RecordCurrencyFollowRefusedError(name, summaryField, recordCurrencyUnfollowedRollupError( + yield [followPairKey('rollup', name, summaryField, `${rollup.child}.${rollup.childField}`), new RecordCurrencyFollowRefusedError(name, summaryField, recordCurrencyUnfollowedRollupError( { object: name, field: summaryField, fn: rollup.fn, childObject: rollup.child, childField: rollup.childField }, childDef, - )); + ))]; } - if (view.partial) return undefined; - // (a) at the child: the incoming body's following amounts, under a parent already registered (or itself). + // (a) at the child: the object's following amounts, under a parent already registered (or itself). for (const [field, def] of Object.entries(own)) { const pointer = recordCurrencyFieldOf(def); const path = pointer === undefined ? undefined : recordCurrencyPathOf(pointer, own); if (!path || path.master === undefined) continue; - const parentFields = path.master === name ? parentFieldsAt(name, own, view) : fieldsOf(view.lookup(path.master)); + const parentFields = path.master === name ? own : fieldsOf(view.lookup(path.master)); if (!parentFields) continue; const message = recordCurrencyFollowedCodeError({ object: name, field, via: path.via, code: path.code, parent: path.master, parentFields, }); - if (message !== undefined) return new RecordCurrencyFollowRefusedError(name, field, message); + if (message !== undefined) yield [followPairKey('follow', name, field, `${path.master}.${String(pointer)}`), new RecordCurrencyFollowRefusedError(name, field, message)]; } // The other ends, already registered: (a) at the parent, (c) at the child. - let incomingAsParent: Record | undefined; for (const other of view.all()) { const otherName = typeof other.name === 'string' ? other.name : undefined; const otherFields = fieldsOf(other); @@ -565,34 +605,31 @@ export function recordCurrencyFollowRefusal( const pointer = recordCurrencyFieldOf(def); const path = pointer === undefined ? undefined : recordCurrencyPathOf(pointer, otherFields); if (path?.master === name) { - incomingAsParent ??= parentFieldsAt(name, own, view); const message = recordCurrencyFollowedCodeError({ - object: otherName, field, via: path.via, code: path.code, parent: name, parentFields: incomingAsParent, + object: otherName, field, via: path.via, code: path.code, parent: name, parentFields: own, }); - if (message !== undefined) { - return new RecordCurrencyFollowRefusedError( - otherName, - field, - `'${name}' does not hold the code a registered amount follows. ${message}`, - ); - } + if (message === undefined) continue; + // R6: an amount an extension adds is named with its package, so the + // upgrade's author learns whose field the change breaks. + const extendedBy = view.extensionPackageOf(otherName, field); + yield [followPairKey('follow', otherName, field, `${name}.${String(pointer)}`), new RecordCurrencyFollowRefusedError( + otherName, + field, + extendedBy === undefined + ? `'${name}' does not hold the code a registered amount follows. ${message}` + : `'${name}' does not hold the code a registered amount follows: '${otherName}.${field}', which package ` + + `'${extendedBy}' adds to '${otherName}'. ${message}`, + )]; continue; } const rollup = rawRollupOf(def); if (!rollup || rollup.child !== name || !declaresRecordCurrency(def)) continue; const childDef = Object.prototype.hasOwnProperty.call(own, rollup.childField) ? own[rollup.childField] : undefined; if (childDef === undefined || recordCurrencyAggregandOf(childDef) !== undefined) continue; - return new RecordCurrencyFollowRefusedError(otherName, field, recordCurrencyUnfollowedRollupError( + yield [followPairKey('rollup', otherName, field, `${name}.${rollup.childField}`), new RecordCurrencyFollowRefusedError(otherName, field, recordCurrencyUnfollowedRollupError( { object: otherName, field, fn: rollup.fn, childObject: name, childField: rollup.childField }, childDef, - )); + ))]; } } - return undefined; -} - -/** The incoming body's fields as a parent: its registered extensions' fields under its own. */ -function parentFieldsAt(name: string, own: Record, view: RecordCurrencyFollowRegistryView): Record { - const extended = view.extensionFieldsOf(name); - return extended ? { ...extended, ...own } : own; } diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 8728bd488ed..2276f7dafc6 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -3943,8 +3943,9 @@ class RegistrationRestorePoint { * the registry. */ noteRegisteredObject(slot: string, layer: RunRegisteredObject): void { + const earlier = this.registered.get(slot); this.registered.delete(slot); - this.registered.set(slot, layer); + this.registered.set(slot, earlier === undefined ? layer : { ...layer, replaced: earlier.replaced }); } /** The object layers the run registered, in registration order. */ @@ -3974,6 +3975,18 @@ class RegistrationRestorePoint { } } +/** + * [#33593] How the follow door is asked of one layer + * ({@link SchemaRegistry.recordCurrencyFollowRefusalOf}): its slot's package, + * the priority it sorts at (the slot's, when omitted), and `before` — what the + * slot held before the change being judged, `null` for an empty slot. + */ +interface FollowDoorLayer { + readonly packageId: string | undefined; + readonly priority?: number; + readonly before: ObjectContributor | null; +} + /** * One object layer a registration run registered: the body its registration's * doors judged, and the contributor it became — the registry's own entry, so @@ -3984,6 +3997,13 @@ interface RunRegisteredObject { readonly fqn: string; readonly schema: ServiceObject; readonly contributor: ObjectContributor; + /** + * What the layer's slot held before the run's first write to it, or `null` + * when it was empty: the run's end judges the layer against the object as + * it was served with this in its place, so a pair the run leaves as it + * found it is not the run's to answer for (#33593 ruling R7). + */ + readonly replaced: ObjectContributor | null; } /** @@ -4452,8 +4472,11 @@ export class SchemaRegistry { * `objectExtensions` after its `objects`, a later package of the artifact, * its residual, on a reload the new version of an object an earlier body * follows — so no registration inside it can ask. Its end can: each layer is - * asked exactly as a single save of it would be, with the registry holding - * the whole run. A pair with an end outside the run is judged against the + * asked as a single save of it would be, with the registry holding the whole + * run, as its object is served ({@link servedFoldWithLayer}), and against + * the object as it was served with what the run replaced in the layer's slot: + * a pair the run leaves as it found it is not the run's to answer for + * (#33593 ruling R7). A pair with an end outside the run is judged against the * object that is registered, as a single save judges it. Where that object * is the environment's own, lying over a package's, and only it earns the * refusal, the refusal says so ({@link followRefusalAsServed}). @@ -4477,12 +4500,13 @@ export class SchemaRegistry { if (layers.length === 0) return undefined; // One read for the whole question: nothing registers while it is asked. const all = this.getAllObjects(); - for (const { fqn, schema, contributor } of layers) { + for (const { fqn, schema, contributor, replaced } of layers) { const sitting = this.objectContributors.get(fqn); if (!sitting?.includes(contributor)) continue; if (contributor.ownership === 'own' && sitting.some((c) => c.ownership === 'overlay')) continue; - const refusal = this.recordCurrencyFollowRefusalOf(schema, contributor.ownership, () => all); - if (refusal) return this.followRefusalAsServed(refusal, schema, contributor.ownership, all); + const layer: FollowDoorLayer = { packageId: contributor.packageId, priority: contributor.priority, before: replaced }; + const refusal = this.recordCurrencyFollowRefusalOf(schema, contributor.ownership, layer, () => all); + if (refusal) return this.followRefusalAsServed(refusal, schema, contributor.ownership, layer, all); } return undefined; } @@ -4507,6 +4531,7 @@ export class SchemaRegistry { refusal: RecordCurrencyFollowRefusedError, schema: ServiceObject, ownership: ObjectOwnership, + layer: FollowDoorLayer, all: readonly ServiceObject[], ): RecordCurrencyFollowRefusedError { const overPackage: string[] = []; @@ -4522,7 +4547,7 @@ export class SchemaRegistry { return fqn !== undefined && throughPackage.has(fqn) ? this.resolveOwnerLayer(fqn) ?? object : object; }; const objects = all.map((object) => read(object) ?? object); - return this.recordCurrencyFollowRefusalOf(schema, ownership, () => objects, (name) => read(this.getObject(name))) !== undefined; + return this.recordCurrencyFollowRefusalOf(schema, ownership, layer, () => objects, (name) => read(this.getObject(name))) !== undefined; }; if (refusedReading(new Set(overPackage))) return refusal; // The ones that decide it, each on its own; all of them when only together they do. @@ -5822,44 +5847,94 @@ export class SchemaRegistry { // option, a registration run at its end // ({@link recordCurrencyFollowRefusalOfRun}). if (opts.againstRegistry === true && this.bareNameHoldersAreSealed) { - const recordCurrencyFollow = this.recordCurrencyFollowRefusalOf(schema, ownership); + const recordCurrencyFollow = this.recordCurrencyFollowRefusalOf(schema, ownership, { packageId, before: null }); if (recordCurrencyFollow) return { refusal: recordCurrencyFollow }; } return { schema }; } /** - * [ADR-0144 D2 and D6, amended] The follow door's question of one body, as + * [ADR-0144 D2 and D6, amended] The follow door's question of one layer, as * `ownership`, against the registry as it stands: the one copy a single * save ({@link judgeRegistrationDoors}) and a registration run * ({@link recordCurrencyFollowRefusalOfRun}) ask. `all` answers the * registered objects; a caller asking of several bodies reads them once. * `lookup` answers one of them by name, and is the served object unless the * caller reads an object another way ({@link followRefusalAsServed}). + * + * [#33593 ruling A, amended] The door judges the layer's object AS SERVED + * with the layer in its slot ({@link servedFoldWithLayer}) — never the bare + * body, so an `extend` contribution's following amount is judged as an own + * body's is (R1), and an owner judges the amounts the extensions already + * registered under it add (R3). An object no owner serves is no verdict + * (R2). `layer.before` is what the slot held before: a pair already refused + * with it in place is not this layer's to answer for (R7). */ private recordCurrencyFollowRefusalOf( schema: ServiceObject, ownership: ObjectOwnership, + layer: FollowDoorLayer, all: () => readonly ServiceObject[] = () => this.getAllObjects(), lookup: (name: string) => ServiceObject | undefined = (name) => this.getObject(name), ): RecordCurrencyFollowRefusedError | undefined { - return recordCurrencyFollowRefusal(schema, { + const fqn = String(schema.name ?? ''); + const served = this.servedFoldWithLayer(fqn, ownership, layer.packageId, { + packageId: layer.packageId, + namespace: '', + ownership, + priority: layer.priority ?? this.followDoorSlotPriority(fqn, ownership, layer.packageId), + definition: { ...schema, name: fqn }, + }); + if (served === undefined) return undefined; + const before = this.servedFoldWithLayer(fqn, ownership, layer.packageId, layer.before ?? undefined); + return recordCurrencyFollowRefusal(served, { lookup, all, - extensionFieldsOf: (name) => { - const fqn = this.resolveObjectKey(name); - // As the served fold reads the parent ({@link resolveObject}): a - // disabled package's extension is withheld, so both ends of the pair - // read one parent. - const extensions = fqn === undefined - ? [] - : this.getObjectContributors(fqn).filter((c) => c.ownership === 'extend' && !this.isPackageDisabled(c.packageId)); - return extensions.length === 0 - ? undefined - : Object.assign({}, ...extensions.map((c) => (c.definition as { fields?: Record }).fields ?? {})); + extensionPackageOf: (name, field) => { + const key = this.resolveObjectKey(name); + if (key === undefined) return undefined; + // As the served fold reads the object ({@link resolveObject}): a + // disabled package's extension is withheld; the last to add wins. + const adders = this.getObjectContributors(key).filter((c) => c.ownership === 'extend' + && !this.isPackageDisabled(c.packageId) + && Object.prototype.hasOwnProperty.call((c.definition as { fields?: object }).fields ?? {}, field)); + return adders.length === 0 ? undefined : adders[adders.length - 1].packageId; }, - partial: ownership === 'extend', - }); + }, before); + } + + /** + * [#33593 ruling R1] The object `fqn` as {@link resolveObject} would serve + * it with `layer` filling the slot `ownership` and `packageId` name (one + * owner, one overlay, one extension per package — the replacement rules + * {@link registerObject} applies), or with that slot empty when `layer` is + * `undefined`. `undefined` when no owner would serve it. Uncached: it is a + * question about a registry the caller has not written. + */ + private servedFoldWithLayer( + fqn: string, + ownership: ObjectOwnership, + packageId: string | undefined, + layer: ObjectContributor | undefined, + ): ServiceObject | undefined { + const others = (this.objectContributors.get(fqn) ?? []).filter((c) => c.ownership !== ownership + || (ownership === 'extend' && c.packageId !== packageId)); + const contributors = layer === undefined ? others : [...others, layer].sort((a, b) => a.priority - b.priority); + const owner = contributors.find((c) => c.ownership === 'own'); + if (!owner) return undefined; + const base = contributors.find((c) => c.ownership === 'overlay') ?? owner; + const withheld = this.withholdDisabledExtensions(contributors); + return withheld + ? this.foldExtendersOntoDefinition(withheld.kept, withoutWithheldMembers(base.definition, withheld)) + : this.foldExtenders(contributors, base); + } + + /** The priority a layer about to register in the slot would take: the sitting one's, else the kind's default. */ + private followDoorSlotPriority(fqn: string, ownership: ObjectOwnership, packageId: string | undefined): number { + const sitting = (this.objectContributors.get(fqn) ?? []).find((c) => c.ownership === ownership + && (ownership !== 'extend' || c.packageId === packageId)); + if (sitting) return sitting.priority; + return ownership === 'own' ? DEFAULT_OWNER_PRIORITY : ownership === 'overlay' ? DEFAULT_OVERLAY_PRIORITY : DEFAULT_EXTENDER_PRIORITY; } /** @@ -6057,6 +6132,8 @@ export class SchemaRegistry { // it keeps `objectKeysByShortName` in step with `objectContributors`) const contributors = this.openObjectEntry(fqn); + // [#33593 ruling R7] What this layer's slot held, for the open run's end. + let replaced: ObjectContributor | null = null; // Validate ownership rules if (ownership === 'own') { const existingOwner = contributors.find(c => c.ownership === 'own'); @@ -6103,6 +6180,7 @@ export class SchemaRegistry { // same owned object), not an error — keep it at debug so a stock boot // stays warning-free (#3420). contributors.splice(contributors.indexOf(existingOwner), 1); + replaced = existingOwner; this.debug(`[Registry] Re-registering owned object: ${fqn} from ${packageId}`); } } else if (ownership === 'overlay') { @@ -6119,14 +6197,14 @@ export class SchemaRegistry { // `loadMetaFromDb`'s per-record `errors` at boot. const idx = contributors.findIndex(c => c.ownership === 'overlay'); if (idx !== -1) { - contributors.splice(idx, 1); + replaced = contributors.splice(idx, 1)[0]; this.debug(`[Registry] Replacing overlay layer of object: ${fqn} from ${packageId}`); } } else { // extend mode: remove existing extension from same package const idx = contributors.findIndex(c => c.packageId === packageId && c.ownership === 'extend'); if (idx !== -1) { - contributors.splice(idx, 1); + replaced = contributors.splice(idx, 1)[0]; } } @@ -6153,7 +6231,7 @@ export class SchemaRegistry { // ({@link restoringOnRefusal}). Outside a run nothing is recorded. this.restorePoint?.noteRegisteredObject( `${fqn}\u0000${ownership}${ownership === 'extend' ? `\u0000${packageId ?? ''}` : ''}`, - { fqn, schema: judged, contributor }, + { fqn, schema: judged, contributor, replaced }, ); // Sort by priority (ascending: lower priority applied first) diff --git a/packages/spec/src/migrations/entries/semantic/18.record-currency-follow-extension-judged-as-served.ts b/packages/spec/src/migrations/entries/semantic/18.record-currency-follow-extension-judged-as-served.ts new file mode 100644 index 00000000000..b5193db0c98 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.record-currency-follow-extension-judged-as-served.ts @@ -0,0 +1,61 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the record-currency follow door (ADR-0144 D2 and +// D6, amended) as it now judges an `objectExtensions` entry and an +// `object_extension` item: against the object as the server serves it. No D2 +// conversion: which field of the parent holds the currency code is the +// author's to say. +export const entry: SemanticMigration = { + id: 'record-currency-follow-extension-judged-as-served', + surface: + 'data.Field.currencyConfig on a field an `objectExtensions` entry (or a stored `object_extension` item) adds to ' + + 'an object: a record-mode amount whose `currencyField` is the path `MASTER_DETAIL.CODE`, judged against the ' + + 'object as the server serves it (its base, every enabled extension, and the incoming body). Where it is asked: ' + + 'an install, upgrade or reload on a running server (the engine\'s `manifest` service, POST ' + + '/api/v1/marketplace/install-local, the artifact hot reload), a published single save of an `object_extension` ' + + 'item through the `/meta` doors, and the batch writers. Also the owner of the extended object, registering after ' + + 'the extension, over the amounts the extension adds. A published single save of an `object_extension` item also ' + + 'meets D6\'s roll-up door, as the batch writer\'s extension row already did, in both directions: a `summary` the ' + + 'extension adds that rolls up `sum` / `avg` / `min` / `max` of a child amount, or an amount the extension adds ' + + 'that a registered parent\'s such roll-up reads, is refused 422 instead of being stored when that child amount is ' + + 'declared `currencyMode: \'record\'` (in each row\'s own currency, or following a parent\'s code but not read on ' + + 'that parent through the master_detail it follows). Not the cold boot', + replacement: + 'Name in the second segment of `currencyField` a field of the master_detail target that declares ' + + '`valueDomain: \'iso_4217_currency\'` (the refusal lists the candidates), or install the package that supplies ' + + 'that field first, or in the same artifact. When the owner of the extended object is refused over an ' + + 'extension\'s amount, the correction is the extension\'s package: it upgrades with the amount corrected, or is ' + + 'uninstalled, and the owner is then installed again unchanged. When a parent\'s upgrade is refused because it ' + + 'removes or de-codes a field an extension\'s amount follows, the refusal names that package and field: keep the ' + + 'field in the upgrade, or have that package move its amount first. When a published `object_extension` save is ' + + 'refused by D6\'s roll-up door, roll up through the master_detail the amount follows ' + + '(`summaryOperations.relationshipField`, on the parent it follows), use `function: \'count\'`, or roll up a ' + + 'stored home-currency amount field of the child instead', + reason: + 'An extension\'s following amount was judged as the extension\'s body alone, which holds only the fields it adds, ' + + 'so the following half was never asked: an extension-only package could add an amount following a parent field ' + + 'with no ISO 4217 code, a field that does not exist, or a field reached through its own new master_detail, and ' + + 'every write of that amount was then refused `ERR_CURRENCY_CODE_REQUIRED` or labelled with whatever the field ' + + 'held. Worse, the next upgrade of the parent\'s owner was refused over the extension\'s field, blaming a package ' + + 'that changed nothing. Every object layer is now judged as its served object, so the run that completes a bad ' + + 'pair is refused 422 `INVALID_METADATA` whichever end it holds, and a run that leaves a pair as it found it is ' + + 'not refused over it. For runs (an install, an upgrade, a reload) this supersedes the entry ' + + '`record-currency-follow-pair-refused-on-install-and-reload` where it says the next upgrade or reload of a ' + + 'package holding only the other end of a pair is refused "although nothing in that package is wrong": such a run ' + + 'is now refused only when it changes the pair (the pair is compared, not the refusal sentence: the object and field ' + + 'declaring it, the pointer, and the object the pointer\'s master_detail reaches, so re-pointing that master_detail ' + + 'onto another parent lacking the code is refused). A single save and ' + + 'the batch writers judge against the slot left empty, so re-publishing an unchanged extension whose amount a cold ' + + 'boot admitted is refused there, as an unchanged own body already was. ' + + 'A field another extension supplies counts only while that extension is installed and ' + + 'enabled. An extension of an object no package owns yet is no verdict until the owner registers. Packages ' + + 'installed before this release keep loading at every boot, which is not asked. There is no mechanical rewrite: ' + + 'only the author knows which parent field holds the code', + acceptanceCriteria: + 'Install the extension package on a running server after the package owning the extended object and its parent, ' + + 'and confirm the answer is 200 and the served object carries the amount. Upgrade the parent\'s owner unchanged ' + + 'and confirm it installs. Insert a child row under a parent holding a code and confirm the amount is stored with ' + + 'that code', +};