Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/35228-package-duplicate-entry-every-door.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/spec': minor
'@objectstack/objectql': minor
---

feat(spec)!: two entries under one identity in one package are refused when a composition or a package body assembles them, as a single stack already refused them

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: none — no skill teaches splitting one package's entries for one identity across sub-stacks or package bodies; `skills/objectstack-data/SKILL.md` teaches one `objectExtensions` entry per extension, and the refusal names both entries and prescribes the merge

<!-- adr-0087: registered stack-package-duplicate-entry-refused-at-every-door -->

**BREAKING** accept-set narrowing, shipped as `minor`. `defineStack` refuses two entries under one identity in one stack for the collections the runtime registers one entry per identity (`objects`, `datasources`, `pages`, …, `queues`, `assignmentRules`, `apps`, `objectExtensions`), but two sub-stacks of ONE package that each declared one such entry composed with both, and a hand-built `packages[i]` body carrying two was accepted. `os validate`, `os build` and the boot all passed, and the boot then kept one entry. For `objectExtensions` that meant only the last entry's fields registered: a field the earlier entry declared was missing, and reads and writes naming it answered `INVALID_FIELD`.

- **Refused now, in the cross-reference envelope (`STACK_CROSS_REFERENCE_INVALID`, 422), with the single-stack wording.** `composeStacks`, for the package it registers under its own `manifest.id`: every input of a flat composition, and under `manifest: 'preserve'` the inputs without a manifest and any other top-level entry no package body claims (the boot's residual). Each finding names the input every entry came from: `Object extension of 'crm_line' is declared twice in \`objectExtensions\`: stack #1 objectExtensions[0] and stack #2 objectExtensions[0]. …`. Every `packages[i]` body, of `defineStack({ packages })` (`stack.packages[1].manifest.objectExtensions[0]`) and of a composition that carries or assembles bodies. The refusal carries the inputs' conversion record like the other composition refusals. Two inputs declaring one app name now answer this refusal first, where they answered `STACK_SINGLE_APP_VIOLATION`.
- **Unchanged.** A single stack's refusal, byte for byte. Two packages reusing one name (ADR-0048 §3.4): under `manifest: 'preserve'`, as two package bodies, or as a nested multi-package artifact's flattened copies of its bodies, each body is judged on its own. The same built sub-stack passed to a composition twice, except its `hooks`: a hook reached twice is refused, because a built artifact binds each copy. Two same-name objects across inputs stay the `objectConflict` strategy's to refuse or fold.
- **Installed packages keep loading (`@objectstack/objectql`).** A package body built before this release that carries two or more `objectExtensions` entries for one object registers as before (only the last entry's fields), and its registration now logs one error per (package, object) naming the object, the package and the entries, and telling the author to merge them and rebuild. Entries for one object that are all equal by value lose nothing and log nothing. Re-registering a package still replaces that package's previous extension of the object.

One-line fix: merge the entries into one (for `objectExtensions`, one entry per target object carrying every field), or rename one of them.
75 changes: 75 additions & 0 deletions packages/objectql/src/engine-registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,67 @@ export interface RegistrationHost {
readonly unavailableDatasources: ObjectQL['unavailableDatasources'];
}

/**
* [#35228 ruling A, runtime arm A1] The one error line a package body owes when
* it carries two or more `objectExtensions` entries for one target: one line
* per (package, target), naming the target, the package and every entry's
* index. The registry keeps one extension of a target per package (the extend
* splice replaces the package's previous contribution, which a reload relies
* on), so only the last entry's fields register. The ruling keeps that outcome
* for a body built before authoring refused it — the line reports the loss and
* the fix, and the body is neither refused nor merged.
*
* Quiet when every entry for the target is EQUAL BY VALUE: then the last one
* registers exactly what each of the others declared, so nothing is lost and
* there is nothing to merge. That is the shape authoring accepts on purpose —
* one built sub-stack passed to a composition twice carries one entry object
* twice, and a build's serialisation turns the two references into two equal
* entries, so identity cannot tell them apart here and value is compared.
*/
function logSameTargetObjectExtensions(
logger: ObjectQL['logger'],
packageId: string,
extensions: readonly unknown[],
): void {
const indicesByTarget = new Map<string, number[]>();
for (const [i, ext] of extensions.entries()) {
const target = ext !== null && typeof ext === 'object' ? (ext as { extend?: unknown }).extend : undefined;
if (typeof target !== 'string' || !target) continue;
indicesByTarget.set(target, [...(indicesByTarget.get(target) ?? []), i]);
}
for (const [target, indices] of indicesByTarget) {
if (indices.length < 2) continue;
const first = extensions[indices[0]!];
if (indices.every((i) => equalByValue(extensions[i], first))) continue;
const positions = indices.map((i) => `objectExtensions[${i}]`);
const named = `${positions.slice(0, -1).join(', ')} and ${positions[positions.length - 1]}`;
logger.error(
`Package '${packageId}' declares ${indices.length} objectExtensions entries for object '${target}' ` +
`(${named}): one extension of an object registers per package, so only the last entry's fields ` +
`(${positions[positions.length - 1]}) are served and the fields of the others are missing, while the ` +
`package keeps loading. Merge them into a single objectExtensions entry for '${target}' and rebuild the package.`,
undefined,
{ package: packageId, target, entries: indices },
);
}
}

/** Structural equality of two JSON-shaped values: same primitives, same arrays in order, same keys with equal values. */
function equalByValue(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
if (Array.isArray(a)) {
const other = b as unknown[];
return a.length === other.length && a.every((value, i) => equalByValue(value, other[i]));
}
const left = a as Record<string, unknown>;
const right = b as Record<string, unknown>;
const keys = Object.keys(left).filter((key) => left[key] !== undefined);
const otherKeys = Object.keys(right).filter((key) => right[key] !== undefined);
return keys.length === otherKeys.length && keys.every((key) => equalByValue(left[key], right[key]));
}

/** The bodies of the "Package, app, plugin, driver and datasource registration" section of `ObjectQL`: a stateless facet, called by the class's stubs. */
export class RegistrationFacet {
/** The body of `ObjectQL#registerApp`; the method's docblock there is its contract. */
Expand Down Expand Up @@ -319,6 +380,20 @@ export class RegistrationFacet {
// 2b. Register object extensions (fields added to objects owned by other packages)
if (Array.isArray(manifest.objectExtensions) && manifest.objectExtensions.length > 0) {
this.logger.debug('Registering object extensions', { id, count: manifest.objectExtensions.length });
// [#35228 ruling A, runtime arm A1] One extension of a target per
// package: each entry below REPLACES the package's earlier
// contribution to its target (the registry's extend splice, which a
// reload depends on), so a body carrying two entries for one target
// registers only the last one's fields. Authoring refuses two
// DIFFERENT entries for one target in one package now (`stack.zod.ts`,
// the #22934 identity check at every door); a body built before that
// still loads, as the ruling keeps it, and says what it lost — at
// `error`, because the boot looks healthy while the earlier entries'
// fields are absent. Once per (package, target), and not for entries
// equal by value (one sub-stack composed twice, which authoring
// accepts): those lose nothing. Neither refused nor merged: the
// outcome is unchanged.
logSameTargetObjectExtensions(this.logger, id, manifest.objectExtensions);
for (const ext of manifest.objectExtensions) {
const targetFqn = ext.extend;
const priority = ext.priority ?? 200;
Expand Down
153 changes: 153 additions & 0 deletions packages/objectql/src/engine-same-target-object-extensions-log.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#35228 ruling A, runtime arm A1] A package body carrying two
* `objectExtensions` entries for one target — an artifact built before
* authoring refused that body — still loads with today's outcome (only the
* last entry's fields register), and the registration says so at `error`, once
* per (package, target), naming the target, the package and every entry.
*
* The ruling: 「推荐 A,已安装的包只记错误日志、照常启动。」 So the body is
* neither refused nor merged, and replace-on-reload is unchanged: one
* registration of a package still replaces that package's previous
* contribution to the target, which is what the reload pin below holds.
*
* Real engine, real `SchemaRegistry` — no doubles: what is pinned is what the
* registration seam serves.
*/
import { describe, it, expect } from 'vitest';
import { composeStacks, defineStack } from '@objectstack/spec';
import { ObjectQL } from './engine';

interface ErrorLine { msg: string; meta: Record<string, unknown> | undefined }

function engineRecordingErrors(): { engine: ObjectQL; errors: ErrorLine[] } {
const errors: ErrorLine[] = [];
const logger = {
debug() {}, info() {}, warn() {},
error: (msg: string, _error?: Error, meta?: Record<string, unknown>) => { errors.push({ msg, meta }); },
};
return { engine: new ObjectQL({ logger } as any), errors };
}

const OWNER = 'com.example.sales';
const EXTENDER = 'com.example.billing';
const TARGET = 'crm_line';

const owner = {
id: OWNER,
name: 'sales',
version: '1.0.0',
type: 'app',
namespace: 'crm',
objects: [{ name: TARGET, label: 'Line', fields: { title: { name: 'title', type: 'text', label: 'Title' } } }],
};

const extension = (field: string) => ({ extend: TARGET, fields: { [field]: { name: field, type: 'text', label: field } } });

const extender = (objectExtensions: unknown[]) => ({
id: EXTENDER,
name: 'billing',
version: '1.0.0',
type: 'module',
namespace: 'crm',
dependencies: { [OWNER]: '^1.0.0' },
objectExtensions,
});

const servedFields = (engine: ObjectQL): string[] => Object.keys(engine.getSchema(TARGET)?.fields ?? {}).sort();

const sameTargetLines = (errors: ErrorLine[]): ErrorLine[] =>
errors.filter((line) => line.msg.includes('objectExtensions entries for object'));

describe('[#35228 A1] two objectExtensions entries for one target in one package body', () => {
it('logs one error naming the target, the package and both entries, and keeps only the last entry\'s fields', () => {
const { engine, errors } = engineRecordingErrors();
engine.registerApp(owner);
engine.registerApp(extender([extension('cb_account'), extension('cb_other')]));

const lines = sameTargetLines(errors);
expect(lines).toHaveLength(1);
expect(lines[0]!.msg).toContain(`Package '${EXTENDER}'`);
expect(lines[0]!.msg).toContain(`object '${TARGET}'`);
expect(lines[0]!.msg).toContain('objectExtensions[0] and objectExtensions[1]');
expect(lines[0]!.msg).toContain(`Merge them into a single objectExtensions entry for '${TARGET}'`);
expect(lines[0]!.meta).toEqual({ package: EXTENDER, target: TARGET, entries: [0, 1] });

// Today's outcome, kept by the ruling: the last entry's field is served,
// the earlier entry's field is absent, and nothing was refused.
expect(servedFields(engine)).toContain('cb_other');
expect(servedFields(engine)).not.toContain('cb_account');
});

it('logs once per (package, target): three entries for one target and two for another are two lines', () => {
const { engine, errors } = engineRecordingErrors();
engine.registerApp({
...owner,
objects: [...owner.objects, { name: 'crm_note', label: 'Note', fields: { title: { name: 'title', type: 'text', label: 'Title' } } }],
});
const note = (field: string) => ({ extend: 'crm_note', fields: { [field]: { name: field, type: 'text', label: field } } });
engine.registerApp(extender([extension('a1'), note('n1'), extension('a2'), note('n2'), extension('a3')]));

const lines = sameTargetLines(errors);
expect(lines.map((line) => line.meta)).toEqual([
{ package: EXTENDER, target: TARGET, entries: [0, 2, 4] },
{ package: EXTENDER, target: 'crm_note', entries: [1, 3] },
]);
expect(lines[0]!.msg).toContain('objectExtensions[0], objectExtensions[2] and objectExtensions[4]');
});

it('CONTROL: one entry per target logs nothing', () => {
const { engine, errors } = engineRecordingErrors();
engine.registerApp(owner);
engine.registerApp(extender([extension('cb_account')]));
expect(sameTargetLines(errors)).toEqual([]);
expect(servedFields(engine)).toContain('cb_account');
});

it('CONTROL: two packages each extending one target is cross-package, served together, and logs nothing', () => {
const { engine, errors } = engineRecordingErrors();
engine.registerApp(owner);
engine.registerApp(extender([extension('cb_account')]));
engine.registerApp({ ...extender([extension('cb_other')]), id: 'com.example.ops', name: 'ops' });
expect(sameTargetLines(errors)).toEqual([]);
expect(servedFields(engine)).toEqual(expect.arrayContaining(['cb_account', 'cb_other']));
});

it('[review S3] the accepted twice-passed sub-stack composition, registered, logs no error — and neither does its built JSON', () => {
const sub = defineStack({ objectExtensions: [extension('cb_account')] } as never);
const manifestOnly = defineStack({ manifest: { id: EXTENDER, name: 'billing', version: '1.0.0', type: 'module', namespace: 'crm' } } as never);
const composed = composeStacks([manifestOnly, sub, sub]) as unknown as { objectExtensions: unknown[] };
expect(composed.objectExtensions, 'anti-vacuity: the composition carries the entry twice').toHaveLength(2);

for (const [label, objectExtensions] of [
['as composed (one object, two references)', composed.objectExtensions],
['as built (serialised: two equal objects)', JSON.parse(JSON.stringify(composed.objectExtensions))],
] as const) {
const { engine, errors } = engineRecordingErrors();
engine.registerApp(owner);
engine.registerApp(extender(objectExtensions as unknown[]));
expect(sameTargetLines(errors), label).toEqual([]);
expect(servedFields(engine), label).toContain('cb_account');
}
});

it('[review S3] equal entries beside one that differs still log, naming every entry', () => {
const { engine, errors } = engineRecordingErrors();
engine.registerApp(owner);
engine.registerApp(extender([extension('cb_account'), extension('cb_account'), extension('cb_other')]));
expect(sameTargetLines(errors).map((line) => line.meta)).toEqual([{ package: EXTENDER, target: TARGET, entries: [0, 1, 2] }]);
});

it('reload: re-registering the package with a renamed field serves the new name and not the old', () => {
const { engine, errors } = engineRecordingErrors();
engine.registerApp(owner);
engine.registerApp(extender([extension('cb_account')]));
expect(servedFields(engine)).toContain('cb_account');

engine.registerApp(extender([extension('cb_account2')]));
expect(servedFields(engine)).toContain('cb_account2');
expect(servedFields(engine)).not.toContain('cb_account');
expect(sameTargetLines(errors)).toEqual([]);
});
});
Loading
Loading