Skip to content

Commit 1a88a78

Browse files
committed
fix(runtime): the base export serves the base's own document while a .custom override of it is live
On a showcase-shaped boot the per-package layer lists only the override copy under the base's name (the metadata service holds the base's code documents too), so the override filter dropped the item from the base's export. Serve the base's code artifact in its place, and pin it on that boot shape. Claude-Session: https://claude.ai/code/session_01JQwxbac7S1AsbGi5a46PrB Co-authored-by: Claude <noreply@anthropic.com>
1 parent b391feb commit 1a88a78

3 files changed

Lines changed: 328 additions & 1 deletion

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
Clause-②: no
6+
Metadata-protocol: none
7+
8+
`GET /packages/<base>/export` carries the base's own document again while its `.custom` pair's override of a dashboard or report is live (ADR-0146 D8 item 3). On a boot that also holds the base's code documents in the metadata service, as every `defineStack` host does, the per-package layer listed only the override copy under the base's name, and the export's override filter (#29563) left the item out of the base's export. The export now serves the base's code artifact in that item's place, so the base's export is byte-identical with or without a published override, and still carries no `overrides` block.
Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#29649, ADR-0146 D8 item 3] "`GET /packages/hotcrm/export` carries the base
5+
* unchanged" while its `.custom` pair's override of an item is live — on a base
6+
* booted as the showcase boots, where the base's code documents are held twice:
7+
* by the registry (`ObjectQL.registerApp`) AND by the metadata service
8+
* (`MetadataPlugin`'s artifact door, which stamps each body with the base's
9+
* envelope before it stores it).
10+
*
11+
* That second holder is what the #29563 pin
12+
* (`packages-export-base-unchanged-per-type.integration.test.ts`) does not
13+
* register, and why it stayed green while a real showcase boot lost the item:
14+
* the per-package layer merges the registry's items over the metadata
15+
* service's, one per `(name, package)` slot, and the published override is
16+
* registered in the registry's bare slot wearing the base's envelope (#29600).
17+
* So the base's slot of the name holds the override alone, and the export's
18+
* "never an override of THIS package" filter (#29563) left nothing in it.
19+
* Measured on a real showcase boot at b391feb1: dashboards 3 → 2, reports
20+
* 4 → 3, views 36 → 36.
21+
*
22+
* Per type (view, dashboard, report), over the real door
23+
* (`HttpDispatcher.handlePackages`), the real protocol, the real `ObjectQL`
24+
* engine on a SQLite file and the real `MetadataManager`:
25+
*
26+
* - the base's export after the override is published is byte-identical to
27+
* the base's export before it, so the item is present and equal, and no
28+
* item in it carries an `overrides` block;
29+
* - the same holds on a restart over the same database;
30+
* - the pair's export carries the overriding item with its `overrides` block;
31+
* - CONTROL: the effective read of the base's name serves the override, so
32+
* the base export's answer is the export's own.
33+
*/
34+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
35+
import { mkdtempSync, rmSync } from 'node:fs';
36+
import { tmpdir } from 'node:os';
37+
import { join } from 'node:path';
38+
import { ObjectQL } from '@objectstack/objectql';
39+
import { SqlDriver } from '@objectstack/driver-sql';
40+
import { MetadataManager } from '@objectstack/metadata';
41+
import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes } from '@objectstack/metadata-protocol';
42+
import {
43+
SysMetadataAuditObject,
44+
SysMetadataCommitObject,
45+
SysMetadataHistoryObject,
46+
SysMetadataObject,
47+
} from '@objectstack/metadata-core';
48+
import { applyProtection } from '@objectstack/spec/shared';
49+
import { expandViewContainer } from '@objectstack/spec/ui';
50+
import { HttpDispatcher } from '../http-dispatcher.js';
51+
52+
const BASE = 'com.example.showcase';
53+
const BASE_VERSION = '0.1.0';
54+
const PAIR = 'com.example.showcase.custom';
55+
const PLATFORM_PKG = 'com.objectstack.platform';
56+
const DECLARATION = { package: BASE, basedOn: BASE_VERSION } as const;
57+
58+
const CALLER: any = {
59+
request: {},
60+
environmentId: 'platform',
61+
executionContext: { userId: 'u_admin', isSystem: false, systemPermissions: ['manage_metadata', 'studio.access'] },
62+
};
63+
64+
const OBJECT = 'showcase_task';
65+
const VIEW = `${OBJECT}.in_progress`;
66+
const DASHBOARD = 'showcase_ops_dashboard';
67+
const REPORT = 'showcase_hours_by_status';
68+
const OVERRIDE_LABEL = 'Edited label';
69+
70+
const COLUMNS = [{ field: 'title' }, { field: 'status' }];
71+
const viewContainer = () => ({
72+
object: OBJECT,
73+
list: { label: 'All Tasks', type: 'grid', data: { provider: 'object', object: OBJECT }, columns: COLUMNS },
74+
listViews: {
75+
in_progress: { label: 'In Progress', type: 'grid', data: { provider: 'object', object: OBJECT }, columns: COLUMNS },
76+
},
77+
});
78+
const dashboards = () => [
79+
{ name: 'showcase_chart_gallery', label: 'Chart Gallery', columns: 12, widgets: [] },
80+
{ name: DASHBOARD, label: 'Delivery Operations', columns: 12, widgets: [] },
81+
{ name: 'showcase_revenue_pulse', label: 'Revenue Pulse', columns: 12, widgets: [] },
82+
];
83+
const report = (name: string, label: string) => ({
84+
name,
85+
label,
86+
type: 'summary',
87+
dataset: 'showcase_task_metrics',
88+
rows: ['status'],
89+
values: ['task_count'],
90+
});
91+
const reports = () => [
92+
report(REPORT, 'Hours by Status'),
93+
report('showcase_task_overview', 'Task Overview'),
94+
];
95+
96+
const TYPES = [
97+
{ type: 'view', plural: 'viewItems', name: VIEW },
98+
{ type: 'dashboard', plural: 'dashboards', name: DASHBOARD },
99+
{ type: 'report', plural: 'reports', name: REPORT },
100+
] as const;
101+
102+
/** The base's body, as the showcase's `defineStack` carries it: one fresh copy per reader. */
103+
function baseBody(): Record<string, any> {
104+
return {
105+
id: BASE,
106+
name: 'showcase',
107+
version: BASE_VERSION,
108+
namespace: 'showcase',
109+
objects: [{
110+
name: OBJECT,
111+
label: 'Task',
112+
sharingModel: 'private',
113+
fields: {
114+
title: { name: 'title', label: 'Title', type: 'text' },
115+
status: { name: 'status', label: 'Status', type: 'text' },
116+
},
117+
}],
118+
datasets: [{
119+
name: 'showcase_task_metrics',
120+
label: 'Task Metrics',
121+
object: OBJECT,
122+
dimensions: [{ name: 'status', label: 'Status', field: 'status', type: 'string' }],
123+
measures: [{ name: 'task_count', label: 'Tasks', aggregate: 'count' }],
124+
}],
125+
views: [viewContainer()],
126+
dashboards: dashboards(),
127+
reports: reports(),
128+
};
129+
}
130+
131+
/**
132+
* The metadata service's copy of the base's documents, stored as
133+
* `MetadataPlugin`'s artifact door stores them: each body stamped with the
134+
* base's envelope (`applyProtection`), a view container under its object and
135+
* each view it expands to under its own name.
136+
*/
137+
async function metadataServiceOf(): Promise<MetadataManager> {
138+
const manager = new MetadataManager({ formats: ['json'], loaders: [] });
139+
const body = baseBody();
140+
const stamp = <T extends Record<string, any>>(item: T): T =>
141+
applyProtection(item as any, { packageId: BASE, packageVersion: BASE_VERSION }) as T;
142+
for (const container of body.views) {
143+
await manager.register('view', OBJECT, stamp(container), { notify: false });
144+
for (const view of expandViewContainer(OBJECT, container)) {
145+
await manager.register('view', view.name, stamp(view as any), { notify: false });
146+
}
147+
}
148+
for (const dashboard of body.dashboards) await manager.register('dashboard', dashboard.name, stamp(dashboard), { notify: false });
149+
for (const item of body.reports) await manager.register('report', item.name, stamp(item), { notify: false });
150+
return manager;
151+
}
152+
153+
let cleanup: Array<() => void | Promise<void>> = [];
154+
afterEach(async () => {
155+
for (const c of cleanup.reverse()) await c();
156+
cleanup = [];
157+
});
158+
159+
const envSnapshot = { OS_HOME: process.env.OS_HOME, OS_METADATA_WRITABLE: process.env.OS_METADATA_WRITABLE };
160+
let home: string;
161+
beforeAll(() => {
162+
home = mkdtempSync(join(tmpdir(), 'os-29649-home-'));
163+
process.env.OS_HOME = home;
164+
});
165+
afterAll(() => {
166+
for (const [k, v] of Object.entries(envSnapshot)) {
167+
if (v === undefined) delete process.env[k];
168+
else process.env[k] = v;
169+
}
170+
rmSync(home, { recursive: true, force: true });
171+
});
172+
beforeEach(() => {
173+
delete process.env.OS_METADATA_WRITABLE;
174+
ObjectStackProtocolImplementation.resetEnvWritableCache();
175+
resetEnvWritableMetadataTypes();
176+
vi.spyOn(console, 'warn').mockImplementation(() => {});
177+
});
178+
afterEach(() => { vi.restoreAllMocks(); });
179+
180+
/** One boot over the SQLite file in `dir`; the pair is installed on the first boot only. */
181+
async function boot(dir: string, { installPair }: { installPair: boolean }) {
182+
const driver = new SqlDriver({
183+
client: 'better-sqlite3',
184+
connection: { filename: join(dir, 'data.sqlite') },
185+
useNullAsDefault: true,
186+
});
187+
const objects = [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject] as any[];
188+
await driver.initObjects(objects);
189+
190+
const engine = new ObjectQL();
191+
engine.registerDriver(driver as any, true);
192+
await engine.init();
193+
for (const o of objects) engine.registry.registerObject(o, PLATFORM_PKG);
194+
cleanup.push(() => engine.destroy());
195+
engine.registerApp(baseBody());
196+
197+
const services = new Map<string, unknown>([['objectql', engine], ['metadata', await metadataServiceOf()]]);
198+
const protocol: any = new ObjectStackProtocolImplementation(engine as any, () => services as any);
199+
services.set('protocol', protocol);
200+
const get = (name: string) => services.get(name) ?? null;
201+
const dispatcher = new HttpDispatcher({ context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) } as any);
202+
203+
if (installPair) {
204+
await protocol.installPackage({
205+
manifest: {
206+
id: PAIR, name: 'showcase-custom', version: '0.1.0', type: 'app',
207+
namespace: 'showcase_custom', dependencies: { [BASE]: '^0' },
208+
},
209+
});
210+
}
211+
212+
return {
213+
protocol,
214+
async exported(id: string): Promise<Record<string, any>> {
215+
const res = await dispatcher.handlePackages(`/${encodeURIComponent(id)}/export`, 'GET', undefined, {}, CALLER);
216+
expect(res.response?.status, JSON.stringify(res.response?.body)).toBe(200);
217+
const body: any = JSON.parse(JSON.stringify(res.response?.body ?? null));
218+
return body?.data ?? body;
219+
},
220+
async override(type: string, name: string, item: Record<string, unknown>) {
221+
const saved = await protocol.saveMetaItem({ type, name, item, mode: 'draft', packageId: PAIR });
222+
expect(saved?.success, `the ${type} draft save`).toBe(true);
223+
await protocol.publishMetaItem({ type, name, packageId: PAIR });
224+
},
225+
};
226+
}
227+
228+
const itemsOf = (manifest: Record<string, any>, plural: string, name: string): any[] =>
229+
(manifest[plural] ?? []).filter((item: any) => item?.name === name);
230+
231+
/** Every exported item, across the collections, that carries an `overrides` block. */
232+
const overridingItems = (manifest: Record<string, any>): string[] => Object.entries(manifest)
233+
.filter(([, value]) => Array.isArray(value))
234+
.flatMap(([plural, value]) => (value as any[])
235+
.filter((item) => item && typeof item === 'object' && 'overrides' in item)
236+
.map((item) => `${plural}/${item.name}`));
237+
238+
describe('[#29649] GET /packages/<base>/export carries the base unchanged on a showcase-shaped boot', () => {
239+
for (const { type, plural, name } of TYPES) {
240+
it(`${type}: the base's export is byte-identical with the override published, and after a restart`, async () => {
241+
const dir = mkdtempSync(join(tmpdir(), 'os-29649-db-'));
242+
cleanup.push(() => rmSync(dir, { recursive: true, force: true }));
243+
244+
const door = await boot(dir, { installPair: true });
245+
const before = await door.exported(BASE);
246+
const shipped = itemsOf(before, plural, name);
247+
expect(shipped, `the base's ${type} before the override`).toHaveLength(1);
248+
249+
await door.override(type, name, { ...shipped[0], label: OVERRIDE_LABEL, overrides: { ...DECLARATION } });
250+
251+
// CONTROL: the effective read of the base's name serves the published override.
252+
const effective: any = await door.protocol.getMetaItem({ type, name, packageId: BASE });
253+
expect(effective?.item?.label, `the effective ${type} read`).toBe(OVERRIDE_LABEL);
254+
255+
const after = await door.exported(BASE);
256+
expect(itemsOf(after, plural, name), `the base's ${type} with the override live`).toEqual(shipped);
257+
expect(overridingItems(after), `the base's export carries no override`).toEqual([]);
258+
expect(JSON.stringify(after), `the base's whole export with the ${type} override live`).toBe(JSON.stringify(before));
259+
260+
const pair = itemsOf(await door.exported(PAIR), plural, name);
261+
expect(pair.map((item) => item.label), `the pair's ${type} export`).toEqual([OVERRIDE_LABEL]);
262+
expect(pair[0].overrides).toEqual(DECLARATION);
263+
264+
// A restart over the same database: the published row is hydrated from storage.
265+
const restarted = await boot(dir, { installPair: false });
266+
expect(JSON.stringify(await restarted.exported(BASE)), `the base's whole export after a restart`).toBe(JSON.stringify(before));
267+
});
268+
}
269+
});

‎packages/runtime/src/domains/packages.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3342,6 +3342,42 @@ function declaresOverrideOf(item: unknown, packageId: string): boolean {
33423342
&& (overrides as { package?: unknown }).package === packageId;
33433343
}
33443344

3345+
/**
3346+
* [#29563, #29649, ADR-0146 D8 item 3] A package's own documents of one type,
3347+
* out of its per-package layer `items`: an item that declares it overrides
3348+
* `packageId` ({@link declaresOverrideOf}) is the package's `.custom` pair's
3349+
* override, never one of the package's documents, so it is replaced, in its
3350+
* place, by the package's own code artifact of the name when the layer lists
3351+
* none beside it, and dropped otherwise. The artifact is the registry's
3352+
* prefer-local answer for the package (`getArtifactItem`), kept only when it is
3353+
* the package's own (`_packageId`) and declares no override itself.
3354+
*/
3355+
function ownDocumentsOf(items: any[], type: string, packageId: string, registry: any): any[] {
3356+
const own = new Set(items
3357+
.filter((it) => !declaresOverrideOf(it, packageId))
3358+
.map((it) => (it as { name?: unknown } | null)?.name));
3359+
const out: any[] = [];
3360+
for (const it of items) {
3361+
if (!declaresOverrideOf(it, packageId)) {
3362+
out.push(it);
3363+
continue;
3364+
}
3365+
const name = (it as { name?: unknown } | null)?.name;
3366+
if (typeof name !== 'string' || own.has(name)) continue;
3367+
let artifact: unknown;
3368+
try {
3369+
artifact = registry?.getArtifactItem?.(type, name, packageId);
3370+
} catch {
3371+
artifact = undefined;
3372+
}
3373+
if ((artifact as { _packageId?: unknown } | null | undefined)?._packageId !== packageId) continue;
3374+
if (declaresOverrideOf(artifact, packageId)) continue;
3375+
own.add(name);
3376+
out.push(artifact);
3377+
}
3378+
return out;
3379+
}
3380+
33453381
async function assemblePackageManifest(
33463382
deps: DomainHandlerDeps,
33473383
packageId: string,
@@ -3420,7 +3456,21 @@ context: HttpProtocolContext,
34203456
// the base's export carried both, the second with the edited label and
34213457
// the `overrides` block. A protocol with no per-package layer is read
34223458
// as before.
3423-
if (perPackageLayer) items = items.filter((it) => !declaresOverrideOf(it, packageId));
3459+
//
3460+
// [#29649] …and the package's own document is served in its place: the
3461+
// override copy is not always listed BESIDE the base's item. On a boot
3462+
// that also holds the base's code documents in the metadata service
3463+
// (`MetadataPlugin`'s artifact door, as every `defineStack` host does),
3464+
// the layer merges the registry's items over the service's, one per
3465+
// `(name, package)` slot, so the copy wearing the base's envelope takes
3466+
// the base's slot and the base's own item is not listed at all.
3467+
// Measured on a real showcase boot: a published dashboard or report
3468+
// override left the base's export without the item. The package's own
3469+
// document is its code artifact, read prefer-local from the registry
3470+
// (`getArtifactItem` with the package's id: the composite slot
3471+
// `registerApp` filled, which the bare-slot copy never reaches), the
3472+
// same body the layer serves for the name while no override is live.
3473+
if (perPackageLayer) items = ownDocumentsOf(items, singular, packageId, registry);
34243474
if (items.length === 0) continue;
34253475
// [#5320] `views` is partitioned rather than dumped: the registry's
34263476
// ADR-0017 dual-read returns the container AND its expanded per-view

0 commit comments

Comments
 (0)