diff --git a/.changeset/34613-scenario-seed-no-retired-mode.md b/.changeset/34613-scenario-seed-no-retired-mode.md new file mode 100644 index 00000000000..d8ffef05342 --- /dev/null +++ b/.changeset/34613-scenario-seed-no-retired-mode.md @@ -0,0 +1,7 @@ +--- +'@objectstack/scenarios': patch +--- + +fix(scenarios): the runner's card seed and restore load under the default seed mode, not the retired `insert` + +The scenario runner wrote every card seed (and every restore of a removed seeded row) as a data-only package whose datasets declared `mode: 'insert'`. That mode is retired (#34613), and the managed install door refuses a dataset declaring it, every row of it, so no card seed loaded. The datasets now name no `mode`: the default, `ignore`, creates each row whose `id` the object does not hold and leaves one it holds as it is, which is what a fresh seed needs. A restore needs more: the install door keeps the organization's record of landed seed rows (`sys_seed_landed_key`) and withholds a recorded row that is gone, as a person's removal, so an install does not put back a seeded row a turn deleted. The restore therefore goes on through that package's sample-data reseed (`POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data`), the platform's deliberate re-seed, which inserts every missing row; and whenever the door skipped a row, the runner reads the objects back and refuses each row still not there by name, with the reason, instead of counting it as written or reinserted. The test double's seed door now judges `mode` with `SeedMode` and keeps the landed-row record, as the real door does, and pins hold that the seed and restore packages carry no retired mode and that a restore brings back a recorded row. diff --git a/.changeset/34613-seed-mode-insert-replace-retired.md b/.changeset/34613-seed-mode-insert-replace-retired.md new file mode 100644 index 00000000000..cbc2872ef90 --- /dev/null +++ b/.changeset/34613-seed-mode-insert-replace-retired.md @@ -0,0 +1,34 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +'@objectstack/runtime': patch +'@objectstack/cloud-connection': patch +'@objectstack/lint': minor +'@objectstack/cli': patch +'@objectstack/metadata': patch +--- + +fix(spec,metadata-protocol)!: retire the seed modes `insert` and `replace`, which inserted every record again on each replay + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up #34798 + + + +**BREAKING** for a seed dataset authored with `mode: 'insert'` or `mode: 'replace'`. A seed is replayed on every single-tenant boot, every package install or upgrade and every publish, and neither mode matched an existing row, so every replay inserted each record again: an un-walled install went from 1 to 2 to 3 rows over three boots, a person reference the first load had to leave empty stayed empty on the first row while only the newest copy named the person, and with a unique field the replay insert was refused and the one row stayed empty. `replace` expected the caller to clear the table first, and no load path ever clears one. + +What moves (each line FROM → TO): + +- `SeedSchema.mode` / `SeedMode` (`@objectstack/spec/data`; `defineSeed`, `defineStack({ data })`, a `seed` metadata item, a package body's seed): FROM `insert` / `update` / `upsert` / `replace` / `ignore` TO `update` / `upsert` / `ignore` (default `ignore`, unchanged). `mode: 'insert'` or `mode: 'replace'` fails parse with a prescription naming the fix; the save and publish doors refuse it with the same message. The retired pair is exported as `RETIRED_SEED_MODE_VALUES` (`@objectstack/spec/data`): it is derived from the parse refusal's own table, and the loader and the artifact door read it. +- a stored dataset that still declares one, replayed by the boot seed, the per-organization replay, the dev hot reload or a package install, upgrade or sample-data reseed (`SeedLoaderService.loadStored`, `@objectstack/metadata-protocol`): FROM inserted again on every load TO refused alone — it writes nothing, the load result carries one error with the prescription and `success: false`, and every other dataset loads. `SeedLoaderService.load()` and `validate()` refuse the dataset the same way when handed one unparsed, so a dry run reports what a real load does. +- a compiled artifact (`objectstack.json`) carrying such a dataset, booted by `os serve` / `os start` / `os dev` (the artifact door, `MetadataPlugin`, `@objectstack/metadata`): the door parses the artifact without that dataset and hands it back to the seed load, which refuses it alone; the door logs a warning naming the dataset and the fix. Everything else in the artifact registers and boots. +- `os diff` (`@objectstack/cli`) on a dataset declaring either mode: FROM "a replay inserts these again" TO a note that the mode is retired, that a replay refuses the dataset, and what to declare. +- the advisory lint rule `seed-insert-mode-duplicates-on-replay` (`validateSeedReplaySafety`, `@objectstack/lint`): FROM a warning on `mode: 'insert'` TO removed; the schema refusal does its job for both modes. The author-time rule count `os validate` / `os build` print drops by one (71 to 70 at this release). +- the save door's and the loader's hint for a key no record carries: FROM "or use mode 'insert' for rows with no natural key" TO a list of fields when no single field names a row, or `'id'` when the records carry their own ids. + +The fix: declare which field identifies a row and drop the mode (or declare `upsert` for reference data the package keeps current). Set `externalId` to the field that names a row, to a list of fields when no single field does (a junction table's `['team', 'project']`), or to `'id'` when the records carry their own ids. Rebuild the package, and reinstall it where it was installed with `os package install`, so the stored body carries the new declaration. + +No conversion is made, at load, at save or by a migration (ADR-0087 D3, entry `seed-mode-insert-replace-retired`): a keyed mode needs the field that identifies a row, and only the author knows it. Rows earlier replays duplicated are data and are left as they are. + +Unchanged: `ignore`, `upsert` and `update` datasets load byte-identically. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index ed2f7782631..25df2611c2f 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -73,9 +73,11 @@ customer has since edited. |:-----|:---------|:---------| | `ignore` | **Default.** Create-only: insert a record whose row is missing (a boot or organization replay skips one a person [deleted](#a-deleted-seed-row-stays-deleted)), leave an existing row exactly as it is | Business and starter data the customer owns once it is loaded | | `upsert` | Create if new (a boot or organization replay skips one a person [deleted](#a-deleted-seed-row-stays-deleted)), and on **every** replay write each declared column back onto the matched row | Reference data the package must keep current | -| `insert` | Insert **every** record unconditionally — no existing-row check, so it **duplicates the table on each replay boot** ([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)). Rarely what you want | Append-only rows loaded exactly once (never re-run) | | `update` | Update only, skip if not found | Migration patches on existing rows | -| `replace` | Insert without checking for an existing match — the seed loader does **not** delete anything itself; the target table must already be empty (or cleared by the caller) | Cache / lookup tables rebuilt from an already-truncated table | + +Every mode matches on `externalId`, so a replay finds the row an earlier load wrote. +The unkeyed modes `insert` and `replace` are retired: see +[Moving off `insert` and `replace`](#moving-off-insert-and-replace). ### `ignore` — The Default (Create-Only) @@ -126,32 +128,57 @@ customer or a job owns, mark those columns create-only — see `mode: 'upsert'` on the datasets that must stay current. -### `replace` — Insert Into an Already-Cleared Table +### Moving off `insert` and `replace` + +`insert` and `replace` matched no existing row, so every replay inserted each +record again: a 3-row fixture became 6, then 9 +([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)), and a person +reference the first load had to leave empty stayed empty on the first row while +only a later copy named the person. `replace` expected the caller to clear the +table first, and no load ever clears one. Both were removed in +`@objectstack/spec` 18.7.0 ([#34613](https://github.com/objectstack-ai/objectstack/issues/34613)): + +- **Authoring refuses them.** `defineSeed`, `defineStack`, `os validate`, `os build` + and the metadata save and publish doors reject `mode: 'insert'` or + `mode: 'replace'` with a message that names the fix. +- **A stored dataset is refused alone.** A package or a compiled artifact + (`objectstack.json`) built before the change, or a seed already stored, can + still carry one. The environment still boots: the boot seed, the organization + replay, the dev hot reload and a package install or upgrade refuse that one + dataset. It writes nothing, the load reports it as an error with the same + message, and every other dataset and definition loads. +- **Rows already duplicated stay.** Earlier replays wrote them as data; nothing + deletes them. Remove the extra copies yourself if they matter. + +To convert a dataset, declare which field identifies a row, then drop the mode +(or declare `upsert` for reference data the package keeps current): + +1. **A field names the row** (a code, a slug, an email): set `externalId` to it. +2. **No single field does** (a join table, a line item under a parent): set + `externalId` to the list of fields that together identify a row, for example + `['team', 'project']`. Reference fields are matched by their resolved ids. A + reference the first load has to leave empty (a person who has not signed up + yet) still belongs in the key: each later load finds that row again by the + key as authored, and the load that can resolve the person fills it in. See + [Composite natural key](#composite-externalid--join--junction-tables). +3. **The records carry their own ids**: set `externalId: 'id'`. ```typescript -// ⚠️ The seed loader does NOT delete existing records for you — `replace` -// always inserts. Truncate/clear the table yourself before this seed runs, -// or every load will attempt to insert duplicate rows. -// Only use for cache or lookup tables with no user-generated data. -defineSeed(ExchangeRateCache, { - externalId: 'key', +// Before — refused since @objectstack/spec 18.7.0 +defineSeed(ExchangeRate, { mode: 'replace', - env: ['dev'], - records: [ - { key: 'USD_EUR', rate: 0.92 }, - { key: 'USD_GBP', rate: 0.79 }, - ], + records: [{ key: 'USD_EUR', rate: 0.92 }], }); -``` -### `insert` — Not Idempotent (Avoid for Replayed Seeds) +// After — one row per key, written once +defineSeed(ExchangeRate, { + externalId: 'key', + records: [{ key: 'USD_EUR', rate: 0.92 }], +}); +``` -Seeds are **replayed** — they re-load on every dev-server boot and every package -re-publish, not applied once. `insert` writes every record with **no existing-row -check**, so a replayed `insert` dataset duplicates its table on each restart -(a 3-row fixture becomes 6, then 9 — [#3434](https://github.com/objectstack-ai/objectstack/issues/3434)). -It is almost never the right mode: leave `mode` unset (create-only), or declare -`upsert` for reference data, with a stable `externalId` instead. `os validate` warns on any `mode: 'insert'` seed. +Rebuild the package (and reinstall it where it was installed with +`os package install`) so the stored body carries the new declaration. ### A Deleted Seed Row Stays Deleted @@ -243,8 +270,8 @@ defineSeed(Instalment, { out of the write: the row keeps the values the jobs gave it, while `amount` (`applyOn: 'always'`, the default) is refreshed. A row whose only differences are create-only columns is not written at all. -- An `update` dataset never writes a create-only column. `insert`, `ignore` and - `replace` never update a matched row, so the policy changes nothing there. +- An `update` dataset never writes a create-only column. `ignore` never updates + a matched row, so the policy changes nothing there. - A create-only **reference** on a matched row is not resolved at all, so a replay neither re-points it nor reports it. - A column of the `externalId` is what the row was matched by, so it stays in @@ -541,8 +568,9 @@ const membershipsSeed = defineSeed(ProjectMembership, { }); ``` -Without a composite key such a table can only fall back to `mode: 'insert'`, which -duplicates on every replay boot ([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)). +Without a composite key such a table has nothing to match a replay on. The +unkeyed `mode: 'insert'` it once fell back to duplicated on every replay boot +([#3434](https://github.com/objectstack-ai/objectstack/issues/3434)) and is retired. --- @@ -807,8 +835,8 @@ behind already wrote — see [Locale Scoping](#locale-scoping). The default, `ignore`, is idempotent and never overwrites an edit. Declare a mode only when the use case requires it — `upsert` for reference data the package keeps current -(with `applyOn: 'create'` on the columns the customer or a job owns), or `replace` -for ephemeral cache tables. +(with `applyOn: 'create'` on the columns the customer or a job owns), or `update` +for a migration patch on rows that already exist. ### Declare a dependency no field expresses @@ -838,7 +866,7 @@ function defineSeed< objectDef: TObj, config: { externalId?: string | string[]; // single field, or a composite list (join tables); default: 'name' - mode?: 'insert' | 'update' | 'upsert' | 'replace' | 'ignore'; // default: 'ignore' + mode?: 'update' | 'upsert' | 'ignore'; // default: 'ignore' 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 diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index cb822bc766e..71f03a48826 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -887,7 +887,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (71)... + → Running author-time rules (70)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index d28c626164a..844a84b278c 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -866,7 +866,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (71)... + → Running author-time rules (70)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index df9b3e58a3c..b3cdd1858d9 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (71)... + → Running author-time rules (70)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/references/api/package-api-assembled.mdx b/content/docs/references/api/package-api-assembled.mdx index ef4f4851700..cf5e7155426 100644 --- a/content/docs/references/api/package-api-assembled.mdx +++ b/content/docs/references/api/package-api-assembled.mdx @@ -99,7 +99,7 @@ Installed package row whose manifest is the assembled package body | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | | **capabilities** | `{ name: string; label?: string; description?: string; scope?: Enum<'platform' \| 'org'>; … }[]` | optional | [ADR-0066 D1] Authorization capabilities this package defines (seeded with package provenance) | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -285,7 +285,7 @@ This schema accepts one of the following structures: | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -349,7 +349,7 @@ This schema accepts one of the following structures: | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Seed Data / Fixtures for bootstrapping | | **capabilities** | `{ name: string; label?: string; description?: string; scope?: Enum<'platform' \| 'org'>; … }[]` | optional | [ADR-0066 D1] Authorization capabilities this package defines (seeded with package provenance) | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/references/api/package-api.mdx b/content/docs/references/api/package-api.mdx index 48ade0c36a5..bae5bca0373 100644 --- a/content/docs/references/api/package-api.mdx +++ b/content/docs/references/api/package-api.mdx @@ -155,7 +155,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -201,7 +201,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -243,7 +243,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **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. | +| **mode** | `Enum<'update' \| 'upsert' \| '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. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. 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 | @@ -310,7 +310,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -352,7 +352,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **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. | +| **mode** | `Enum<'update' \| 'upsert' \| '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. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. 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 | @@ -428,7 +428,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -570,7 +570,7 @@ Upgrade package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -664,7 +664,7 @@ Resolve dependencies request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index ed6902f7f54..feee8113694 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -2190,7 +2190,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index ac7c1bf2d34..bf232d2845c 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -153,7 +153,7 @@ Result of loading a single dataset | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Object that was loaded | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | ✅ | Import mode used | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | ✅ | Import mode used | | **inserted** | `integer` | ✅ | Records inserted | | **updated** | `integer` | ✅ | Records updated | | **skipped** | `integer` | ✅ | Records skipped | @@ -195,7 +195,7 @@ Seed data loader configuration | **dryRun** | `boolean` | optional (default: `false`) | Validate references without writing data | | **haltOnError** | `boolean` | optional (default: `false`) | Stop on first reference resolution error | | **multiPass** | `boolean` | optional (default: `true`) | Enable multi-pass loading for circular dependencies | -| **defaultMode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | +| **defaultMode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | | **batchSize** | `integer` | optional (default: `1000`) | Maximum records per batch insert/upsert | | **transaction** | `boolean` | optional (default: `false`) | Wrap entire load in a transaction (all-or-nothing) | | **env** | `Enum<'prod' \| 'dev' \| 'test'>` | optional | Only load datasets matching this environment | @@ -221,8 +221,8 @@ Seed loader request with datasets and configuration | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **seeds** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | ✅ | Seeds to load | -| **config** | `{ dryRun?: boolean; haltOnError?: boolean; multiPass?: boolean; defaultMode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; … }` | optional (has default) | Loader configuration | +| **seeds** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | ✅ | Seeds to load | +| **config** | `{ dryRun?: boolean; haltOnError?: boolean; multiPass?: boolean; defaultMode?: Enum<'update' \| 'upsert' \| 'ignore'>; … }` | optional (has default) | Loader configuration | ### Nested Shape: `SeedLoaderRequest.seeds[number]` @@ -230,7 +230,7 @@ Seed loader request with datasets and configuration | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **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. | +| **mode** | `Enum<'update' \| 'upsert' \| '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. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. 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 | @@ -252,7 +252,7 @@ Seed loader request with datasets and configuration | **dryRun** | `boolean` | optional (default: `false`) | Validate references without writing data | | **haltOnError** | `boolean` | optional (default: `false`) | Stop on first reference resolution error | | **multiPass** | `boolean` | optional (default: `true`) | Enable multi-pass loading for circular dependencies | -| **defaultMode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | +| **defaultMode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | optional (default: `"ignore"`) | Default conflict resolution strategy: the seed `mode` default (`ignore`, create-only) | | **batchSize** | `integer` | optional (default: `1000`) | Maximum records per batch insert/upsert | | **transaction** | `boolean` | optional (default: `false`) | Wrap entire load in a transaction (all-or-nothing) | | **env** | `Enum<'prod' \| 'dev' \| 'test'>` | optional | Only load datasets matching this environment | @@ -274,7 +274,7 @@ Complete seed loader result | **success** | `boolean` | ✅ | Overall success status | | **dryRun** | `boolean` | ✅ | Whether this was a dry-run | | **dependencyGraph** | `{ nodes: object[]; insertOrder: string[]; circularDependencies?: string[][] }` | ✅ | Object dependency graph | -| **results** | `{ object: string; mode: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; inserted: integer; updated: integer; … }[]` | ✅ | Per-object load results | +| **results** | `{ object: string; mode: Enum<'update' \| 'upsert' \| 'ignore'>; inserted: integer; updated: integer; … }[]` | ✅ | Per-object load results | | **errors** | `{ sourceObject: string; field: string; targetObject: string; targetField: string; … }[]` | ✅ | All reference resolution errors | | **summary** | `{ objectsProcessed: integer; totalRecords: integer; totalInserted: integer; totalUpdated: integer; … }` | ✅ | Summary statistics | @@ -293,7 +293,7 @@ Result of loading a single dataset | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Object that was loaded | -| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | ✅ | Import mode used | +| **mode** | `Enum<'update' \| 'upsert' \| 'ignore'>` | ✅ | Import mode used | | **inserted** | `integer` | ✅ | Records inserted | | **updated** | `integer` | ✅ | Records updated | | **skipped** | `integer` | ✅ | Records skipped | diff --git a/content/docs/references/data/seed.mdx b/content/docs/references/data/seed.mdx index 85b470d265c..c113b1fb172 100644 --- a/content/docs/references/data/seed.mdx +++ b/content/docs/references/data/seed.mdx @@ -30,7 +30,7 @@ const result = SeedSchema.parse(data); | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **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. | +| **mode** | `Enum<'update' \| 'upsert' \| '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. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. 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 | @@ -80,10 +80,8 @@ One bundled seed file: its bytes and what they must hash to ### Allowed Values -* `insert` * `update` * `upsert` -* `replace` * `ignore` diff --git a/content/docs/references/kernel/manifest.mdx b/content/docs/references/kernel/manifest.mdx index 0a6ae3cce51..31798189bd5 100644 --- a/content/docs/references/kernel/manifest.mdx +++ b/content/docs/references/kernel/manifest.mdx @@ -55,7 +55,7 @@ Install mode: managed (registered as code, upgradeable, sealed) | unmanaged (cop | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -97,7 +97,7 @@ Install mode: managed (registered as code, upgradeable, sealed) | unmanaged (cop | :--- | :--- | :--- | :--- | | **object** | `string` | ✅ | Target Object Name | | **externalId** | `string \| string[]` | optional (default: `"name"`) | Field (or composite list of fields) matched for the uniqueness check | -| **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. | +| **mode** | `Enum<'update' \| 'upsert' \| '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. Every mode matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. 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 | diff --git a/content/docs/references/kernel/package-registry.mdx b/content/docs/references/kernel/package-registry.mdx index b01891eb534..34d19a404cf 100644 --- a/content/docs/references/kernel/package-registry.mdx +++ b/content/docs/references/kernel/package-registry.mdx @@ -210,7 +210,7 @@ Install package request | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | @@ -308,7 +308,7 @@ Installed package with runtime lifecycle state | **dependencies** | `Record` | optional | Package dependencies | | **configuration** | `never` | optional | [REMOVED] `manifest.configuration` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — nothing ever read the block: no settings UI rendered it and no loader resolved a setting from it, so authoring it configured nothing. Worse, `properties.*.secret` promised "value is encrypted/masked (e.g. API Keys)" while nothing encrypted, masked or even parsed the flag — a false assurance about credential handling. Delete the key. A plugin is configured by the host that composes it: pass options to its constructor in `defineStack({ plugins: [new MyPlugin({ … })] })`, which is the enforced channel. A declarative settings surface must be designed with an enforcing reader first, not revived here. | | **contributes** | `{ kinds?: object[] }` | optional | Platform contributions | -| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | +| **data** | `{ object: string; externalId?: string \| string[]; mode?: Enum<'update' \| 'upsert' \| 'ignore'>; columns?: Record; … }[]` | optional | Initial seed data (prefer top-level data field) | | **capabilities** | `never` | optional | [REMOVED] `manifest.capabilities` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — no discovery path ever consulted the block: nothing read `implements`, `provides`, `requires`, `extensionPoints` or `extensions`, so the declared "interoperability and automatic discovery" never happened. Delete the key. Real dependency resolution runs off top-level `manifest.dependencies`, which stays. Capability-based discovery must be designed with an enforcing reader first, not revived here. | | **extensions** | `never` | optional | [REMOVED] `manifest.extensions` was removed in @objectstack/spec 17 (ADR-0049 enforce-or-remove) — an untyped map with zero readers: whatever was parked here was stored and never consulted. Delete the key. Extend the platform through the enforced channels instead: `contributes.kinds` registers metadata kinds, `navigationContributions` injects navigation into other packages' apps, and code-level extension happens in the plugin itself (`init`/`start`). | | **navigationContributions** | `{ app: string; group?: string; priority?: integer; items: (object \| … +9 more)[] }[]` | optional | Navigation items this package contributes into apps owned by other packages | diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 321b2d90c8c..b52c38b01c8 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (71)... + → Running author-time rules (70)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts index 36e7cb95eb1..fda3fd47177 100644 --- a/packages/cli/src/commands/diff.ts +++ b/packages/cli/src/commands/diff.ts @@ -78,8 +78,12 @@ function diffNamedArrays( function seedModeNote(mode: string): string { if (seedModeOverwritesMatchedRows(mode)) return '; a replay writes its columns over the rows it matches'; - if (mode === 'replace') return '; a replay deletes nothing and inserts these again, so rows already in the table stay'; - if (mode === 'insert') return "; a replay inserts these again, and a row the database refuses is that row's error"; + // [#34613] `insert` and `replace` are retired: a replay refuses such a + // dataset whole and writes none of it, so the note says what to declare. + if (mode === 'insert' || mode === 'replace') { + return `; \`${mode}\` is a retired seed mode: a replay refuses this dataset and writes none of it. ` + + "Declare `mode: 'ignore'` (or 'upsert') with an `externalId` that names a row"; + } return ''; } diff --git a/packages/cli/test/diff-upgrade-plan.test.ts b/packages/cli/test/diff-upgrade-plan.test.ts index 135d0c94408..f0a8b90306a 100644 --- a/packages/cli/test/diff-upgrade-plan.test.ts +++ b/packages/cli/test/diff-upgrade-plan.test.ts @@ -144,7 +144,8 @@ describe('os diff — what the upgrade plan adds', () => { { type: 'removed', category: 'data', name: 'acme_old', breaking: false, detail: 'seed dataset removed, mode insert' }, { type: 'added', category: 'data', name: 'acme_tier', breaking: false, - detail: 'seed dataset added: 1 record(s); mode replace; a replay deletes nothing and inserts these again, so rows already in the table stay', + detail: 'seed dataset added: 1 record(s); mode replace; `replace` is a retired seed mode: a replay refuses this ' + + "dataset and writes none of it. Declare `mode: 'ignore'` (or 'upsert') with an `externalId` that names a row", }, { type: 'modified', category: 'data', name: 'acme_stage', breaking: false, @@ -154,7 +155,10 @@ describe('os diff — what the upgrade plan adds', () => { ]); }); - it('an insert dataset, added or changed, says a replay inserts its records again; ignore stays silent', () => { + // [#34613] A stored artifact built before the retirement can still carry + // `insert`: the diff names the mode as retired and the fix, rather than + // describing a replay that no longer writes the dataset. + it('a retired insert dataset, added or changed, says a replay refuses it; ignore stays silent', () => { const before = lead({}, [ { object: 'acme_source', mode: 'insert', records: [{ name: 'web' }] }, { object: 'acme_region', mode: 'ignore', records: [{ name: 'emea' }] }, @@ -164,7 +168,8 @@ describe('os diff — what the upgrade plan adds', () => { { object: 'acme_region', mode: 'ignore', records: [{ name: 'apac' }] }, { object: 'acme_channel', mode: 'insert', records: [{ name: 'email' }] }, ]); - const insertNote = "a replay inserts these again, and a row the database refuses is that row's error"; + const insertNote = '`insert` is a retired seed mode: a replay refuses this dataset and writes none of it. ' + + "Declare `mode: 'ignore'` (or 'upsert') with an `externalId` that names a row"; expect(diffStacks(before, after)).toEqual([ { type: 'added', category: 'data', name: 'acme_channel', breaking: false, diff --git a/packages/cli/test/seed-record-values-load-parity.test.ts b/packages/cli/test/seed-record-values-load-parity.test.ts index 0d9c80ad21d..0802f2f0bd2 100644 --- a/packages/cli/test/seed-record-values-load-parity.test.ts +++ b/packages/cli/test/seed-record-values-load-parity.test.ts @@ -54,8 +54,8 @@ async function seedLoad(): Promise<{ written: string[]; refused: Map PROJECT, listObjects: async () => [PROJECT] }; const loader = new SeedLoaderService(engine as never, metadata as never, silent as never); const result = await loader.load({ - seeds: [{ object: 'proj_project', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], records: structuredClone(RECORDS) }], - config: { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'insert', batchSize: 1, transaction: false, organizationId: 'org_parity' }, + seeds: [{ object: 'proj_project', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: structuredClone(RECORDS) }], + config: { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1, transaction: false, organizationId: 'org_parity' }, } as never); const refused = new Map(); for (const e of result.errors as Array<{ recordIndex?: number; message: string }>) { diff --git a/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts b/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts index 3505a368aab..4f7ac3689ed 100644 --- a/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts +++ b/packages/cloud-connection/src/cloud-connection-auth-gate.pin.test.ts @@ -42,6 +42,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -50,6 +51,11 @@ import { isAuthGateAllowlisted } from '@objectstack/core'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts b/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts index 5ac91550641..8bcb5d2ada9 100644 --- a/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-api-key-account-posture.pin.test.ts @@ -29,6 +29,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -37,6 +38,11 @@ import { currentCredentialUseClient, hashApiKey } from '@objectstack/core'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts b/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts index b9230733d01..75fcd6455ac 100644 --- a/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-capability-enumeration.test.ts @@ -62,6 +62,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -69,6 +70,11 @@ import { tmpdir } from 'node:os'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts b/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts index 4d94fbc1a97..cdca8081771 100644 --- a/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-composed-bundle-seeds.test.ts @@ -20,6 +20,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -30,6 +31,11 @@ let seedResult: any; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } async buildDependencyGraph(objects: string[]) { return { objects }; } }, diff --git a/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts b/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts index ac58b8aca88..9efb153e720 100644 --- a/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-composed-top-level-reads.test.ts @@ -47,6 +47,8 @@ const heldDatasources = vi.hoisted(() => new Map()); vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The stored-seed funnel the plugin calls; it ends in `load`. + async loadStored() { return this.load(); } async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } async buildDependencyGraph(objects: string[]) { return { objects }; } }, diff --git a/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts b/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts index fb8211daf3f..87577277af3 100644 --- a/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-corrupt-ledger.test.ts @@ -41,6 +41,8 @@ import { tmpdir } from 'node:os'; // does so these tests exercise rehydrate's reporting, not seeding. vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The stored-seed funnel the plugin calls; it ends in `load`. + async loadStored() { return this.load(); } async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts index 7344130221e..16505f407e8 100644 --- a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts @@ -18,6 +18,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -29,6 +30,11 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } // The purge reads the loader's dependency order; these objects // reference nothing, so the order is the order asked. diff --git a/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts b/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts index dc83594492f..fcae6d05ad8 100644 --- a/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts @@ -433,3 +433,52 @@ describe('an unmanaged copy\'s sample data: the install honours the record, the expect(names('lk_account')).toEqual(['Acme', 'Globex']); }); }); + +/** + * The record has no package component (`(organization_id, object_name, + * seed_key)`), so it is the organization's, not the installing package's. The + * scenario runner loads its seed, and puts a removed seed row back, as data-only + * packages keyed on `id`, each under a namespace of its own + * (`loadSeedRows` in `packages/qa/scenarios/src/runner/orchestrate.ts`). This + * pins what such a load meets at this door: a second package carrying a + * recorded row that is gone does not insert it (withheld, counted in + * `skipped`, no error), and that package's reseed does. + */ +describe('a data-only package keyed on `id`: the record is the organization\'s, whichever package carries the row', () => { + const dataOnly = (namespace: string, records: Row[]) => ({ + id: `com.scenario.seed.${namespace}`, + namespace, + version: '0.0.1', + type: 'app', + scope: 'project', + name: 'Scenario seed', + data: [{ object: 'lk_account', externalId: 'id', records }], + }); + const ids = (object: string) => (store[object] ?? []).filter((r) => r.organization_id === ORG).map((r) => r.id).sort(); + + it('a row deleted after one package seeded it is withheld from a second package\'s install; the second package\'s reseed brings it back', async () => { + const rt = await boot(); + const first = await rt.install(dataOnly('scenarioseeda', [{ id: 'ct1', name: 'Ann' }, { id: 'ct2', name: 'Ben' }])); + expect(first.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 2, skipped: 0, errors: 0 }); + expect(landed()).toEqual(['lk_account:ct1', 'lk_account:ct2']); + store.lk_account = store.lk_account!.filter((r) => r.id !== 'ct2'); + + const second = await rt.install(dataOnly('scenarioseedb', [{ id: 'ct2', name: 'Ben' }])); + expect(second.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 0, skipped: 1, errors: 0, errorList: [] }); + expect(ids('lk_account')).toEqual(['ct1']); + + const reseed = await rt.reseed('com.scenario.seed.scenarioseedb'); + expect(reseed.status, JSON.stringify(reseed.payload)).toBe(200); + expect(reseed.payload.data).toMatchObject({ inserted: 1, skipped: 0, errors: 0 }); + expect(ids('lk_account')).toEqual(['ct1', 'ct2']); + expect(landed()).toEqual(['lk_account:ct1', 'lk_account:ct2']); + }); + + it('control: a row no load recorded is inserted by a second package\'s install', async () => { + const rt = await boot(); + await rt.install(dataOnly('scenarioseeda', [{ id: 'ct1', name: 'Ann' }])); + const second = await rt.install(dataOnly('scenarioseedb', [{ id: 'ct2', name: 'Ben' }])); + expect(second.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 1, skipped: 0, errors: 0 }); + expect(ids('lk_account')).toEqual(['ct1', 'ct2']); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts b/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts index 11673d8454d..12339f78b27 100644 --- a/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-no-active-organization.test.ts @@ -35,6 +35,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -43,6 +44,11 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index 1bbbe6c18a6..11b5d81aec4 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -7691,10 +7691,7 @@ export class MarketplaceInstallLocalPlugin implements Plugin { try { metadata = ctx.getService('metadata'); } catch { /* none */ } if (!ql || !metadata) throw new Error('objectql-or-metadata-missing'); - const [{ SeedLoaderService, appDefaultSeedLocale, describeSeedLocale, resolveSeedLocaleForLoad }, { SeedLoaderRequestSchema }] = await Promise.all([ - import('@objectstack/runtime'), - import('@objectstack/spec/data'), - ]); + const { SeedLoaderService, appDefaultSeedLocale, describeSeedLocale, resolveSeedLocaleForLoad } = await import('@objectstack/runtime'); const seedLocale = await resolveSeedLocaleForLoad(ctx, { seeds: datasets, organizationId, @@ -7703,7 +7700,9 @@ export class MarketplaceInstallLocalPlugin implements Plugin { }); ctx.logger?.info?.(`[MarketplaceInstallLocal] seed locale${organizationId ? ` for org ${organizationId}` : ''}: ${describeSeedLocale(seedLocale)}`); const seedLoader = new (SeedLoaderService as any)(ql, metadata, ctx.logger, { landedKeys }); - const request = (SeedLoaderRequestSchema as any).parse({ + // [#34613] `loadStored`: a stored dataset declaring a retired `mode` + // is refused alone, as an error of the result; the rest load. + const result = await seedLoader.loadStored({ // ADR-0036 / seed rename: the field is `seeds` (was `datasets`). seeds: datasets, config: { @@ -7718,7 +7717,6 @@ export class MarketplaceInstallLocalPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale.locale } : {}), }, }); - const result = await seedLoader.load(request); // [#30324 · ruling 6670861426] The rows this load CREATED get the // person this door names as `owner_id` and `created_by`, then follow // the ordinary permission rules like any record they own. diff --git a/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts b/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts index 77924fa7f97..f8bdc6f2ab1 100644 --- a/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-reseed.test.ts @@ -21,6 +21,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -33,6 +34,11 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, // [#30281] The seed-locale producer, answering "no locale": this suite's diff --git a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts index 30b2e967221..dd63ea8179b 100644 --- a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts @@ -35,6 +35,8 @@ import { tmpdir } from 'node:os'; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The stored-seed funnel the plugin calls; it ends in `load`. + async loadStored() { return this.load(); } async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } async buildDependencyGraph(objects: string[]) { return { objects }; } }, diff --git a/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts b/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts index 4dedcc05f1d..0e1b6ab3229 100644 --- a/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-seed-owner.test.ts @@ -21,6 +21,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -30,6 +31,11 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts b/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts index d6de3dba016..6246746b3d4 100644 --- a/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-seed-replayer.test.ts @@ -39,6 +39,7 @@ // replayer IS the scenario. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -93,6 +94,11 @@ const appDefaultBodies: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts b/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts index 6a1cf3b288e..72a75fe1ed1 100644 --- a/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-tenancy-admission.test.ts @@ -54,6 +54,7 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -61,6 +62,11 @@ import { tmpdir } from 'node:os'; const seedCalls: unknown[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: unknown) { seedCalls.push(request); return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; diff --git a/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts b/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts index 7789aa9f275..61d9f9723e6 100644 --- a/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-tenancy-posture.test.ts @@ -44,6 +44,7 @@ // this package use) so the assertions can read what the seeder was ASKED to do. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { SeedLoaderRequestSchema } from '@objectstack/spec/data'; import { mkdtempSync, rmSync, existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -53,6 +54,11 @@ let loadCalls: any[] = []; vi.mock('@objectstack/runtime', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + return this.load(SeedLoaderRequestSchema.parse(raw)); + } async load(request: any) { loadCalls.push(request); return seedResult; } }, recordSeedOutcome: vi.fn(), diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 90860eb1187..b5e747f4118 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -132,7 +132,6 @@ import { validateSemanticRoles } from './validate-semantic-roles.js'; import { validateFormLayout } from './validate-form-layout.js'; import { validatePublicFormFileFields } from './validate-public-form-file-fields.js'; import { validateThankYouRecordFields } from './validate-thank-you-record-fields.js'; -import { validateSeedReplaySafety } from './validate-seed-replay-safety.js'; import { validateAssignmentRules } from './validate-assignment-rules.js'; import { validateSeedStateMachine } from './validate-seed-state-machine.js'; import { validateVisibilityPredicates } from './validate-visibility-predicates.js'; @@ -1855,18 +1854,10 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateAssignmentRules(stack), }, - // framework#3434 — seeds replay on every boot, so a `mode: 'insert'` dataset - // duplicates its table on every restart. - { - name: 'validateSeedReplaySafety', - tier: 'advisory', - input: 'parsed', - commands: ALL, - source: 'packages/lint/src/validate-seed-replay-safety.ts', - surfaces: CLI_ONLY, - surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, - run: (stack) => validateSeedReplaySafety(stack), - }, + // [#34613] `validateSeedReplaySafety` (framework#3434, the `insert`-mode + // replay warning) is retired: `SeedMode` itself refuses `insert` and + // `replace` at parse (ruling 6942780880), so no stack this rule could flag + // gets past the schema. // framework#3433 follow-up — #3433 exempts seed writes from the // `state_machine` rule, so a seeded status the FSM does not declare is no // longer rejected at write time. Re-added at author time; advisory, because diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 48bed036b98..e99997db292 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -359,12 +359,6 @@ export { } from './validate-assignment-rules.js'; export type { AssignmentRuleFinding, AssignmentRuleSeverity } from './validate-assignment-rules.js'; -export { - validateSeedReplaySafety, - SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, -} from './validate-seed-replay-safety.js'; -export type { SeedReplaySafetyFinding, SeedReplaySafetySeverity } from './validate-seed-replay-safety.js'; - export { validateSeedStateMachine, SEED_VALUE_OUTSIDE_STATE_MACHINE, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 4831f6e0974..1103448ad3f 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -5699,7 +5699,7 @@ const PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION: RuleExplanation = { ], }; -// ── Seed datasets (`validate-seed-replay-safety.ts`, `validate-seed-state-machine.ts`) ── +// ── Seed datasets (`validate-seed-state-machine.ts`) ── // ── Assignment rules (`validate-assignment-rules.ts`) ── @@ -5737,26 +5737,6 @@ const ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION: RuleExplanation = { ], }; -const SEED_INSERT_MODE_DUPLICATES_ON_REPLAY_EXPLANATION: RuleExplanation = { - rule: 'seed-insert-mode-duplicates-on-replay', - covers: 'why a seed dataset must be safe to replay', - paragraphs: [ - 'Seeds are replayed, not applied once: every `data` dataset is loaded again on each dev-server ' + - 'boot and each package re-publish, so a dataset\'s mode must be idempotent. `mode: \'insert\'` ' + - 'is the one that is not: the loader\'s insert path writes every record unconditionally, with no ' + - 'existing-row check, so the table grows by the dataset\'s size on every restart (three rows, ' + - 'then six, then nine).', - // The modes are held to the rule by its test, each one silent. - 'The fix line names the idempotent modes, `ignore` (skip rows that already exist) and `upsert` ' + - '(create or update), each matching on the dataset\'s `externalId`: a single natural-key field ' + - '(`externalId: \'code\'`), ' + - 'or a composite list of fields for a join or junction table with no single natural key ' + - '(`[\'team\', \'project\']`).', - 'A warning, not a refusal: an insert seed loads and works on a fresh database, and the defect ' + - 'shows only from the second boot on.', - ], -}; - const SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION: RuleExplanation = { rule: 'seed-value-outside-state-machine', covers: 'which states a seeded value may name', @@ -6484,7 +6464,6 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION.rule]: PERMISSION_RETIRED_LIFECYCLE_RESIDUE_EXPLANATION, [ASSIGNMENT_RULE_USER_TARGET_EXPLANATION.rule]: ASSIGNMENT_RULE_USER_TARGET_EXPLANATION, [ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION.rule]: ASSIGNMENT_RULE_QUEUE_UNSTAFFED_EXPLANATION, - [SEED_INSERT_MODE_DUPLICATES_ON_REPLAY_EXPLANATION.rule]: SEED_INSERT_MODE_DUPLICATES_ON_REPLAY_EXPLANATION, [SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION.rule]: SEED_VALUE_OUTSIDE_STATE_MACHINE_EXPLANATION, [SEMANTIC_ROLE_FIELD_UNPROVISIONED_EXPLANATION.rule]: SEMANTIC_ROLE_FIELD_UNPROVISIONED_EXPLANATION, [ACTION_NO_PLACEMENT_EXPLANATION.rule]: ACTION_NO_PLACEMENT_EXPLANATION, diff --git a/packages/lint/src/validate-seed-replay-safety.test.ts b/packages/lint/src/validate-seed-replay-safety.test.ts deleted file mode 100644 index 6d2a9f55be5..00000000000 --- a/packages/lint/src/validate-seed-replay-safety.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { - validateSeedReplaySafety as validateSeedReplaySafetyUnrecorded, - SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, -} from './validate-seed-replay-safety.js'; -import { explainRule } from './rule-explanations.js'; - -// [#22161] Each finding is one verdict sentence; the reasoning it used to -// carry is `os explain seed-insert-mode-duplicates-on-replay`. Every direct -// call below records what it fired, and the last cases in this file hold each -// recorded verdict to one line of at most 200 characters — every firing -// variant this suite exercises, not a chosen few. Run the whole file: those -// cases read what the cases above fired. -const fired: Array<{ rule: string; message: string; hint: string }> = []; -const validateSeedReplaySafety: typeof validateSeedReplaySafetyUnrecorded = (...args) => { - const findings = validateSeedReplaySafetyUnrecorded(...args); - fired.push(...findings); - return findings; -}; - -describe('validateSeedReplaySafety (framework#3434 replay-unsafe seed gate)', () => { - it('passes a stack with no seed data', () => { - expect(validateSeedReplaySafety({})).toHaveLength(0); - expect(validateSeedReplaySafety({ data: [] })).toHaveLength(0); - }); - - it('passes idempotent modes (ignore / upsert / update / replace) and the default (unset)', () => { - const findings = validateSeedReplaySafety({ - data: [ - { object: 'a', mode: 'ignore', externalId: ['team', 'project'], records: [] }, - { object: 'b', mode: 'upsert', externalId: 'code', records: [] }, - { object: 'c', mode: 'update', records: [] }, - { object: 'd', mode: 'replace', records: [] }, - { object: 'e', records: [] }, // mode unset → defaults to upsert, safe - ], - }); - expect(findings).toHaveLength(0); - }); - - it("flags a mode: 'insert' seed with location + an actionable fix hint", () => { - const findings = validateSeedReplaySafety({ - data: [ - { object: 'showcase_project_membership', mode: 'insert', records: [{ team: 'x', project: 'y' }] }, - ], - }); - expect(findings).toHaveLength(1); - expect(findings[0]).toMatchObject({ - severity: 'warning', - rule: SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, - path: 'data[0].mode', - }); - expect(findings[0].where).toContain('showcase_project_membership'); - expect(findings[0].message).toContain('replay'); - // Hint steers to the idempotent modes and the composite externalId the fix - // added; [#22161] the composite example itself is the explanation's. - expect(findings[0].hint).toContain('ignore'); - expect(findings[0].hint).toContain('upsert'); - expect(findings[0].hint).toContain('externalId'); - expect(findings[0].hint).toContain('a list of fields for a junction table'); - }); - - it('flags each insert seed and reports its index in the path; leaves safe seeds alone', () => { - const findings = validateSeedReplaySafety({ - data: [ - { object: 'safe', mode: 'upsert', records: [] }, - { object: 'bad_one', mode: 'insert', records: [] }, - { object: 'also_safe', mode: 'ignore', records: [] }, - { object: 'bad_two', mode: 'insert', records: [] }, - ], - }); - expect(findings).toHaveLength(2); - expect(findings.map((f) => f.path)).toEqual(['data[1].mode', 'data[3].mode']); - expect(findings.map((f) => f.where)).toEqual(['seed "bad_one"', 'seed "bad_two"']); - }); - - it('falls back to a data[i] location when a seed has no object name', () => { - const findings = validateSeedReplaySafety({ data: [{ mode: 'insert', records: [] }] }); - expect(findings).toHaveLength(1); - expect(findings[0].where).toBe('data[0]'); - }); - - it('ignores non-object entries defensively', () => { - const findings = validateSeedReplaySafety({ data: [null, 'insert', 42, { object: 'z', mode: 'insert', records: [] }] }); - expect(findings).toHaveLength(1); - expect(findings[0].where).toContain('z'); - }); -}); - -describe('[#22161] one-line verdicts — seed-insert-mode-duplicates-on-replay', () => { - it('reads as one sentence', () => { - const findings = validateSeedReplaySafety({ data: [{ object: 'z', mode: 'insert', records: [] }] }); - expect(findings.map((f) => f.message)).toEqual([ - "`mode: 'insert'` re-inserts every record on each replay boot (dev-server restart, package re-publish) " - + 'with no existing-row check, so every restart duplicates its rows', - ]); - }); - - it('`os explain` carries what the verdict no longer says', () => { - const entry = explainRule(SEED_INSERT_MODE_DUPLICATES_ON_REPLAY); - expect(entry, 'no `os explain seed-insert-mode-duplicates-on-replay` entry').toBeDefined(); - const text = entry!.paragraphs.join('\n'); - // The idempotent modes are held to the rule by the silent case above. - for (const fact of [ - 'Seeds are replayed, not applied once', - 'no existing-row check', - '`ignore` (skip rows that already exist)', - '`upsert` (create or update)', - '`externalId`', - '(`[\'team\', \'project\']`)', - 'only from the second boot on', - ]) { - expect(text, `explanation names ${fact}`).toContain(fact); - } - }); - - it('every verdict the cases in this file fired is one line of at most 200 characters', () => { - const converted = fired.filter((f) => f.rule === SEED_INSERT_MODE_DUPLICATES_ON_REPLAY); - // The coverage control first: the id fired, on more than one seed. - expect(converted.length).toBeGreaterThan(1); - for (const f of converted) { - expect(f.message, f.rule).not.toContain('\n'); - expect(f.message.length, `${f.rule}: ${f.message}`).toBeLessThanOrEqual(200); - } - }); -}); - -// [#22161] Slice 16: the `fix:` line names the two idempotent modes and the -// match key in one line; what each mode does and the examples are the -// explanation's (pinned above, and here for what moved). -describe('[#22161] one-line fix — seed-insert-mode-duplicates-on-replay', () => { - it('reads as one remedy', () => { - const [f] = validateSeedReplaySafety({ data: [{ object: 'z', mode: 'insert', records: [] }] }); - expect(f!.hint).toBe( - "Use `mode: 'ignore'` or `'upsert'` with an `externalId` to match on (a natural-key field, or a list of " + - 'fields for a junction table)', - ); - }); - - it('every `fix:` line the cases in this file fired is one line of at most 200 characters', () => { - const converted = fired.filter((f) => f.rule === SEED_INSERT_MODE_DUPLICATES_ON_REPLAY); - expect(converted.length).toBeGreaterThan(1); - for (const f of converted) { - expect(f.hint, f.rule).not.toContain('\n'); - expect(f.hint.length, `${f.rule}: ${f.hint}`).toBeLessThanOrEqual(200); - } - }); - - it('`os explain` carries the examples the `fix:` line dropped', () => { - const text = explainRule(SEED_INSERT_MODE_DUPLICATES_ON_REPLAY)!.paragraphs.join('\n'); - expect(text).toContain("(`externalId: 'code'`)"); - expect(text).toContain("(`['team', 'project']`)"); - }); -}); diff --git a/packages/lint/src/validate-seed-replay-safety.ts b/packages/lint/src/validate-seed-replay-safety.ts deleted file mode 100644 index 0316dc2e283..00000000000 --- a/packages/lint/src/validate-seed-replay-safety.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// -// Build-time guardrail for replay-unsafe seed datasets (framework#3434). -// -// A pure `(stack) => Finding[]` rule (ADR-0019), run from `os validate` and -// reusable by AI authoring. Seeds are REPLAYED — they re-load on every -// dev-server boot and every package re-publish, not applied once — so a -// dataset's mode has to be idempotent. `mode: 'insert'` is the one mode that -// is not: the loader's `insert` path writes every record unconditionally, with -// no existing-row check, so the table grows by the dataset's size on every -// restart (the showcase `showcase_project_membership` fixture went 3 → 6 → 9). -// -// This is the authoring-time nudge that would have caught #3434 before boot: -// flag `insert`, and point at the idempotent modes (`ignore` / `upsert`) plus -// the `externalId` — single field, or a COMPOSITE list of fields for a join / -// junction table that has no single natural key (`['team', 'project']`), the -// support for which #3434 added. -// -// Advisory (warning): an `insert` seed is not a schema error — it loads and -// "works" on a fresh DB; the defect only shows on the second boot. So it earns -// a located fix-it, not a hard `os compile` gate. - -export type SeedReplaySafetySeverity = 'error' | 'warning'; - -export interface SeedReplaySafetyFinding { - severity: SeedReplaySafetySeverity; - rule: string; - /** Human-readable location, e.g. `seed "showcase_project_membership"`. */ - where: string; - /** Config path, e.g. `data[12].mode`. */ - path: string; - message: string; - hint: string; -} - -// Rule id (registry entry). -export const SEED_INSERT_MODE_DUPLICATES_ON_REPLAY = 'seed-insert-mode-duplicates-on-replay'; - -type AnyRec = Record; - -/** - * Flag every seed dataset declared with `mode: 'insert'` — the one non-idempotent - * mode, which duplicates its rows on every replay boot (framework#3434). Returns - * the findings (empty = clean). The caller decides how to surface them / whether - * to fail the build; the CLI folds them in as advisory warnings. - * - * Reads `stack.data` (the `SeedSchema[]` fixtures). Safe on any shape — a stack - * with no `data` array yields no findings. - */ -export function validateSeedReplaySafety(stack: AnyRec): SeedReplaySafetyFinding[] { - const out: SeedReplaySafetyFinding[] = []; - const seeds = Array.isArray(stack.data) ? (stack.data as AnyRec[]) : []; - - seeds.forEach((seed, i) => { - if (!seed || typeof seed !== 'object') return; - if (seed.mode !== 'insert') return; - - const object = typeof seed.object === 'string' ? seed.object : undefined; - const where = object ? `seed "${object}"` : `data[${i}]`; - - out.push({ - severity: 'warning', - rule: SEED_INSERT_MODE_DUPLICATES_ON_REPLAY, - where, - path: `data[${i}].mode`, - // [#22161] One verdict sentence and one remedy line; why seeds are - // replayed, what each idempotent mode does and the composite - // `externalId` of a junction table are - // `os explain seed-insert-mode-duplicates-on-replay`. - message: - "`mode: 'insert'` re-inserts every record on each replay boot (dev-server restart, " + - 'package re-publish) with no existing-row check, so every restart duplicates its rows', - hint: - "Use `mode: 'ignore'` or `'upsert'` with an `externalId` to match on (a natural-key field, or a " + - 'list of fields for a junction table)', - }); - }); - - return out; -} diff --git a/packages/metadata-core/src/package-upgrade-plan.ts b/packages/metadata-core/src/package-upgrade-plan.ts index 8db2829d20c..185112e0c06 100644 --- a/packages/metadata-core/src/package-upgrade-plan.ts +++ b/packages/metadata-core/src/package-upgrade-plan.ts @@ -269,10 +269,10 @@ const DEFAULT_SEED_EXTERNAL_ID: string | string[] = SeedSchema.shape.externalId. /** * Does a replay of a dataset in this mode write its columns over a row it * MATCHED by `externalId`? `upsert` and `update` do (a column declaring - * `applyOn: 'create'` excepted); `insert` and `ignore` never touch a matched - * row, and `replace` deletes every row before it inserts, so it matches none. - * The rows a customer edited that an upgrade's replay would overwrite are - * counted for these modes only. + * `applyOn: 'create'` excepted); `ignore` never touches a matched row. The + * retired `insert` and `replace` (#34613) matched no row, and a replay now + * refuses a dataset that still declares one. The rows a customer edited that + * an upgrade's replay would overwrite are counted for these modes only. */ export function seedModeOverwritesMatchedRows(mode: string): boolean { return mode === 'upsert' || mode === 'update'; diff --git a/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts b/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts index 4dceab80a02..5ef20ff814b 100644 --- a/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts +++ b/packages/metadata-protocol/src/protocol-publish-drafts-all-or-nothing.test.ts @@ -282,7 +282,7 @@ function cardDrafts(autonumberFormat: string): Array<[string, string, Record 0 ? clashes.map((c) => c.message).join(' ') : null; } -/** The seed modes whose load matches incoming records to existing rows by the dataset's `externalId`. */ +/** + * The seed modes whose load matches incoming records to existing rows by the + * dataset's `externalId`: every live mode since the unkeyed `insert` and + * `replace` were retired (#34613). A retired mode is the schema's refusal, not + * this one's. + */ const KEYED_SEED_MODES: ReadonlySet = new Set(['upsert', 'update', 'ignore']); /** @@ -1055,7 +1060,8 @@ export async function seedExternalIdSaveRefusal( if (missing.length === 0) return undefined; const consequence = `so a load in \`${mode}\` mode could never match a row it wrote before: each publish and each ` + `replay would ${mode === 'update' ? 'skip every record' : 'insert every record again'}. Name a field the object ` - + "declares, or use `mode: 'insert'` for rows with no natural key."; + + "declares, a list of fields when no single field names a row, or `'id'` when the records carry " + + 'their own ids.'; const issues: MetadataIssueEntry[] = missing.map(({ member, index }) => ({ path: composite ? `externalId.${index}` : 'externalId', message: (declared diff --git a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts index d0b6149fed0..778797ca31d 100644 --- a/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts @@ -341,11 +341,14 @@ describe('[#28952] controls — an `externalId` the object has is not refused', expect(stored(rows, 'seed', 'r_ok')).toEqual([`active|${PKG}|${JSON.stringify(externalId ?? null)}`]); }); - it.each([['insert'], ['replace']])('mode `%s` never matches by `externalId`, so it is not judged', async (mode) => { + // [#34613] The unkeyed `insert` and `replace` modes, which this suite once + // held out as "never matches, so not judged", are retired: the save door + // refuses them with `SeedMode`'s prescription, whatever the key names. + it.each([['insert'], ['replace']])('the retired mode `%s` is refused with its prescription', async (mode) => { const { protocol, rows } = makeSession({ objects: OBJECTS }); - const res = await protocol.saveMetaItem({ type: 'seed', name: 'r_ins', item: seed('seedkey_other', 'no_such_field', mode), mode: 'draft' }); - expect(res.success).toBe(true); - expect(stored(rows, 'seed', 'r_ins')).toEqual(['draft|-|"no_such_field"']); + const attempt = protocol.saveMetaItem({ type: 'seed', name: 'r_ins', item: seed('seedkey_other', 'sku', mode), mode: 'draft' }); + await expect(attempt).rejects.toThrow(new RegExp(`seed\\.mode: '${mode}'\` was removed in @objectstack/spec 18\\.7\\.0`)); + expect(stored(rows, 'seed', 'r_ins')).toEqual([]); }); it('an object drafted in the same batch that declares the field publishes with the seed', async () => { @@ -368,10 +371,6 @@ describe('[#28952] controls — an `externalId` the object has is not refused', it('a `migrate-stored` re-save of a stored seed is not judged', async () => { const { protocol, rows } = makeSession({ objects: OBJECTS }); - const res = await protocol.saveMetaItem({ - type: 'seed', name: 'r_old', item: seed('seedkey_other', 'no_such_field', 'insert'), mode: 'draft', - }); - expect(res.success).toBe(true); const migrated = await protocol.saveMetaItem({ type: 'seed', name: 'r_old', item: seed('seedkey_other', 'no_such_field'), mode: 'draft', source: 'migrate-stored', }); diff --git a/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts b/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts index 840af8737f7..2206b9dadac 100644 --- a/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts +++ b/packages/metadata-protocol/src/seed-loader-composite-external-id.test.ts @@ -10,7 +10,7 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin * * A join / junction table has no single-field natural key — the PAIR of its * foreign keys is what's unique. Before composite externalId support, such a - * dataset could only run `mode: 'insert'`, which re-inserts every row on each + * dataset could only run `mode: 'insert'` (since retired, #34613), which re-inserts every row on each * replay boot and duplicates the table (the showcase memberships went 3→6→9). * * A composite `externalId: ['team', 'project']` + `mode: 'ignore'` dedupes the diff --git a/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts b/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts index 7114185ce00..952f4b887a4 100644 --- a/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts +++ b/packages/metadata-protocol/src/seed-loader-deferred-dropped.test.ts @@ -124,7 +124,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -134,14 +134,14 @@ const compositeSeeds = (region: string) => [ { object: 'drop_department', externalId: ['name', 'region'], - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', region, head_id: 'Alice' }], }, { object: 'drop_worker', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', department_id: 'Engineering' }], }, @@ -205,7 +205,13 @@ describe('pass 2 heals a row whose natural key evaluated empty (#5127 → #11674 }); expect(logger.error).not.toHaveBeenCalled(); - expect(logger.warn).not.toHaveBeenCalled(); + // [#34613] The dataset is keyed now (the unkeyed `insert` it ran in is + // retired), so the one `warn` is #28952's notice that every record keys + // empty — a fact about the declaration. Nothing at warn is about the + // deferral the load healed. + const warned = logger.warn.mock.calls.map((c: unknown[]) => String(c[0])); + expect(warned).toHaveLength(1); + expect(warned[0]).toMatch(/keys every record on externalId 'name\+region', and no record carries a value for it/); }); /** @@ -281,7 +287,7 @@ describe('pass 2 finds no id because the source row failed in pass 1 (#5127)', ( { object: 'drop_department', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', region: 'APAC', head_id: 'Alice' }], }, @@ -291,7 +297,7 @@ describe('pass 2 finds no id because the source row failed in pass 1 (#5127)', ( // deferred update that would muddy the assertions below. object: 'drop_worker', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice' }], }, diff --git a/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts b/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts index dfc72bee430..1753de45f02 100644 --- a/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-deferred-failure.test.ts @@ -107,7 +107,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -116,14 +116,14 @@ const SEEDS = [ { object: 'audit_department', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', head_id: 'Alice' }], }, { object: 'audit_worker', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', department_id: 'Engineering' }], }, diff --git a/packages/metadata-protocol/src/seed-loader-driver-text.test.ts b/packages/metadata-protocol/src/seed-loader-driver-text.test.ts index 3a53f957a0d..07e081b7c36 100644 --- a/packages/metadata-protocol/src/seed-loader-driver-text.test.ts +++ b/packages/metadata-protocol/src/seed-loader-driver-text.test.ts @@ -247,8 +247,8 @@ describe('[#8442] raw driver text is withheld from the seed `errors[].message`', const logger = createLogger(); const result = await new SeedLoaderService(engine, metadata, logger as never).load({ seeds: [ - { object: 'dept', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', head_id: 'Alice' }] }, - { object: 'worker', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', dept_id: 'Engineering' }] }, + { object: 'dept', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Engineering', head_id: 'Alice' }] }, + { object: 'worker', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice', dept_id: 'Engineering' }] }, ], config: CONFIG, } as never); diff --git a/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts b/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts index 3abe76c0a10..c2450c57f29 100644 --- a/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts +++ b/packages/metadata-protocol/src/seed-loader-empty-key-warn.test.ts @@ -159,12 +159,13 @@ describe('[#28952] the boot loader — a keyed dataset whose every record keys e expect(emptyKeyWarnings(logger)).toEqual([]); }); - it('control: an `insert` dataset never matches, so it is not warned about', async () => { + it('control: a retired `insert` dataset is refused before any key is read, so it is not warned about (#34613)', async () => { const { engine } = createFaithfulEngine(); const logger = createLogger(); - await new SeedLoaderService(engine, createMetadata(), logger).load({ + const result = await new SeedLoaderService(engine, createMetadata(), logger).load({ seeds: [dataset('no_such_field', 'insert')] as any[], config: CONFIG, }); + expect(result.results[0]).toMatchObject({ inserted: 0, errored: 1 }); expect(emptyKeyWarnings(logger)).toEqual([]); }); diff --git a/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts b/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts index d828c6821a1..91c9e4dc576 100644 --- a/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-existing-records-read-failure.test.ts @@ -180,7 +180,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as never; @@ -306,7 +306,7 @@ describe('[#8896] seed loader — an existing-records read that FAILED is not "n }); const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).load({ - seeds: seedOf('insert', [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }]), + seeds: seedOf('ignore', [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }]), config: CONFIG, }); diff --git a/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts b/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts index d268f58f12b..2197666d1c3 100644 --- a/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts +++ b/packages/metadata-protocol/src/seed-loader-organization-stamp.test.ts @@ -103,19 +103,19 @@ const silentLogger = () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debu function seeds(organizationId?: string) { return { seeds: [ - { object: 'sys_business_unit', externalId: 'code', mode: 'insert', env: ['prod', 'dev', 'test'], + { object: 'sys_business_unit', externalId: 'code', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Head Office', code: 'HQ' }] }, - { object: 'my_app_widget', externalId: 'sku', mode: 'insert', env: ['prod', 'dev', 'test'], + { object: 'my_app_widget', externalId: 'sku', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'Gizmo', sku: 'G-1' }, // Carries its own organization: that IS an explicit owner. { name: 'Pinned', sku: 'P-1', organization_id: 'org_named_by_author' }, ] }, - { object: 'billing_license', externalId: 'sku', mode: 'insert', env: ['prod', 'dev', 'test'], + { object: 'billing_license', externalId: 'sku', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Site licence', sku: 'L-1' }] }, ], config: { - dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'insert', batchSize: 1000, + dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1000, transaction: false, ...(organizationId ? { organizationId } : {}), }, } as never; diff --git a/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts b/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts index 66389d2073b..d87f569d140 100644 --- a/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts +++ b/packages/metadata-protocol/src/seed-loader-pointer-pair.test.ts @@ -520,10 +520,11 @@ const ADOPTER_SCHEMAS: Record = { }; /** A dataset for an object with no natural key of its own — every adopted - * object here is engine/append-only owned, so `mode: 'insert'` (no - * `externalId`) is how such rows would honestly be authored. */ + * object here is engine/append-only owned. The keyless `insert` mode such + * rows were once authored with is retired (#34613), so the dataset keys on + * `id`; these rows carry none, so each one is written as a new row. */ function insertSeed(object: string, records: Array>) { - return { object, mode: 'insert', env: ['prod', 'dev', 'test'], records }; + return { object, externalId: 'id', mode: 'ignore', env: ['prod', 'dev', 'test'], records }; } describe('pointer-pair adoption per object (#11386)', () => { diff --git a/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts new file mode 100644 index 00000000000..128a7e6dc57 --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts @@ -0,0 +1,184 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34613] `SeedLoaderService.loadStored`: a STORED seed dataset that still + * declares a retired `SeedMode` (`insert`, `replace`; ruling 6942780880) is + * refused alone, loudly, and every other dataset of the load lands. + * + * The request parse refuses a retired mode by name, so a load built straight + * through `SeedLoaderRequestSchema.parse` would refuse the WHOLE boot seed (or + * install, or replay) over one dataset a package carried from before the + * retirement. `loadStored` is the funnel the replaying loads go through: the + * refused dataset writes nothing, its error names the object and carries the + * schema's own prescription, and the result says `success: false`. + * + * Controls: a load with no retired dataset is `load()`'s answer unchanged, and + * a malformed dataset that is not a retired mode still throws from the parse, + * as it did before. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { SeedMode } from '@objectstack/spec/data'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { assertEngineDeleteDispatch, assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { SeedLoaderService } from './seed-loader.js'; + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +/** An in-memory engine: equality `where` (a combinator is refused, not read as a field), ids minted on insert. */ +function createEngine(): { engine: IDataEngine; store: Record>> } { + const store: Record>> = {}; + let next = 0; + const find = async (object: string, query?: { where?: Record; limit?: number }) => { + let rows = store[object] ?? []; + if (query?.where) { + rows = rows.filter((r) => Object.entries(query.where!).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`in-memory engine: unsupported operator ${k}`); + return r[k] === v; + })); + } + return typeof query?.limit === 'number' ? rows.slice(0, query.limit) : rows; + }; + const engine = { + find: vi.fn(find), + findOne: vi.fn(async (object: string, query?: any) => { + assertEngineFindOnePredicate(object, query); + return (await find(object, { ...query, limit: 1 }))[0] ?? null; + }), + insert: vi.fn(async (object: string, data: any) => { + const put = (d: Record) => { + const row = { id: `r${++next}`, ...d }; + (store[object] ??= []).push(row); + return row; + }; + return Array.isArray(data) ? data.map(put) : put(data); + }), + update: vi.fn(async (_object: string, data: any, options?: any) => { + assertEngineUpdateDispatch(data, options); + return data; + }), + delete: vi.fn(async (_object: string, options?: any) => { + assertEngineDeleteDispatch(options); + return { deleted: 0 }; + }), + count: vi.fn(async (object: string) => (store[object] ?? []).length), + aggregate: vi.fn(async () => []), + } as unknown as IDataEngine; + return { engine, store }; +} + +function createMetadata(): IMetadataService { + const objects: Record = { + rm_region: { name: 'rm_region', fields: { name: { type: 'text' } } }, + rm_source: { name: 'rm_source', fields: { name: { type: 'text' } } }, + rm_tier: { name: 'rm_tier', fields: { name: { type: 'text' } } }, + }; + return { + getObject: vi.fn(async (name: string) => objects[name]), + listObjects: vi.fn(async () => Object.values(objects)), + register: vi.fn(async () => {}), + get: vi.fn(async (_t: string, name: string) => objects[name]), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + } as unknown as IMetadataService; +} + +const prescriptionOf = (mode: string): string => { + const verdict = SeedMode.safeParse(mode); + if (verdict.success) throw new Error(`'${mode}' is a live mode — wrong fixture`); + return verdict.error.issues[0]!.message; +}; + +describe('loadStored — a stored dataset with a retired mode is refused alone (#34613)', () => { + it.each([['insert'], ['replace']])('`%s`: that dataset writes nothing, every other dataset lands, the result names the refusal', async (mode) => { + const { engine, store } = createEngine(); + const logger = createLogger(); + + const result = await new SeedLoaderService(engine, createMetadata(), logger).loadStored({ + seeds: [ + { object: 'rm_region', records: [{ name: 'emea' }] }, + { object: 'rm_source', mode, records: [{ name: 'web' }] }, + { object: 'rm_tier', mode: 'upsert', externalId: 'name', records: [{ name: 'gold' }] }, + ], + config: { multiPass: true }, + }); + + // The refused dataset wrote nothing; both others landed. + expect(store.rm_source).toBeUndefined(); + expect(store.rm_region?.map((r) => r.name)).toEqual(['emea']); + expect(store.rm_tier?.map((r) => r.name)).toEqual(['gold']); + expect(result.results.map((r) => r.object).sort()).toEqual(['rm_region', 'rm_tier']); + + // Loud: the load failed, and its one error is the dataset's refusal with + // the schema's prescription, read from `SeedMode` rather than restated. + expect(result.success).toBe(false); + expect(result.errors).toHaveLength(1); + expect(result.errors[0]).toMatchObject({ sourceObject: 'rm_source', field: 'mode', attemptedValue: mode, recordIndex: 0 }); + expect(result.errors[0]!.message).toBe(`Seed dataset for 'rm_source' was not loaded: ${prescriptionOf(mode)}`); + expect(result.errors[0]!.message).toMatch(/`mode: 'ignore'`.*`externalId`/s); + }); + + it('a load whose only dataset is retired writes nothing and still answers, failed', async () => { + const { engine, store } = createEngine(); + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ + seeds: [{ object: 'rm_source', mode: 'insert', records: [{ name: 'web' }] }], + }); + expect(store).toEqual({}); + expect(result.success).toBe(false); + expect(result.errors.map((e) => e.sourceObject)).toEqual(['rm_source']); + }); + + it.each([['insert'], ['replace']])('`load()` itself refuses a `%s` dataset it was handed unparsed: nothing written, every record errored (S1)', async (mode) => { + const { engine, store } = createEngine(); + const logger = createLogger(); + const result = await new SeedLoaderService(engine, createMetadata(), logger).load({ + seeds: [ + { object: 'rm_source', mode, externalId: 'name', records: [{ name: 'web' }, { name: 'mail' }] }, + { object: 'rm_region', mode: 'ignore', externalId: 'name', records: [{ name: 'emea' }] }, + ], + config: { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1000, transaction: false }, + } as never); + expect(store.rm_source).toBeUndefined(); + expect(store.rm_region?.map((r) => r.name)).toEqual(['emea']); + expect(result.success).toBe(false); + expect(result.results.find((r) => r.object === 'rm_source')).toMatchObject({ inserted: 0, updated: 0, errored: 2, total: 2 }); + expect(result.errors.map((e) => e.message)).toEqual([`Seed dataset for 'rm_source' was not loaded: ${prescriptionOf(mode)}`]); + expect(logger.error).toHaveBeenCalledTimes(1); + }); + + it('`validate()` (the dry run) answers the same refusal a real load would, not a clean result (S1)', async () => { + const { engine, store } = createEngine(); + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).validate( + [{ object: 'rm_source', mode: 'insert', externalId: 'name', records: [{ name: 'web' }] }] as never, + ); + expect(store).toEqual({}); + expect(result.success).toBe(false); + expect(result.errors[0]!.message).toBe(`Seed dataset for 'rm_source' was not loaded: ${prescriptionOf('insert')}`); + }); + + it('CONTROL: with no retired dataset the answer is the load’s own', async () => { + const { engine, store } = createEngine(); + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ + seeds: [{ object: 'rm_region', records: [{ name: 'emea' }] }], + }); + expect(result.success).toBe(true); + expect(result.errors).toEqual([]); + expect(store.rm_region?.map((r) => r.name)).toEqual(['emea']); + }); + + it('CONTROL: a mode that was never a seed mode is still the parse’s refusal, for the whole load', async () => { + const { engine, store } = createEngine(); + const attempt = new SeedLoaderService(engine, createMetadata(), createLogger()).loadStored({ + seeds: [ + { object: 'rm_region', records: [{ name: 'emea' }] }, + { object: 'rm_source', mode: 'merge', records: [{ name: 'web' }] }, + ], + }); + await expect(attempt).rejects.toThrow(); + expect(store).toEqual({}); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader-retry.test.ts b/packages/metadata-protocol/src/seed-loader-retry.test.ts index 8a49d691991..eaf55af4382 100644 --- a/packages/metadata-protocol/src/seed-loader-retry.test.ts +++ b/packages/metadata-protocol/src/seed-loader-retry.test.ts @@ -102,7 +102,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -111,7 +111,7 @@ const SEEDS = [ { object: 'my_app_employee', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice' }, { name: 'Bob' }], }, @@ -169,7 +169,7 @@ describe('seed batched path — idempotent retry after commit-then-lost-response seeds: [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Widget A', sku: 'W-A' }, { name: 'Widget B', sku: 'W-B' }], }] as any, @@ -211,7 +211,7 @@ describe('seed batched path — partial-success engine (framework#3172)', () => seeds: [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'Good A', sku: 'W-A' }, @@ -265,7 +265,7 @@ describe('seed batched path — a recompute failure is recovered, not re-written seeds: [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }], }] as any, diff --git a/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts b/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts index 0eacd844747..0da96e23af7 100644 --- a/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts +++ b/packages/metadata-protocol/src/seed-loader-sole-organization-read-failure.test.ts @@ -169,7 +169,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as never; @@ -177,7 +177,7 @@ const CONFIG = { const seedOf = (records: Array>) => [{ object: 'my_app_widget', externalId: 'sku', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records, }] as never; diff --git a/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts b/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts index 40bbba4c5bd..0985ba1f5f0 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-scope.test.ts @@ -154,7 +154,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -200,7 +200,7 @@ describe('[#17177] the pass-2 deferred-reference summary says WHEN it is true', { object: 'claim_contract', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'ACME-001', owner_id: 'dev-admin' }], }, @@ -268,14 +268,14 @@ describe('[#17177] the pass-2 deferred-reference summary says WHEN it is true', { object: 'claim_contract', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'ACME-002', owner_id: 'Ada' }], }, { object: 'claim_user', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Ada', contract_id: 'ACME-002' }], }, @@ -318,14 +318,14 @@ describe('[#17177] the pass-2 deferred-reference summary says WHEN it is true', { object: 'claim_contract', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'ACME-003', owner_id: 'Ada' }], }, { object: 'claim_user', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Ada', contract_id: 'ACME-003' }], }, diff --git a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts index 9a083bbd8be..2104d167946 100644 --- a/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts +++ b/packages/metadata-protocol/src/seed-loader-summary-stale.test.ts @@ -103,7 +103,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -111,7 +111,7 @@ const CONFIG = { const seedFor = (object: string, records: any[]) => ({ object, externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records, }); @@ -286,7 +286,7 @@ describe('the counter survives the contract, and the contract survives older pay // a pre-#4998 producer's output, and it must still parse. const legacyPerObject = { object: 'roll_invoice', - mode: 'insert', + mode: 'ignore', inserted: 2, updated: 0, skipped: 0, errored: 0, total: 2, referencesResolved: 0, referencesDeferred: 0, errors: [], diff --git a/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts b/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts index 7d478270072..6176c7e797c 100644 --- a/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts +++ b/packages/metadata-protocol/src/seed-loader-unresolved-drop.test.ts @@ -120,7 +120,7 @@ const SINGLE_PASS = { dryRun: false, haltOnError: false, multiPass: false, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -130,7 +130,7 @@ const ORDERS = [ { object: 'drop_order', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'ORD-1' }, @@ -223,7 +223,7 @@ describe('a record dropped for an unresolvable reference is logged, not only cou { object: 'drop_customer', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Ghost Inc' }], }, @@ -322,7 +322,7 @@ describe('a deferred reference still unresolved after pass 2 is logged too (fram { object: 'drop_team', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], // 'Nobody' is never seeded and is not in the database — pass 2 cannot // rescue it, so the deferred reference is permanently NULL. diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 195e71f0f09..ce3ff470a0f 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -2,6 +2,7 @@ import type { IDataEngine, IFieldFileService, IMetadataService, ISeedLoaderService } from '@objectstack/spec/contracts'; import type { + SeedLoaderRequest, SeedLoaderRequestParsed, SeedLoaderResultParsed, SeedLoaderConfig, @@ -16,6 +17,9 @@ import type { } from '@objectstack/spec/data'; import { SeedLoaderConfigSchema, + SeedLoaderRequestSchema, + SeedMode, + RETIRED_SEED_MODE_VALUES, isMultiValueField, isTenancyDisabled, referenceTargetOf, @@ -402,6 +406,13 @@ function perOrganizationSeedRowId(authoredId: string, organizationId: string): s */ const SEED_LANDED_KEY_OBJECT = 'sys_seed_landed_key'; +/** + * [#34613] The `SeedMode` values retired by ruling 6942780880 that a stored + * seed can still carry. Only membership is read here: the prescription a + * refused dataset reports is `SeedMode`'s own refusal. + */ +const RETIRED_SEED_MODES: ReadonlySet = new Set(RETIRED_SEED_MODE_VALUES); + /** * [#31021] The key a landed seed row is recorded under in * {@link SEED_LANDED_KEY_OBJECT}: the dataset's `externalId` field names, each @@ -485,8 +496,8 @@ interface LandedKeyLedger { * - Topological dependency ordering (parents before children) * - Multi-pass loading for circular references — pass 2 writes a deferred * reference back through the source row's INTERNAL id captured at insert - * time (commit 9a884c6e4), so it heals KEYLESS datasets (`mode: 'insert'`, no - * `externalId`) the same as keyed ones + * time (commit 9a884c6e4), so it heals a row whose key evaluates empty the + * same as a keyed one * - Dry-run validation mode * - Upsert support honoring SeedSchema mode * - Idempotent replay: an upsert/update whose declared fields already match @@ -1559,6 +1570,66 @@ export class SeedLoaderService implements ISeedLoaderService { return fromMetadata; } + /** + * [#34613] Load a request built from STORED seeds: the loads that replay a + * seed the author is not there to fix — the single-tenant boot seed, the + * per-organization replay, the dev hot reload, a package install, upgrade + * or sample-data reseed. + * + * `SeedMode` retired `insert` and `replace` (ruling 6942780880, ADR-0049): + * neither matched a row, so every replay inserted each record again. A + * package built or a seed stored before the retirement can still carry one, + * and the request parse would refuse the WHOLE load over it. Here that + * dataset alone is refused: it writes nothing, its prescription (the + * `SeedMode` refusal, read from the schema, never restated) becomes one + * error of the result with `success: false`, and every other dataset loads. + * No log line of its own: the refusal is handed to the caller, which + * reports a failed load's errors as it reports any other. (A compiled + * artifact reaches here too: the artifact door parses the rest of the + * artifact without such a dataset, see `@objectstack/metadata`'s + * `artifact-retired-seed-modes.ts`; and `loadDataset` refuses the mode again + * for a caller that skips this funnel.) + * + * The publish doors do not come here. A publish has its author present, so + * it parses the request itself and refuses the whole publish with the same + * prescription. + * + * Every other problem of the request is the parse's, as before: it throws. + */ + async loadStored(request: { + seeds: ReadonlyArray; + config?: SeedLoaderRequest['config']; + }): Promise { + const admitted: unknown[] = []; + const refusals: ReferenceResolutionError[] = []; + for (const seed of request.seeds) { + const mode = (seed as { mode?: unknown } | null)?.mode; + const verdict = typeof mode === 'string' && RETIRED_SEED_MODES.has(mode) ? SeedMode.safeParse(mode) : undefined; + if (!verdict || verdict.success) { + admitted.push(seed); + continue; + } + const objectName = String((seed as { object?: unknown }).object ?? '(unnamed)'); + refusals.push({ + sourceObject: objectName, + field: 'mode', + targetObject: objectName, + targetField: '(dataset)', + attemptedValue: mode, + // The mode is the dataset's, not a row's; no row was attempted. + recordIndex: 0, + message: `Seed dataset for '${objectName}' was not loaded: ${verdict.error.issues[0]?.message ?? `mode '${mode}' is retired`}`, + }); + } + if (refusals.length === 0) return this.load(SeedLoaderRequestSchema.parse({ config: {}, ...request })); + // Every dataset refused: there is nothing to load (and the request schema + // asks for at least one dataset), so the answer is the empty load, failed. + const result = admitted.length === 0 + ? this.buildEmptyResult(SeedLoaderConfigSchema.parse(request.config ?? {}), 0) + : await this.load(SeedLoaderRequestSchema.parse({ config: {}, ...request, seeds: admitted })); + return { ...result, success: false, errors: [...refusals, ...result.errors] }; + } + async validate(datasets: Seed[], config?: SeedLoaderConfig): Promise { const parsedConfig = SeedLoaderConfigSchema.parse({ ...config, dryRun: true }); // `datasets` is the AUTHOR state (that is what `validate` takes); `load` @@ -1583,6 +1654,44 @@ export class SeedLoaderService implements ISeedLoaderService { ): Promise { const objectName = dataset.object; const mode = dataset.mode || config.defaultMode; + // [#34613] A mode outside the live `SeedMode` set refuses the dataset HERE, + // whatever the caller parsed: `load()` and `validate()` take requests they + // do not parse, and the retired `insert` / `replace` would otherwise fall to + // the default arm below and insert every record again on each replay. The + // refusal writes nothing, counts every record errored, and carries the + // schema's own prescription. (No mode at all, a request built without the + // parse's defaults, keeps its old path below.) + const modeVerdict = mode === undefined ? undefined : SeedMode.safeParse(mode); + if (modeVerdict && !modeVerdict.success) { + const error: ReferenceResolutionError = { + sourceObject: objectName, + field: 'mode', + targetObject: objectName, + targetField: '(dataset)', + attemptedValue: mode, + // The mode is the dataset's, not a row's; no row was attempted. + recordIndex: 0, + message: `Seed dataset for '${objectName}' was not loaded: ${modeVerdict.error.issues[0]?.message ?? `mode '${String(mode)}' is not a seed mode`}`, + }; + allErrors.push(error); + this.logger.error(`[SeedLoader] ${error.message}`, undefined, { object: objectName, mode }); + return { + object: objectName, + mode, + inserted: 0, + updated: 0, + skipped: 0, + errored: dataset.records.length, + total: dataset.records.length, + referencesResolved: 0, + referencesDeferred: 0, + referencesDropped: 0, + summariesStale: 0, + landedIds: [], + insertedIds: [], + errors: [error], + }; + } const externalId = dataset.externalId || 'name'; // [#25761] Left out of every write to a row this dataset MATCHED — see // `matchesExistingRow` in the record loop below. @@ -1665,7 +1774,8 @@ export class SeedLoaderService implements ISeedLoaderService { `[SeedLoader] Seed dataset for '${objectName}' keys every record on externalId ` + `'${this.externalIdLabel(externalId)}', and no record carries a value for it, so this ${mode} load can ` + `match no existing row: ${mode === 'update' ? 'every record is skipped' : 'every record is written as a new row, on every load'}. ` + - `Set externalId to a field the object declares and each record carries, or use mode 'insert'.`, + `Set externalId to a field the object declares and each record carries, a list of fields when no ` + + `single field names a row, or 'id' when the records carry their own ids.`, { object: objectName, externalId: this.externalIdLabel(externalId), mode, records: dataset.records.length }, ); } @@ -1694,8 +1804,8 @@ export class SeedLoaderService implements ISeedLoaderService { // [#31021] The record of landed seed rows, for the datasets that insert a // keyed row they do not find (`upsert`, `ignore`): the modes the - // create-only rule reaches. `update` never inserts; `insert` / `replace` - // match no key. + // create-only rule reaches. `update` never inserts. (The unkeyed + // `insert` / `replace` modes are retired, #34613.) const recordedKeys = this.landedKeyLedger && (mode === 'upsert' || mode === 'ignore') ? await this.landedKeysOf(objectName) : undefined; @@ -1729,8 +1839,7 @@ export class SeedLoaderService implements ISeedLoaderService { // gets the batched path below. See framework#2678. const hasSelfRef = objectRefs.some(ref => ref.targetObject === objectName); - // Records resolved as inserts (mode 'insert'/'replace', or an unmatched - // upsert/ignore) are buffered here and flushed in batches through the + // Records resolved as inserts (an unmatched upsert/ignore) are buffered here and flushed in batches through the // engine's array-form insert() — one round-trip per batch instead of one // per record, with transient-error retry and per-row degradation on a // logical/validation failure. See framework#2678. @@ -1746,9 +1855,9 @@ export class SeedLoaderService implements ISeedLoaderService { // unlike the `insertedRecords` registrations, which need a non-empty // natural key. Once the dataset has fully written, the deferred updates it // pushed are annotated from this map (see the loop after the final flush), - // so pass 2 back-fills BY INTERNAL ID and a KEYLESS dataset (`mode: - // 'insert'`, no `externalId` — the honest authoring for an engine-owned - // object with no natural key) heals exactly like a keyed one. Before this, + // so pass 2 back-fills BY INTERNAL ID and a row whose key evaluates empty + // heals exactly like a keyed one (the keyless `insert` mode this was first + // written for is retired, #34613). Before this, // pass 2 re-resolved the source row through its externalId and a keyless // deferral was structurally unreachable: it resolved the target, then // dropped the link ("empty externalId, so no internal id"). @@ -2272,8 +2381,8 @@ export class SeedLoaderService implements ISeedLoaderService { * asks. The same lookup {@link SeedLoaderService.decideWriteAction} * makes: the record's natural key, as resolved so far, against the rows * pre-loaded for the modes that match one (`upsert`, `update`, - * `ignore`). A dry run and the `insert` / `replace` modes pre-load - * nothing, so every row they see is one they create. + * `ignore`). A dry run pre-loads nothing, so every row it sees is one + * it creates. */ const matchesExistingRow = (): boolean => existingRowsFor()?.has(this.externalIdKey(record, externalId)) === true; @@ -3980,11 +4089,6 @@ export class SeedLoaderService implements ISeedLoaderService { const opts = this.writeOptionsFor(rowOrganization) as any; switch (mode) { - case 'insert': { - const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); - return { action: 'inserted', id: this.extractId(result) }; - } - case 'update': { if (!existing) { return { action: 'skipped' }; @@ -4019,12 +4123,8 @@ export class SeedLoaderService implements ISeedLoaderService { return { action: 'inserted', id: this.extractId(result) }; } - case 'replace': { - // Replace mode: just insert (caller should have cleared the table) - const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); - return { action: 'inserted', id: this.extractId(result) }; - } - + // The retired `insert` / `replace` (#34613) never reach here: + // `loadDataset` refuses a mode outside the live set before any write. default: { const result = await this.writeRecoveringSummary(objectName, () => withTransientRetry(() => this.engine.insert(objectName, record, opts))); return { action: 'inserted', id: this.extractId(result) }; @@ -4070,8 +4170,6 @@ export class SeedLoaderService implements ISeedLoaderService { : { action: 'update', id: this.extractId(existing)! }; case 'ignore': return existing ? { action: 'skip', id: this.extractId(existing) } : { action: 'insert' }; - case 'insert': - case 'replace': default: return { action: 'insert' }; } @@ -5326,8 +5424,8 @@ interface DeferredUpdate { * The source record's INTERNAL id, captured at the moment its pass-1 write * landed (commit 9a884c6e4). This is the handle pass 2 writes the resolved reference * back through: it exists for every row this load actually wrote — - * including rows of a KEYLESS dataset (`mode: 'insert'`, no `externalId`) - * and rows whose composite key evaluated to the empty string — so the + * including rows whose key (single or composite) evaluated to the empty + * string — so the * "pass 2 resolved the target and had nowhere to write it" loss (#5127) is * reduced to the one case where it is true: the source row never landed. * diff --git a/packages/metadata/src/artifact-retired-seed-modes.test.ts b/packages/metadata/src/artifact-retired-seed-modes.test.ts new file mode 100644 index 00000000000..3a3ef830a8c --- /dev/null +++ b/packages/metadata/src/artifact-retired-seed-modes.test.ts @@ -0,0 +1,62 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34613] The artifact door takes a retired-mode seed dataset out of every + * seed collection an artifact can hold (top-level `data`, `manifest.data`, each + * assembled package body's `data` and `manifest.data`) before its strict parse, + * and hands it back to the same collection after. The boot over a real artifact + * is pinned in `@objectstack/runtime` + * (`standalone-stack-artifact-retired-seed-mode-34613.test.ts`). + */ + +import { describe, it, expect } from 'vitest'; +import { SeedMode } from '@objectstack/spec/data'; +import { restoreWithheldSeedDatasets, withholdRetiredSeedModes } from './artifact-retired-seed-modes.js'; + +const live = { object: 'a_region', externalId: 'name', records: [{ name: 'emea' }] }; +const stale = (mode: string, object = 'a_source') => ({ object, mode, records: [{ name: 'web' }] }); + +describe('withholdRetiredSeedModes', () => { + it('takes a retired-mode dataset out of every seed collection, without mutating the input', () => { + const input = { + data: [live, stale('insert')], + manifest: { id: 'x', data: [stale('replace', 'm_source')] }, + packages: [{ id: 'p', data: [stale('insert', 'p_source'), live], manifest: { data: [live] } }], + }; + const before = JSON.stringify(input); + const { definition, withheld } = withholdRetiredSeedModes(input) as { definition: any; withheld: any[] }; + + expect(JSON.stringify(input)).toBe(before); + expect(definition.data).toEqual([live]); + expect(definition.manifest.data).toEqual([]); + expect(definition.packages[0].data).toEqual([live]); + expect(definition.packages[0].manifest.data).toEqual([live]); + expect(withheld.map((w) => [w.path.join('.'), w.object, w.mode])).toEqual([ + ['', 'a_source', 'insert'], + ['manifest', 'm_source', 'replace'], + ['packages.0', 'p_source', 'insert'], + ]); + // The prescription is SeedMode's own refusal, not restated. + const verdict = SeedMode.safeParse('insert'); + expect(verdict.success).toBe(false); + expect(withheld[0].prescription).toBe(verdict.success ? '' : verdict.error.issues[0]!.message); + }); + + it('hands each withheld dataset back to the collection it came from', () => { + const { definition, withheld } = withholdRetiredSeedModes({ + data: [live, stale('insert')], + packages: [{ id: 'p', data: [stale('replace', 'p_source')] }], + }) as { definition: any; withheld: any[] }; + const parsed = structuredClone(definition); + restoreWithheldSeedDatasets(parsed, withheld); + expect(parsed.data).toEqual([live, stale('insert')]); + expect(parsed.packages[0].data).toEqual([stale('replace', 'p_source')]); + }); + + it('CONTROL: a never-valid mode and a definition with nothing retired are left for the parse, untouched', () => { + const input = { data: [live, stale('merge')] }; + const { definition, withheld } = withholdRetiredSeedModes(input); + expect(definition).toBe(input); + expect(withheld).toEqual([]); + }); +}); diff --git a/packages/metadata/src/artifact-retired-seed-modes.ts b/packages/metadata/src/artifact-retired-seed-modes.ts new file mode 100644 index 00000000000..16887adb3a8 --- /dev/null +++ b/packages/metadata/src/artifact-retired-seed-modes.ts @@ -0,0 +1,127 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { RETIRED_SEED_MODE_VALUES, SeedMode } from '@objectstack/spec/data'; + +/** + * [#34613] A compiled artifact built before the seed modes `insert` and + * `replace` were retired can still carry a dataset declaring one. The artifact + * door strict-parses the whole definition, and `SeedSchema.mode` refuses both + * values, so without this the boot would abort over one seed dataset: no + * object, view or flow of the artifact would register either. Ruling + * 6942780880 asks for the opposite: that dataset is refused, loudly, and the + * rest of the environment loads. + * + * So the door parses the definition WITHOUT such datasets and hands them back + * afterwards, unparsed, to the collection they came from. Seeds are never + * registered as metadata items (they are applied by the seed loader off the + * bundle), so the only reader of the handed-back dataset is a seed load, and + * every seed load refuses it alone with `SeedMode`'s prescription + * (`SeedLoaderService.loadStored`, and `loadDataset` beneath it). + * + * Only a RETIRED value is withheld. A mode that was never a seed mode, or any + * other malformed dataset, is still the parse's refusal, as before. + */ + +/** Where a seed collection sits in an artifact definition, as a key path. */ +type SeedCollectionPath = ReadonlyArray; + +export interface WithheldSeedDataset { + /** The path of the `data` collection the dataset was taken from. */ + readonly path: SeedCollectionPath; + readonly dataset: unknown; + readonly object: string; + readonly mode: string; + /** `SeedMode`'s own refusal of the mode: the prescription, never restated. */ + readonly prescription: string; +} + +const RETIRED = new Set(RETIRED_SEED_MODE_VALUES); + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Every container that can hold a seed `data` collection, by path. */ +function seedCollectionPaths(definition: Record): SeedCollectionPath[] { + const paths: SeedCollectionPath[] = [[], ['manifest']]; + const packages = definition.packages; + if (Array.isArray(packages)) { + packages.forEach((_body, index) => { + paths.push(['packages', index], ['packages', index, 'manifest']); + }); + } + return paths; +} + +function at(root: unknown, path: SeedCollectionPath): unknown { + let node: unknown = root; + for (const key of path) { + if (Array.isArray(node) && typeof key === 'number') node = node[key]; + else if (isRecord(node) && typeof key === 'string') node = node[key]; + else return undefined; + } + return node; +} + +/** + * The definition with every retired-mode seed dataset taken out of its `data` + * collection (the input is not mutated: each container on the way is copied), + * and the datasets taken out. With none, the definition is returned as is. + */ +export function withholdRetiredSeedModes(definition: unknown): { + definition: unknown; + withheld: WithheldSeedDataset[]; +} { + if (!isRecord(definition)) return { definition, withheld: [] }; + const withheld: WithheldSeedDataset[] = []; + let copy: Record | undefined; + + for (const path of seedCollectionPaths(definition)) { + const container = at(copy ?? definition, path); + if (!isRecord(container) || !Array.isArray(container.data)) continue; + const kept: unknown[] = []; + const taken: WithheldSeedDataset[] = []; + for (const dataset of container.data) { + const mode = isRecord(dataset) ? dataset.mode : undefined; + if (typeof mode === 'string' && RETIRED.has(mode)) { + const verdict = SeedMode.safeParse(mode); + taken.push({ + path, + dataset, + object: String((dataset as Record).object ?? '(unnamed)'), + mode, + prescription: verdict.success ? '' : verdict.error.issues[0]?.message ?? '', + }); + } else { + kept.push(dataset); + } + } + if (taken.length === 0) continue; + withheld.push(...taken); + // Copy the containers along the path, then replace the collection. + copy ??= { ...definition }; + let parent: Record | unknown[] = copy; + for (const key of path) { + const child: unknown = (parent as Record)[key as never]; + const cloned: Record | unknown[] = Array.isArray(child) ? [...child] : { ...(child as Record) }; + (parent as Record)[key as never] = cloned; + parent = cloned; + } + (parent as Record).data = kept; + } + return { definition: copy ?? definition, withheld }; +} + +/** + * Hand the withheld datasets back to the collection each came from in the + * PARSED definition, after its own datasets, so a seed load that reads the + * parsed definition (the dev hot reload reads the top-level `data`) still meets + * them and refuses them. Mutates `parsed`, which the caller owns. + */ +export function restoreWithheldSeedDatasets(parsed: unknown, withheld: readonly WithheldSeedDataset[]): void { + for (const entry of withheld) { + const container = at(parsed, entry.path); + if (!isRecord(container)) continue; + container.data = [...(Array.isArray(container.data) ? container.data : []), entry.dataset]; + } +} diff --git a/packages/metadata/src/plugin.ts b/packages/metadata/src/plugin.ts index c42d084bd1e..85eedd30463 100644 --- a/packages/metadata/src/plugin.ts +++ b/packages/metadata/src/plugin.ts @@ -14,6 +14,7 @@ import { Plugin, PluginContext } from '@objectstack/core'; import { resolveArtifactPackageOrder, artifactPackageId } from '@objectstack/core'; import { NodeMetadataManager } from './node-metadata-manager.js'; import { MemoryLoader } from './loaders/memory-loader.js'; +import { restoreWithheldSeedDatasets, withholdRetiredSeedModes, type WithheldSeedDataset } from './artifact-retired-seed-modes.js'; import { PACKAGE_SLOTTED_STORE_TYPES, bundleEntryKey, isBundledStoreType, storedItemPackageId } from './package-slotted-store.js'; import { DEFAULT_METADATA_TYPE_REGISTRY, judgeCollectionItemOwnerStamp, OWNER_STAMP_JUDGED_COLLECTIONS } from '@objectstack/spec/kernel'; import type { MetadataPluginConfig } from '@objectstack/spec/kernel'; @@ -1380,22 +1381,33 @@ export class MetadataPlugin implements Plugin { let metadata: Record; + // [#34613] A seed dataset declaring a retired mode is taken out before + // the strict parse and handed back after it, so the seed load refuses + // that dataset alone instead of this parse refusing the whole artifact + // (see `artifact-retired-seed-modes.ts`). + let withheld: WithheldSeedDataset[] = []; + const prepare = (definition: unknown): unknown => { + const split = withholdRetiredSeedModes(this._convertArtifactForward(ctx, definition, label)); + withheld = split.withheld; + return split.definition; + }; + const obj = raw as any; if (obj?.schemaVersion && obj?.commitId && obj?.metadata !== undefined) { const artifact = EnvironmentArtifactSchema.parse({ ...obj, - metadata: this._convertArtifactForward(ctx, obj.metadata, label), + metadata: prepare(obj.metadata), }); metadata = artifact.metadata as Record; } else if (obj?.success && obj?.data?.metadata) { // Unwrap cloud API envelope: { success: true, data: { metadata: {...} } } const artifact = EnvironmentArtifactSchema.parse({ ...obj.data, - metadata: this._convertArtifactForward(ctx, obj.data.metadata, label), + metadata: prepare(obj.data.metadata), }); metadata = artifact.metadata as Record; } else { - const def = ObjectStackDefinitionSchema.parse(this._convertArtifactForward(ctx, obj, label)); + const def = ObjectStackDefinitionSchema.parse(prepare(obj)); const canonical = JSON.stringify(def, Object.keys(def).sort()); const checksum = createHash('sha256').update(canonical).digest('hex'); const environmentId = this.options.environmentId ?? 'env_local'; @@ -1409,6 +1421,18 @@ export class MetadataPlugin implements Plugin { metadata = def as Record; } + if (withheld.length > 0) { + restoreWithheldSeedDatasets(metadata, withheld); + for (const entry of withheld) { + ctx.logger.warn( + `[MetadataPlugin] artifact '${label}': the seed dataset for '${entry.object}' declares the retired ` + + `mode '${entry.mode}'. Everything else in the artifact loads; the seed load refuses that dataset ` + + `and writes none of it. ${entry.prescription} Rebuild the artifact after the fix.`, + { object: entry.object, mode: entry.mode }, + ); + } + } + this.lastParsedMetadata = metadata; const memLoader = new MemoryLoader(); diff --git a/packages/objectql/src/engine-seed-required-deferral.test.ts b/packages/objectql/src/engine-seed-required-deferral.test.ts index a710be59110..f15c83cfa8c 100644 --- a/packages/objectql/src/engine-seed-required-deferral.test.ts +++ b/packages/objectql/src/engine-seed-required-deferral.test.ts @@ -154,7 +154,7 @@ const CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; @@ -235,7 +235,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { // in pass 1, so the loader defers by DELETING required `record_id`. const result = await loader().load({ seeds: [ - { object: 'rq_approval', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson', status: 'pending' }, ] }, LEAD_SEED, @@ -270,7 +270,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { const result = await loader().load({ seeds: [ LEAD_SEED, - { object: 'rq_approval', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson', status: 'pending' }, ] }, ] as any, @@ -287,7 +287,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { it('MEASURED: an OPTIONAL id half on a KEYLESS dataset heals out-of-order through the real engine (#11674 end-to-end)', async () => { const result = await loader().load({ seeds: [ - { object: 'rq_ledger', mode: 'insert', env: ENV, records: [ + { object: 'rq_ledger', mode: 'ignore', env: ENV, records: [ { action: 'read', object_name: 'rq_lead', record_id: 'Lisa Thompson' }, ] }, LEAD_SEED, @@ -314,7 +314,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { // signal moves when the author learns, it does not move the verdict. const result = await loader(logger).load({ seeds: [ - { object: 'rq_approval', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson', status: 'pending' }, ] }, LEAD_SEED, @@ -343,7 +343,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { const logger = silentLogger(); const result = await loader(logger).load({ seeds: [ - { object: 'rq_ledger', mode: 'insert', env: ENV, records: [ + { object: 'rq_ledger', mode: 'ignore', env: ENV, records: [ { action: 'read', object_name: 'rq_lead', record_id: 'Lisa Thompson' }, ] }, LEAD_SEED, @@ -416,7 +416,7 @@ describe('seed deferral vs required:true, on the real engine (#11674)', () => { const logger = silentLogger(); const result = await loader(logger).load({ seeds: [ - { object: 'rq_approval_ro', mode: 'insert', env: ENV, records: [ + { object: 'rq_approval_ro', mode: 'ignore', env: ENV, records: [ { process_name: 'flow:discount', object_name: 'rq_lead', record_id: 'Lisa Thompson' }, ] }, LEAD_SEED, diff --git a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts index 6fb3e39600b..804c57f3523 100644 --- a/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts +++ b/packages/qa/dogfood/test/grant-table-write-contract.dogfood.test.ts @@ -280,7 +280,7 @@ describe('an agent ceiling set reaches no person through a position or a seed', it('a published seed granting an agent ceiling set stores no grant, and a person-set seed does', async () => { const seed = (name: string, set: string) => stack.apiAs(admin, 'PUT', `/meta/seed/${name}?mode=draft&package=${PKG}`, { - object: 'sys_user_permission_set', mode: 'insert', records: [{ user_id: personId, permission_set: set }], + object: 'sys_user_permission_set', externalId: ['user_id', 'permission_set'], records: [{ user_id: personId, permission_set: set }], }); expect((await seed('agent_ceiling_grant_seed', CEILING)).status).toBe(200); expect((await seed('person_set_grant_seed', SET)).status).toBe(200); diff --git a/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts b/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts index 809d2c792fc..34198df0ed6 100644 --- a/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts +++ b/packages/qa/dogfood/test/seed-external-id-refusal.dogfood.test.ts @@ -22,7 +22,8 @@ // nothing is stored, so `publish-drafts` has nothing of it to publish. // Controls: the same seed keyed on `name` saves, publishes and converges on // replay (`inserted: 1`, then `inserted: 0, updated: 0`, one row served); an -// `insert` seed is not judged. The publish door's refusal of a draft stored +// `insert` seed, a mode #34613 retired, is refused for its mode and never +// reaches the key judgment. The publish door's refusal of a draft stored // before this rule, and of a seed whose object is drafted in the same batch, // is pinned in-process // (`packages/metadata-protocol/src/protocol.seed-external-id-refusal.test.ts`): @@ -114,8 +115,11 @@ describe('dogfood: a seed whose externalId names no field of its object is refus expect(JSON.stringify(listed.json).match(/"G1"/g) ?? []).toHaveLength(1); }); - it('control: an `insert` seed never matches by its key, so it is not judged', async () => { + it('control: an `insert` seed is refused for its retired mode, not judged on its key (#34613)', async () => { const saved = await call('PUT', `/meta/seed/r_insert?mode=draft&package=${PKG}`, seed('no_such_field', 'insert')); - expect(saved.status, JSON.stringify(saved.json)).toBe(200); + expect(saved.status, JSON.stringify(saved.json)).toBe(422); + const wire = JSON.stringify(saved.json); + expect(wire).toContain("`seed.mode: 'insert'` was removed"); + expect(wire).not.toContain('which is not a field of object'); }); }); diff --git a/packages/qa/scenarios/src/runner/app.ts b/packages/qa/scenarios/src/runner/app.ts index ead42d2af23..b1ba8ad8f4c 100644 --- a/packages/qa/scenarios/src/runner/app.ts +++ b/packages/qa/scenarios/src/runner/app.ts @@ -164,6 +164,17 @@ export interface AppHarness { * it that refusal stays the mode's finding, and every seed row is refused. */ installManaged?(manifest: Record): Promise; + /** + * The sample-data reseed of a package the managed door installed + * (`POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data`): + * its `data[]` loaded again under the deliberate re-seed posture, which + * inserts every missing row whatever the organization's record of landed + * seed rows says. It is how a restore puts back a seeded row a turn removed, + * which an install withholds (`loadSeedRows` in `orchestrate.ts`). Optional, + * so a harness written before it keeps compiling; without it such a row is + * refused, named, and the operation is not measured. + */ + reseedManaged?(manifestId: string): Promise; /** The environment's metadata of every collection the template carries, as an artifact. */ metadataAsArtifact(collections: readonly string[]): Promise>; /** One MCP tool call as the owner of `apiKey`, through the door the agent uses (`mcpUrl`). */ @@ -337,6 +348,10 @@ export class HttpApp implements AppHarness { return this.call('POST', '/api/v1/marketplace/install-local', { packageId, manifest, installMode: 'managed' }, { session: this.admin }); } + reseedManaged(manifestId: string): Promise { + return this.call('POST', `/api/v1/marketplace/install-local/${encodeURIComponent(manifestId)}/reseed-sample-data`, {}, { session: this.admin }); + } + async callTool(apiKey: string, tool: string, args: Record): Promise { const res = await fetch(this.mcpUrl, { method: 'POST', diff --git a/packages/qa/scenarios/src/runner/orchestrate.ts b/packages/qa/scenarios/src/runner/orchestrate.ts index 2232b84c082..902855e249e 100644 --- a/packages/qa/scenarios/src/runner/orchestrate.ts +++ b/packages/qa/scenarios/src/runner/orchestrate.ts @@ -1234,7 +1234,8 @@ interface SeedLoaderAnswer { mode?: string; reason?: string; inserted?: number; - errorList?: Array<{ sourceObject?: string; field?: string; recordIndex?: number; attemptedValue?: unknown; code?: string; message?: string }>; + skipped?: number; + errorList?: Array<{ sourceObject?: string; field?: string; targetField?: string; recordIndex?: number; attemptedValue?: unknown; code?: string; message?: string }>; } /** The seed loads made in this process, which name each load's package apart (one namespace per installed package). */ @@ -1247,12 +1248,22 @@ function seedLoadLetters(n: number): string { return out; } +/** + * Why the install door skipped a row of a load and the object does not hold it + * ({@link loadSeedRows}): an install reads a recorded row that is gone as a + * person's removal, which it must not undo. Short, so the restore's refusal + * line ({@link restoreSeededRows}) keeps the reason after it. + */ +const WITHHELD = 'withheld by the install door: its key is recorded as landed (`sys_seed_landed_key`), the row gone'; + /** * Write rows through the platform's own seed path: one data-only package * whose `data[]` carries them, each object a dataset keyed on `id` - * (`externalId: 'id'`, `mode: 'insert'`), installed through the managed - * install door (`installManaged`). The platform's seed loader writes a - * package's `data[]` under its seed posture (`SEED_WRITE_EXECUTION_CONTEXT` in + * (`externalId: 'id'`) under the default seed mode (`ignore`), installed + * through the managed install door (`installManaged`). The dataset names no + * `mode`: `insert` and `replace` are retired (#34613), and the door refuses a + * dataset declaring either, every row of it. The platform's seed loader writes + * a package's `data[]` under its seed posture (`SEED_WRITE_EXECUTION_CONTEXT` in * `@objectstack/spec/kernel`): the object's `state_machine` rule is skipped, * every other validation rule and hook still runs, and record-triggered flows * do not fire. A row keeps the card's own `id`, and a lookup value naming a @@ -1260,18 +1271,42 @@ function seedLoadLetters(n: number): string { * holds the claim seeded as `c001`. A user id in a row (`owner_id`, a `user` * field, a rewritten handle) is written as sent. * + * `ignore` at the install door is not "create every row the object does not + * hold". The door keeps the organization's record of landed seed rows + * (`sys_seed_landed_key`, keyed on the organization, the object and the row's + * key, with no package in it) and installs under its `honour` posture: a row + * the object holds is left as it is, and a row it does not hold whose key is + * recorded is withheld, as a person's removal, counted in `skipped` with no + * error. A fresh seed meets no record. A restore does: every row it sends is a + * seeded row a turn removed, recorded when the seed landed it. So with + * `reseedWithheld` (the restore, {@link restoreSeededRows}) a load the door + * skipped rows of goes on through that package's sample-data reseed + * (`reseedManaged`), the platform's deliberate re-seed, which inserts every + * missing row whatever the record says. Whenever the door skipped a row, each + * object of the load is read back, and every row sent that the door did not + * refuse and the object does not hold is refused by name with the reason + * ({@link WITHHELD}, and why the reseed did not bring it back), never counted + * as written. A read refused there leaves the rows of that object unconfirmed: + * each is refused with the read's answer. + * * Each package takes a namespace of its own, because one environment refuses * a second package claiming a namespace another already holds. * * The answer's `errorList` names each row the loader could not write - * (`field: '(write)'`), which is refused, and each reference it could not - * resolve on a row it did write, which is refused with the `fields` the row - * does not hold. An entry carries the loader's message and no error code. A - * door that refuses the package, a harness with no managed door, or a load - * that did not run inline (`seeded.mode` other than `inline`) refuses every - * row, with that reason in its message (the door's status and code included). + * (`field: '(write)'`), which is refused; each dataset it refused whole + * (`field: 'mode'`, `targetField: '(dataset)'`, a retired mode), every row of + * which is refused; and each reference it could not resolve on a row it did + * write, which is refused with the `fields` the row does not hold. An entry + * carries the loader's message and no error code. A door that refuses the + * package, a harness with no managed door, or a load that did not run inline + * (`seeded.mode` other than `inline`) refuses every row, with that reason in + * its message (the door's status and code included). */ -async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): Promise<{ inserted: number; refused: RunHalf['seed']['refused'] }> { +async function loadSeedRows( + app: AppHarness, + datasets: readonly SeedDataset[], + opts: { reseedWithheld?: boolean } = {}, +): Promise<{ inserted: number; refused: RunHalf['seed']['refused'] }> { const sent = datasets.flatMap((d) => d.records.map((r) => ({ object: d.object, id: String(r.id) }))); if (sent.length === 0) return { inserted: 0, refused: [] }; const all = (message: string) => ({ inserted: 0, refused: sent.map((r) => ({ ...r, message: message.slice(0, 300) })) }); @@ -1284,7 +1319,7 @@ async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): type: 'app', scope: 'project', name: 'Scenario seed', - data: datasets.map((d) => ({ object: d.object, mode: 'insert', externalId: 'id', records: d.records })), + data: datasets.map((d) => ({ object: d.object, externalId: 'id', records: d.records })), }; const answer = await app.installManaged(manifest); if (!answer.ok) return all(`the seed package was refused: ${answer.status}${answer.code ? ` ${answer.code}` : ''}${answer.message ? ` ${answer.message}` : ''}`); @@ -1297,10 +1332,18 @@ async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): const unheld = new Map(); for (const e of seeded.errorList ?? []) { const object = String(e.sourceObject ?? ''); + const said = { ...(typeof e.code === 'string' ? { code: e.code } : {}), ...(e.message ? { message: e.message.slice(0, 300) } : {}) }; + if (e.field === 'mode' && e.targetField === '(dataset)') { + // The dataset refused whole: no row of it was attempted. + for (const row of records.get(object) ?? []) { + const id = String(row.id); + if (!unwritten.has(`${object}/${id}`)) unwritten.set(`${object}/${id}`, { object, id, ...said }); + } + continue; + } const row = typeof e.recordIndex === 'number' ? records.get(object)?.[e.recordIndex] : undefined; const id = String(row?.id ?? e.attemptedValue ?? ''); const key = `${object}/${id}`; - const said = { ...(typeof e.code === 'string' ? { code: e.code } : {}), ...(e.message ? { message: e.message.slice(0, 300) } : {}) }; if (e.field === '(write)') { if (!unwritten.has(key)) unwritten.set(key, { object, id, ...said }); } else { @@ -1310,10 +1353,40 @@ async function loadSeedRows(app: AppHarness, datasets: readonly SeedDataset[]): } } for (const key of unwritten.keys()) unheld.delete(key); + let written = typeof seeded.inserted === 'number' ? seeded.inserted : sent.length - unwritten.size; + + // Rows the door skipped: brought back through the reseed when asked, then named if still not held. + const notBack = new Map(); + if (typeof seeded.skipped === 'number' && seeded.skipped > 0) { + let why: string | undefined; + if (opts.reseedWithheld) { + if (!app.reseedManaged) why = 'no reseed door'; + else { + const r = await app.reseedManaged(manifest.id); + const again = (r.body as { data?: { inserted?: unknown } } | null)?.data?.inserted; + if (r.ok && typeof again === 'number') written += again; + else why = `reseed refused: ${r.status}${r.code ? ` ${r.code}` : ''}${r.message ? ` ${r.message}` : ''}`; + } + why ??= 'the reseed left it out'; + } + for (const [object, rows] of records) { + const asked = rows.map((row) => String(row.id)).filter((id) => !unwritten.has(`${object}/${id}`)); + if (!asked.length) continue; + const read = await app.listRows(object); + const holds = new Set(read.ok ? read.rows.map((row) => String(row.id)) : []); + for (const id of asked) { + if (holds.has(id)) continue; + const message = read.ok + ? `${WITHHELD}${why ? `; ${why}` : ''}` + : `the door skipped ${seeded.skipped} row(s) of this load, and the read that would say whether this one is in was refused: ${read.status}${read.code ? ` ${read.code}` : ''}`; + notBack.set(`${object}/${id}`, { object, id, message: message.slice(0, 300) }); + } + } + for (const key of notBack.keys()) unheld.delete(key); + } const order = (r: { object: string; id: string }) => position.get(`${r.object}/${r.id}`) ?? sent.length; - const refused = [...unwritten.values(), ...unheld.values()].sort((a, b) => order(a) - order(b)); - const inserted = (typeof seeded.inserted === 'number' ? seeded.inserted : sent.length - unwritten.size) - unheld.size; - return { inserted, refused }; + const refused = [...unwritten.values(), ...notBack.values(), ...unheld.values()].sort((a, b) => order(a) - order(b)); + return { inserted: written - unheld.size, refused }; } /** @@ -1408,7 +1481,10 @@ async function seedDrift(card: Card, app: AppHarness, seeded: SeededRows, built? * 1. a row a turn added is deleted; * 2. a seeded row a turn removed is inserted again through the seed path * ({@link loadSeedRows}, the posture the seed loaded it under, so a row - * already `paid` is not refused as a new record) — the very body the + * already `paid` is not refused as a new record; the install withholds a + * row the seed recorded as landed, so the load goes on through that + * package's reseed, and a row still not back is refused by name, never + * counted as reinserted) — the very body the * seed sent ({@link seedRowBody}), or, for a row the app made itself * while seeding, the row as it was read, less the columns the platform * stamps ({@link RESTORE_UNWRITTEN}); the round's rows go in as one @@ -1476,7 +1552,8 @@ export async function restoreSeededRows( else refused(`delete ${d.object} ${id}`, r); } } - // 2. The seeded rows a turn removed, through the seed path ({@link loadSeedRows}), in its load order, one load a round. + // 2. The seeded rows a turn removed, through the seed path ({@link loadSeedRows}), in its load order, one load a round; + // the install withholds the ones the seed recorded as landed, which the package's reseed puts back. const back: Array<{ object: string; records: Array> }> = []; for (const d of [...drifts].sort((a, b) => order.indexOf(a.object) - order.indexOf(b.object))) { const records: Array> = []; @@ -1493,7 +1570,7 @@ export async function restoreSeededRows( } if (records.length) back.push({ object: d.object, records }); } - const load = await loadSeedRows(app, back); + const load = await loadSeedRows(app, back, { reseedWithheld: true }); const notBack = new Set(load.refused.filter((r) => !r.fields).map((r) => `${r.object}/${r.id}`)); for (const r of load.refused) refusals.add(`insert ${r.object} ${r.id}: ${r.code ? `${r.code} ` : ''}${r.fields ? `[${r.fields.join(', ')}] ` : ''}${(r.message ?? '').slice(0, 120)}`.trim()); for (const d of back) for (const row of d.records) if (!notBack.has(`${d.object}/${String(row.id)}`)) reinserted.add(`${d.object}/${String(row.id)}`); diff --git a/packages/qa/scenarios/test/runner/orchestrate.test.ts b/packages/qa/scenarios/test/runner/orchestrate.test.ts index c014ce1e086..17de0b23ece 100644 --- a/packages/qa/scenarios/test/runner/orchestrate.test.ts +++ b/packages/qa/scenarios/test/runner/orchestrate.test.ts @@ -22,11 +22,12 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it, vi } from 'vitest'; import { validateRollupSourceVisibility } from '@objectstack/lint'; +import { RETIRED_SEED_MODE_VALUES } from '@objectstack/spec/data'; import { formatRefusal, loadScenarioFile, readCapabilityAreas, type LoadedScenario } from '../../src/loader.js'; import { buildDeniesWrite, gradeCardAnswer, truthFigures } from '../../src/score/index.js'; import type { AppHarness, HttpAnswer, PersonaAccount, ToolAnswer } from '../../src/runner/app.js'; -import { seedDoorAnswer } from './seed-door.js'; +import { reseedDoorAnswer, seedDoorAnswer, type SeedDoorRecord } from './seed-door.js'; import { RecordedDriver, RecordingDriver, ReplayNotFaithfulError, stepKey, type AgentDriver, type AskTask, type AuthorTask, type DriverInfo, type Recording } from '../../src/runner/driver.js'; import { loadedCardStamp, main as runScenarios, makeDriver, parseArgs, promptChoiceOf } from '../../src/runner/cli.js'; import { citationLabels, namespacedScenario } from '../../src/runner/namespace.js'; @@ -193,15 +194,32 @@ class FakeApp implements AppHarness { seedDrops(_object: string, _row: Record): Record { return {}; } - /** The managed door: a data-only package's `data[]` is the seed ({@link seedDoorAnswer}); any other manifest is a build. */ + /** The organization's record of landed seed rows (`sys_seed_landed_key`), `object/id`, kept across every package the door loads ({@link seedDoorAnswer}). */ + landed = new Set(); + /** The data-only packages the managed door installed, by id: what the reseed door loads again. */ + seedPackageById = new Map>(); + private seedRecord(): SeedDoorRecord { + return { landed: this.landed, holds: (object, id) => (this.rows[object] ?? []).some((r) => String(r.id) === id) }; + } + /** The managed door: a data-only package's `data[]` is the seed ({@link seedDoorAnswer}), under the install's `honour` posture; any other manifest is a build. */ async installManaged(manifest: Record): Promise { if (!Array.isArray(manifest.data)) { this.installed = manifest; return this.installAnswer; } + this.seedPackageById.set(String(manifest.id), manifest); + this.seeding = true; + try { + return await seedDoorAnswer((object, row) => this.insertRow(object, row), manifest, (object, row) => this.seedDrops(object, row), this.seedRecord()); + } finally { + this.seeding = false; + } + } + /** The sample-data reseed door of an installed data-only package ({@link reseedDoorAnswer}): every missing row, whatever the record says. */ + async reseedManaged(manifestId: string): Promise { this.seeding = true; try { - return await seedDoorAnswer((object, row) => this.insertRow(object, row), manifest, (object, row) => this.seedDrops(object, row)); + return await reseedDoorAnswer((object, row) => this.insertRow(object, row), this.seedPackageById.get(manifestId), manifestId, this.seedRecord(), (object, row) => this.seedDrops(object, row)); } finally { this.seeding = false; } @@ -968,6 +986,101 @@ describe('seedApp — a card row already past its entry state loads through the expect(app.rows.demotravel_expense_claim!.find((r) => r.id === 'c001')).toMatchObject({ status: 'paid' }); }); + it('[#34613] the seed and restore packages declare no retired seed mode: each dataset names no `mode`, so the default (`ignore`) loads it', async () => { + /** Records every data-only package the runner sends the managed door. */ + class ManifestTap extends TravelRulesApp { + readonly seedPackages: Array> = []; + override async installManaged(manifest: Record): Promise { + if (Array.isArray(manifest.data)) this.seedPackages.push(manifest); + return super.installManaged(manifest); + } + } + const scenario = travel(); + const app = new ManifestTap(); + expect((await seedApp(scenario, app, [])).refused).toEqual([]); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); + await restoreSeededRows(scenario, app, [], seeded); + expect(app.seedPackages.length).toBeGreaterThanOrEqual(2); // the seed, then the restore + const datasets = app.seedPackages.flatMap((m) => m.data as Array>); + expect(datasets.filter((d) => 'mode' in d)).toEqual([]); + for (const d of datasets) expect(d.externalId).toBe('id'); + }); + + it('[#34613] control: the test door refuses a dataset declaring a retired mode whole, with SeedMode\'s own message, as the real door does', async () => { + for (const mode of RETIRED_SEED_MODE_VALUES) { + const written: string[] = []; + const answer = await seedDoorAnswer(async (_o, row) => (written.push(String(row.id)), { ok: true, status: 200, body: {} }), { + id: 'com.scenario.seed.x', + data: [{ object: 'demotravel_department', mode, externalId: 'id', records: [{ id: 'dep_a' }, { id: 'dep_b' }] }], + }); + const seeded = (answer.body as { data: { seeded: { inserted: number; errorList: Array<{ field: string; targetField: string; recordIndex: number; message: string }> } } }).data.seeded; + expect(written).toEqual([]); + expect(seeded.inserted).toBe(0); + // One entry for the dataset, as `loadStored` answers it: the mode is the dataset's, no row was attempted. + expect(seeded.errorList.map(({ field, targetField, recordIndex }) => ({ field, targetField, recordIndex }))).toEqual([{ field: 'mode', targetField: '(dataset)', recordIndex: 0 }]); + expect(seeded.errorList[0]!.message).toContain(`seed.mode: '${mode}'\` was removed`); + } + }); + + it('[#34613] control: the test door keeps the landed-row record as the real door does — an install withholds a recorded row that is gone, the package\'s reseed brings it back, an unrecorded row lands', async () => { + const app = new FakeApp(); + const pkg = (id: string, rows: Array>) => ({ id, data: [{ object: 'x', externalId: 'id', records: rows }] }); + const seededOf = (a: HttpAnswer) => (a.body as { data: { seeded: { inserted: number; skipped: number; errors: number } } }).data.seeded; + expect(seededOf(await app.installManaged(pkg('com.scenario.seed.a', [{ id: 'r1' }, { id: 'r2' }])))).toMatchObject({ inserted: 2, skipped: 0, errors: 0 }); + app.rows.x = app.rows.x!.filter((r) => r.id !== 'r2'); + // A second package carrying the recorded, removed row: withheld, `skipped`, no error. + expect(seededOf(await app.installManaged(pkg('com.scenario.seed.b', [{ id: 'r2' }])))).toMatchObject({ inserted: 0, skipped: 1, errors: 0 }); + expect(app.rows.x!.map((r) => r.id)).toEqual(['r1']); + // That package's reseed inserts it, whatever the record says. + const reseed = await app.reseedManaged('com.scenario.seed.b'); + expect(reseed).toMatchObject({ ok: true, body: { data: { inserted: 1, skipped: 0, errors: 0 } } }); + expect(app.rows.x!.map((r) => r.id)).toEqual(['r1', 'r2']); + // A row the object holds is left as it is; a row no load recorded lands. + expect(seededOf(await app.installManaged(pkg('com.scenario.seed.c', [{ id: 'r1' }, { id: 'r3' }])))).toMatchObject({ inserted: 1, skipped: 1, errors: 0 }); + expect(app.rows.x!.map((r) => r.id)).toEqual(['r1', 'r2', 'r3']); + expect(await app.reseedManaged('com.scenario.seed.none')).toMatchObject({ ok: false, status: 404 }); + }); + + it('[#34613] a restore puts back a seeded row the install withholds: the restore package\'s reseed brings it in, and is the only reseed asked', async () => { + class ReseedTap extends TravelRulesApp { + readonly reseeds: string[] = []; + override async reseedManaged(manifestId: string): Promise { + this.reseeds.push(manifestId); + return super.reseedManaged(manifestId); + } + } + const scenario = travel(); + const app = new ReseedTap(); + expect((await seedApp(scenario, app, [])).refused).toEqual([]); + expect(app.reseeds).toEqual([]); // a fresh seed meets no record + expect(app.landed.has('demotravel_expense_claim/c001')).toBe(true); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); + expect(await restoreSeededRows(scenario, app, [], seeded)).toEqual({ restored: { reinserted: ['demotravel_expense_claim/c001'] } }); + expect(app.reseeds).toHaveLength(1); + expect(app.reseeds[0]).toMatch(/^com\.scenario\.seed\.scenarioseed[a-z]+$/); + expect(app.rows.demotravel_expense_claim!.filter((r) => r.id === 'c001')).toEqual([expect.objectContaining({ status: 'paid' })]); + }); + + it('[#34613] a withheld row a restore cannot put back is refused by name with the reason, never booked as reinserted', async () => { + const scenario = travel(); + const app = new TravelRulesApp(); + Object.assign(app, { reseedManaged: undefined }); // a harness with no reseed door + await seedApp(scenario, app, []); + const seeded = await seededRows(app, restoreObjects(scenario.card)); + app.rows.demotravel_expense_claim = app.rows.demotravel_expense_claim!.filter((r) => r.id !== 'c001'); + const out = await restoreSeededRows(scenario, app, [], seeded); + expect(out.restored).toBeUndefined(); + expect(out.failed).toContain('the rows could not be restored to the seeded state: demotravel_expense_claim: 1 missing (c001)'); + // The refusal names the row, the record that withheld it, and why the reseed did not run. + const refusal = /\(refused: (.*)\)$/.exec(out.failed!)?.[1] ?? ''; + expect(refusal).toMatch(/^insert demotravel_expense_claim c001: /); + expect(refusal).toContain('sys_seed_landed_key'); + expect(refusal).toContain('no reseed door'); + expect(app.rows.demotravel_expense_claim!.some((r) => r.id === 'c001')).toBe(false); + }); + it('a reference the loader drops from a row it wrote refuses that row with the field and keeps its second-pass patch; a row also refused on write counts once; a restore counts the written row as reinserted', async () => { /** Departments under a self-lookup `parent`. Finance breaks a budget floor, so its write is refused; a `parent` naming a department not in is dropped, as an optional lookup the loader cannot resolve. */ class DroppedParentApp extends TravelRulesApp { diff --git a/packages/qa/scenarios/test/runner/seed-door.ts b/packages/qa/scenarios/test/runner/seed-door.ts index 941f7c042e1..1a10cea40f8 100644 --- a/packages/qa/scenarios/test/runner/seed-door.ts +++ b/packages/qa/scenarios/test/runner/seed-door.ts @@ -14,20 +14,68 @@ * it, and the answer carries one entry with `field` set to that lookup, as the * real loader reports a reference it could not resolve (`referencesDropped`). * A row whose write then fails carries both entries. + * + * A dataset whose `mode` `SeedMode` does not accept (a retired `insert` or + * `replace`, #34613) is refused whole, as the real door refuses it + * (`loadStored`): one entry for the dataset, `field: 'mode'`, + * `targetField: '(dataset)'`, `recordIndex: 0`, with `SeedMode`'s own message, + * and no row written. + * + * `record` is the organization's record of landed seed rows + * (`sys_seed_landed_key`), as the real door keeps it: keyed on the object and + * the row's `id` (every runner dataset is keyed on `id`), with no package in + * the key, so every package the door loads shares it. With it, each row of an + * (`ignore`) dataset is read first (`record.holds`): a row the object holds is + * left as it is (`skipped`); a row it does not hold whose key is recorded is + * withheld under the install's `honour` posture (`skipped`, not written, no + * error, as `isWithdrawnRow` in the real loader) and written under the + * reseed's `reseed` posture; every row written is recorded. Without `record` + * the door keeps no record and writes every row, the shape before the record + * was modelled. */ +import { SeedMode } from '@objectstack/spec/data'; import type { HttpAnswer } from '../../src/runner/app.js'; +/** The landed-seed-row record a double's door keeps ({@link seedDoorAnswer}), and the read it judges a row by. */ +export interface SeedDoorRecord { + /** `object/id` of every seed row the door has landed, across every package it loaded. */ + landed: Set; + /** Whether the object holds a row with this `id` now. */ + holds(object: string, id: string): boolean | Promise; + /** `honour` for an install (the default), `reseed` for the package's sample-data reseed. */ + posture?: 'honour' | 'reseed'; +} + export async function seedDoorAnswer( write: (object: string, row: Record) => Promise, manifest: Record, drops: (object: string, row: Record) => Record = () => ({}), + record?: SeedDoorRecord, ): Promise { - const datasets = manifest.data as Array<{ object: string; records: Array> }>; + const datasets = manifest.data as Array<{ object: string; mode?: unknown; records: Array> }>; let inserted = 0; + let skipped = 0; const errorList: Array> = []; - for (const { object, records } of datasets) { + for (const { object, mode, records } of datasets) { + const judged = mode === undefined ? undefined : SeedMode.safeParse(mode); + if (judged && !judged.success) { + const said = judged.error.issues[0]?.message ?? `seed mode ${String(mode)} refused`; + errorList.push({ sourceObject: object, field: 'mode', targetObject: object, targetField: '(dataset)', attemptedValue: mode, recordIndex: 0, message: `Seed dataset for '${object}' was not loaded: ${said}` }); + continue; + } for (const [recordIndex, sent] of records.entries()) { + const key = `${object}/${String(sent.id)}`; + if (record) { + if (await record.holds(object, String(sent.id))) { + skipped++; + continue; + } + if ((record.posture ?? 'honour') === 'honour' && record.landed.has(key)) { + skipped++; + continue; + } + } const row = { ...sent }; for (const [field, targetObject] of Object.entries(drops(object, sent))) { errorList.push({ @@ -42,8 +90,10 @@ export async function seedDoorAnswer( delete row[field]; } const r = await write(object, row); - if (r.ok) inserted++; - else + if (r.ok) { + inserted++; + record?.landed.add(key); + } else errorList.push({ sourceObject: object, field: '(write)', @@ -55,6 +105,31 @@ export async function seedDoorAnswer( }); } } - const seeded = { mode: 'inline', inserted, updated: 0, skipped: 0, errors: errorList.length, errorList, droppedRefs: 0 }; + const seeded = { mode: 'inline', inserted, updated: 0, skipped, errors: errorList.length, errorList, droppedRefs: 0 }; return { ok: true, status: 200, body: { success: true, data: { manifestId: manifest.id, seeded } } }; } + +/** + * The sample-data reseed door's answer for an installed data-only package + * (`POST …/install-local/:manifestId/reseed-sample-data`), as the real door + * gives it: the package's datasets loaded again under the `reseed` posture + * ({@link seedDoorAnswer}), answered with the loader's four counts and no + * error list; a run that wrote nothing and found nothing already there is + * `422 RESEED_NO_ROWS`, and a package the door never installed is `404`. + */ +export async function reseedDoorAnswer( + write: (object: string, row: Record) => Promise, + manifest: Record | undefined, + manifestId: string, + record: SeedDoorRecord, + drops?: (object: string, row: Record) => Record, +): Promise { + if (!manifest) return { ok: false, status: 404, body: {}, code: 'RESOURCE_NOT_FOUND', message: `No marketplace install for ${manifestId}.` }; + const answer = await seedDoorAnswer(write, manifest, drops, { ...record, posture: 'reseed' }); + const { inserted, updated, skipped, errors, errorList } = (answer.body as { data: { seeded: { inserted: number; updated: number; skipped: number; errors: number; errorList: Array<{ message?: string }> } } }).data.seeded; + if (inserted + updated === 0 && !(errors === 0 && skipped > 0)) { + const message = errors > 0 ? `Reseed wrote no rows (${errors} error${errors === 1 ? '' : 's'}).${errorList[0]?.message ? ` First error: ${errorList[0].message}` : ''}` : 'Reseed wrote no rows. The package declares no seedable records for this runtime.'; + return { ok: false, status: 422, body: {}, code: 'RESEED_NO_ROWS', message }; + } + return { ok: true, status: 200, body: { success: true, data: { manifestId, inserted, updated, skipped, errors, withSampleData: true } } }; +} diff --git a/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts b/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts index ef33e93c8e6..f79e641e7f1 100644 --- a/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts +++ b/packages/runtime/src/app-plugin.seed-stamped-additive.test.ts @@ -17,7 +17,7 @@ * resolves its collections, and a dataset has no `name`, so it is claimed by * value. With the stamps counted as part of that value the body copy was a * second dataset: two entries in the shared `seed-datasets` registry, and a - * `mode: 'insert'` row written twice. + * `mode: 'insert'` row written twice (that mode is since retired, #34613). * * The fixtures elsewhere could not see this: they are `upsert`-only, which is * idempotent, and their additive fixture shares object REFERENCES between the @@ -25,6 +25,8 @@ */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; import { LiteKernel, type PluginContext } from '@objectstack/core'; import { ObjectQLPlugin } from '@objectstack/objectql'; import { applyProtection } from '@objectstack/spec/shared'; @@ -40,7 +42,7 @@ const coreBody = () => ({ version: '1.0.0', type: 'app', objects: [{ name: 'stamped_account', label: 'Account', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }], - data: [{ object: 'stamped_account', mode: 'insert', records: [{ name: 'once' }] }], + data: [{ object: 'stamped_account', mode: 'ignore', records: [{ name: 'once' }] }], }); const ordersBody = (withOwnDataset = false) => ({ @@ -50,7 +52,7 @@ const ordersBody = (withOwnDataset = false) => ({ type: 'module', dependencies: { [CORE_ID]: '^1.0.0' }, objects: [{ name: 'stamped_order', label: 'Order', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }], - ...(withOwnDataset ? { data: [{ object: 'stamped_order', mode: 'insert', records: [{ name: 'second' }] }] } : {}), + ...(withOwnDataset ? { data: [{ object: 'stamped_order', mode: 'ignore', records: [{ name: 'second' }] }] } : {}), }); /** The compiled additive shape: both halves, round-tripped through JSON. */ @@ -90,7 +92,7 @@ describe('additive artifact — real registration, then the seed registry', () = expect(artifact.data[0]._packageId).toBeUndefined(); expect(seeds).toHaveLength(1); - expect(seeds).toEqual([expect.objectContaining({ object: 'stamped_account', mode: 'insert' })]); + expect(seeds).toEqual([expect.objectContaining({ object: 'stamped_account', mode: 'ignore' })]); }); it('still registers a second package\'s OWN dataset', async () => { diff --git a/packages/runtime/src/app-plugin.seed.test.ts b/packages/runtime/src/app-plugin.seed.test.ts index 4f3b56fe8ca..303c70ec9da 100644 --- a/packages/runtime/src/app-plugin.seed.test.ts +++ b/packages/runtime/src/app-plugin.seed.test.ts @@ -1,6 +1,8 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; import { AppPlugin } from './app-plugin'; import { readSeedDatasets } from './seed-datasets.js'; import { readSeedSettlement } from './seed-settlement.js'; @@ -288,7 +290,7 @@ describe('AppPlugin flat-bundle seed collection (#15262)', () => { data: [ { object: 'sys_user', - mode: 'insert', + mode: 'ignore', records: [{ id: 'flat_u1', name: 'Flat One' }], }, ], @@ -332,9 +334,9 @@ describe('AppPlugin flat-bundle seed collection (#15262)', () => { const bundle = { manifest: { id: 'com.test.nested-seed', - data: [{ object: 'sys_user', mode: 'insert', records: [{ id: 'legacy_u1' }] }], + data: [{ object: 'sys_user', mode: 'ignore', records: [{ id: 'legacy_u1' }] }], }, - data: [{ object: 'sys_user', mode: 'insert', records: [{ id: 'top_u1' }] }], + data: [{ object: 'sys_user', mode: 'ignore', records: [{ id: 'top_u1' }] }], }; await new AppPlugin(bundle).start(ctx); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 951925471dd..46a1172fbd3 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -1961,8 +1961,8 @@ export class AppPlugin implements Plugin { // just contributed and every dataset lands twice. `mergeSeedDatasets` // is a plain `push` with no de-duplication, so both copies reach the // shared registry, the inline loader and every later per-org replay: - // for a `mode: 'insert'` dataset that is the row applied twice per - // boot, not merely doubled work. + // for a dataset whose key matches no row yet, that is the row applied + // twice per boot, not merely doubled work. const manifest = this.bundle.manifest || this.bundle; if (manifest && Array.isArray(manifest.data) && manifest.data !== this.collections.data) { seedDatasets.push(...manifest.data); @@ -2063,8 +2063,9 @@ export class AppPlugin implements Plugin { const seedLoader = new SeedLoaderService( ql, md, loggerRef, seedLoaderOptionsFor(ctx, options?.reseed === true ? 'reseed' : 'honour'), ); - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); - const request = SeedLoaderRequestSchema.parse({ + // [#34613] `loadStored`: a stored dataset declaring a + // retired `mode` is refused alone; the rest load. + const result = await seedLoader.loadStored({ seeds: datasetsNow, config: { // [#30081] No mode of its own: each dataset's @@ -2086,7 +2087,6 @@ export class AppPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale.locale } : {}), }, }); - const result = await seedLoader.load(request); // [#23354] The rows this replay landed on, for the // organization's owner-bind claim (`seededRecordIds` with // this organization): it hands over these rows and no @@ -2164,11 +2164,12 @@ export class AppPlugin implements Plugin { const metadata = ctx.getService('metadata') as IMetadataService | undefined; if (metadata) { const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx, 'honour')); - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); // [#16595] `Seed.locale`'s producer on the DEFAULT boot // path — see {@link resolveSeedLocale}. const seedLocale = this.resolveSeedLocale(); - const request = SeedLoaderRequestSchema.parse({ + // [#34613] `loadStored`: a stored dataset declaring a + // retired `mode` is refused alone; the rest load. + const result = await seedLoader.loadStored({ seeds: normalizedDatasets, config: { // [#30081] No mode of its own: a replay on a @@ -2181,7 +2182,6 @@ export class AppPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale } : {}), }, }); - const result = await seedLoader.load(request); // [#34458] A person the seed names who does not exist yet // (the first admin) left a NULL; the handoff below // resolves it once a `sys_user` row is inserted. @@ -2652,13 +2652,14 @@ export class AppPlugin implements Plugin { return; } const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx, 'honour')); - const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); // [#16595] `Seed.locale`'s producer on the dev hot-reload // path. Resolved from the BOOT bundle, not from `payload`: a // reload re-parses the artifact's metadata collections, and // `i18n` is an envelope key that does not travel in it. const seedLocale = this.resolveSeedLocale(); - const request = SeedLoaderRequestSchema.parse({ + // [#34613] `loadStored`: a stored dataset declaring a retired + // `mode` is refused alone; the rest load. + const result = await seedLoader.loadStored({ seeds, config: { // [#30081] No mode of its own — the spec default applies. @@ -2666,7 +2667,6 @@ export class AppPlugin implements Plugin { ...(seedLocale ? { locale: seedLocale } : {}), }, }); - const result = await seedLoader.load(request); const { totalInserted, totalUpdated, totalErrored } = result.summary; ctx.logger.info( `[Seeder] Hot-reload seeded new object(s) ${fresh.join(', ')}: ` + diff --git a/packages/runtime/src/artifact-collections.test.ts b/packages/runtime/src/artifact-collections.test.ts index d9ac2effe23..4d3e2d21c7e 100644 --- a/packages/runtime/src/artifact-collections.test.ts +++ b/packages/runtime/src/artifact-collections.test.ts @@ -192,10 +192,10 @@ describe('resolveArtifactCollections', () => { // resolves its collections after that. A nameless item is claimed by // value, so the stamps alone used to turn one definition into two. const additive = JSON.parse(JSON.stringify({ - data: [{ object: 'account', mode: 'insert', records: [{ name: 'once' }] }], + data: [{ object: 'account', mode: 'ignore', records: [{ name: 'once' }] }], datasourceMapping: [{ datasource: 'primary', default: true }], packages: packagesOf({ - data: [{ object: 'account', mode: 'insert', records: [{ name: 'once' }] }], + data: [{ object: 'account', mode: 'ignore', records: [{ name: 'once' }] }], datasourceMapping: [{ datasource: 'primary', default: true }], }), })); @@ -223,8 +223,8 @@ describe('resolveArtifactCollections', () => { // out of identity. A dataset whose records differ is a second // definition, and it still arrives. const additive = JSON.parse(JSON.stringify({ - data: [{ object: 'account', mode: 'insert', records: [{ name: 'top' }] }], - packages: packagesOf({ data: [{ object: 'account', mode: 'insert', records: [{ name: 'body' }] }] }), + data: [{ object: 'account', mode: 'ignore', records: [{ name: 'top' }] }], + packages: packagesOf({ data: [{ object: 'account', mode: 'ignore', records: [{ name: 'body' }] }] }), })); applyProtection(additive.packages[1].manifest.data[0], { packageId: 'com.example.core' }); diff --git a/packages/runtime/src/bulk-write-real-driver.integration.test.ts b/packages/runtime/src/bulk-write-real-driver.integration.test.ts index 8902d067945..f8685c929b9 100644 --- a/packages/runtime/src/bulk-write-real-driver.integration.test.ts +++ b/packages/runtime/src/bulk-write-real-driver.integration.test.ts @@ -84,7 +84,7 @@ const TREENODE = { fields: { name: { type: 'text' }, parent: { type: 'lookup', reference: 'treenode' } }, }; -const SEED_CONFIG = { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'insert', batchSize: 1000, transaction: false } as any; +const SEED_CONFIG = { dryRun: false, haltOnError: false, multiPass: true, defaultMode: 'ignore', batchSize: 1000, transaction: false } as any; const logger = { info() {}, warn() {}, error() {}, debug() {} }; function metadataFor(objects: any[]) { @@ -183,7 +183,7 @@ describe('bulk-write hardening on a REAL SqlDriver (framework#3147–#3152, #317 }); const seeder = new SeedLoaderService(e as any, metadataFor([WIDGET]), logger as any); const result = await seeder.load({ - seeds: [{ object: 'widget', externalId: 'sku', mode: 'insert', env: ['prod', 'dev', 'test'], + seeds: [{ object: 'widget', externalId: 'sku', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'A', sku: 'W-A' }, { name: 'B', sku: 'W-B' }] }] as any, config: SEED_CONFIG, }); @@ -202,7 +202,7 @@ describe('bulk-write hardening on a REAL SqlDriver (framework#3147–#3152, #317 }); const seeder = new SeedLoaderService(e as any, metadataFor([TREENODE]), logger as any); const result = await seeder.load({ - seeds: [{ object: 'treenode', externalId: 'name', mode: 'insert', env: ['prod', 'dev', 'test'], + seeds: [{ object: 'treenode', externalId: 'name', mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Alice' }, { name: 'Bob' }] }] as any, config: SEED_CONFIG, }); diff --git a/packages/runtime/src/seed-datasets.test.ts b/packages/runtime/src/seed-datasets.test.ts index 937db858545..f288f9df4e8 100644 --- a/packages/runtime/src/seed-datasets.test.ts +++ b/packages/runtime/src/seed-datasets.test.ts @@ -1,6 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; /** * #3453 — the multi-tenant seed-replay seam. @@ -42,6 +44,12 @@ let seedResult: any = loaderResult({ totalInserted: 0, totalUpdated: 0, totalSki vi.mock('./seed-loader.js', () => ({ SeedLoaderService: class { + // [#34613] The real `loadStored` parses the stored request and hands it to `load`; + // the stand-in keeps that funnel, so the request `load` records is the parsed one. + async loadStored(raw: any) { + const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data'); + return this.load(SeedLoaderRequestSchema.parse(raw)); + } constructor(..._args: any[]) { /* ql / metadata / logger ignored — mocked */ } async load(request: any) { loadCalls.push(request); return seedResult; } }, diff --git a/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts b/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts index 597d68835b6..e8d48ca883a 100644 --- a/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts +++ b/packages/runtime/src/seed-loader-driver-text-real-driver.integration.test.ts @@ -72,7 +72,7 @@ const ACCT = { const SEED_CONFIG = { dryRun: false, haltOnError: false, multiPass: true, - defaultMode: 'insert', batchSize: 1000, transaction: false, + defaultMode: 'ignore', batchSize: 1000, transaction: false, } as any; function metadataFor(objects: any[]) { @@ -162,7 +162,7 @@ describe('[#8442] a REAL driver constraint violation is withheld from the seed r seeds: [{ object: 'dt_acct', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [ { name: 'first', email: 'dup@example.com' }, diff --git a/packages/runtime/src/seed-loader.test.ts b/packages/runtime/src/seed-loader.test.ts index c0f3ecf1a84..8ee4ceab9d3 100644 --- a/packages/runtime/src/seed-loader.test.ts +++ b/packages/runtime/src/seed-loader.test.ts @@ -1117,7 +1117,7 @@ describe('SeedLoaderService', () => { { object: 'note', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'N1', author: cel('os.user.id') }], }, @@ -1150,7 +1150,7 @@ describe('SeedLoaderService', () => { { object: 'note', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'N1', author: cel('os.user.id') }], }, @@ -1185,7 +1185,7 @@ describe('SeedLoaderService', () => { { object: 'note', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'N1', org_label: cel('os.org.id') }], }, @@ -1194,7 +1194,7 @@ describe('SeedLoaderService', () => { }); expect(result.success).toBe(true); - // One record, mode 'insert' ⇒ exactly ONE engine write. Seed application is + // One record ⇒ exactly ONE engine write. Seed application is // the very path where a doubled collect writes twice and stays green under // `toHaveBeenCalledWith` (#15607). expect(engine.insert).toHaveBeenCalledTimes(1); @@ -1220,12 +1220,12 @@ describe('SeedLoaderService', () => { { object: 'account', externalId: 'name', - mode: 'insert', + mode: 'ignore', env: ['prod', 'dev', 'test'], records: [{ name: 'Acme' }], }, ], - config: baseConfig({ defaultMode: 'insert' }), + config: baseConfig({ defaultMode: 'ignore' }), }); expect(result.success).toBe(false); diff --git a/packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts b/packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts new file mode 100644 index 00000000000..700da3be77d --- /dev/null +++ b/packages/runtime/src/standalone-stack-artifact-retired-seed-mode-34613.test.ts @@ -0,0 +1,93 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [#34613] A compiled artifact built before the seed modes `insert` and +// `replace` were retired still boots, and only that dataset is refused. +// +// The composition is the one `os serve` / `os start` / `os dev` boot +// (`createStandaloneStack`): the artifact door (`MetadataPlugin`), which +// strict-parses the definition, and the `AppPlugin` that seeds from the same +// bytes. `SeedSchema.mode` refuses both retired values, so before the door +// withheld such a dataset from its parse, one stale seed dataset aborted the +// whole boot: no object registered, no other dataset loaded (L2 review M1 on +// PR #34791). Ruling 6942780880 item 2 asks for the opposite, and this file +// drives the real boot to the seeder: +// +// - the artifact's object registers and its keyed dataset lands, once; +// - the retired dataset writes nothing, with `insert` and with `replace`; +// - CONTROL: a mode that was never a seed mode is still the door's parse +// refusal, for the whole boot, exactly as before. + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ObjectQL } from '@objectstack/objectql'; +import { Runtime } from './runtime.js'; +import { createStandaloneStack } from './standalone-stack.js'; + +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/metadata'; +import '@objectstack/objectql'; +import '@objectstack/service-datasource'; + +const BOOT_TIMEOUT = 90_000; +const SYSTEM = { context: { isSystem: true } } as const; + +const artifact = (staleMode: string) => ({ + manifest: { id: 'com.test.retired-seed-mode', name: 'retired_seed_mode', type: 'app', version: '1.0.0', namespace: 'rsm' }, + objects: [ + { name: 'rsm_region', label: 'Region', tenancy: { enabled: false }, fields: { name: { type: 'text', label: 'Name' } } }, + { name: 'rsm_source', label: 'Source', tenancy: { enabled: false }, fields: { name: { type: 'text', label: 'Name' } } }, + ], + data: [ + { object: 'rsm_region', externalId: 'name', records: [{ name: 'emea' }, { name: 'apac' }] }, + { object: 'rsm_source', mode: staleMode, records: [{ name: 'web' }] }, + ], +}); + +describe('#34613 — a compiled artifact carrying a retired seed mode boots; only that dataset is refused', () => { + const dirs: string[] = []; + const kernels: any[] = []; + + afterEach(async () => { + for (const k of kernels.splice(0)) { + try { await k.shutdown(); } catch { /* noop */ } + } + for (const d of dirs.splice(0)) { + try { rmSync(d, { recursive: true, force: true }); } catch { /* noop */ } + } + }); + + async function bootOverArtifact(staleMode: string) { + const dir = mkdtempSync(join(tmpdir(), 'os-retired-seed-mode-')); + dirs.push(dir); + const artifactPath = join(dir, 'objectstack.json'); + writeFileSync(artifactPath, JSON.stringify(artifact(staleMode)), 'utf-8'); + const stack = await createStandaloneStack({ + artifactPath, + projectRoot: dir, + databaseUrl: ':memory:', + runPlatformMigrations: false, + }); + const runtime = new Runtime({ cluster: false }); + const kernel = runtime.getKernel(); + kernels.push(kernel); + for (const p of stack.plugins) await kernel.use(p as any); + await kernel.bootstrap(); + return kernel; + } + + it.each([['insert'], ['replace']])('`%s`: the boot completes, the object registers, the keyed dataset lands, the stale one writes nothing', async (staleMode) => { + const kernel = await bootOverArtifact(staleMode); + const ql = kernel.getService('objectql'); + + expect(ql.registry.getObject('rsm_source'), 'the object of the refused dataset still registers').toBeDefined(); + const regions = await ql.find('rsm_region', { where: {}, ...SYSTEM } as never); + expect((regions as Array<{ name: string }>).map((r) => r.name).sort()).toEqual(['apac', 'emea']); + expect(await ql.find('rsm_source', { where: {}, ...SYSTEM } as never)).toEqual([]); + }, BOOT_TIMEOUT); + + it('CONTROL: a mode that was never a seed mode is still the artifact door’s parse refusal', async () => { + await expect(bootOverArtifact('merge')).rejects.toThrow(/mode/); + }, BOOT_TIMEOUT); +}); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 0097b3131e6..3e37980bceb 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -671,6 +671,7 @@ "REFERENCE_VALUE_TYPES (const)", "RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS (const)", + "RETIRED_SEED_MODE_VALUES (const)", "RETIRED_SUB_DAY_INTERVALS (const)", "RLS_DENY_FILTER (const)", "ROUTE_SHADOWED_DATASOURCE_NAMES (const)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index b57563a62af..6534a63ccdb 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -660,6 +660,7 @@ "REFERENCE_VALUE_TYPES": "src/data/field-value.zod.ts#REFERENCE_VALUE_TYPES (const)", "RETIRED_DRIVER_ID_GUIDANCE": "src/data/driver/config-registry.zod.ts#RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS": "src/data/filter.zod.ts#RETIRED_FILTER_OPERATORS (const)", + "RETIRED_SEED_MODE_VALUES": "src/data/seed.zod.ts#RETIRED_SEED_MODE_VALUES (const)", "RETIRED_SUB_DAY_INTERVALS": "src/data/analytics.zod.ts#RETIRED_SUB_DAY_INTERVALS (const)", "RLS_DENY_FILTER": "src/data/readable-ids.ts#RLS_DENY_FILTER (const)", "ROUTE_SHADOWED_DATASOURCE_NAMES": "src/data/datasource.zod.ts#ROUTE_SHADOWED_DATASOURCE_NAMES (const)", diff --git a/packages/spec/src/data/seed-loader.test.ts b/packages/spec/src/data/seed-loader.test.ts index 81c0a72fee1..c7b07142c5f 100644 --- a/packages/spec/src/data/seed-loader.test.ts +++ b/packages/spec/src/data/seed-loader.test.ts @@ -261,7 +261,7 @@ describe('SeedLoaderConfigSchema', () => { }); it('should accept all valid dataset modes as default', () => { - const modes = ['insert', 'update', 'upsert', 'replace', 'ignore'] as const; + const modes = ['update', 'upsert', 'ignore'] as const; modes.forEach(mode => { const config = SeedLoaderConfigSchema.parse({ defaultMode: mode }); expect(config.defaultMode).toBe(mode); @@ -326,7 +326,7 @@ describe('SeedLoadResultSchema', () => { it('should accept a result with deferred references', () => { const result = SeedLoadResultSchema.parse({ object: 'task', - mode: 'insert', + mode: 'ignore', inserted: 10, updated: 0, skipped: 0, @@ -341,7 +341,7 @@ describe('SeedLoadResultSchema', () => { it('should default errors to empty array', () => { const result = SeedLoadResultSchema.parse({ object: 'product', - mode: 'insert', + mode: 'ignore', inserted: 1, updated: 0, skipped: 0, diff --git a/packages/spec/src/data/seed-loader.zod.ts b/packages/spec/src/data/seed-loader.zod.ts index 0cd7da1ec4c..855aff99898 100644 --- a/packages/spec/src/data/seed-loader.zod.ts +++ b/packages/spec/src/data/seed-loader.zod.ts @@ -418,8 +418,8 @@ export const SeedLoadResultSchema = lazySchema(() => z.object({ * and left as it was. Each id appears once, in record order. Empty on a * dry run, which writes nothing and matches nothing. * - * [#30348] Exactly what the loader fills, per mode: `insert` / `replace` — - * each row an insert created; `ignore` (the default since #30081) — each row + * [#30348] Exactly what the loader fills, per mode: `ignore` (the default + * since #30081; the unkeyed `insert` / `replace` modes are retired, #34613) — each row * an insert created AND each existing row a record's key matched, which the * mode then leaves as it was; `upsert` — created, updated, and matched-but- * unchanged rows; `update` — updated and matched-but-unchanged rows (an diff --git a/packages/spec/src/data/seed.test.ts b/packages/spec/src/data/seed.test.ts index 4760d92f3c5..42a5dfdbf8d 100644 --- a/packages/spec/src/data/seed.test.ts +++ b/packages/spec/src/data/seed.test.ts @@ -5,13 +5,26 @@ import { FieldMappingEntrySchema } from '../api/export.zod'; describe('SeedMode', () => { it('should accept valid dataset modes', () => { - const validModes = ['insert', 'update', 'upsert', 'replace', 'ignore']; + const validModes = ['update', 'upsert', 'ignore']; validModes.forEach(mode => { expect(() => SeedMode.parse(mode)).not.toThrow(); }); }); + // [#34613] The two unkeyed modes are retired (ADR-0049 enforce-or-remove): + // each refusal names the mode, the version and the keyed fix. + it.each([ + ['insert', /`seed\.mode: 'insert'` was removed in @objectstack\/spec 18\.7\.0.*every replay.*inserted each record again.*`mode: 'ignore'`.*`externalId`/s], + ['replace', /`seed\.mode: 'replace'` was removed in @objectstack\/spec 18\.7\.0.*no load ever clears one.*`mode: 'ignore'`.*`externalId`/s], + ])('refuses the retired mode %s with its prescription', (mode, prescription) => { + expect(() => SeedMode.parse(mode)).toThrow(prescription); + const parsed = SeedSchema.safeParse({ object: 'task', mode, records: [{ name: 'a' }] }); + expect(parsed.success).toBe(false); + expect(parsed.error?.issues[0]?.path).toEqual(['mode']); + expect(parsed.error?.issues[0]?.message).toMatch(prescription); + }); + it('should reject invalid modes', () => { expect(() => SeedMode.parse('merge')).toThrow(); expect(() => SeedMode.parse('delete')).toThrow(); @@ -61,7 +74,7 @@ describe('SeedSchema', () => { }); it('keeps every authored mode as written — only an omitted mode takes the default', () => { - for (const mode of ['insert', 'update', 'upsert', 'replace', 'ignore'] as const) { + for (const mode of ['update', 'upsert', 'ignore'] as const) { expect(SeedSchema.parse({ object: 'product', mode, records: [] }).mode).toBe(mode); } }); @@ -84,7 +97,7 @@ describe('SeedSchema', () => { }); it('should accept different modes', () => { - const modes: Array = ['insert', 'update', 'upsert', 'replace', 'ignore']; + const modes: Array = ['update', 'upsert', 'ignore']; modes.forEach(mode => { const dataset = SeedSchema.parse({ @@ -208,7 +221,7 @@ describe('SeedSchema', () => { const demoData = SeedSchema.parse({ object: 'project', externalId: 'name', - mode: 'replace', + mode: 'ignore', env: ['dev'], records: [ { name: 'Demo Project 1', status: 'active' }, @@ -217,7 +230,7 @@ describe('SeedSchema', () => { }); expect(demoData.env).toEqual(['dev']); - expect(demoData.mode).toBe('replace'); + expect(demoData.mode).toBe('ignore'); }); it('should handle test data use case', () => { diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index acfd2e15f12..c3a5e157711 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -7,6 +7,7 @@ import { z } from 'zod'; * Defines how the engine handles existing records when a seed is applied. */ import { lazySchema } from '../shared/lazy-schema'; +import { enumWithRetiredValues } from '../shared/retired-key'; import { strictObject } from '../shared/strict-object'; import { MetadataProtectionFields } from '../kernel/metadata-protection.zod'; import { LocaleSchema } from '../system/translation.zod'; @@ -20,13 +21,58 @@ import { SeedFileReferenceSchema, isSeedFileReference, } from './seed-file.zod'; -export const SeedMode = z.enum([ - 'insert', // Insert every record, no match: each replay inserts them again (a row the database refuses is that row's error) +/** + * The fix both retired modes share: a seed row's identity is declared, never + * guessed by the loader (#34613, ruling 6942780880). + */ +const SEED_MODE_RETIRED_FIX = + 'Declare the rows\' identity instead: keep the default `mode: \'ignore\'` (or `\'upsert\'`) and set ' + + '`externalId` to the field that names a row, to a list of fields when no single field does (a junction ' + + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the ' + + 'records carry their own ids.'; + +/** + * The parse refusals an author meets for the two unkeyed modes (ADR-0049 + * enforce-or-remove; `enumWithRetiredValues`, `../shared/retired-key.ts`). + * A seed is replayed — every single-tenant boot, every package install or + * upgrade, every publish — and neither mode matched a row, so each replay + * inserted every record again: the table grew by the dataset on every restart, + * and a person reference the first load had to leave NULL stayed NULL on the + * first row while a later copy got it (#34613, measured 1 → 2 → 3 rows over + * three boots). `replace` promised a table "the caller cleared" and no load + * path ever cleared one. No D2 conversion: which field names a row is the + * author's to say. The D3 semantic entry `seed-mode-insert-replace-retired` + * carries that judgement. + */ +const SEED_MODE_INSERT_RETIRED = + "`seed.mode: 'insert'` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — a seed is " + + 'replayed on every boot, package install and publish, and `insert` matched no existing row, so every replay ' + + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; +const SEED_MODE_REPLACE_RETIRED = + "`seed.mode: 'replace'` was removed in @objectstack/spec 18.7.0 (ADR-0049 enforce-or-remove) — it inserted " + + 'every record and left clearing the table to the caller, and no load ever clears one, so every replay ' + + 'inserted each record again. ' + SEED_MODE_RETIRED_FIX; + +/** The live seed modes, in the order the reference documents them. */ +const SEED_MODE_VALUES = [ 'update', // Only update found records, ignore new 'upsert', // Create new or update existing: every replay writes the declared columns back - 'replace', // Insert every record, no match, deleting nothing: for a cache table the caller cleared - 'ignore' // Create-only (the default): insert missing rows, leave existing rows alone -]); + 'ignore', // Create-only (the default): insert missing rows, leave existing rows alone +] as const; + +const SEED_MODE_RETIRED = { insert: SEED_MODE_INSERT_RETIRED, replace: SEED_MODE_REPLACE_RETIRED }; + +/** + * [#34613] The retired `SeedMode` values, for the doors that hold a STORED + * seed (a compiled artifact, an installed package body, a stored seed item): + * such a door hands a dataset declaring one to the seed load, which refuses + * that dataset alone with `SeedMode`'s own prescription, instead of failing + * every other dataset and definition with it. Membership only: the + * prescription is always read from `SeedMode`, never restated. + */ +export const RETIRED_SEED_MODE_VALUES: readonly string[] = Object.freeze(Object.keys(SEED_MODE_RETIRED)); + +export const SeedMode = enumWithRetiredValues(SEED_MODE_VALUES, SEED_MODE_RETIRED); /** * Seed Column — the write policy a seed dataset declares for one of its @@ -46,8 +92,8 @@ export const SeedColumnSchema = lazySchema(() => strictObject({ * replay's no-op check, not written, and — a reference column — not * resolved and not deferred to pass 2, so nothing the load does afterwards * writes it back. A row the load creates gets it like any other column. - * `insert`, `ignore` and `replace` never update a matched row, so the policy - * changes nothing on those modes. + * `ignore` never updates a matched row, so the policy changes nothing on + * that mode. * * A column of the dataset's `externalId` is the key the row was matched by: * it stays in the matched row's update whatever it declares, as an import's @@ -154,8 +200,9 @@ export const SeedSchema = lazySchema(() => strictObject({ * — a list of field names — is required for objects with no single-field * natural key, most commonly a **join / junction table** keyed by both of its * foreign keys (e.g. `externalId: ['team', 'project']`). Without it such a - * dataset can only run `mode: 'insert'`, which re-inserts every row on each - * replay boot and duplicates the table (framework#3434). The reference fields + * dataset has no key to match a replay on (the unkeyed `insert` mode, which + * re-inserted every row on each replay boot and duplicated the table — + * framework#3434 — is retired, #34613). The reference fields * are matched by their RESOLVED ids, so a composite of foreign keys dedupes * correctly across restarts. */ @@ -214,9 +261,8 @@ export const SeedSchema = lazySchema(() => strictObject({ '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 ' + + 'declare it for reference data the package keeps current. `update` writes matched rows only. Every mode ' + + 'matches on `externalId`, so a replay finds the row an earlier load wrote instead of inserting it again. 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 ' + diff --git a/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts new file mode 100644 index 00000000000..cb0852a104b --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.seed-mode-insert-replace-retired.ts @@ -0,0 +1,37 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The upgrade-guide entry of the two unkeyed seed modes, `insert` and +// `replace`, retired from `SeedSchema.mode` (ADR-0049 enforce-or-remove; +// maintainer ruling on #34613, option B). No D2 conversion: which field names +// a seed row is the author's to declare, and a rewrite to a keyed mode would +// guess it. +export const entry: SemanticMigration = { + id: 'seed-mode-insert-replace-retired', + surface: + 'data.Seed.mode (a seed dataset in `defineStack({ data })`, `defineSeed`, a `seed` metadata item, or a package ' + + 'body\'s seed): the values `insert` and `replace`', + replacement: + 'Keep the default `mode: \'ignore\'` (or declare `\'upsert\'` for reference data the package keeps current) and ' + + 'set `externalId` to the field that names a row, to a list of fields when no single field does (a junction ' + + 'table\'s `[\'team\', \'project\']`), or to `\'id\'` when the records carry their own ids', + reason: + 'A seed is replayed, not applied once: on every single-tenant boot, every package install or upgrade, every ' + + 'publish. `insert` matched no existing row, so every replay inserted each record again, and `replace` did the ' + + 'same while promising a table the caller cleared, which no load path ever clears. Measured on an un-walled ' + + 'install over three boots: 1, then 2, then 3 rows; a person reference the first load had to leave NULL stayed ' + + 'NULL on the first row while only the newest copy named the person; with a unique field the replay insert was ' + + 'refused and the one row stayed NULL. Both values are now refused where a seed is parsed, with the ' + + 'prescription. A dataset already stored with either value (a compiled artifact, an installed package body, a ' + + 'stored seed item) is refused loudly by the seed load itself (the boot seed, the per-organization replay, the ' + + 'dev hot reload, a package install or upgrade; the artifact door parses the rest of an artifact without it, so ' + + 'the environment still boots): that dataset writes nothing, the load result fails with its prescription and ' + + 'the boot log names it, and every other dataset loads. There is no ' + + 'mechanical rewrite, because a keyed mode needs the field that identifies a row, and only the author knows it. ' + + 'Rows earlier replays duplicated are data, not metadata, and are left as they are', + acceptanceCriteria: + 'os validate reports no seed dataset whose `mode` is `insert` or `replace`; every dataset that declared one ' + + 'declares `ignore` or `upsert` with an `externalId` naming fields its object has; after two restarts over the ' + + 'same database the seeded object holds one row per record, and the boot log carries no seed-mode refusal.', +}; diff --git a/packages/verify/src/harness.seed-temporal-form.test.ts b/packages/verify/src/harness.seed-temporal-form.test.ts index 7461ae63ab4..2ee48e74e02 100644 --- a/packages/verify/src/harness.seed-temporal-form.test.ts +++ b/packages/verify/src/harness.seed-temporal-form.test.ts @@ -24,6 +24,9 @@ */ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +// Paid at collection, not inside a case's clock (check:test-source-alias). +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; import { cel, defineStack } from '@objectstack/spec'; import { Field, ObjectSchema } from '@objectstack/spec/data'; import { bootStack, type VerifyStack } from './harness.js'; @@ -89,9 +92,9 @@ const app = defineStack({ }, ], data: [ - { object: 'stf_handler', mode: 'insert', records: rows('handler') }, - { object: 'stf_body', mode: 'insert', records: rows('body') }, - { object: 'stf_guarded', mode: 'insert', records: rows('guarded') }, + { object: 'stf_handler', mode: 'ignore', records: rows('handler') }, + { object: 'stf_body', mode: 'ignore', records: rows('body') }, + { object: 'stf_guarded', mode: 'ignore', records: rows('guarded') }, ], } as never); diff --git a/scripts/check-skill-identifier-liveness.mjs b/scripts/check-skill-identifier-liveness.mjs index 746cd36ad3b..ad5315e1204 100644 --- a/scripts/check-skill-identifier-liveness.mjs +++ b/scripts/check-skill-identifier-liveness.mjs @@ -367,7 +367,9 @@ const BINDINGS = [ id: 'seed-modes', file: 'skills/objectstack-platform/SKILL.md', heading: '## Seed Data', - symbol: 'SeedMode', + // [#34613] `SeedMode` is an `enumWithRetiredValues` call this gate does not + // read whole; its live members are the `SEED_MODE_VALUES` array it wraps. + symbol: 'SEED_MODE_VALUES', source: 'packages/spec/src/data/seed.zod.ts', why: 'The mode table is the only place an author learns what `mode` accepts.', }, diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index fefab8f2dac..14a85f7d948 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -2661,6 +2661,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-retired-mode-34613.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/seed-loader-retry.test.ts", "verb": "delete",