Skip to content
Merged
39 changes: 39 additions & 0 deletions .changeset/34095-upgrade-plan-object-extensions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
'@objectstack/metadata-core': patch
'@objectstack/objectql': patch
'@objectstack/cloud-connection': patch
'@objectstack/cli': patch
---

fix(metadata-core,objectql,cloud-connection,cli)!: the package upgrade plan counts the fields a package adds through `objectExtensions`

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any authorable schema is added, removed, renamed or re-shaped and no stored row changes: what moves is which fields the package upgrade comparison reads from each version, so there is nothing for `objectstack migrate meta` to rewrite. -->

**BREAKING** for an upgrade that changes a field the package adds to an object through `objectExtensions`. Four kinds of upgrade that installed without a question before are now refused, exactly as the same change to a field of an object the package declares is:

- an extension field retyped to a `needs_confirm` or `destructive` type: `409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED`;
- an extension field dropped while another stored extension field of the same object is added, with no `renamedFrom` linking them: `409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED`, as a suspected rename;
- a stored field dropped from an object's own declaration in the upgraded version while an extension of the same object adds a stored field, or an extension field dropped while the object's own declaration adds one: `409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED`, as a suspected rename. The owned and the extension fields of one object are now one field map, so the two pair; before, they were never compared;
- an extension field that declares `renamedFrom` and whose new type stores no column (a `formula`, for example): `422 VALIDATION_ERROR` with `details.refusals[].reason: 'destructive_type'`, before anything is written, as for an owned field. No token answers this refusal.

The package upgrade plan (`comparePackageVersions`) read only a version's `objects` and `data`. A field an `objectExtensions` entry adds, retypes or drops was therefore missing from the upgrade preview, from the rows counted per touched column, and from the schema upgrade verdict. A preview of an upgrade that added seven columns through extensions listed no added field, and its rollback listed no removed one.

Now each side of the comparison is the objects as the registry serves them from that version: the owner's declaration, with every extension's `fields` merged over it by name, in ascending `priority` (`200` when none is declared). The existing rules then apply to an extension field unchanged:

- an extension field added is listed in `plan.fields.added`, and one dropped in `plan.fields.removed`, with the rows holding a value counted in `environment.columns`;
- an extension field retyped is a type change; `needs_confirm` and `destructive` changes need the confirmation, and a `safe` one does not;
- an extension field dropped while another stored field of the same object is added, with no `renamedFrom` linking them, is a suspected rename and needs the confirmation; a field dropped alone is listed and refused by nothing, as an owned one is.

An object a version reaches only through an extension (another package owns it) is compared by the fields the extension adds. It is never listed in `plan.objects.added` or `plan.objects.removed`, because the upgrade neither creates nor drops it. `os diff` prints the field changes of such an object under `objects.<name>.fields`.

`PackageUpgradeSide` (`@objectstack/metadata-core`) gains an optional `objectExtensions` list. A caller that builds a side itself passes the version's `objectExtensions` beside its `objects`, read with the same collection reader; a side without the key compares as before.

Who moves, and the fix for each:

- An installer upgrading a package whose new version retypes an extension field, or drops a field of an object while another stored field of the same object is added (extension or owned, in either pairing): the `409`. Confirm the findings with the token the refusal names (`--confirm-upgrade <token>` on `os deploy` and `os package install`); for a suspected rename the refusal names the other way forward too.
- A package author whose new version renames an extension field with `renamedFrom` into a type that stores no column: the `422`. `--confirm-upgrade` does not answer it. Keep a stored type for the renamed field, or carry the values by hand, as the refusal's message says.

Unchanged: a plan over packages that declare no `objectExtensions` is the same plan as before; seed datasets are compared as before; `fieldPatches` changes display properties only and stays out of the comparison.
14 changes: 11 additions & 3 deletions packages/cli/src/commands/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,18 @@ function diffObjectsAndSeeds(beforeConfig: any, afterConfig: any): DiffEntry[] {
for (const name of plan.objects.removed) entries.push({ type: 'removed', category: 'objects', name, breaking: true });
for (const name of plan.objects.added) entries.push({ type: 'added', category: 'objects', name, breaking: false });

const beforeObjects = getNames(beforeConfig.objects);
const afterObjects = getNames(afterConfig.objects);
for (const [name, beforeObj] of getNames(beforeConfig.objects)) {
// Every object both configs declare, then (#34095) each object the plan
// lists field changes on that a config reaches only through
// `objectExtensions`: the plan compares those too, and they print alike.
const compared = [...beforeObjects.keys()].filter((name) => afterObjects.has(name));
for (const list of [plan.fields.removed, plan.fields.added, plan.declaredRenames, plan.typeChanges, plan.suspectedRenames]) {
for (const item of list) if (!compared.includes(item.object)) compared.push(item.object);
}
for (const name of compared) {
const beforeObj = beforeObjects.get(name);
const afterObj = afterObjects.get(name);
if (!afterObj) continue;
const category = `objects.${name}.fields`;
const mine = <T extends { object: string }>(list: T[]): T[] => list.filter((item) => item.object === name);

Expand Down Expand Up @@ -138,7 +146,7 @@ function diffObjectsAndSeeds(beforeConfig: any, afterConfig: any): DiffEntry[] {
}

// Label / ownership changes on the object itself
if (beforeObj.label !== afterObj.label) {
if (beforeObj && afterObj && beforeObj.label !== afterObj.label) {
entries.push({
type: 'modified',
category: 'objects',
Expand Down
24 changes: 24 additions & 0 deletions packages/cli/test/diff-upgrade-plan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,27 @@ describe('os diff — what the upgrade plan adds', () => {
]);
});
});

describe('os diff — objectExtensions fields, as the plan compares them (#34095)', () => {
const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text' } } };

it('an extension field added to an object the config owns prints under that object', () => {
const entries = diffStacks(
{ objects: [ACCOUNT] },
{ objects: [ACCOUNT], objectExtensions: [{ extend: 'crm_account', fields: { invoiced_amount: { type: 'number' } } }] },
);
expect(entries).toEqual([
{ type: 'added', category: 'objects.crm_account.fields', name: 'invoiced_amount', breaking: false, detail: 'optional field added' },
]);
});

it('an object reached only through an extension prints its field changes, and is never an added or removed object', () => {
const entries = diffStacks(
{ objectExtensions: [{ extend: 'crm_contact', fields: { tier: { type: 'text' } } }] },
{ objectExtensions: [{ extend: 'crm_contact', fields: { tier: { type: 'number' } } }] },
);
expect(entries).toEqual([
{ type: 'modified', category: 'objects.crm_contact.fields', name: 'tier', breaking: true, detail: 'type changed: text → number' },
]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,28 @@ describe('a declared rename that cannot be carried is refused 422 before any wri
await refusedBefore(door, driver, before);
});

it('`destructive_type` on an extension field: the renamed field an `objectExtensions` entry adds turns a type that stores no column (#34095)', async () => {
// The upgrade plan folds the extension's fields onto `acme_lead`, so the
// destructive retype on the declared rename reaches the planner as it
// does for an owned field: refused by name, which no token answers.
const driver = fakeDriver({ acme_lead: new Set(['id', 'company']) });
const ext = (version: string, fields: Row) => ({
id: 'com.acme.ext', namespace: 'acmeext', version, objectExtensions: [{ extend: 'acme_lead', fields }],
});
const served = { acme_lead: lead({ company: { type: 'text' } }) };
const door = await mount({ installed: ext('1.0.0', { company: { type: 'text' } }), driver, served });
const before = ledgerFiles();
const res = await door.install(makeC({
manifest: ext('2.0.0', { account_name: { type: 'formula', expression: '1', renamedFrom: ['company'] } }),
}));
expect(res.status).toBe(422);
expect(res.payload.error.code).toBe('VALIDATION_ERROR');
expect(res.payload.error.details.refusals).toEqual([expect.objectContaining({
object: 'acme_lead', field: 'account_name', from: ['company'], reason: 'destructive_type',
})]);
await refusedBefore(door, driver, before);
});

it('`outside_package`: an extension\'s field names a column its own package never contributed (the owner\'s just-dropped key)', async () => {
// The owner's table still holds `company` (the owner dropped it); this
// package only ever extended the object with `nickname`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,11 @@ afterEach(() => {
vi.restoreAllMocks();
});

const fold = (artifact: unknown) => ({ objects: resolveStackCollection(artifact, 'objects'), data: resolveStackCollection(artifact, 'data') });
const fold = (artifact: unknown) => ({
objects: resolveStackCollection(artifact, 'objects'),
objectExtensions: resolveStackCollection(artifact, 'objectExtensions'),
data: resolveStackCollection(artifact, 'data'),
});

async function mount(options: { installed?: Row; planUpgrade?: false; columns?: Row[]; overrides?: unknown; registryPackages?: Row[]; driver?: unknown } = {}) {
const register = vi.fn();
Expand Down Expand Up @@ -494,3 +498,51 @@ describe('step 2c′: the schema upgrade verdict on a managed re-install', () =>
expect(entry()?.schemaUpgradeConfirmation).toBeUndefined();
});
});

describe('step 2c′ judges an objectExtensions field like an owned one (#34095)', () => {
/** The vendor package, adding fields to an object another package owns. */
const extending = (version: string, fields: Row) => ({
...vendorBody(version, { company: { type: 'text' } }),
objectExtensions: [{ extend: 'crm_account', fields }],
});

it('a retyped extension field answers 409 SCHEMA_UPGRADE_CONFIRMATION_REQUIRED naming it, and writes nothing', async () => {
const door = await mount({ installed: extending('1.0.0', { tier: { type: 'text' } }) });
const before = ledgerFiles();

const res = await door.install(makeC({ manifest: extending('2.0.0', { tier: { type: 'number' } }) }));

expect(res.status).toBe(409);
expect(res.payload.error.code).toBe('SCHEMA_UPGRADE_CONFIRMATION_REQUIRED');
expect(res.payload.error.details.findings).toEqual([expect.objectContaining({
kind: 'type_change', object: 'crm_account', field: 'tier', from: 'text', to: 'number', category: 'needs_confirm',
})]);
expect(door.register).not.toHaveBeenCalled();
expect(ledgerFiles()).toEqual(before);
});

it('an extension field dropped beside one added answers 409 as a suspected rename', async () => {
const door = await mount({ installed: extending('1.0.0', { tier: { type: 'text' } }) });
const res = await door.install(makeC({ manifest: extending('2.0.0', { segment: { type: 'text' } }) }));
expect(res.status).toBe(409);
expect(res.payload.error.code).toBe('SCHEMA_UPGRADE_CONFIRMATION_REQUIRED');
expect(res.payload.error.details.findings).toEqual([expect.objectContaining({
kind: 'suspected_rename', object: 'crm_account', field: 'tier', candidates: [{ field: 'segment', type: 'text' }],
})]);
});

it('the dry run lists an added extension field; adding it, or dropping one alone, installs unrefused as an owned field does', async () => {
const door = await mount({ installed: extending('1.0.0', { tier: { type: 'text' } }) });
const preview = await door.install(makeC({ manifest: extending('2.0.0', { tier: { type: 'text' }, invoiced_amount: { type: 'number' } }), dryRun: true }));
expect(preview.status).toBe(200);
expect(preview.payload.data.plan.fields.added).toEqual([
{ object: 'crm_account', field: 'invoiced_amount', type: 'number', required: false, stored: true },
]);

const added = await door.install(makeC({ manifest: extending('2.0.0', { tier: { type: 'text' }, invoiced_amount: { type: 'number' } }) }));
expect(added.status).toBe(200);
const dropped = await door.install(makeC({ manifest: extending('3.0.0', { tier: { type: 'text' } }) }));
expect(dropped.status).toBe(200);
expect(new LocalManifestSource(dir).read(VENDOR).entry?.schemaUpgradeConfirmation).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,18 @@ export function convertPackageBodyForward(ctx: PluginContext, manifest: unknown)
return typeof ql?.convertPackageBodyForward === 'function' ? ql.convertPackageBodyForward(manifest) : manifest;
}

/** One side of a package version comparison, a multi-package artifact folded as `planUpgrade` folds it. */
/**
* One side of a package version comparison, a multi-package artifact folded as
* `planUpgrade` folds it: `objects`, `objectExtensions` (#34095: the comparison
* merges each extension's fields onto its target, so the verdict judges an
* extension field like an owned one) and `data`.
*/
export function packageUpgradeSideOf(artifact: unknown): PackageUpgradeSide {
return { objects: resolveStackCollection(artifact, 'objects'), data: resolveStackCollection(artifact, 'data') };
return {
objects: resolveStackCollection(artifact, 'objects'),
objectExtensions: resolveStackCollection(artifact, 'objectExtensions'),
data: resolveStackCollection(artifact, 'data'),
};
}

/**
Expand Down
Loading
Loading