diff --git a/.changeset/34940-seed-locale-fallback.md b/.changeset/34940-seed-locale-fallback.md new file mode 100644 index 00000000000..62b404cecb5 --- /dev/null +++ b/.changeset/34940-seed-locale-fallback.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +--- + +feat(spec, metadata-protocol): `Seed.fallback` marks the set an organization gets when its locale matches no set of the object + +Clause-②: yes (widening) — one new optional key, `fallback: true`, on a seed dataset (`SeedSchema`); a seed without it parses and loads exactly as before +Metadata-protocol: added + +An app that splits a seed by language with `locale` (a `zh-CN` and an `en` set of the standard price book) used to leave an organization on any other locale (`ja-JP`, `es-ES`) with neither set. Mark one set `fallback: true` and it also loads for every resolved locale that no locale-scoped set of the same object lists: + +```ts +defineSeed(PriceBook, { locale: ['zh-CN'], records: [{ name: '标准价格表' }] }); +defineSeed(PriceBook, { locale: ['en', 'en-US'], fallback: true, records: [{ name: 'Standard' }] }); +``` + +It is honoured wherever a load filters by locale: the boot seed and the dev hot reload (the app's `i18n.defaultLocale`), and the per-organization replay, marketplace install, sample-data reseed and restart heal (the locale `resolveSeedLocaleForLoad` resolves). The loader logs each fallback set it loaded, at info. + +- The marker needs `locale`: `fallback: true` on a dataset with no `locale` is refused when the seed is parsed, because an unscoped dataset already loads for every locale. The published JSON Schema carries the rule as `dependentRequired`. +- A dataset with no `locale` does not count as a match: it loads beside whichever set is chosen. +- `env` is applied first; a set it scoped out neither matches nor falls back. +- At most one fallback set per object in a load: with two different marked sets of one object, only the fallback choice is refused. No marked set fills in for a locale no set lists, and the load reports one error per object (`field: 'fallback'`), logged at warn; every marked set still loads for the locales it lists, as an unmarked set would, and every other object still seeds. Identical copies of one set (a package's datasets merged twice) count once; an upgrade that changed a package's marked set leaves two sets on the replay list until the process restarts. +- A load with no locale (package apply, draft publish, an install no rung resolved a locale for) loads every dataset, the fallback set included, and warns as before. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index ed2f7782631..f8d0809946e 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -339,6 +339,62 @@ dataset wrote: both sets stay resident and queryable, because the switch is additive and not a migration. Clearing the market you left behind is the operator's job — to switch locales cleanly, start from a fresh database. +### A Fallback Set — `fallback: true` + +A locale that no dataset of an object names gets **none** of that object's +locale-scoped rows. Where the seed is functional rather than decorative — the +standard price book that quotes fall back to — an organization on `ja-JP` would +end up with no price book at all when you ship only a `zh-CN` and an `en` set. +Mark one set `fallback: true` and it also loads for every locale no other set +of the object names: + +```typescript +defineSeed(PriceBook, { + locale: ['zh-CN'], + records: [{ name: '标准价格表' }], +}); + +defineSeed(PriceBook, { + locale: ['en', 'en-US'], + fallback: true, // also loads for ja-JP, es-ES, … — any locale no PriceBook set names + records: [{ name: 'Standard' }], +}); +``` + +| Resolved locale | `PriceBook` rows loaded | +|:---|:---| +| `zh-CN` | the `zh-CN` set | +| `en`, `en-US` | the `en` set (its own locales) | +| `ja-JP`, `es-ES`, … | the `en` set, as the fallback | +| none (package apply, draft publish, an unresolved install) | both sets, with the usual warning | + +The rules: + +- **The fallback set lists its own locales.** `fallback: true` on a dataset with + no `locale` is refused when the seed is parsed: an unscoped dataset already + loads for every locale, so it cannot also be the set that loads only when no + other set matches. Write the locales the set is in and keep the marker. +- **A set with no `locale` does not count as a match.** It is locale-neutral: it + loads beside whichever set is chosen, and the fallback still fills in. +- **Matching is per object**, case-insensitive and otherwise exact, as above. A + `ja-JP` set of some *other* object does not stop the price book's fallback. +- **`env` is applied first.** A set `env` scoped out of the load neither matches + nor falls back. +- **At most one fallback set per object in a load.** Two different sets of one + object both marked `fallback: true` leave no single choice, so only the + fallback choice is refused: no marked set fills in for a locale no set lists, + and the load's error (also logged at warn) names the object. Every marked set + still loads for the locales it lists, exactly as an unmarked set would, and + every other object still seeds. Identical copies of one set — the same + package's datasets merged twice — count once. Two versions of one package + whose marked set changed are two sets: an upgrade keeps the earlier + version's datasets on the per-organization replay list until the process + restarts, so until then an organization on an unlisted locale gets no + fallback for that object. + +The loader logs, at info, each fallback set it loaded and the locale it filled +in for. Datasets without the marker load exactly as before. + **Where the loading locale comes from.** On the normal boot path your stack supplies it: the runtime reads your app's `i18n.defaultLocale` and passes it to @@ -801,7 +857,9 @@ When the same records need different display strings per language, author both datasets and scope each with `locale`. Selecting between them in application code instead bakes the choice into your build output, so shipping another market means another build. Neither approach removes what the market you left -behind already wrote — see [Locale Scoping](#locale-scoping). +behind already wrote — see [Locale Scoping](#locale-scoping). Mark one set +`fallback: true` so a market you did not author still gets functional rows — +see [A Fallback Set](#a-fallback-set--fallback-true). ### Leave `mode` unset for data the customer owns @@ -842,6 +900,7 @@ function defineSeed< columns?: { [field: string]: { applyOn?: 'create' | 'always' } }; // per-column write policy; default: 'always' env?: Array<'prod' | 'dev' | 'test'>; // default: ['prod','dev','test'] locale?: string[]; // BCP-47 tags; omitted = every locale + fallback?: true; // also load for a locale no other set of the object names (needs locale) dependsOn?: string[]; // objects this dataset loads after (see "Load Order") records: Array>; // declared fields + injectable system columns } diff --git a/content/docs/references/api/package-api.mdx b/content/docs/references/api/package-api.mdx index 48ade0c36a5..a0b070a9827 100644 --- a/content/docs/references/api/package-api.mdx +++ b/content/docs/references/api/package-api.mdx @@ -246,7 +246,8 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | -| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | +| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn. A locale no dataset of the object names gets none of its locale-scoped rows, unless one is marked `fallback: true` | +| **fallback** | `true` | optional | Marks this locale-scoped dataset as its object's fallback: it also loads for a resolved locale that no other locale-scoped dataset of the same object lists. Requires `locale`: a dataset with no locale already loads everywhere, and the pair is refused. At most one dataset per object in a load may be marked; with two different marked datasets of one object, none is used as the fallback and the load reports the object, while each still loads for the locales it lists, as an unmarked dataset would (identical copies count once). A load with no locale loads it like every other dataset. Omitted, the dataset loads only for the locales it lists. | | **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | @@ -355,7 +356,8 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | -| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | +| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn. A locale no dataset of the object names gets none of its locale-scoped rows, unless one is marked `fallback: true` | +| **fallback** | `true` | optional | Marks this locale-scoped dataset as its object's fallback: it also loads for a resolved locale that no other locale-scoped dataset of the same object lists. Requires `locale`: a dataset with no locale already loads everywhere, and the pair is refused. At most one dataset per object in a load may be marked; with two different marked datasets of one object, none is used as the fallback and the load reports the object, while each still loads for the locales it lists, as an unmarked dataset would (identical copies count once). A load with no locale loads it like every other dataset. Omitted, the dataset loads only for the locales it lists. | | **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index ac7c1bf2d34..be4a7a1dcc4 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -233,7 +233,8 @@ Seed loader request with datasets and configuration | **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | -| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | +| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn. A locale no dataset of the object names gets none of its locale-scoped rows, unless one is marked `fallback: true` | +| **fallback** | `true` | optional | Marks this locale-scoped dataset as its object's fallback: it also loads for a resolved locale that no other locale-scoped dataset of the same object lists. Requires `locale`: a dataset with no locale already loads everywhere, and the pair is refused. At most one dataset per object in a load may be marked; with two different marked datasets of one object, none is used as the fallback and the load reports the object, while each still loads for the locales it lists, as an unmarked dataset would (identical copies count once). A load with no locale loads it like every other dataset. Omitted, the dataset loads only for the locales it lists. | | **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | diff --git a/content/docs/references/data/seed.mdx b/content/docs/references/data/seed.mdx index 85b470d265c..3362e249cf5 100644 --- a/content/docs/references/data/seed.mdx +++ b/content/docs/references/data/seed.mdx @@ -33,7 +33,8 @@ const result = SeedSchema.parse(data); | **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | -| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | +| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn. A locale no dataset of the object names gets none of its locale-scoped rows, unless one is marked `fallback: true` | +| **fallback** | `true` | optional | Marks this locale-scoped dataset as its object's fallback: it also loads for a resolved locale that no other locale-scoped dataset of the same object lists. Requires `locale`: a dataset with no locale already loads everywhere, and the pair is refused. At most one dataset per object in a load may be marked; with two different marked datasets of one object, none is used as the fallback and the load reports the object, while each still loads for the locales it lists, as an unmarked dataset would (identical copies count once). A load with no locale loads it like every other dataset. Omitted, the dataset loads only for the locales it lists. | | **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | diff --git a/content/docs/references/kernel/manifest.mdx b/content/docs/references/kernel/manifest.mdx index 0a6ae3cce51..3af88175c6d 100644 --- a/content/docs/references/kernel/manifest.mdx +++ b/content/docs/references/kernel/manifest.mdx @@ -100,7 +100,8 @@ Install mode: managed (registered as code, upgradeable, sealed) | unmanaged (cop | **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | -| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | +| **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn. A locale no dataset of the object names gets none of its locale-scoped rows, unless one is marked `fallback: true` | +| **fallback** | `true` | optional | Marks this locale-scoped dataset as its object's fallback: it also loads for a resolved locale that no other locale-scoped dataset of the same object lists. Requires `locale`: a dataset with no locale already loads everywhere, and the pair is refused. At most one dataset per object in a load may be marked; with two different marked datasets of one object, none is used as the fallback and the load reports the object, while each still loads for the locales it lists, as an unmarked dataset would (identical copies count once). A load with no locale loads it like every other dataset. Omitted, the dataset loads only for the locales it lists. | | **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | diff --git a/packages/metadata-protocol/src/seed-loader-locale-scope.test.ts b/packages/metadata-protocol/src/seed-loader-locale-scope.test.ts index 5d619224d35..e74505bede9 100644 --- a/packages/metadata-protocol/src/seed-loader-locale-scope.test.ts +++ b/packages/metadata-protocol/src/seed-loader-locale-scope.test.ts @@ -80,6 +80,8 @@ function createMetadata(): IMetadataService { plan_zh: { name: 'plan_zh', fields: { name: { type: 'text' } } }, plan_en: { name: 'plan_en', fields: { name: { type: 'text' } } }, demo_user: { name: 'demo_user', fields: { name: { type: 'text' } } }, + price_book: { name: 'price_book', fields: { name: { type: 'text' } } }, + tax_rate: { name: 'tax_rate', fields: { name: { type: 'text' } } }, }; return { getObject: vi.fn(async (name: string) => objects[name]), @@ -321,3 +323,229 @@ describe('Seed.locale scopes a dataset to a language market (#16510)', () => { }); }); }); + +/** + * `Seed.fallback` — the set an organization receives when its locale matches + * no locale-scoped set of the object. An app that splits its standard price + * book into a `zh-CN` set and an `en` set used to leave a `ja-JP` organization + * with neither; marking the `en` set `fallback: true` gives it that set. + * + * Every case reads which RECORDS reached the engine, and each positive case + * has a control beside it (the same sets unmarked, or a locale some set does + * name), so a filter that loaded the fallback always, or never, fails here. + */ +describe('Seed.fallback fills in for a locale no set of the object names', () => { + let savedNodeEnv: string | undefined; + beforeEach(() => { + savedNodeEnv = process.env.NODE_ENV; + process.env.NODE_ENV = 'production'; + }); + afterEach(() => { + if (savedNodeEnv === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = savedNodeEnv; + }); + + const PRICE_BOOK_ZH = { + object: 'price_book', + externalId: 'name', + mode: 'upsert', + locale: ['zh-CN'], + records: [{ name: '标准价格表' }], + }; + const PRICE_BOOK_EN = { + object: 'price_book', + externalId: 'name', + mode: 'upsert', + locale: ['en', 'en-US'], + records: [{ name: 'Standard' }], + }; + const PRICE_BOOK_EN_FALLBACK = { ...PRICE_BOOK_EN, fallback: true }; + /** Locale-neutral rows of the same object. */ + const PRICE_BOOK_SHARED = { + object: 'price_book', + externalId: 'name', + mode: 'upsert', + records: [{ name: 'Internal' }], + }; + + const names = (store: Record, object = 'price_book') => + (store[object] ?? []).map((r) => r.name).sort(); + + it('loads the fallback set for a locale no set names (ja-JP gets the en price book)', async () => { + const { store, result } = await seedUnder('ja-JP', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['Standard']); + expect(result.success).toBe(true); + }); + + it('control: unmarked, the same sets give a ja-JP load no price book — behaviour without the key is unchanged', async () => { + const { store, result } = await seedUnder('ja-JP', [PRICE_BOOK_ZH, PRICE_BOOK_EN]); + expect(names(store)).toEqual([]); + expect(result.success).toBe(true); + }); + + it('does not load the fallback set when another set names the locale', async () => { + const { store } = await seedUnder('zh-CN', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['标准价格表']); + }); + + it('matches case-insensitively when deciding a set names the locale', async () => { + const { store } = await seedUnder('zh-cn', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['标准价格表']); + }); + + it('loads the fallback set for its own locales like any other set', async () => { + const { store } = await seedUnder('en-US', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['Standard']); + }); + + it('a set with no locale is locale-neutral: it loads beside the fallback and does not block it', async () => { + const { store } = await seedUnder('ja-JP', [PRICE_BOOK_SHARED, PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['Internal', 'Standard']); + }); + + it('is judged per object: a match on another object does not block it', async () => { + const TAX_JA = { object: 'tax_rate', externalId: 'name', mode: 'upsert', locale: ['ja-JP'], records: [{ name: '消費税' }] }; + const { store } = await seedUnder('ja-JP', [TAX_JA, PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['Standard']); + expect(names(store, 'tax_rate')).toEqual(['消費税']); + }); + + it('names the fallback it loaded, at info', async () => { + const { logger } = await seedUnder('ja-JP', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + const info = logger.info.mock.calls.map((c: any[]) => String(c[0])).find((m: string) => m.includes('fallback set(s) loaded')); + expect(info).toContain("Locale 'ja-JP'"); + expect(info).toContain('price_book (locale: en, en-US; fallback)'); + }); + + it('a load with no locale loads every set, the fallback included, and warns', async () => { + const { store, logger } = await seedUnder(undefined, [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['Standard', '标准价格表']); + expect(localeWarning(logger)).toContain('price_book (locale: en, en-US; fallback)'); + }); + + describe('composition with env', () => { + it('a matching set that env scoped out is no match: the fallback loads', async () => { + const zhDevOnly = { ...PRICE_BOOK_ZH, env: ['dev'] }; + const { store } = await seedUnder('zh-CN', [zhDevOnly, PRICE_BOOK_EN_FALLBACK]); + expect(names(store)).toEqual(['Standard']); + }); + + it('a fallback set env scoped out does not fill in', async () => { + const fallbackDevOnly = { ...PRICE_BOOK_EN_FALLBACK, env: ['dev'] }; + const { store } = await seedUnder('ja-JP', [PRICE_BOOK_ZH, fallbackDevOnly]); + expect(names(store)).toEqual([]); + }); + }); + + describe('at most one fallback set per object in a load', () => { + const PRICE_BOOK_ZH_FALLBACK = { ...PRICE_BOOK_ZH, fallback: true }; + + it('refuses only that object\'s fallback choice when two distinct sets of it are marked; the rest still seed', async () => { + const PRICE_BOOK_SHARED_ROWS = { ...PRICE_BOOK_SHARED }; + const { store, result, logger } = await seedUnder('ja-JP', [ACCOUNT_DATASET, PRICE_BOOK_SHARED_ROWS, PRICE_BOOK_ZH_FALLBACK, PRICE_BOOK_EN_FALLBACK]); + // Neither marked price-book set fills in for ja-JP; the object's unmarked set and every other object load. + expect(names(store)).toEqual(['Internal']); + expect(store.account).toEqual([expect.objectContaining({ name: 'Acme Corporation' })]); + expect(result.success).toBe(false); + expect(result.errors).toHaveLength(1); + expect(result.errors[0]).toMatchObject({ sourceObject: 'price_book', field: 'fallback', targetField: '(dataset)' }); + expect(result.errors[0]!.message.split('. ')[0]).toBe( + "Seed datasets of 'price_book' mark 2 different sets `fallback: true` (locale: zh-CN; locale: en, en-US)", + ); + // Named once at warn, whatever level the caller reports a failed load at. + const warned = logger.warn.mock.calls.map((c: any[]) => String(c[0])).filter((m: string) => m.includes('fallback: true')); + expect(warned).toHaveLength(1); + expect(warned[0]).toContain("'price_book'"); + }); + + it('reports the object whatever the locale, and each marked set still loads for the locales it lists, as unmarked', async () => { + // The declaration is ambiguous on every load, so every load reports it; + // the refusal never costs a load rows the same sets give it unmarked. + const cases: Array<[string | undefined, string[]]> = [ + ['zh-CN', ['标准价格表']], + ['en', ['Standard']], + ['ja-JP', []], + [undefined, ['Standard', '标准价格表']], + ]; + for (const [locale, expected] of cases) { + const marked = await seedUnder(locale, [ACCOUNT_DATASET, PRICE_BOOK_ZH_FALLBACK, PRICE_BOOK_EN_FALLBACK]); + const unmarked = await seedUnder(locale, [ACCOUNT_DATASET, PRICE_BOOK_ZH, PRICE_BOOK_EN]); + expect(marked.result.success, `locale=${locale}`).toBe(false); + expect(marked.result.errors.map((e) => e.field), `locale=${locale}`).toEqual(['fallback']); + expect(names(marked.store), `locale=${locale}`).toEqual(expected); + expect(names(unmarked.store), `control, locale=${locale}`).toEqual(expected); + expect(marked.store.account, `locale=${locale}`).toHaveLength(1); + } + }); + + it('names no fallback it did not use, and does not tell a correctly authored package to drop its marker', async () => { + const { logger, result } = await seedUnder('ja-JP', [PRICE_BOOK_ZH_FALLBACK, PRICE_BOOK_EN_FALLBACK]); + const infos = logger.info.mock.calls.map((c: any[]) => String(c[0])); + expect(infos.some((m: string) => m.includes('fallback set(s) loaded'))).toBe(false); + const message = result.errors[0]!.message; + expect(message).toContain('an upgrade within this process changed a package'); + expect(message).not.toContain('drop it from the others'); + }); + + it('an upgrade that changed the marked set (versions 1 and 2 on one list): en keeps its rows, ja-JP gets no fallback, warn names the object', async () => { + // The shared replay list after an upgrade in a running process: version 1's + // datasets, then version 2's, whose marked en set gained a row. + const v1 = [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK]; + const EN_V2 = { ...PRICE_BOOK_EN_FALLBACK, records: [{ name: 'Standard' }, { name: 'Partner' }] }; + const v2 = [structuredClone(PRICE_BOOK_ZH), EN_V2]; + const unmarkedV2 = { ...PRICE_BOOK_EN, records: EN_V2.records }; + + const en = await seedUnder('en', [ACCOUNT_DATASET, ...v1, ...v2]); + const enControl = await seedUnder('en', [ACCOUNT_DATASET, PRICE_BOOK_ZH, PRICE_BOOK_EN, structuredClone(PRICE_BOOK_ZH), unmarkedV2]); + expect(names(en.store)).toEqual(['Partner', 'Standard']); + expect(names(en.store)).toEqual(names(enControl.store)); + expect(en.store.account).toHaveLength(1); + + const ja = await seedUnder('ja-JP', [ACCOUNT_DATASET, ...v1, ...v2]); + expect(ja.store.price_book).toBeUndefined(); + expect(ja.store.account).toHaveLength(1); + expect(ja.result.errors.map((e) => e.sourceObject)).toEqual(['price_book']); + const warned = ja.logger.warn.mock.calls.map((c: any[]) => String(c[0])).filter((m: string) => m.includes('fallback: true')); + expect(warned).toHaveLength(1); + expect(warned[0]).toContain("'price_book'"); + }); + + it('identical copies of one fallback set count once: a list merged twice seeds normally', async () => { + // The shared per-organization replay list holds a package's datasets once per merge. + const copy = structuredClone(PRICE_BOOK_EN_FALLBACK); + const reordered = Object.fromEntries(Object.entries(structuredClone(PRICE_BOOK_EN_FALLBACK)).reverse()); + const { store, result } = await seedUnder('ja-JP', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK, structuredClone(PRICE_BOOK_ZH), copy, reordered]); + expect(result.success).toBe(true); + expect(result.errors).toEqual([]); + expect(names(store)).toEqual(['Standard']); + }); + + it('two packages marking the same object with different sets refuse only that object\'s fallback choice', async () => { + const otherPackage = { object: 'price_book', externalId: 'name', mode: 'upsert', locale: ['de-DE'], fallback: true, records: [{ name: 'Standardpreisliste' }], _packageId: 'com.example.other' }; + const seeds = [ACCOUNT_DATASET, PRICE_BOOK_ZH, { ...PRICE_BOOK_EN_FALLBACK, _packageId: 'com.example.first' }, otherPackage]; + const { store, result } = await seedUnder('ja-JP', seeds); + expect(store.price_book).toBeUndefined(); + expect(store.account).toHaveLength(1); + expect(result.errors.map((e) => e.sourceObject)).toEqual(['price_book']); + // Each package's marked set still loads for its own locale. + const de = await seedUnder('de-DE', seeds); + expect(names(de.store)).toEqual(['Standardpreisliste']); + }); + + it('one fallback set on each of two objects is fine', async () => { + const TAX_EN_FALLBACK = { object: 'tax_rate', externalId: 'name', mode: 'upsert', locale: ['en'], fallback: true, records: [{ name: 'VAT' }] }; + const { store, result } = await seedUnder('ja-JP', [PRICE_BOOK_ZH, PRICE_BOOK_EN_FALLBACK, TAX_EN_FALLBACK]); + expect(result.success).toBe(true); + expect(names(store)).toEqual(['Standard']); + expect(names(store, 'tax_rate')).toEqual(['VAT']); + }); + + it('two marked sets in different environments are not both in one load: not refused', async () => { + const devFallback = { ...PRICE_BOOK_ZH_FALLBACK, env: ['dev'] }; + const prodFallback = { ...PRICE_BOOK_EN_FALLBACK, env: ['prod'] }; + const { store, result } = await seedUnder('ja-JP', [devFallback, prodFallback]); + expect(result.success).toBe(true); + expect(names(store)).toEqual(['Standard']); + }); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 195e71f0f09..95540e642a1 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -370,7 +370,30 @@ function isLocaleScopedDataset(dataset: Seed): boolean { /** Render a dataset's declared locale scope for a log line. */ function localeScopeLabel(dataset: Seed): string { - return `${dataset.object} (locale: ${(dataset.locale as string[]).join(', ')})`; + return `${dataset.object} (locale: ${(dataset.locale as string[]).join(', ')}${isFallbackDataset(dataset) ? '; fallback' : ''})`; +} + +/** + * [Seed.fallback] True when the dataset is marked its object's fallback set. + * The schema refuses the marker on a dataset with no `locale`, so a marked + * dataset is always locale-scoped. + */ +function isFallbackDataset(dataset: Seed): boolean { + return (dataset as { fallback?: unknown }).fallback === true; +} + +/** + * [Seed.fallback] The objects for which a locale-scoped dataset of `datasets` + * lists `locale`. A dataset with no `locale` is locale-neutral and is not a + * match: it loads beside whichever set is chosen, and does not keep the + * object's fallback set from filling in. + */ +function objectsWithLocaleMatch(datasets: readonly Seed[], locale: string): Set { + const matched = new Set(); + for (const dataset of datasets) { + if (isLocaleScopedDataset(dataset) && datasetAllowsLocale(dataset, locale)) matched.add(dataset.object); + } + return matched; } /** @@ -1312,15 +1335,28 @@ export class SeedLoaderService implements ISeedLoaderService { ? { context: { ...SEED_WRITE_EXECUTION_CONTEXT, tenantId: writeOrganization } } : SeedLoaderService.SEED_OPTIONS; - // 1. Filter datasets by the scope axes (environment AND locale) - const datasets = this.filterDatasets(request.seeds, config); + // 1. Filter datasets by the scope axes (environment AND locale). An object + // whose env-scoped datasets mark two DISTINCT fallback sets has no single + // set to fall back to (`Seed.fallback`): only its fallback CHOICE is + // refused. Every marked set still goes through the locale filter and loads + // for the locales it lists, exactly as an unmarked set would; none fills in + // for a locale no set lists. Identical copies of one declaration count + // once — the shared per-organization replay list holds a package's + // datasets once per merge. + const envScoped = this.filterByEnv(request.seeds, config.env); + const fallbackRefusals = findDuplicateFallbackSets(envScoped); + const refusedFallbackObjects = new Set(fallbackRefusals.map(refusal => refusal.object)); + const datasets = this.filterByLocale(envScoped, config.locale, refusedFallbackObjects); + allErrors.push(...this.reportDuplicateFallbackSets(fallbackRefusals)); // [#31021] The record of landed seed rows, once the organization this load // seeds is known. A load with nothing to seed reads and writes none. this.landedKeyLedger = datasets.length > 0 ? await this.openLandedKeyLedger(config) : undefined; if (datasets.length === 0) { - return this.buildEmptyResult(config, Date.now() - startTime); + return allErrors.length > 0 + ? this.buildResult(config, { nodes: [], insertOrder: [], circularDependencies: [] }, [], allErrors, Date.now() - startTime) + : this.buildEmptyResult(config, Date.now() - startTime); } // 2. Build dependency graph. `Seed.dependsOn` adds its declared edges to @@ -1332,7 +1368,10 @@ export class SeedLoaderService implements ISeedLoaderService { const graph = await this.buildDependencyGraph(objectNames, declared.edges); const dependsOnRefusals = [...declared.refusals, ...this.findDeclaredEdgeCycles(graph.nodes, declared.edges)]; if (dependsOnRefusals.length > 0) { - return this.refuseDeclaredDependencies(config, graph, dependsOnRefusals, Date.now() - startTime); + const refused = this.refuseDeclaredDependencies(config, graph, dependsOnRefusals, Date.now() - startTime); + // [Seed.fallback] An object's refused fallback choice stays reported on a load refused for its declarations. + refused.errors.unshift(...allErrors); + return refused; } this.logger.info('[SeedLoader] Dependency graph built', { @@ -4472,6 +4511,31 @@ export class SeedLoaderService implements ISeedLoaderService { return refusals; } + /** + * [Seed.fallback] The errors for the objects whose fallback choice this + * load refused, one per object (`field: 'fallback'`), each named once at + * `warn`. Every dataset still loads where its own scope admits it, so the + * errors join the load's own and its result reads `success: false`. The + * `warn` is a functional degradation (an organization on a locale no set + * lists visibly gets none of that object's rows), said here because a + * replay's consumer may report a failed load's errors at `info` only. + */ + private reportDuplicateFallbackSets(refusals: DuplicateFallbackRefusal[]): ReferenceResolutionError[] { + for (const refusal of refusals) { + this.logger.warn(`[SeedLoader] ${refusal.message}`, { object: refusal.object, fallbackSets: refusal.scopes }); + } + return refusals.map(refusal => ({ + sourceObject: refusal.object, + field: 'fallback', + targetObject: refusal.object, + targetField: '(dataset)', + attemptedValue: refusal.scopes.join(' | '), + // The marker is the dataset's, not a row's; no row was attempted. + recordIndex: 0, + message: refusal.message, + })); + } + /** * [Seed.dependsOn] The answer of a load refused for its declarations: * nothing written, `success: false`, one error per refused declaration @@ -4664,34 +4728,48 @@ export class SeedLoaderService implements ISeedLoaderService { } /** - * Drop datasets that do not apply to this load, on every scope axis. - * - * The axes COMPOSE by conjunction: a dataset is kept when it passes `env` - * **and** `locale`. They stay separate functions — and separate log lines — - * because the two answer different operator questions ("why are my demo rows - * missing in production" vs "why did the Chinese dataset load"), and a single - * merged message would have to name a reason it did not measure. - */ - private filterDatasets(datasets: Seed[], config: SeedLoaderConfigParsed): Seed[] { - return this.filterByLocale(this.filterByEnv(datasets, config.env), config.locale); - } - - /** - * Drop datasets that do not apply to the resolved locale. + * Drop datasets that do not apply to the resolved locale. Runs on the + * datasets {@link filterByEnv} kept: the axes COMPOSE by conjunction, a + * dataset is kept when it passes `env` **and** `locale`. They stay separate + * functions — and separate log lines — because the two answer different + * operator questions ("why are my demo rows missing in production" vs "why + * did the Chinese dataset load"), and a single merged message would have to + * name a reason it did not measure. * * The mirror of {@link filterByEnv}, down to the reporting posture: skipping * is the declared, intended outcome of `locale: ['zh-CN']`, so it logs at * `info` — but it always NAMES what it dropped. + * + * [Seed.fallback] A dataset marked `fallback: true` that the locale would + * drop is kept instead when no locale-scoped dataset of its object lists + * the locale ({@link objectsWithLocaleMatch}), and that is named too — + * unless its object is in `refusedFallbackObjects` (two distinct marked + * sets, {@link findDuplicateFallbackSets}): there the marker is ignored and + * the dataset is filtered like an unmarked one. A load with no locale + * returns every dataset above, the fallback set included. */ - private filterByLocale(datasets: Seed[], locale?: string): Seed[] { + private filterByLocale(datasets: Seed[], locale?: string, refusedFallbackObjects: ReadonlySet = new Set()): Seed[] { if (!locale) return datasets; + const matched = objectsWithLocaleMatch(datasets, locale); const kept: Seed[] = []; const skipped: Seed[] = []; + const fellBack: Seed[] = []; for (const dataset of datasets) { - (datasetAllowsLocale(dataset, locale) ? kept : skipped).push(dataset); + if (datasetAllowsLocale(dataset, locale)) kept.push(dataset); + else if (isFallbackDataset(dataset) && !matched.has(dataset.object) && !refusedFallbackObjects.has(dataset.object)) { + kept.push(dataset); + fellBack.push(dataset); + } else skipped.push(dataset); } + if (fellBack.length > 0) { + this.logger.info( + `[SeedLoader] Locale '${locale}': no dataset is scoped to it for ${fellBack.length} object(s), so their ` + + `fallback set(s) loaded: ${fellBack.map(localeScopeLabel).join('; ')}`, + { locale, fallback: fellBack.map(d => d.object) }, + ); + } if (skipped.length > 0) { this.logger.info( `[SeedLoader] Locale '${locale}': skipped ${skipped.length} dataset(s) scoped to other ` + @@ -5292,6 +5370,78 @@ export class SeedLoaderService implements ISeedLoaderService { // Internal Types // ========================================================================== +/** [Seed.fallback] One object whose fallback choice a load refuses: it marks more than one distinct set. */ +interface DuplicateFallbackRefusal { + readonly object: string; + /** The locale scopes of the distinct marked datasets, one entry each, for the error's `attemptedValue`. */ + readonly scopes: string[]; + readonly message: string; +} + +/** + * [Seed.fallback] A dataset's declaration, for telling a second COPY of one + * declaration from a second declaration: every key but the runtime protection + * envelope (`_`-prefixed, stamped by the loader that read the artifact), + * serialised with sorted keys so key order does not make two copies differ. + */ +function seedDeclarationFingerprint(dataset: Seed): string { + const canonical = (value: unknown): unknown => { + if (Array.isArray(value)) return value.map(canonical); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.keys(value as Record).sort().map(key => [key, canonical((value as Record)[key])]), + ); + } + return value; + }; + const declared = Object.fromEntries(Object.entries(dataset as Record).filter(([key]) => !key.startsWith('_'))); + return JSON.stringify(canonical(declared)); +} + +/** + * [Seed.fallback] Every object for which `datasets` (the datasets `env` kept + * for this load) mark more than one DISTINCT declaration `fallback: true`. + * Identical copies count once: the shared per-organization replay list holds + * a package's datasets once per merge (boot rehydrate, install or upgrade, + * reseed), and a second copy of the one fallback set is not a second choice. + * Object names are global, so two packages marking the same object are two + * declarations and that object's fallback choice is refused. So are two + * versions of one package whose marked set changed: an upgrade appends the new + * version's datasets beside the old version's until the process restarts. + * + * Judged whatever the load's locale: the declaration is ambiguous on every + * load, not only on one that needs the fallback, and a refusal that waited for + * an unmatched locale would surface on the first organization in a new market. + */ +function findDuplicateFallbackSets(datasets: readonly Seed[]): DuplicateFallbackRefusal[] { + const byObject = new Map>(); + for (const dataset of datasets) { + if (!isFallbackDataset(dataset)) continue; + const distinct = byObject.get(dataset.object) ?? new Map(); + const fingerprint = seedDeclarationFingerprint(dataset); + if (!distinct.has(fingerprint)) distinct.set(fingerprint, dataset); + byObject.set(dataset.object, distinct); + } + const refusals: DuplicateFallbackRefusal[] = []; + for (const [object, distinct] of byObject) { + if (distinct.size < 2) continue; + const scopes = [...distinct.values()].map(d => `locale: ${((d.locale as string[] | undefined) ?? []).join(', ')}`); + refusals.push({ + object, + scopes, + message: + `Seed datasets of '${object}' mark ${distinct.size} different sets \`fallback: true\` (${scopes.join('; ')}). ` + + 'An object has at most one fallback set: it is the one set that loads when no other set lists the ' + + `resolved locale. No fallback was used for '${object}': each marked set still loads for the locales it ` + + 'lists, and a locale none of them lists gets none of them; every other object seeds as usual. Two causes ' + + `leave more than one marked set: the packages being seeded mark more than one set of '${object}' (keep the ` + + 'marker on one), or 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).', + }); + } + return refusals; +} + /** [Seed.dependsOn] One declaration a load refuses: `object` named `target`. */ interface DeclaredDependencyRefusal { readonly object: string; diff --git a/packages/runtime/src/app-plugin.seed-locale-producer.test.ts b/packages/runtime/src/app-plugin.seed-locale-producer.test.ts index 45ea6214fc7..05659a45a22 100644 --- a/packages/runtime/src/app-plugin.seed-locale-producer.test.ts +++ b/packages/runtime/src/app-plugin.seed-locale-producer.test.ts @@ -2,7 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { AppPlugin } from './app-plugin'; -import { appDefaultSeedLocale } from './seed-locale'; +import { appDefaultSeedLocale, resolveSeedLocaleForLoad } from './seed-locale'; +import { SeedLoaderService } from './seed-loader'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; +// The source reaches `@objectstack/metadata` lazily (app-plugin.ts); pay its first load during collection. +import '@objectstack/metadata'; import type { PluginContext } from '@objectstack/core'; import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; import { assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; @@ -89,6 +93,7 @@ function createMetadata(): IMetadataService { account: { name: 'account', fields: { name: { type: 'text' } } }, plan_zh: { name: 'plan_zh', fields: { name: { type: 'text' } } }, plan_en: { name: 'plan_en', fields: { name: { type: 'text' } } }, + price_book: { name: 'price_book', fields: { name: { type: 'text' } } }, }; return { getObject: vi.fn(async (name: string) => objects[name]), @@ -508,3 +513,297 @@ describe('appDefaultSeedLocale (#30281)', () => { expect(appDefaultSeedLocale(undefined)).toBeUndefined(); }); }); + +/** + * `Seed.fallback` on every path that picks datasets by locale (ADR-0049: the + * key is honoured where a load filters, not only in the loader's own suite). + * A `zh-CN` and an `en` set of the standard price book, the `en` set marked + * `fallback: true`: an organization on `ja-JP`, which neither set names, gets + * the `en` set. Each path carries a control: the same sets UNMARKED give the + * `ja-JP` load no price book, which is the behaviour before the key existed. + */ +describe('Seed.fallback on the boot and install paths', () => { + const OLD_BUDGET = process.env.OS_INLINE_SEED_BUDGET_MS; + const OLD_MULTI = process.env.OS_MULTI_ORG_ENABLED; + const OLD_NODE_ENV = process.env.NODE_ENV; + + const ZH = { object: 'price_book', externalId: 'name', mode: 'upsert', locale: ['zh-CN'], records: [{ name: '标准价格表' }] }; + const EN = { object: 'price_book', externalId: 'name', mode: 'upsert', locale: ['en', 'en-US'], records: [{ name: 'Standard' }] }; + const MARKED = [ZH, { ...EN, fallback: true }]; + const UNMARKED = [ZH, EN]; + + let engine: IDataEngine; + let store: Record; + let services: Map; + let hooks: Map any>>; + let logger: { info: any; warn: any; error: any; debug: any }; + let settingFor: Record; + + beforeEach(() => { + process.env.OS_INLINE_SEED_BUDGET_MS = '60000'; + delete process.env.OS_MULTI_ORG_ENABLED; + ({ engine, store } = createEngine()); + services = new Map(); + hooks = new Map(); + logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + settingFor = {}; + services.set('settings', { + get: vi.fn(async (_ns: string, _key: string, ctx?: { tenantId?: string }) => + settingFor[ctx?.tenantId ?? ''] ?? { value: 'en-US', source: 'default' }), + }); + }); + afterEach(() => { + if (OLD_BUDGET === undefined) delete process.env.OS_INLINE_SEED_BUDGET_MS; + else process.env.OS_INLINE_SEED_BUDGET_MS = OLD_BUDGET; + if (OLD_MULTI === undefined) delete process.env.OS_MULTI_ORG_ENABLED; + else process.env.OS_MULTI_ORG_ENABLED = OLD_MULTI; + if (OLD_NODE_ENV === undefined) delete process.env.NODE_ENV; + else process.env.NODE_ENV = OLD_NODE_ENV; + }); + + const ctx = (): PluginContext => ({ + logger, + registerService: vi.fn((name: string, svc: unknown) => { services.set(name, svc); }), + getService: vi.fn((name: string) => { + if (name === 'objectql') return engine; + if (name === 'metadata') return createMetadata(); + return services.get(name); + }), + getServices: vi.fn(() => services), + hook: vi.fn((event: string, fn: (payload: any) => any) => { + const list = hooks.get(event) ?? []; + list.push(fn); + hooks.set(event, list); + }), + trigger: vi.fn(), + }) as unknown as PluginContext; + + const priceBooks = () => (store.price_book ?? []).map((r) => r.name).sort(); + const app = (defaultLocale: string | undefined, data: unknown[]) => new AppPlugin({ + id: 'com.example.fallback-app', + ...(defaultLocale ? { i18n: { defaultLocale } } : {}), + data, + }); + + describe('boot: filters on the app\'s i18n.defaultLocale', () => { + it('inline boot seed: a ja-JP app gets the fallback set', async () => { + await app('ja-JP', MARKED).start(ctx()); + expect(priceBooks()).toEqual(['Standard']); + }); + + it('inline boot seed control: unmarked, a ja-JP app gets no price book', async () => { + await app('ja-JP', UNMARKED).start(ctx()); + expect(priceBooks()).toEqual([]); + }); + + it('inline boot seed: a zh-CN app gets its own set, not the fallback', async () => { + await app('zh-CN', MARKED).start(ctx()); + expect(priceBooks()).toEqual(['标准价格表']); + }); + + it('dev hot reload: a ja-JP app gets the fallback set; unmarked, none', async () => { + process.env.NODE_ENV = 'development'; + const reload = async (data: unknown[]) => { + hooks = new Map(); + ({ engine, store } = createEngine()); + await app('ja-JP', []).start(ctx()); + await hooks.get('metadata:reloaded')![0]!({ metadata: { objects: [{ name: 'price_book' }], data } }); + return priceBooks(); + }; + expect(await reload(MARKED)).toEqual(['Standard']); + expect(await reload(UNMARKED)).toEqual([]); + }); + }); + + describe('per-organization replay: filters on resolveSeedLocaleForLoad', () => { + const replayerOf = async (data: unknown[]) => { + process.env.OS_MULTI_ORG_ENABLED = 'true'; + await app('en', data).start(ctx()); + return services.get('seed-replayer') as (orgId: string, options?: { userId?: string }) => Promise; + }; + + it('an organization whose Localization setting is ja-JP gets the fallback set; unmarked, none', async () => { + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + await (await replayerOf(MARKED))('org_ja'); + expect(priceBooks()).toEqual(['Standard']); + + ({ engine, store } = createEngine()); + await (await replayerOf(UNMARKED))('org_ja'); + expect(priceBooks()).toEqual([]); + }); + + it('a founder whose language is es-ES gets the fallback set', async () => { + store.sys_user = [{ id: 'usr_es', locale: 'es-ES' }]; + await (await replayerOf(MARKED))('org_new', { userId: 'usr_es' }); + expect(priceBooks()).toEqual(['Standard']); + }); + + /** + * The shared `seed-datasets` list is appended to on every merge: boot + * rehydrate, install / upgrade and reseed each add the package's + * datasets again. The loader counts distinct declarations, so the + * second copy of the one fallback set is not a second fallback set. + */ + it('a replay after the same package merged twice still gets the fallback set, and the rest seeds', async () => { + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + const data = [ACCOUNT_DATASET, ...MARKED]; + const replay = await replayerOf(data); + await app('en', data).start(ctx()); + expect((services.get('seed-datasets') as unknown[]).length).toBe(6); + + const summary = await replay('org_ja'); + expect(priceBooks()).toEqual(['Standard']); + expect((store.account ?? []).map((r) => r.name)).toEqual(['Acme Corporation']); + expect(summary.errors ?? []).toEqual([]); + }); + + /** + * Object names are global: two packages that each mark a different + * fallback set for one object leave no single choice. Only that + * object's fallback choice is refused: each marked set still loads for + * the locales it lists, and every other object still seeds. + */ + it('two packages marking different fallback sets of one object refuse only that object\'s fallback choice', async () => { + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + const replay = await replayerOf([ACCOUNT_DATASET, ...MARKED]); + const DE = { object: 'price_book', externalId: 'name', mode: 'upsert', locale: ['de-DE'], fallback: true, records: [{ name: 'Standardpreisliste' }] }; + await new AppPlugin({ id: 'com.example.second-app', data: [DE, PLAN_EN_DATASET] }).start(ctx()); + + settingFor.org_en = { value: 'en', source: 'tenant' }; + await replay('org_ja'); + expect(store.price_book).toBeUndefined(); + expect((store.account ?? []).map((r) => r.name)).toEqual(['Acme Corporation']); + expect(logger.warn.mock.calls.map((c: any[]) => String(c[0])).filter((m: string) => m.includes("'price_book' mark 2 different sets"))).toHaveLength(1); + + // The other package's other object seeds where its locale matches, and + // the first package's marked en set loads for en, as it would unmarked. + await replay('org_en'); + expect((store.plan_en ?? []).map((r) => r.name)).toEqual(['Professional']); + expect(priceBooks()).toEqual(['Standard']); + }); + + /** + * An upgrade in a running process appends version 2's datasets beside + * version 1's on the shared list. When the marked set changed between + * the versions, the list holds two distinct marked declarations of one + * object from one correctly authored package. Only the fallback choice + * is refused: an `en` organization gets what the same versions give it + * unmarked, and a `ja-JP` organization gets what it got before the key + * existed. + */ + it('a replay after an upgrade that changed the marked set: en gets its rows, ja-JP no fallback, warn names the object', async () => { + settingFor.org_en = { value: 'en', source: 'tenant' }; + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + const EN_V2_RECORDS = [{ name: 'Standard' }, { name: 'Partner' }]; + const replayAfterUpgrade = async (v1: unknown[], v2: unknown[], organizationId: string) => { + // A fresh process per organization: its own shared list, replayer and engine. + const settings = services.get('settings'); + services = new Map([['settings', settings]]); + hooks = new Map(); + ({ engine, store } = createEngine()); + logger.warn.mockClear(); + const replay = await replayerOf(v1); + await app('en', v2).start(ctx()); + expect((services.get('seed-datasets') as unknown[]).length).toBe(v1.length + v2.length); + await replay(organizationId); + const warned = logger.warn.mock.calls.map((c: any[]) => String(c[0])).filter((m: string) => m.includes("'price_book' mark 2 different sets")); + return { priceBooks: priceBooks(), account: (store.account ?? []).map((r) => r.name), warned: warned.length }; + }; + const V1_MARKED = [ACCOUNT_DATASET, ...MARKED]; + const V2_MARKED = [ACCOUNT_DATASET, ZH, { ...EN, fallback: true, records: EN_V2_RECORDS }]; + const V1_UNMARKED = [ACCOUNT_DATASET, ...UNMARKED]; + const V2_UNMARKED = [ACCOUNT_DATASET, ZH, { ...EN, records: EN_V2_RECORDS }]; + + for (const [org, expected] of [['org_en', ['Partner', 'Standard']], ['org_ja', []]] as const) { + const marked = await replayAfterUpgrade(V1_MARKED, V2_MARKED, org); + const control = await replayAfterUpgrade(V1_UNMARKED, V2_UNMARKED, org); + expect(marked.priceBooks, org).toEqual(expected); + expect(marked.priceBooks, org).toEqual(control.priceBooks); + expect(marked.account, org).toEqual(['Acme Corporation']); + expect(control.account, org).toEqual(['Acme Corporation']); + expect(marked.warned, org).toBe(1); + expect(control.warned, org).toBe(0); + } + }); + }); + + /** + * The install, sample-data reseed and restart heal build their request the + * way `marketplace-install-local-plugin.ts#runInlineSeed` does: the locale + * from `resolveSeedLocaleForLoad`, then `SeedLoaderRequestSchema.parse`, + * then `SeedLoaderService.load`. Reproduced here with the same three calls, + * one question per path. + */ + describe('install, reseed and heal: resolveSeedLocaleForLoad → SeedLoaderService', () => { + const runInlineSeed = async ( + data: unknown[], + question: { organizationId?: string; userId?: string; appDefaultLocale?: string }, + ) => { + const host = ctx(); + const seedLocale = await resolveSeedLocaleForLoad(host, { seeds: data, ...question }); + const request = SeedLoaderRequestSchema.parse({ + seeds: data, + config: { + multiPass: true, + ...(question.organizationId ? { organizationId: question.organizationId } : {}), + ...(seedLocale ? { locale: seedLocale.locale } : {}), + }, + }); + return new SeedLoaderService(engine, createMetadata(), logger as any).load(request); + }; + + it('install: the organization\'s ja-JP setting gets the fallback set; unmarked, none', async () => { + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + const marked = await runInlineSeed(MARKED, { organizationId: 'org_ja', userId: 'usr_x', appDefaultLocale: 'zh-CN' }); + expect(marked.success).toBe(true); + expect(priceBooks()).toEqual(['Standard']); + + ({ engine, store } = createEngine()); + await runInlineSeed(UNMARKED, { organizationId: 'org_ja', userId: 'usr_x', appDefaultLocale: 'zh-CN' }); + expect(priceBooks()).toEqual([]); + }); + + it('reseed: the reseeding user\'s es-ES language gets the fallback set', async () => { + store.sys_user = [{ id: 'usr_es', locale: 'es-ES' }]; + await runInlineSeed(MARKED, { organizationId: 'org_1', userId: 'usr_es' }); + expect(priceBooks()).toEqual(['Standard']); + }); + + it('heal: no organization and no user, the package\'s ja-JP default gets the fallback set', async () => { + await runInlineSeed(MARKED, { appDefaultLocale: 'ja-JP' }); + expect(priceBooks()).toEqual(['Standard']); + }); + + it('two different marked sets of one object refuse that object\'s fallback choice; the rest seeds', async () => { + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + const DOUBLY_MARKED = [ACCOUNT_DATASET, { ...ZH, fallback: true }, { ...EN, fallback: true }]; + const result = await runInlineSeed(DOUBLY_MARKED, { organizationId: 'org_ja' }); + expect(result.success).toBe(false); + expect(result.errors.map((e) => e.field)).toEqual(['fallback']); + expect(store.price_book).toBeUndefined(); + expect((store.account ?? []).map((r) => r.name)).toEqual(['Acme Corporation']); + + // A locale a marked set lists still gets that set. + ({ engine, store } = createEngine()); + settingFor.org_zh = { value: 'zh-CN', source: 'tenant' }; + await runInlineSeed(DOUBLY_MARKED, { organizationId: 'org_zh' }); + expect(priceBooks()).toEqual(['标准价格表']); + }); + + it('the same marked set twice in one request (a list merged twice) is one fallback set', async () => { + settingFor.org_ja = { value: 'ja-JP', source: 'tenant' }; + const result = await runInlineSeed([...MARKED, ...structuredClone(MARKED)], { organizationId: 'org_ja' }); + expect(result.success).toBe(true); + expect(priceBooks()).toEqual(['Standard']); + }); + + it('a marked set with no locale is refused when the request is parsed', () => { + const parsed = SeedLoaderRequestSchema.safeParse({ + seeds: [{ object: 'price_book', fallback: true, records: [{ name: 'Standard' }] }], + config: { locale: 'ja-JP' }, + }); + expect(parsed.success).toBe(false); + expect(!parsed.success && parsed.error.issues[0]?.path).toEqual(['seeds', 0, 'fallback']); + }); + }); +}); diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 8c9b6f88d8a..73e8740e18e 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -952,6 +952,7 @@ "data/Seed:dependsOn", "data/Seed:env", "data/Seed:externalId", + "data/Seed:fallback", "data/Seed:files", "data/Seed:locale", "data/Seed:mode", diff --git a/packages/spec/liveness/seed.json b/packages/spec/liveness/seed.json index 1eddc78372e..15f1402ae52 100644 --- a/packages/spec/liveness/seed.json +++ b/packages/spec/liveness/seed.json @@ -52,6 +52,14 @@ "producer": "packages/runtime/src/app-plugin.ts#resolveSeedLocale (AppPlugin resolves the load-time locale ITSELF off the app's declared `i18n.defaultLocale` — the same ENVELOPE key, read the same way `loadTranslations` reads it for `setDefaultLocale` — and threads it into all THREE `SeedLoaderRequest`s this plugin builds: the inline boot seed, the per-org replayer registered for tenant provisioning, and the dev hot-reload seeder. A blank or undeclared `defaultLocale` sends NO `locale` key rather than an `'en'` default, because absence is the loader's unrestricted spelling and a default would have turned a wiring change into a data change)", "note": "FLIPPED experimental → live 2026-09-09 by #16595, which supplied the missing PRODUCER. The consumer half (#16510 / PR #16592) was always closed and tested; what was missing was the second input the effect depends on, `SeedLoaderConfig.locale`, which no first-party call site passed — so `filterByLocale` returned its input on its first line and `dataset.locale` was never read at all on the default boot path. That is the same shape `Seed.env` was in before framework#4704, which is why this row was recorded as `experimental` instead of published `live` on a correct-but-insufficient consumer pointer (#4837). EVIDENCE FOR THE FLIP, and it is a NEGATIVE leg rather than a green suite: `packages/runtime/src/app-plugin.seed-locale-producer.test.ts` asserts on the rows that reach the engine, not on the request object, and an ablation that neutralises `resolveSeedLocale` (returning `undefined`) turns 5 of its 7 cases red in the inert direction — a `locale: ['zh-CN']` dataset loads on an `en` stack. All three of this plugin's call sites go red, so the pin covers each one. ⚠️ WHAT THIS `live` ASSERTS, AND WHAT IT DOES NOT — read this before citing the row. It ASSERTS the ledger's own criterion and nothing wider: authoring `locale` changes runtime behaviour, on the boot path a `defineStack()` app actually boots through, and the `producer` field names the code that makes that true. ⛔ It does NOT assert that every path which can reach `SeedLoaderService.load()` supplies a locale — two do not, they are named below, and a reader who takes `live` as \"the axis is honoured everywhere\" is reading something this row does not say. That is the distinction between this row and the #4837 specimen one entry up: `Seed.env` was `live` while ZERO of six call sites supplied it, so authoring the key changed nothing anywhere and the verdict was false in the only sense the criterion has. Here it is true, and bounded, and the bound is written down. ⚠️ THE SCOPE OF THIS `live`, stated rather than left to be discovered: this repo has SIX request builders, the same six the `env` row one entry up enumerates. FOUR supply a locale, each named by the function that builds its request: (1) packages/runtime/src/app-plugin.ts#start, the inline boot seed (single-tenant boot) — the app's declared `i18n.defaultLocale`, read by `resolveSeedLocale`; (2) packages/runtime/src/app-plugin.ts#registerHotReloadSeeder, the dev hot-reload seeder — the same `resolveSeedLocale`, off the boot bundle; (3) packages/runtime/src/app-plugin.ts#start, the per-organization replayer it registers as `seed-replayer` for tenant provisioning — `resolveSeedLocaleForLoad` (packages/runtime/src/seed-locale.ts), resolved per organization at replay time: the organization's `localization.locale` setting when somebody set it (a `source: 'default'` answer does not count), then the founder's `sys_user.locale`, then the app's `i18n.defaultLocale`; (4) packages/cloud-connection/src/marketplace-install-local-plugin.ts#runInlineSeed, one builder behind four paths, all through `resolveSeedLocaleForLoad` — the marketplace install and the sample-data reseed (`applySideEffects`: the setting, then the installing or reseeding user's `sys_user.locale`, then the package's declared `i18n.defaultLocale`), the restart heal (`maybeHealSampleData`: no organization and no user, so the setting as read for a load naming no organization, then the package's default) and this plugin's own per-organization replayer (`buildSeedReplayer`, registered only where no `AppPlugin` replayer already is: the setting, then the founder, and no app-default rung, because its shared list is every installed package's datasets). #16595 wired (1)–(3) in `packages/runtime/src/app-plugin.ts` — the default boot path, which is what makes authoring `locale` change runtime behaviour and therefore what makes this row `live` — and PR #30346 (`Fixes #30281`, merged 2026-11-05) moved (3) onto `resolveSeedLocaleForLoad`, keeping `resolveSeedLocale` as its last rung, and wired (4). A builder whose source answers nothing sends no `locale` key, never an `'en'` guess. TWO are publish-time paths and still pass no locale: (5) packages/runtime/src/domains/packages.ts#applyPublishedSeeds (package apply) and (6) packages/metadata-protocol/src/protocol-publish-batch.ts#applySeedBodies (draft publish — the body `packages/metadata-protocol/src/protocol.ts#applySeedBodies` delegates to; the request moved out of `protocol.ts` with it). Neither is handed the stack config, and neither passes `env` either, so this is the SAME frontier the `live` `env` row already sits behind rather than a new one — but `env` crosses it because `resolveEnvConfig` can read an ambient `NODE_ENV` inside `load()`, and a locale has no ambient source inside `load()`, so it cannot be closed the same way: the four builders that supply one resolve it at the call site. RULED 2026-09-10 on #17011 (director seat, one-class self-adjudication, option A 「不扩散」): publish and install are locale-neutral acts, so this bound is the CONTRACT rather than an open defect — 「无违约、非缺陷」, because `content/docs/data-modeling/seed-data.mdx` already declared that these three paths load every dataset and warn. What the ruling ordered was wording, not wiring: `SeedSchema.locale`'s describe and that docs page now state the bound, and ⛔ no behaviour changed on the three sites — making them pass a locale (option B) and turning the warning into a refusal (option C) were both explicitly ⛔ not ruled. So this line is a DECISION, not a to-do. ⚠️ NARROWED 2026-11-05 — the ruling above is kept as it was recorded, and its \"three paths\" and \"three sites\" are the 2026-09-10 set, marketplace install included. A maintainer ruling on #30281 (2026-11-05, option A, reversing #17011's install-path bound) ordered the install paths to pick datasets by locale, on HotCRM's request for zh-CN demo data rather than through the measurement the premise below names; PR #30346 (`Fixes #30281`, merged 2026-11-05) carried it out and moved the marketplace-install path, builder (4) above, across that bound. The ruling's bound now covers package apply and draft publish only — builders (5) and (6) — and `SeedSchema.locale`'s describe (PR #30604) and that docs page state it narrowed the same way. ⚠️ THE RULING'S LOAD-BEARING PREMISE, and the one thing that reopens it: real first-party seed data using `locale`, measured repo-wide, is ZERO — re-derived 2026-09-22 against 1f53b0b685 by a structural scan of all 49 `defineSeed` call sites (24 of them real app data in `examples/`, none declaring `locale`), self-lit because the same scan does find the two `locale`-declaring call sites on the docs page. That reach is THIS repo only; cloud / hotcrm / external customer apps stay unmeasured. A measured use of `locale`-scoped seed data in any of them reopens this as option B. ⚠️ AND THEREFORE `SeedLoaderService#warnOnUnresolvedLocaleScope` STAYS (the judgement #16595 was asked to make, decided with its reason recorded here rather than deleted silently): it is not a signpost for an unwired state that has now gone away. It is the live diagnostic for the two call sites above that pass none (package apply, draft publish), for any embedding host that builds its own request, for a stack that declares no `i18n` block (the boot seed and the dev hot-reload seeder have no other source), and, since 2026-11-05, for an install, reseed, heal or replay on which no rung of `resolveSeedLocaleForLoad` answers — all of which still reach `load()` with locale-scoped datasets and no `config.locale`. Deleting it would make exactly those paths silently inert, which is the property this row spent a release being. REPOINTED while flipping: the pre-flip text of this note named four call sites (the three in app-plugin.ts plus draft publish) and called the `protocol.ts` one unconfirmed. Re-derived against `main` at bb7d91f19f: the `protocol.ts` site is REAL — the earlier negative came from grepping `seedLoader.load`, and that call site names its local `loader` — and the enumeration was short by two (package apply, marketplace install). The full set is the six named above, found by scanning `SeedLoaderRequestSchema` rather than a variable name. RE-COUNTED 2026-11-05 against b8929f48 by the same scan of production `SeedLoaderRequestSchema` parses: still SIX builders, the six named above, with the draft-publish request now built in `protocol-publish-batch.ts`. A control scan of every `new SeedLoaderService(` finds no seventh: its three other constructions, in the marketplace plugin's sample-data scope, purge and count reads (`sampleDataInScope`, `handlePurge`, `handleSampleDataCount`), call only `buildDependencyGraph` and never `load()`." }, + "fallback": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/metadata-protocol/src/seed-loader.ts#isFallbackDataset (`fallback === true` — the one read of the key); packages/metadata-protocol/src/seed-loader.ts#filterByLocale (a marked dataset the resolved locale would drop is kept when `objectsWithLocaleMatch` finds no locale-scoped dataset of its object listing that locale, and the load names it at info); packages/metadata-protocol/src/seed-loader.ts#findDuplicateFallbackSets (two different marked datasets of one object among the env-kept datasets — identical copies counted once — refuse that object's fallback choice alone: no marked set fills in for an unlisted locale, each still loads for the locales it lists, the object is reported at warn, and the rest of the load seeds)", + "producer": "the same locale producers as the `locale` row above: packages/runtime/src/app-plugin.ts#resolveSeedLocale (boot seed and dev hot reload, off the app's `i18n.defaultLocale`) and packages/runtime/src/seed-locale.ts#resolveSeedLocaleForLoad (per-organization replay, and the marketplace install, sample-data reseed and restart heal through packages/cloud-connection/src/marketplace-install-local-plugin.ts#runInlineSeed). The marker only changes a load that carries a locale, so it is live exactly where `locale` is", + "note": "Seeded 2026-11-17 (seat 3 ruling, route A, on the card: an explicit per-set marker, additive and opt-in). Loads the marked set for a locale no locale-scoped set of its object lists, so an organization outside every declared market still gets one set of a locale-split seed. A dataset with no `locale` is locale-neutral: it neither matches nor blocks. The schema refuses `fallback: true` without `locale` (`dependentRequired`, projected into the published JSON Schema); with two different marked sets of one object in one load, the loader refuses only that object's fallback choice and reports it; each marked set still loads for the locales it lists. A load with no locale (package apply, draft publish, an unresolved install) loads every dataset, the marked one included, behind the `locale` row's bound. Pins, on rows reaching the engine: packages/metadata-protocol/src/seed-loader-locale-scope.test.ts (`Seed.fallback fills in…`: selection, per-object matching, env composition, the duplicate refusal) and packages/runtime/src/app-plugin.seed-locale-producer.test.ts (`Seed.fallback on the boot and install paths`: inline boot seed, dev hot reload, per-organization replay, and the install, reseed and heal request shape), each with an unmarked control giving no rows." + }, "dependsOn": { "status": "live", "verifiedAt": "2026-11-16", diff --git a/packages/spec/liveness/state-counts/seed.md b/packages/spec/liveness/state-counts/seed.md index c6d098c3ec4..5be3f959710 100644 --- a/packages/spec/liveness/state-counts/seed.md +++ b/packages/spec/liveness/state-counts/seed.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `seed` | 19 | 0 | 0 | 0 | 0 | 19 | +| `seed` | 20 | 0 | 0 | 0 | 0 | 20 | diff --git a/packages/spec/src/data/seed.test.ts b/packages/spec/src/data/seed.test.ts index 4760d92f3c5..84ead3a5800 100644 --- a/packages/spec/src/data/seed.test.ts +++ b/packages/spec/src/data/seed.test.ts @@ -309,6 +309,55 @@ describe('SeedSchema', () => { }); }); + // ── Fallback locale set ────────────────────────────────────────────────── + // + // `fallback: true` marks the set an organization receives when its locale + // matches no locale-scoped set of the object. The loader decides when it + // loads; the schema owns the one per-dataset rule: the marker needs `locale`. + + describe('fallback locale set', () => { + const withFallback = (extra: Record) => + SeedSchema.safeParse({ object: 'price_book', records: [], ...extra }); + + it('accepts `fallback: true` on a locale-scoped dataset, and keeps it', () => { + // Value reachability: the WHOLE parse succeeds, not only "no unrecognized key". + const parsed = withFallback({ locale: ['en', 'en-US'], fallback: true }); + expect(parsed.success).toBe(true); + expect(parsed.success && parsed.data.fallback).toBe(true); + expect(parsed.success && parsed.data.locale).toEqual(['en', 'en-US']); + }); + + it('is optional with no default: a seed without it parses to no key', () => { + const parsed = SeedSchema.parse({ object: 'price_book', locale: ['zh-CN'], records: [] }); + expect('fallback' in parsed).toBe(false); + }); + + it('refuses `fallback: true` with no `locale`, at the fallback key, naming the fix', () => { + const parsed = withFallback({ fallback: true }); + expect(parsed.success).toBe(false); + const issue = !parsed.success ? parsed.error.issues[0] : undefined; + expect(issue?.code).toBe('custom'); + expect(issue?.path).toEqual(['fallback']); + expect(issue?.message.split('. ')[0]).toBe('`fallback: true` needs `locale`'); + }); + + it('takes only `true`: `false` and a string are refused at the key', () => { + for (const value of [false, 'true', 1]) { + const parsed = withFallback({ locale: ['en'], fallback: value }); + expect(parsed.success, `fallback: ${JSON.stringify(value)}`).toBe(false); + expect(!parsed.success && parsed.error.issues[0]?.path).toEqual(['fallback']); + } + }); + + it('defineSeed carries the marker onto the seed and refuses it without a locale', () => { + const PriceBook = { name: 'price_book', fields: { name: { type: 'text' } } } as const; + const seed = defineSeed(PriceBook, { locale: ['en'], fallback: true, records: [{ name: 'Standard' }] }); + expect(seed.fallback).toBe(true); + expect(() => defineSeed(PriceBook, { fallback: true, records: [{ name: 'Standard' }] })) + .toThrow(/fallback: true` needs `locale`/); + }); + }); + // ── Column policies (#25761) ───────────────────────────────────────────── // // `columns..applyOn: 'create'` is the import door's create-only column diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index acfd2e15f12..c57242a8785 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -13,6 +13,7 @@ import { LocaleSchema } from '../system/translation.zod'; import { findClosestMatches, formatSuggestion } from '../shared/suggestions.zod'; import { resolveInjectedSystemColumns, type InjectedSystemColumnName } from './injected-system-columns'; import { ColumnApplyOnSchema } from './column-apply-on.zod'; +import { dependentRequired } from '../shared/refinement-projection'; import { FILE_REFERENCE_TYPES } from './field-value.zod'; import { SeedFileContentSchema, @@ -313,9 +314,67 @@ export const SeedSchema = lazySchema(() => strictObject({ * That is the bound ruled on #17011 (2026-09-10), narrowed to these two * paths when the maintainer ruled that the install paths pick by locale * (2026-11-05). + * + * A locale no dataset of an object names gets none of that object's + * locale-scoped rows — unless one of them is marked + * {@link SeedSchema.shape.fallback}. */ locale: z.array(LocaleSchema).min(1).optional() - .describe('Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app\'s i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app\'s i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn'), + .describe('Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app\'s i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app\'s i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn. A locale no dataset of the object names gets none of its locale-scoped rows, unless one is marked `fallback: true`'), + + /** + * Fallback Locale Set + * + * Marks this locale-scoped dataset as its object's fallback: it loads for the + * locales it lists, like any other, AND for a locale that no other dataset of + * the same object lists. An app that splits a seed by language — a `zh-CN` + * set and an `en` set of the standard price book — marks one of them, and an + * organization whose language is neither (`ja-JP`, `es-ES`) receives that + * set instead of no price book at all. + * + * ```ts + * defineSeed(PriceBook, { locale: ['zh-CN'], records: [{ name: '标准价格表' }] }), + * defineSeed(PriceBook, { locale: ['en', 'en-US'], fallback: true, records: [{ name: 'Standard' }] }), + * ``` + * + * - **Requires `locale`.** A dataset with no `locale` already loads for every + * locale, so `fallback: true` on it could only mean something it does not + * do; the schema refuses the pair rather than read the marker as redundant. + * The fallback set lists the locales it is written in, the way every + * locale-scoped set does. + * - **"Matches" means a locale-scoped dataset of the same object lists the + * resolved locale.** A dataset with no `locale` is locale-neutral: it loads + * beside whichever set is chosen and does not stop the fallback from + * filling in. Matching is the `locale` rule's own: case-insensitive, and + * otherwise exact. + * - **Judged after `env`.** A dataset `env` scoped out of the load neither + * matches nor falls back. + * - **At most one per object in a load.** Two different datasets of one + * object both marked `fallback: true` leave the loader no single choice, + * so only the fallback choice is refused: no marked set is used as the + * fallback for a locale no set lists, and the load reports the object at + * `warn`. Every marked set still loads for the locales it lists, exactly as + * an unmarked set would, and every other object still seeds. Identical + * copies of one dataset (a package's list merged twice) count once; two + * versions of one package whose marked set changed are two datasets (an + * upgrade keeps the earlier version's on the replay list until restart). + * - **A load with no locale** (package apply, draft publish, or a load no rung + * resolved a locale for) loads every dataset, the fallback set included, + * and warns, as for any locale-scoped dataset. + * + * The one value is `true`; omitted, the dataset loads only for the locales it + * lists, as before this key existed. + */ + fallback: z.literal(true).optional() + .describe( + 'Marks this locale-scoped dataset as its object\'s fallback: it also loads for a resolved locale that no ' + + 'other locale-scoped dataset of the same object lists. Requires `locale`: a dataset with no locale already ' + + 'loads everywhere, and the pair is refused. At most one dataset per object in a load may be marked; with ' + + 'two different marked datasets of one object, none is used as the fallback and the load reports the object, ' + + 'while each still loads for the locales it lists, as an unmarked dataset would (identical copies count once). ' + + 'A load with no locale loads it like every other dataset. Omitted, the dataset loads only for the locales it ' + + 'lists.', + ), /** * Load-Order Dependencies @@ -394,6 +453,19 @@ export const SeedSchema = lazySchema(() => strictObject({ // (#4001 findings log, entry 2). Declared here so closing the shape cannot // repeat it. ...MetadataProtectionFields, +}).refine(dependentRequired({ fallback: ['locale'] }), { + // [Seed.fallback] Declared through the closed projection list, so the + // published JSON Schema carries the rule as `dependentRequired` instead of + // accepting what this parse refuses. A dataset with no `locale` already loads + // for every locale, so the marker could only promise a behaviour the loader + // does not have: refused, with the fix, rather than read as redundant — a + // marker that is silently a no-op is the declared-not-enforced shape ADR-0049 + // forbids. + path: ['fallback'], + message: + '`fallback: true` needs `locale`. A dataset with no locale already loads for every locale, so it cannot ' + + 'also be the set that loads only when no other set matches. List the locales this dataset is written in ' + + '(`locale: [\'en\']`) and keep `fallback: true`, or drop `fallback`.', })); /** Parsed/output type — all defaults are applied (env, mode, externalId always present) */