Skip to content

Commit 8596c80

Browse files
fix(runtime, cloud-connection): an upgrade replaces the package's seed datasets on the shared replay list (#35374)
Fixes #35109 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 1. 用户能看到什么变化:多组织部署里,运行中升级一个已安装的应用包后,之后新建的组织只拿到新版本的示例数据,不再混入旧版本的数据,也不用等重启。 2. 为什么做:来自"安装、升级与卸载可靠性"这条主线,是示例数据兜底语种功能评审时发现的升级后旧数据残留问题。 3. 出错会怎样:若有误,升级后新建的组织可能少了该应用的示例数据;撤回本次改动即可恢复原状。 4. 要你做什么:无,席位落地。 ## What changes - `packages/runtime/src/seed-datasets.ts`: `mergeSeedDatasets(ctx, datasets, owner?)` takes an optional owner. Given, the owner's earlier entries are taken off the SAME live array (by reference, one occurrence each, latest first) and the new entries go where the first of them stood; an empty `datasets` removes them; an owner with nothing to add on a host with no list registers nothing. Omitted, today's append is unchanged. The owner index rides on the array under `Symbol.for('objectstack.seed-datasets.owners')`, non-enumerable, so the inline fallback reads the same index. - `packages/cloud-connection/src/marketplace-install-local-plugin.ts`: `mergeSeedDatasetsIntoKernel` / `mergeSeedDatasetsInline` take the owner and pass it on (the inline mirrors the helper); the one call in `applySideEffects` passes the package id, so install, upgrade, reinstall, reseed and rehydrate all replace. When the body's datasets were read and are empty, the call is made with none, so a version that ships no seed data takes its predecessor's off the list. - Config apps (`AppPlugin`) are untouched: they merge un-owned, once per boot. ## Tests - `packages/runtime/src/seed-datasets.test.ts`, new top-level describe: v1 then v2 of one package leaves v2 only, in place, on the same reference; CONTROL two packages both kept; CONTROL the same version merged again adds no duplicate; an empty version removes; an owned replace never removes an un-owned copy of the same object; install v1, upgrade v2, then the real `AppPlugin` replayer replays host + v2 only. - `packages/runtime/src/app-plugin.seed-locale-producer.test.ts`, new top-level describe (the carried N5 composition, real seed loader): a `dependsOn` dataset on an object whose marked set changed between versions, for a ja-JP organization no set lists, now loads. - `packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts`, new top-level describe through the real install route: install v1, upgrade to v2, then the registered replayer replays v2's sets only; CONTROL two packages through an upgrade of one; CONTROL reinstall of the same version; a version with no seed data empties the package's entries; the door hands the runtime helper the package id. - Stale pins this change made false, updated: `marketplace-install-local-sample-data-not-loaded.test.ts` and `install-local-sample-data-not-loaded.dogfood.test.ts` asserted that a reseed adds the package's datasets to the list a second time; both now assert it holds them once. Two comments in `app-plugin.seed-locale-producer.test.ts` now name the un-owned append only. ## Acceptance notes - The seed loader's duplicate-fallback refusal text (metadata-protocol `seed-loader.ts`, `findDuplicateFallbackSets`, pinned by `seed-loader-locale-scope.test.ts`) still names "an upgrade within this process changed a package's marked set (the earlier version's datasets stay on the replay list until the process restarts)" as a cause. After this change the install door no longer produces that state. The text was not edited here: that file is outside this card's surface and is being edited by an in-flight sibling. Reported to the seat to carry. - Uninstall still leaves the package's entries on the list until a restart. The same rule would cover it, as one owner-keyed call with no datasets on the uninstall path. Reported, not built (out of scope by dispatch). - The reseed control in `marketplace-install-local-sample-data-not-loaded.test.ts` no longer moves the `seedDatasets` axis, by design; the translations axis still makes that control non-vacuous. ## Verification Readings are below. Every assertion is against HEAD `8de43b35`. <details><summary>Package tests and typecheck</summary> - `pnpm --filter @objectstack/runtime test`: Test Files 625 passed (625), Tests 11576 passed, 25 skipped. Run at `94d3a6bf`. No runtime file changed after that commit. - `pnpm --filter @objectstack/cloud-connection test`: Test Files 90 passed (90), Tests 1331 passed (1331). Run at `758ae1b0`; the only later commit edits a dogfood test. - `pnpm --filter @objectstack/dogfood exec vitest run --maxWorkers=2 test/install-local-sample-data-not-loaded.dogfood.test.ts`: 7 passed, against a fresh build of the dogfood dependency closure. - typecheck: runtime (tsc plus `check:test-typecheck` OK), cloud-connection and dogfood, all exit 0 at `8de43b35`. - `test:repo` was not run locally (CI-owned). </details> <details><summary>Red first: ablations, each landed on disk and restored to HEAD by scripts/ablation-replace.mjs</summary> - runtime: `replaceOwnedSeedDatasets(...)` changed back to `list.push(...datasets)` (anchor 1 to 0, blob 19d4919 to 010f55a2). 6 failed of 52: the five new seed-datasets cases (CONTROL two-packages stays green) and the N5 pin. Restored: blob equals HEAD, `git diff HEAD` empty. - cloud-connection inline: the owner index read replaced with an empty list (blob fd57994 to 228c5ea5). 4 failed: upgrade replay, both controls that go through an upgrade or reinstall, and the empty version. Restored. - cloud-connection helper leg: the owner argument dropped from the helper call (blob fd57994 to dcceb504). The owner pin failed. Restored. - N5 before the fix, on the appended list with the length assertion removed: the replay answered errors `fallback` (price_book) and `dependsOn` x2 (quote), and wrote no row. </details> <details><summary>Gates (derived set, local)</summary> - `node scripts/pm/dispatch-gates.mjs --commands` derived 75 families for this diff. All 75 were run one by one, each exit captured before any pipe. 74 exited 0. `pnpm check:dual-build-cjs-loads` exited 3, PREREQUISITE NOT MET: it needs repo-wide dist, so it is NOT MEASURED locally and CI's Lint and Repo Gates runs it. - `--ran` reconciliation: "75 derived famil(ies) accounted for, 74 run, 1 NOT-MEASURED (1 DERIVED from a recorded exit 3)". - `node scripts/check-nul-bytes.mjs`: OK. - `node scripts/pm/overlap-check.mjs --branch=HEAD` before each push: VERDICT clean. Shares the plugin file with #35347, and both merge cleanly. </details> ## 席位核对 - Read first: `packages/runtime/src/seed-datasets.ts` (`replaceOwnedSeedDatasets`, the removal loop); `packages/cloud-connection/src/marketplace-install-local-plugin.ts` (`mergeSeedDatasetsInline` mirror, and the `else if (datasetsRead)` branch in `applySideEffects`); `packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts` (the new describe). - Two-minute check: `pnpm --filter @objectstack/cloud-connection exec vitest run src/marketplace-install-local-seed-replayer.test.ts -t 35109`. Expected: 5 passed. - Mechanism readings at `e4bfa339`: A1 holds (`list.push(...datasets)`, nothing removes). A2 holds: no dataset entry carries a package identity (`seedDatasetsOf` → `resolveStackCollection(body, 'data')` returns the raw entries), so the caller tags them; `AppPlugin` left un-owned. A3 reproduced red: see the ablations. - N5 (carried nit 6969452030): on the appended list the replay answers three errors (`fallback` for `price_book`, then `dependsOn` twice for `quote`) and writes no row. On the replaced list it answers no error, and price_book, quote and account all seed. It changed, so it is pinned. - File-surface deviations: the call site in `applySideEffects` (the owner argument and the empty-version branch); the pins went into the existing harness files as top-level describes (AGENTS.md: a new pin for a component with a shared harness goes into that file), not a new file; two stale pins outside the surface (one cloud-connection test, one dogfood test) updated as consequences of this change. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CaysxGzF62ACvZ1x9x)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CaysxGzF62ACvZ1x9x --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1c05546 commit 8596c80

8 files changed

Lines changed: 410 additions & 19 deletions
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/runtime': patch
3+
'@objectstack/cloud-connection': patch
4+
---
5+
6+
fix(runtime, cloud-connection): an upgrade replaces the package's seed datasets on the shared replay list
7+
8+
Clause-②: yes (widening)
9+
Metadata-protocol: none
10+
11+
The shared `seed-datasets` list that per-organization seed replay reads was append-only. After a package was upgraded in a running process, the superseded version's datasets stayed on the list until a restart, so every organization founded in between replayed the old and the new version's seed sets. When the upgrade changed an object's `fallback: true` set, the two marked sets refused that object's fallback choice, and a dataset declaring `dependsOn` that object refused the whole load for an organization whose locale no set lists.
12+
13+
`mergeSeedDatasets(ctx, datasets, owner?)` takes an optional `owner`. Given, the owner's earlier entries are replaced on the same live array (in their place) instead of kept beside the new ones; an empty `datasets` takes them off. Omitted, the datasets are appended as before, which is what a config app's boot merge still does. The install-local door merges under the package id on install, upgrade, reinstall, reseed and rehydrate, so the list holds the installed version only: reinstalling the same version adds no duplicate, and a version that ships no seed data takes its predecessor's datasets off the list.

‎packages/cloud-connection/src/marketplace-install-local-plugin.ts‎

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2261,15 +2261,20 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
22612261
* did. {@link registerSeedReplayerIntoKernel} is that consumer; the two are
22622262
* called together so the split cannot recur.
22632263
*/
2264-
private mergeSeedDatasetsIntoKernel = async (ctx: PluginContext, datasets: any[]): Promise<number> => {
2264+
//
2265+
// [#35109] `owner` is the package id: the merge REPLACES what an earlier
2266+
// merge of the same package put on the shared list (an upgrade, a reinstall,
2267+
// a reseed, a rehydrate), so the list holds the installed version's datasets
2268+
// only and an organization founded after an upgrade replays no superseded set.
2269+
private mergeSeedDatasetsIntoKernel = async (ctx: PluginContext, datasets: any[], owner: string): Promise<number> => {
22652270
try {
22662271
const mod: any = await import('@objectstack/runtime');
22672272
if (typeof mod?.mergeSeedDatasets === 'function') {
2268-
const list = mod.mergeSeedDatasets(ctx, datasets);
2273+
const list = mod.mergeSeedDatasets(ctx, datasets, owner);
22692274
return Array.isArray(list) ? list.length : datasets.length;
22702275
}
22712276
} catch { /* fall through to the inline merge below */ }
2272-
return this.mergeSeedDatasetsInline(ctx, datasets);
2277+
return this.mergeSeedDatasetsInline(ctx, datasets, owner);
22732278
};
22742279

22752280
/**
@@ -2280,12 +2285,34 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
22802285
* `(ctx as any).kernel` read clobbered instead of accumulating — push in place,
22812286
* and register only when the service does not yet exist so a second source
22822287
* cannot trip the duplicate-register throw. Returns the post-merge total.
2288+
*
2289+
* [#35109] Replaces `owner`'s earlier entries as the runtime helper does, on
2290+
* the one owner index the helper keeps on the array (the same registry
2291+
* symbol): removed by reference, latest first, and the new entries put where
2292+
* the first of them stood.
22832293
*/
2284-
private mergeSeedDatasetsInline = (ctx: PluginContext, datasets: any[]): number => {
2294+
private mergeSeedDatasetsInline = (ctx: PluginContext, datasets: any[], owner: string): number => {
22852295
const c = ctx as any;
22862296
const current = this.readSharedSeedDatasets(ctx);
2297+
if (datasets.length === 0 && !Array.isArray(current)) return 0;
22872298
const list: any[] = Array.isArray(current) ? current : [];
2288-
list.push(...datasets);
2299+
const ownersKey = Symbol.for('objectstack.seed-datasets.owners');
2300+
let owners = (list as any)[ownersKey] as Map<string, unknown[]> | undefined;
2301+
if (!(owners instanceof Map)) Object.defineProperty(list, ownersKey, { value: owners = new Map(), enumerable: false });
2302+
const stale = new Map<unknown, number>();
2303+
for (const entry of owners.get(owner) ?? []) stale.set(entry, (stale.get(entry) ?? 0) + 1);
2304+
let at = list.length;
2305+
for (let i = list.length - 1; i >= 0 && stale.size > 0; i--) {
2306+
const left = stale.get(list[i]);
2307+
if (left === undefined) continue;
2308+
if (left > 1) stale.set(list[i], left - 1);
2309+
else stale.delete(list[i]);
2310+
list.splice(i, 1);
2311+
at = i;
2312+
}
2313+
list.splice(at, 0, ...datasets);
2314+
if (datasets.length > 0) owners.set(owner, [...datasets]);
2315+
else owners.delete(owner);
22892316
if (!Array.isArray(current)) {
22902317
if (typeof c?.kernel?.registerService === 'function') c.kernel.registerService('seed-datasets', list);
22912318
else if (typeof c?.registerService === 'function') c.registerService('seed-datasets', list);
@@ -7512,16 +7539,18 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
75127539
// is reported in the summary rather than thrown, per this method's
75137540
// contract.
75147541
let datasets: PurgeSeedDataset[] = [];
7542+
let datasetsRead = false;
75157543
try {
75167544
datasets = seedDatasetsOf(manifest);
7545+
datasetsRead = true;
75177546
} catch (err: any) {
75187547
seedSummary = { mode: 'skipped', reason: `seed-datasets-unread: ${err?.message ?? err}` };
75197548
ctx.logger?.warn?.(`[MarketplaceInstallLocal] ${appId}: its seed datasets could not be read, so none were merged or seeded: ${err?.message ?? err}`);
75207549
}
75217550

75227551
if (datasets.length > 0) {
75237552
try {
7524-
const total = await this.mergeSeedDatasetsIntoKernel(ctx, datasets);
7553+
const total = await this.mergeSeedDatasetsIntoKernel(ctx, datasets, appId);
75257554
ctx.logger?.info?.(`[MarketplaceInstallLocal] merged ${datasets.length} seed dataset(s) into kernel (total: ${total})`);
75267555
} catch (err: any) {
75277556
ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to merge seed-datasets: ${err?.message ?? err}`);
@@ -7545,6 +7574,14 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
75457574
} catch (err: any) {
75467575
ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to register seed-replayer: ${err?.message ?? err}`);
75477576
}
7577+
} else if (datasetsRead) {
7578+
// [#35109] A version that ships no seed data takes its predecessor's
7579+
// datasets off the shared list (a no-op for a package that never had any).
7580+
try {
7581+
await this.mergeSeedDatasetsIntoKernel(ctx, [], appId);
7582+
} catch (err: any) {
7583+
ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to clear ${appId}'s previous seed-datasets: ${err?.message ?? err}`);
7584+
}
75487585
}
75497586

75507587
// ── 3. Optional immediate seed ───────────────────────────────────

‎packages/cloud-connection/src/marketplace-install-local-sample-data-not-loaded.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,9 @@ describe('reseed and purge on a loadable entry answer as before', () => {
440440
});
441441
const after = h.state();
442442
expect(after.translationsLoaded - before.translationsLoaded).toBe(2);
443-
expect(after.seedDatasets - before.seedDatasets).toBe(1);
443+
// The reseed merges the package's datasets again under its id, which replaces
444+
// its entries on the shared list rather than adding a second copy (#35109).
445+
expect(after.seedDatasets - before.seedDatasets).toBe(0);
444446
expect(recorded(dir, LOADED.id)).toEqual({ withSampleData: true, sampleDataPurged: false });
445447
});
446448

‎packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ const helperRegisterOnce = vi.fn((ctx: any, replayer: unknown): boolean => {
7272
try { if (ctx.getService('seed-replayer') !== undefined) return false; } catch { /* absent */ }
7373
try { ctx.registerService('seed-replayer', replayer); return true; } catch { return false; }
7474
});
75-
const helperMerge = vi.fn((ctx: any, datasets: readonly unknown[]): unknown[] => {
75+
const helperMerge = vi.fn((ctx: any, datasets: readonly unknown[], _owner?: string): unknown[] => {
7676
let current: any[] | undefined;
7777
try { const v = ctx.getService('seed-datasets'); if (Array.isArray(v)) current = v; } catch { /* absent */ }
7878
const list: any[] = current ?? [];
@@ -638,3 +638,84 @@ describe('#30281 — the install paths seed for the organization\'s locale', ()
638638
expect(JSON.stringify(res.payload)).toContain('settings backend down');
639639
});
640640
});
641+
642+
/**
643+
* #35109 — an upgrade in a running process REPLACES the package's datasets on
644+
* the shared list. The list was append-only: after an upgrade it kept the
645+
* superseded version's datasets beside the new ones until a restart, and every
646+
* organization founded in between replayed both versions. The install door now
647+
* merges under the package id, so the list holds the installed version only.
648+
*
649+
* Driven on the inline fallback (`helpersPresent = false`) for the end-to-end
650+
* legs, because that is this package's own merge; the helper's semantics are
651+
* pinned in `packages/runtime/src/seed-datasets.test.ts`, and the helper leg
652+
* here pins only that the door hands it the package id.
653+
*/
654+
describe('#35109 — an upgrade replaces the package\'s datasets on the shared list', () => {
655+
// The locale is not this block's subject; the block above leaves a throwing answer behind.
656+
beforeEach(() => { localeAnswer = async () => undefined; });
657+
658+
const V2 = {
659+
...MANIFEST,
660+
version: '2.0.0',
661+
objects: [...MANIFEST.objects, { name: 'crm_y', fields: { name: { type: 'text' } } }],
662+
data: [
663+
{ object: 'crm_x', records: [{ id: 'a2', name: 'a2' }] },
664+
{ object: 'crm_y', records: [{ id: 'y2', name: 'y2' }] },
665+
],
666+
};
667+
668+
it('install v1, upgrade to v2, then create an organization: only v2\'s sets are replayed', async () => {
669+
helpersPresent = false;
670+
const { rawApp, harness } = freshHarness();
671+
const { plugin } = await installOn(harness, rawApp);
672+
const upgraded = await installOn(harness, rawApp, V2, plugin);
673+
expect(upgraded.res.payload?.success, JSON.stringify(upgraded.res.payload)).toBe(true);
674+
675+
const replayer = harness.peek('seed-replayer') as (id: string) => Promise<any>;
676+
await replayer('org_after_upgrade');
677+
678+
expect(loadCalls).toHaveLength(1);
679+
expect(loadCalls[0].seeds).toEqual(V2.data);
680+
});
681+
682+
it('CONTROL: two different packages are both kept through an upgrade of one of them', async () => {
683+
helpersPresent = false;
684+
const { rawApp, harness } = freshHarness();
685+
const { plugin } = await installOn(harness, rawApp);
686+
await installOn(harness, rawApp, MANIFEST_2, plugin);
687+
await installOn(harness, rawApp, V2, plugin);
688+
689+
expect(harness.peek('seed-datasets')).toEqual([...V2.data, ...MANIFEST_2.data]);
690+
});
691+
692+
it('CONTROL: installing the same version again adds no duplicate', async () => {
693+
helpersPresent = false;
694+
const { rawApp, harness } = freshHarness();
695+
const { plugin } = await installOn(harness, rawApp);
696+
const again = await installOn(harness, rawApp, MANIFEST, plugin);
697+
expect(again.res.payload?.success, JSON.stringify(again.res.payload)).toBe(true);
698+
699+
expect(harness.peek('seed-datasets')).toEqual(MANIFEST.data);
700+
});
701+
702+
it('a version that ships no seed data takes its predecessor\'s datasets off the list', async () => {
703+
helpersPresent = false;
704+
const { rawApp, harness } = freshHarness();
705+
const { plugin } = await installOn(harness, rawApp);
706+
const { data: _dropped, ...noData } = { ...MANIFEST, version: '2.0.0' };
707+
const upgraded = await installOn(harness, rawApp, noData, plugin);
708+
expect(upgraded.res.payload?.success, JSON.stringify(upgraded.res.payload)).toBe(true);
709+
710+
expect(harness.peek('seed-datasets')).toEqual([]);
711+
});
712+
713+
it('hands the runtime helper the package id as the owner', async () => {
714+
const { rawApp, harness } = freshHarness();
715+
await installOn(harness, rawApp);
716+
717+
expect(helperMerge).toHaveBeenCalledTimes(1);
718+
expect(helperMerge.mock.calls[0][0]).toBe(harness.ctx);
719+
expect(helperMerge.mock.calls[0][2]).toBe(MANIFEST.id);
720+
});
721+
});

‎packages/qa/dogfood/test/install-local-sample-data-not-loaded.dogfood.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,10 @@ describe('dogfood: reseed and purge refuse a package the restart refused to load
255255
// Control for the "unchanged" above: the same probes, on the same boot, move.
256256
expect(afterReseed.translationLoads - beforeReseed.translationLoads).toBe(boot1Loads);
257257
expect([typeof beforeReseed.seedDatasets, typeof afterReseed.seedDatasets]).toEqual(['number', 'number']);
258-
expect((afterReseed.seedDatasets as number) - (beforeReseed.seedDatasets as number)).toBe(CRM_DATASETS);
258+
// The reseed merges the package's datasets again under its id: they replace its
259+
// entries on the shared list, so the list holds them once (#35109).
260+
expect((afterReseed.seedDatasets as number) - (beforeReseed.seedDatasets as number)).toBe(0);
261+
expect(beforeReseed.seedDatasets as number).toBeGreaterThanOrEqual(CRM_DATASETS);
259262
expect(purgeLoaded.status, JSON.stringify(purgeLoaded.body)).toBe(200);
260263
expect(purgeLoaded.body?.data).toMatchObject({ deleted: SEED_TOTAL, skipped: 0, errors: 0, withSampleData: false });
261264
expect(rowsAfterPurge).toBe(0);

‎packages/runtime/src/app-plugin.seed-locale-producer.test.ts‎

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
44
import { AppPlugin } from './app-plugin';
55
import { appDefaultSeedLocale, resolveSeedLocaleForLoad } from './seed-locale';
66
import { SeedLoaderService } from './seed-loader';
7+
import { mergeSeedDatasets } from './seed-datasets';
78
import { SeedLoaderRequestSchema } from '@objectstack/spec/data';
89
// The source reaches `@objectstack/metadata` lazily (app-plugin.ts); pay its first load during collection.
910
import '@objectstack/metadata';
@@ -639,10 +640,10 @@ describe('Seed.fallback on the boot and install paths', () => {
639640
});
640641

641642
/**
642-
* The shared `seed-datasets` list is appended to on every merge: boot
643-
* rehydrate, install / upgrade and reseed each add the package's
644-
* datasets again. The loader counts distinct declarations, so the
645-
* second copy of the one fallback set is not a second fallback set.
643+
* An un-owned merge appends to the shared `seed-datasets` list, as a
644+
* config app's boot does (the install door replaces its package's
645+
* entries instead, #35109). The loader counts distinct declarations,
646+
* so a second copy of the one fallback set is not a second fallback set.
646647
*/
647648
it('a replay after the same package merged twice still gets the fallback set, and the rest seeds', async () => {
648649
settingFor.org_ja = { value: 'ja-JP', source: 'tenant' };
@@ -683,9 +684,10 @@ describe('Seed.fallback on the boot and install paths', () => {
683684
});
684685

685686
/**
686-
* An upgrade in a running process appends version 2's datasets beside
687-
* version 1's on the shared list. When the marked set changed between
688-
* the versions, the list holds two distinct marked declarations of one
687+
* Two un-owned merges of one app's versions leave version 2's datasets
688+
* beside version 1's on the shared list (the install door's upgrade no
689+
* longer does, #35109). When the marked set changed between the
690+
* versions, the list holds two distinct marked declarations of one
689691
* object from one correctly authored package. Only the fallback choice
690692
* is refused: an `en` organization gets what the same versions give it
691693
* unmarked, and a `ja-JP` organization gets what it got before the key
@@ -807,3 +809,81 @@ describe('Seed.fallback on the boot and install paths', () => {
807809
});
808810
});
809811
});
812+
813+
/**
814+
* #35109, carried from the contract review of `Seed.fallback` (N5): a dataset
815+
* that declares `dependsOn` an object whose fallback choice is refused, for an
816+
* organization whose locale no set lists, refuses the whole load. On the
817+
* append-only shared list an upgrade that changed a package's marked set built
818+
* exactly that: v1's and v2's marked sets side by side, the choice refused,
819+
* the dependent dataset left without its target. The install door's merge now
820+
* names the package, so v2 replaces v1 on the list and the replay is v2's
821+
* alone: one marked set, chosen, and the dependent dataset loads after it.
822+
*/
823+
describe('an upgrade that changed the marked set, on the replaced list: the dependent dataset loads (#35109)', () => {
824+
const OLD_MULTI = process.env.OS_MULTI_ORG_ENABLED;
825+
const ZH = { object: 'price_book', externalId: 'name', mode: 'upsert', locale: ['zh-CN'], records: [{ name: '标准价格表' }] };
826+
const EN = { object: 'price_book', externalId: 'name', mode: 'upsert', locale: ['en', 'en-US'], records: [{ name: 'Standard' }] };
827+
const QUOTE = { object: 'quote', externalId: 'name', mode: 'upsert', dependsOn: ['price_book'], records: [{ name: 'Q-1' }] };
828+
const V1 = [ZH, { ...EN, fallback: true }, QUOTE];
829+
const V2 = [ZH, { ...EN, fallback: true, records: [{ name: 'Standard' }, { name: 'Partner' }] }, QUOTE];
830+
831+
let engine: IDataEngine;
832+
let store: Record<string, any[]>;
833+
let services: Map<string, unknown>;
834+
let logger: { info: any; warn: any; error: any; debug: any };
835+
836+
beforeEach(() => {
837+
process.env.OS_MULTI_ORG_ENABLED = 'true';
838+
({ engine, store } = createEngine());
839+
services = new Map();
840+
logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
841+
services.set('settings', {
842+
get: vi.fn(async (_ns: string, _key: string, c?: { tenantId?: string }) =>
843+
c?.tenantId === 'org_ja' ? { value: 'ja-JP', source: 'tenant' } : { value: 'en-US', source: 'default' }),
844+
});
845+
});
846+
afterEach(() => {
847+
if (OLD_MULTI === undefined) delete process.env.OS_MULTI_ORG_ENABLED;
848+
else process.env.OS_MULTI_ORG_ENABLED = OLD_MULTI;
849+
});
850+
851+
const metadata = (): IMetadataService => {
852+
const base = createMetadata();
853+
const quote = { name: 'quote', fields: { name: { type: 'text' } } };
854+
return {
855+
...base,
856+
getObject: vi.fn(async (name: string) => (name === 'quote' ? quote : base.getObject(name))),
857+
listObjects: vi.fn(async () => [...(await base.listObjects()), quote]),
858+
} as unknown as IMetadataService;
859+
};
860+
const ctx = (): PluginContext => ({
861+
logger,
862+
registerService: vi.fn((name: string, svc: unknown) => { services.set(name, svc); }),
863+
getService: vi.fn((name: string) => {
864+
if (name === 'objectql') return engine;
865+
if (name === 'metadata') return metadata();
866+
return services.get(name);
867+
}),
868+
getServices: vi.fn(() => services),
869+
hook: vi.fn(),
870+
trigger: vi.fn(),
871+
}) as unknown as PluginContext;
872+
873+
it('a ja-JP organization founded after the upgrade gets v2\'s fallback set, the dependent quote and the host\'s rows', async () => {
874+
const host = ctx();
875+
await new AppPlugin({ id: 'com.example.host', data: [ACCOUNT_DATASET] }).start(host);
876+
const replay = services.get('seed-replayer') as (organizationId: string) => Promise<any>;
877+
878+
// The install door's merges, as the marketplace install and upgrade make them.
879+
mergeSeedDatasets(host, V1, 'com.example.priced');
880+
mergeSeedDatasets(host, V2, 'com.example.priced');
881+
expect((services.get('seed-datasets') as unknown[]).length).toBe(1 + V2.length);
882+
883+
const summary = await replay('org_ja');
884+
expect(summary.errors ?? []).toEqual([]);
885+
expect((store.price_book ?? []).map((r) => r.name).sort()).toEqual(['Partner', 'Standard']);
886+
expect((store.quote ?? []).map((r) => r.name)).toEqual(['Q-1']);
887+
expect((store.account ?? []).map((r) => r.name)).toEqual(['Acme Corporation']);
888+
});
889+
});

0 commit comments

Comments
 (0)