Skip to content

Commit 857941d

Browse files
fix(cloud-connection): install-local seeds a composed bundle's package datasets on install, reseed, upgrade and restart (#34403)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XHBgb29oZuAnPqZyY6nR8UE)_ Fixes #34336 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:install-local 的所有样例数据入口(安装、重新灌入、升级、重启自愈、清除、计数、已装应用列表)改为同一个读法,组合包(`packages[]`)每个子包里的 seed 数据都能读到。 - **为什么改**:HotCRM 6.2 起发布的是组合包,没有顶层 `data`,托管租户装上后 订单与回款、项目交付 等模块一条演示数据都没有。 - **风险与回滚**:低。单包(平铺)读法不变,已有对照测试钉住;回滚即 revert 本 PR。 - **先看**:`packages/cloud-connection/src/marketplace-install-local-plugin.ts` 的 `seedDatasetsOf` 与 `applySideEffects` 第 2 步;`marketplace-install-local-composed-bundle-seeds.test.ts`。 - **两分钟验证**:`pnpm --filter @objectstack/cloud-connection exec vitest run src/marketplace-install-local-composed-bundle-seeds.test.ts`,预期 9/9 通过。 - **需要你做的**:无,席位落地。卡上第 2 条(升级时把新增 seed 补进所有已有组织)是新产品行为,未实现,见下方 Acceptance notes,待决定。 ## What changes Every seed door of `MarketplaceInstallLocalPlugin` read the top-level `data` only. A composed bundle (`dist/objectstack.json` with `packages[]`, ADR-0130 D4) has no top-level `data`, so all of them answered as if the package had no sample data. They now share one reader, `seedDatasetsOf(body)`, which is `resolveStackCollection(body, 'data')` from `@objectstack/core` filtered to datasets that name an object and carry records. It reads the top-level `data` when the body has one. Otherwise it reads every package body's `data`, in the artifact's package order (dependency order, the order the packages register in). | Seed door | Before (composed bundle) | After | |:--|:--|:--| | install, `POST install-local` (`applySideEffects` step 2 + 3) | `seeded: skipped / no-datasets`, nothing shared | every package body seeded, merged into `seed-datasets` | | upgrade (re-install of a newer version) | same as install | incoming version's datasets seeded into the caller's organization (single-tenant: the database), a package the upgrade adds included | | reseed, `POST …/reseed-sample-data` | `400 RESEED_SKIPPED no-datasets` | seeds every package body | | restart rehydrate (`applySideEffects` with `seedNow: false`) | nothing merged for the per-organization replay | merged, so a new organization gets them | | restart heal (`maybeHealSampleData`) | nothing to heal | heals an empty single-tenant database | | purge, `POST …/purge-sample-data` | `400 NOTHING_TO_PURGE` | matches every package body's rows | | count, `GET …/sample-data` | `count: 0` | counts every package body's rows | | listing `withSampleData` | `false` | read from every package body | The unmanaged copy (`installMode: 'unmanaged'`) is unchanged: its import refuses a multi-package artifact by name, and its doors read the seed receipt, not the body. A malformed `packages` gets the resolver's ADR-0112 refusal, the same one the `manifest` service raises on those bytes. `applySideEffects` reports it in `seeded` (`seed-datasets-unread: …`) and does not throw, as its contract says. The listing answers `withSampleData: false` for that entry and logs it at `warn`. The heal logs it and skips. ## Tests New file `packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts`, 9 cases. The composed fixture lists the order module before the core module it depends on, so package order is not array order: - install: the loader gets `[core, o2c]`, and `seed-datasets` gets the same list; - reseed, count, purge, listing: each door is handed `[core, o2c]`; - upgrade 6.3.0 to 6.4.0 adding a PSA package: the loader gets all three, core first; - restart: `seed-datasets` is refilled and the heal seeds `[core, o2c]`; - controls: a flat bundle reads its top-level `data` unchanged; a composed artifact that still carries a flattened top-level `data` reads it once, not again per package; a composed artifact with no datasets still answers `no-datasets`. <details><summary>Red on the base plugin source, green on the fix (HEAD f54ec13)</summary> Red leg: `marketplace-install-local-plugin.ts` restored from `719b6b537` (base), the new test run, then restored with `git checkout HEAD --` and the blob hash checked against HEAD. ``` × install seeds every package body's datasets … (expected { mode: 'skipped', …(1) } to match object { mode: 'inline', inserted: 3 }) × reseed loads them again ({"code":"RESEED_SKIPPED","message":"Reseed did not run: no-datasets"}: expected 400 to be 200) × an upgrade that adds a package seeds the incoming version's datasets … × the sample-data count and the purge match the rows of every package body × the installed-apps listing reads the package's sample data from every package body × a restart shares them for new organizations and heals an empty database from them Tests 6 failed | 3 passed (9) ``` Green leg: `Tests 9 passed (9)`. Package: `pnpm --filter @objectstack/cloud-connection typecheck` (both `tsc --noEmit` programs) and `vitest run`: `Test Files 84 passed (84)`, `Tests 1236 passed (1236)`. </details> ## Acceptance notes - **Card ask 2 is not built.** The card says an upgrade replays new seed keys into existing organizations, and that `sys_seed_landed_key` already keeps a deleted row from coming back. Measured on this door, for a flat bundle as well as a composed one: - an upgrade seeds only the organization the request acts in (or the single-tenant database). No code path replays an upgrade's seed into other existing organizations. The per-organization replayer runs only when a `sys_organization` row is inserted; - `runInlineSeed` builds `SeedLoaderService` with no `landedKeys` option, so this door neither reads nor writes `sys_seed_landed_key`. On this door a row a tenant deleted comes back on reinstall or reseed (create-only `ignore` default). So ask 2 would be new behaviour, not a fix. After this PR a composed upgrade does what a flat upgrade does: a package the upgrade adds gets its rows in the upgrading organization. The question is open on the card. - **Same family, not changed here:** `applySideEffects` step 1 reads `translations` from the top level only. Measured on a scratch run: a composed bundle with a package-body `translations` answers `translationsLoaded: 0`, and the same translations on a flat bundle answer `1`. The ADR-0120 D5e global-unique gate (`evaluateGlobalUniqueGate`) also reads `manifest.objects` from the top level only. That one is read from the code, not measured. Both are reported to the seat. - The seed locale's last fallback (`appDefaultSeedLocale`) still reads the composed artifact's top-level `i18n`, the same as `AppPlugin.resolveSeedLocale` does for a boot bundle. That is unchanged. ## Verification <details><summary>Local gates (HEAD f54ec13)</summary> - `node scripts/pm/dispatch-gates.mjs --commands`: 71 families derived. All 71 were run. Reconciliation with `--ran` and recorded exit codes: `71 derived famil(ies) accounted for — 70 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3)`. - 70 passed with exit 0. Among them: `check:type-check-debt` (`0 raw tsc error(s) total`), `check:durability-log-level`, `check:startup-registry-verdict`, `check:test-source-alias`, `check:nul-bytes`, `check:route-envelope`. - `pnpm check:dual-build-cjs-loads`: exit 3, PREREQUISITE NOT MET (it needs a full workspace build). NOT MEASURED locally; CI runs it. - Before push, a `git merge-tree` against the one open PR that touches `marketplace-install-local-plugin.ts` (#34316, `claude/area-A5-33922`) produced no conflict. </details> ## Fix round 2 (head `543a53e54b`) - Merged `origin/main` (`9e67ea6cf4`, no conflicts; none of the 17 incoming commits touches `packages/cloud-connection`). - L1 Should (6918284604): the purge (`POST …/purge-sample-data`) and the sample-data count (`GET …/sample-data`) now read a ledger entry's seed datasets through `ledgerSeedDatasets`. A body the resolver refuses (a malformed `packages`, ADR-0112 `INVALID_ARTIFACT_PACKAGES`) now gets the unreadable-entry answer the reseed already gives (500 `MARKETPLACE_STORAGE_FAILED`, naming the ledger file and quoting the refusal) instead of a throw into the route's error path. No row is matched or deleted. `LocalManifestSource.fileNameOf` names the file by the existing `safeFilename` rule. - Pins: two new cases in `marketplace-install-local-composed-bundle-seeds.test.ts`, red on `f54ec13b` (2 failed, thrown refusal), green at head (11/11). - Package: typecheck clean, 84 files / 1238 tests passed. Local gates: 72 derived, 71 exit 0, `check:dual-build-cjs-loads` not measured (exit 3, needs a full build; CI runs it). - CI on `543a53e54b`: 35 success, 16 skipped, 0 failure. Dev report 6920915310 on #34336. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pHNFS9mn8hS13iGyL)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5pHNFS9mn8hS13iGyL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fa9d695 commit 857941d

4 files changed

Lines changed: 443 additions & 20 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/cloud-connection': patch
3+
---
4+
5+
fix(cloud-connection): install-local seeds a composed bundle's package datasets on install, reseed, upgrade and restart
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A composed bundle (`dist/objectstack.json` with `packages[]`, the ADR-0130 D4 publish shape) carries its seed datasets inside each package body and has no top-level `data`. Every seed door of `MarketplaceInstallLocalPlugin` read the top-level `data` only, so such a bundle installed with no sample data: the install, the reseed and an upgrade reported `seeded: { mode: 'skipped', reason: 'no-datasets' }`, nothing was shared for the per-organization replay of new organizations, the restart heal had nothing to seed, the purge answered `NOTHING_TO_PURGE`, the sample-data count answered `0`, and the installed-apps listing answered `withSampleData: false`.
11+
12+
Every one of those doors now reads the seed datasets through `resolveStackCollection(body, 'data')` from `@objectstack/core`: the top-level `data` when the body carries one, otherwise each package body's, in the artifact's package order (the dependency order the packages register in). A flat bundle, and a composed artifact that still carries its flattened top-level `data`, read exactly that list, once, as before.
13+
14+
An upgrade seeds the incoming version's datasets into the organization the request acts in (or the single-tenant database), the same as a flat bundle's upgrade, so a package an upgrade adds gets its sample rows there. Organizations other than the caller's are not reseeded by an upgrade, for a flat bundle or a composed one.

‎packages/cloud-connection/src/local-manifest-source.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,16 @@ export class LocalManifestSource {
436436
}
437437
}
438438

439+
/**
440+
* [#34336] The basename of this manifest id's ledger file, as it sits on
441+
* disk (`SkippedManifestEntry.file`'s spelling) — for a caller that read the
442+
* entry and then found its body unusable, so the answer names the file to
443+
* repair the same way a failed read does.
444+
*/
445+
fileNameOf(manifestId: string): string {
446+
return safeFilename(manifestId);
447+
}
448+
439449
/** Whether the ledger holds an entry for this manifest id. */
440450
has(manifestId: string): boolean {
441451
return existsSync(this.fileFor(manifestId));
Lines changed: 320 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,320 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#34336, ADR-0130 D4] The seed datasets of a COMPOSED bundle reach every
5+
* seed door of install-local.
6+
*
7+
* A multi-package `dist/objectstack.json` carries `packages[]`, one assembled
8+
* body per package, and no flattened `data` beside it: the seed datasets sit
9+
* in each package body. Every door of this plugin that reads seed datasets
10+
* read the top-level `data` alone, so a composed bundle installed, reseeded,
11+
* upgraded, purged, counted and rehydrated as a package with no sample data
12+
* ("no-datasets"). Each door now reads them through one reader,
13+
* `resolveStackCollection(body, 'data')`: the top-level list when the body
14+
* carries one, otherwise every package body's, in the artifact's package
15+
* order (dependency-topological, the order the packages register in).
16+
*
17+
* The flat-bundle control pins that a body with a top-level `data` reads
18+
* exactly that list, and the composed control that a composed artifact which
19+
* still carries a flattened top-level `data` reads it once, never twice.
20+
*/
21+
22+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
23+
import { mkdtempSync, rmSync } from 'node:fs';
24+
import { join } from 'node:path';
25+
import { tmpdir } from 'node:os';
26+
27+
/** Every request the (mocked) seed loader was handed, in order. */
28+
let loadCalls: any[] = [];
29+
let seedResult: any;
30+
31+
vi.mock('@objectstack/runtime', () => ({
32+
SeedLoaderService: class {
33+
async load(request: any) { loadCalls.push(request); return seedResult; }
34+
async buildDependencyGraph(objects: string[]) { return { objects }; }
35+
},
36+
// The locale is not this suite's subject (marketplace-install-local-seed-replayer.test.ts pins it).
37+
resolveSeedLocaleForLoad: async () => undefined,
38+
appDefaultSeedLocale: () => undefined,
39+
describeSeedLocale: () => 'none',
40+
}));
41+
// Only the seed-request parse is stubbed; every other export stays the real one.
42+
vi.mock('@objectstack/spec/data', async (importOriginal) => ({
43+
...(await importOriginal<typeof import('@objectstack/spec/data')>()),
44+
SeedLoaderRequestSchema: { parse: (x: any) => x },
45+
}));
46+
// The purge, the count and the listing's row match: what each door was handed.
47+
const purgeCalls: any[] = [];
48+
const countCalls: any[] = [];
49+
const matchCalls: any[] = [];
50+
vi.mock('./marketplace-install-local-purge.js', async (importOriginal) => ({
51+
...(await importOriginal<typeof import('./marketplace-install-local-purge.js')>()),
52+
purgeSeedRows: async (args: any) => { purgeCalls.push(args); return { deleted: 1, skipped: 0, errors: [] }; },
53+
countSeedRows: async (args: any) => { countCalls.push(args); return { count: 1, unidentified: 0 }; },
54+
matchSeedRows: async (args: any) => { matchCalls.push(args); return { rows: [{ id: 'r1' }] }; },
55+
}));
56+
57+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
58+
import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
59+
import { LocalManifestSource } from './local-manifest-source.js';
60+
61+
type Handler = (c: any) => Promise<any>;
62+
63+
const ROUTE = '/api/v1/marketplace/install-local';
64+
const SUITE = 'com.example.suite';
65+
66+
const CORE_DATA = { object: 'crm_account', records: [{ name: '华东客户' }, { name: '华南客户' }] };
67+
const O2C_DATA = { object: 'crm_order', records: [{ name: 'SO-0001' }] };
68+
const PSA_DATA = { object: 'crm_project', records: [{ name: 'PRJ-0001' }] };
69+
70+
const body = (id: string, version: string, object: string, data: unknown, dependencies?: Record<string, string>) => ({
71+
manifest: {
72+
id,
73+
name: id,
74+
version,
75+
type: 'module',
76+
...(dependencies ? { dependencies } : {}),
77+
objects: [{ name: object, label: object, fields: { name: { type: 'text', label: 'Name' } } }],
78+
data: [data],
79+
},
80+
});
81+
82+
/**
83+
* A composed artifact: `packages[]` and no top-level `data`. The order module
84+
* is listed FIRST and depends on the core one, so the artifact's package order
85+
* (core, then orders) is not its array order.
86+
*/
87+
const composed = (version: string, withPsa = false) => ({
88+
id: SUITE,
89+
name: 'Suite',
90+
version,
91+
type: 'app',
92+
packages: [
93+
body(`${SUITE}.o2c`, version, 'crm_order', O2C_DATA, { [`${SUITE}.core`]: '*' }),
94+
body(`${SUITE}.core`, version, 'crm_account', CORE_DATA),
95+
...(withPsa ? [body(`${SUITE}.psa`, version, 'crm_project', PSA_DATA, { [`${SUITE}.core`]: '*' })] : []),
96+
],
97+
});
98+
99+
const FLAT = {
100+
id: 'com.example.flat',
101+
version: '1.0.0',
102+
objects: [{ name: 'crm_account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }],
103+
data: [CORE_DATA],
104+
};
105+
106+
/** What a dataset list comes to, by object and record names: the reader's answer, not the parse's defaults. */
107+
const shape = (datasets: any[] | undefined) =>
108+
(datasets ?? []).map((d: any) => `${d.object}:${(d.records ?? []).map((r: any) => r.name).join('|')}`);
109+
const CORE = shape([CORE_DATA])[0];
110+
const O2C = shape([O2C_DATA])[0];
111+
const PSA = shape([PSA_DATA])[0];
112+
113+
function makeRawApp() {
114+
const routes = new Map<string, Handler>();
115+
return {
116+
routes,
117+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
118+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
119+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
120+
};
121+
}
122+
123+
function makeC(reqBody: any, manifestId?: string) {
124+
const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 }));
125+
return {
126+
req: {
127+
url: `http://localhost:3000${ROUTE}`,
128+
raw: new Request(`http://localhost:3000${ROUTE}`),
129+
json: async () => reqBody,
130+
param: (k: string) => (k === 'manifestId' ? manifestId : undefined),
131+
header: () => undefined,
132+
query: () => undefined,
133+
},
134+
json,
135+
};
136+
}
137+
138+
/** One runtime over the ledger directory: a fresh plugin, booted through `kernel:ready`. */
139+
async function boot(dir: string) {
140+
const rawApp = makeRawApp();
141+
const hooks = new Map<string, any>();
142+
const services: Record<string, any> = {
143+
manifest: { register: vi.fn() },
144+
auth: installerAuthService(),
145+
objectql: withInstallerGrants({ syncSchemas: async () => undefined }),
146+
metadata: {},
147+
};
148+
const ctx = {
149+
hook: (e: string, h: any) => hooks.set(e, h),
150+
getService: (name: string) => {
151+
if (name === 'http-server') return { getRawApp: () => rawApp };
152+
const svc = services[name];
153+
if (svc === undefined) throw new Error(`no ${name}`);
154+
return svc;
155+
},
156+
registerService: (name: string, svc: unknown) => { services[name] = svc; },
157+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
158+
};
159+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
160+
await plugin.start(ctx as any);
161+
await hooks.get('kernel:ready')?.();
162+
const route = (key: string) => rawApp.routes.get(key)!;
163+
return {
164+
install: (manifest: unknown) => route(`POST ${ROUTE}`)(makeC({ manifest })),
165+
reseed: (id: string) => route(`POST ${ROUTE}/:manifestId/reseed-sample-data`)(makeC({}, id)),
166+
purge: (id: string) => route(`POST ${ROUTE}/:manifestId/purge-sample-data`)(makeC({}, id)),
167+
count: (id: string) => route(`GET ${ROUTE}/:manifestId/sample-data`)(makeC({}, id)),
168+
list: () => route(`GET ${ROUTE}`)(makeC({})),
169+
/** The kernel's shared `seed-datasets` list — what the per-organization replay seeds a new organization from. */
170+
sharedSeedDatasets: () => services['seed-datasets'] as any[] | undefined,
171+
};
172+
}
173+
174+
let dir: string;
175+
beforeEach(() => {
176+
dir = mkdtempSync(join(tmpdir(), 'mil-composed-seeds-'));
177+
loadCalls = [];
178+
purgeCalls.length = 0;
179+
countCalls.length = 0;
180+
matchCalls.length = 0;
181+
seedResult = { summary: { totalInserted: 3, totalUpdated: 0, totalSkipped: 0 }, errors: [] };
182+
});
183+
afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); });
184+
185+
describe('a composed bundle: every seed door reads each package body, in package order', () => {
186+
it('install seeds every package body\'s datasets, core before the module that depends on it, and shares them for new organizations', async () => {
187+
const rt = await boot(dir);
188+
const res = await rt.install(composed('6.3.0'));
189+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
190+
expect(res.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 3 });
191+
expect(loadCalls).toHaveLength(1);
192+
expect(shape(loadCalls[0].seeds)).toEqual([CORE, O2C]);
193+
expect(shape(rt.sharedSeedDatasets())).toEqual([CORE, O2C]);
194+
});
195+
196+
it('reseed loads them again', async () => {
197+
const rt = await boot(dir);
198+
expect((await rt.install(composed('6.3.0'))).status).toBe(200);
199+
loadCalls = [];
200+
const res = await rt.reseed(SUITE);
201+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
202+
expect(res.payload.data).toMatchObject({ manifestId: SUITE, inserted: 3, withSampleData: true });
203+
expect(shape(loadCalls[0].seeds)).toEqual([CORE, O2C]);
204+
});
205+
206+
it('an upgrade that adds a package seeds the incoming version\'s datasets, the added package\'s included', async () => {
207+
const rt = await boot(dir);
208+
expect((await rt.install(composed('6.3.0'))).status).toBe(200);
209+
loadCalls = [];
210+
const res = await rt.install(composed('6.4.0', true));
211+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
212+
expect(res.payload.data.upgradedFrom).toBe('previous-marketplace-version');
213+
expect(shape(loadCalls[0].seeds)).toEqual(expect.arrayContaining([CORE, O2C, PSA]));
214+
expect(shape(loadCalls[0].seeds)).toHaveLength(3);
215+
// Package order: the core body before both modules that depend on it.
216+
expect(shape(loadCalls[0].seeds)[0]).toBe(CORE);
217+
});
218+
219+
it('the sample-data count and the purge match the rows of every package body', async () => {
220+
const rt = await boot(dir);
221+
expect((await rt.install(composed('6.3.0'))).status).toBe(200);
222+
223+
const counted = await rt.count(SUITE);
224+
expect(counted.status, JSON.stringify(counted.payload)).toBe(200);
225+
expect(counted.payload.data).toEqual({ manifestId: SUITE, count: 1, unidentified: 0 });
226+
expect(shape(countCalls[0].datasets)).toEqual([CORE, O2C]);
227+
228+
const purged = await rt.purge(SUITE);
229+
expect(purged.status, JSON.stringify(purged.payload)).toBe(200);
230+
expect(shape(purgeCalls[0].datasets)).toEqual([CORE, O2C]);
231+
});
232+
233+
it('the installed-apps listing reads the package\'s sample data from every package body', async () => {
234+
const rt = await boot(dir);
235+
expect((await rt.install(composed('6.3.0'))).status).toBe(200);
236+
const res = await rt.list();
237+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
238+
const entry = res.payload.data.items.find((e: any) => e.manifestId === SUITE);
239+
expect(shape(matchCalls[0]?.datasets)).toEqual([CORE, O2C]);
240+
expect(entry?.withSampleData).toBe(true);
241+
});
242+
243+
it('a restart shares them for new organizations and heals an empty database from them', async () => {
244+
const first = await boot(dir);
245+
expect((await first.install(composed('6.3.0'))).status).toBe(200);
246+
loadCalls = [];
247+
248+
const restarted = await boot(dir);
249+
expect(shape(restarted.sharedSeedDatasets())).toEqual([CORE, O2C]);
250+
// Single-tenant, every seeded object empty: the heal seeds the package bodies.
251+
expect(loadCalls).toHaveLength(1);
252+
expect(shape(loadCalls[0].seeds)).toEqual([CORE, O2C]);
253+
});
254+
});
255+
256+
describe('controls: a body that carries a top-level data reads that list, once', () => {
257+
it('a flat bundle seeds its top-level data, unchanged', async () => {
258+
const rt = await boot(dir);
259+
const res = await rt.install(FLAT);
260+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
261+
expect(shape(loadCalls[0].seeds)).toEqual([CORE]);
262+
expect(shape(rt.sharedSeedDatasets())).toEqual([CORE]);
263+
});
264+
265+
it('a composed artifact that still carries its flattened top-level data seeds that union once, never per package as well', async () => {
266+
const rt = await boot(dir);
267+
const res = await rt.install({ ...composed('6.3.0'), data: [CORE_DATA, O2C_DATA] });
268+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
269+
expect(shape(loadCalls[0].seeds)).toEqual([CORE, O2C]);
270+
});
271+
272+
it('a composed artifact with no dataset in any package body still answers no-datasets', async () => {
273+
const rt = await boot(dir);
274+
const bare = composed('6.3.0');
275+
for (const p of bare.packages) delete (p.manifest as any).data;
276+
const res = await rt.install(bare);
277+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
278+
expect(res.payload.data.seeded).toEqual({ mode: 'skipped', reason: 'no-datasets' });
279+
expect(loadCalls).toHaveLength(0);
280+
});
281+
});
282+
283+
/**
284+
* A ledger entry whose body the resolver refuses — a `packages` that is present
285+
* but is not an array (ADR-0112 `INVALID_ARTIFACT_PACKAGES`) — reaches the purge
286+
* and the count as the answer those doors give an unreadable entry: the stable
287+
* `MARKETPLACE_STORAGE_FAILED` 500 naming the ledger file to repair, never a
288+
* throw into the route's error path with no entry named.
289+
*/
290+
describe('purge and count over a ledger body the resolver refuses', () => {
291+
async function installThenCorrupt() {
292+
const rt = await boot(dir);
293+
expect((await rt.install(composed('6.3.0'))).status).toBe(200);
294+
const ledger = new LocalManifestSource(dir);
295+
const { entry } = ledger.read(SUITE);
296+
ledger.write({ ...entry!, manifest: { ...(entry!.manifest as object), packages: 'not-a-list' } } as any);
297+
// The ledger file's basename, as it sits on disk.
298+
return { rt, file: `${SUITE}.json` };
299+
}
300+
301+
it('the purge answers the unreadable-entry 500 naming the ledger file, and deletes nothing', async () => {
302+
const { rt, file } = await installThenCorrupt();
303+
const res = await rt.purge(SUITE);
304+
expect(res.status).toBe(500);
305+
expect(res.payload.success).toBe(false);
306+
expect(res.payload.error.code).toBe('MARKETPLACE_STORAGE_FAILED');
307+
expect(res.payload.error.message).toContain(file);
308+
expect(purgeCalls).toHaveLength(0);
309+
});
310+
311+
it('the count answers the same', async () => {
312+
const { rt, file } = await installThenCorrupt();
313+
const res = await rt.count(SUITE);
314+
expect(res.status).toBe(500);
315+
expect(res.payload.success).toBe(false);
316+
expect(res.payload.error.code).toBe('MARKETPLACE_STORAGE_FAILED');
317+
expect(res.payload.error.message).toContain(file);
318+
expect(countCalls).toHaveLength(0);
319+
});
320+
});

0 commit comments

Comments
 (0)