diff --git a/.changeset/install-local-honours-landed-keys.md b/.changeset/install-local-honours-landed-keys.md new file mode 100644 index 00000000000..c5b1369f4d2 --- /dev/null +++ b/.changeset/install-local-honours-landed-keys.md @@ -0,0 +1,27 @@ +--- +'@objectstack/cloud-connection': patch +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +'@objectstack/metadata-protocol': patch +--- + +fix(cloud-connection): a sample row a tenant deleted stays deleted when install-local reinstalls, upgrades, heals or replays the package + +Clause-②: no (the door starts honouring the loader's existing `landedKeys` guard, #31021; no accepted shape or public export widens; the dev confirms) +Metadata-protocol: none + +install-local's seed loads now keep, and honour, the per-organization record of which seed rows landed (`sys_seed_landed_key`, registered by `@objectstack/platform-objects`). Before, the door built its seed loader without the `landedKeys` option, so it neither read nor wrote that record: a seed row a person deleted (a demo account, a demo order) was inserted again by the next reinstall, upgrade, restart heal or per-organization replay. + +- The install and the upgrade (in the installing person's organization under an organization wall, otherwise in the install's sole organization), the restart heal of an empty database, the per-organization replay of a new organization and an unmanaged copy's first load honour the record: a seed row whose key landed in that organization before and whose row is now gone is not inserted again. A key that never landed still lands, so a row an upgrade adds to the seed is inserted, and a new database, which holds no record, is healed whole. A row the record keeps out is counted in `skipped`. +- The sample-data reseed (`POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data`, for a ledgered package and for an unmanaged copy alike) is the deliberate re-seed: it inserts every missing row whatever the record says, and records it again. Its answer is unchanged. +- The `seed-replayer` service this door registers when no app has registered one now takes `{ reseed: true }`, as the AppPlugin replayer does: that call inserts every missing row; any other call honours the record. + +Every row a load lands is recorded, whether it inserted, updated or matched the row. An existing install keeps no record until its next install, upgrade, reseed, replay or restart heal, so a row a person deletes before that load, after this release too, comes back once on it, and stays deleted from then on. + +A restart heal that withholds every row (a seed a person emptied, or a purge then a reinstall) reports a settled seed: the withheld rows are counted in `skipped` and logged at `info`, not recorded as an empty install, so the boot banner, `objectstack:seed-settled`, `GET /ready` and `os verify` read it as settled. The split reads the loader's `skipped`, which also counts an `update` seed row with no match, so a heal whose only skips are those also reports settled. A heal that lands nothing and skips nothing, or errors, is still the empty install. + +`@objectstack/spec`: the `mode` description of a seed dataset no longer says a package install keeps no record: a seed publish is the load that keeps none, and the sample-data reseed is named beside `seed-replayer(organizationId, { reseed: true })` as the deliberate re-seed. + +`@objectstack/platform-objects`: the `sys_seed_landed_key` object's description names install-local's loads among the record's writers and readers, and its sample-data reseed beside `seed-replayer` as the deliberate re-seed. + +`@objectstack/metadata-protocol`: the seed loader's `info` line for withheld rows names an installed package's sample-data reseed beside `seed-replayer` with `{ reseed: true }` as the way back. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index 7e084283195..ed2f7782631 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -163,19 +163,22 @@ organization. A row an upgrade adds to the seed has never landed, so it is still inserted. A reference to the deleted row from another seed row is left unwritten rather than reported as an error. -The record is kept and honoured only where AppPlugin runs the load for a known -organization: the single-tenant boot seed (`objectstack serve`, `os start`, on -every restart; a multi-tenant boot seeds through the per-organization replay -instead), the per-organization replay (`seed-replayer`), and the dev hot reload. -A seed publish, a package install or upgrade (`os package install`, the -marketplace install, its heal and its sample-data reseed) keep no record, so a -deleted row comes back on those. So do a load with no organization, a -composition that does not register `sys_seed_landed_key` -(`@objectstack/platform-objects`), and the marketplace's fallback -`seed-replayer`, which it registers when no app has seed data. - -A row deleted before your runtime had this rule comes back once, on the first -replay after the upgrade, and stays deleted from then on. +The record is kept and honoured where a load seeds a known organization: the +single-tenant boot seed (`objectstack serve`, `os start`, on every restart; a +multi-tenant boot seeds through the per-organization replay instead), the +per-organization replay (`seed-replayer`, the marketplace's fallback one +included, which it registers when no app has seed data), the dev hot reload, +and a package install or upgrade (`os package install`, the marketplace +install, into the installing person's organization) with its restart heal. A +seed publish keeps no record, so a deleted row comes back on that. So do a load +with no organization and a composition that does not register +`sys_seed_landed_key` (`@objectstack/platform-objects`). + +A row deleted before any load recorded it comes back once, on the first load +that keeps the record, and stays deleted from then on. For the boot seed that +is the first boot after the upgrade. An installed package records nothing +until its next install, upgrade, reseed, replay or restart heal, so a row +deleted before that load, even after the upgrade, comes back on it. To bring the deleted rows back on purpose, a host or plugin calls the `seed-replayer` kernel service with `{ reseed: true }`: @@ -185,6 +188,10 @@ const replay = ctx.getService('seed-replayer'); // ctx: the plugin's context await replay(organizationId, { reseed: true }); // inserts every missing seed row ``` +For an installed package, the sample-data reseed +(`POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data`) does +the same in the caller's organization. + --- ## Seeds and State Machines diff --git a/content/docs/references/api/package-api.mdx b/content/docs/references/api/package-api.mdx index bc04716fe5b..48ade0c36a5 100644 --- a/content/docs/references/api/package-api.mdx +++ b/content/docs/references/api/package-api.mdx @@ -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 AppPlugin runs for an organization (the boot seed, the seed-replayer replay, the dev hot reload), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish or package install keeps no such record, and seed-replayer called with `{ reseed: true }` inserts every missing row. | +| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | @@ -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 AppPlugin runs for an organization (the boot seed, the seed-replayer replay, the dev hot reload), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish or package install keeps no such record, and seed-replayer called with `{ reseed: true }` inserts every missing row. | +| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index 864c98dd13e..ac7c1bf2d34 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -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 AppPlugin runs for an organization (the boot seed, the seed-replayer replay, the dev hot reload), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish or package install keeps no such record, and seed-replayer called with `{ reseed: true }` inserts every missing row. | +| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | diff --git a/content/docs/references/data/seed.mdx b/content/docs/references/data/seed.mdx index 58c14a8869a..85b470d265c 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 AppPlugin runs for an organization (the boot seed, the seed-replayer replay, the dev hot reload), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish or package install keeps no such record, and seed-replayer called with `{ reseed: true }` inserts every missing row. | +| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | diff --git a/content/docs/references/kernel/manifest.mdx b/content/docs/references/kernel/manifest.mdx index dd385376dd2..0a6ae3cce51 100644 --- a/content/docs/references/kernel/manifest.mdx +++ b/content/docs/references/kernel/manifest.mdx @@ -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 AppPlugin runs for an organization (the boot seed, the seed-replayer replay, the dev hot reload), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish or package install keeps no such record, and seed-replayer called with `{ reseed: true }` inserts every missing row. | +| **mode** | `Enum<'insert' \| 'update' \| 'upsert' \| 'replace' \| 'ignore'>` | optional (default: `"ignore"`) | What a load does with a record whose `externalId` matches an existing row. `ignore` (default) is create-only: a missing row is inserted and an existing row is left as it is, so a replay (every boot, a package install or upgrade, a publish) never writes a seeded value back over a later edit. `upsert` also writes every declared column back onto the matched row on each replay; declare it for reference data the package keeps current. `update` writes matched rows only, `insert` inserts every record with no match, so each replay inserts them again, and `replace` does the same and deletes nothing: it is for a table the caller cleared. On the loads that seed an organization (the boot seed, a seed-replayer replay, the dev hot reload, a package install or upgrade), an `ignore` or `upsert` row that landed once and was later deleted is not inserted again; a publish, or a load that names no organization and finds no sole one, keeps no such record, and seed-replayer called with `{ reseed: true }` or the sample-data reseed inserts every missing row. | | **columns** | `Record }>` | optional | Per-column write policy, keyed by field name: `{ status: { applyOn: 'create' } }` writes `status` only when the seed creates the row. Omitted, every column is written on create and update. | | **env** | `Enum<'prod' \| 'dev' \| 'test'>[]` | optional (default: `["prod","dev","test"]`) | Applicable environments | | **locale** | `string[]` | optional | Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app's i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app's i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn | diff --git a/packages/cli/test/package-install-local-sample-owner.integration.test.ts b/packages/cli/test/package-install-local-sample-owner.integration.test.ts index f0bcc6136b1..2f9450ac1da 100644 --- a/packages/cli/test/package-install-local-sample-owner.integration.test.ts +++ b/packages/cli/test/package-install-local-sample-owner.integration.test.ts @@ -53,6 +53,7 @@ import { spawn, type ChildProcess } from 'node:child_process'; import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import Database from 'better-sqlite3'; import { CLI, childEnv, @@ -303,8 +304,15 @@ beforeAll(async () => { rec.reseededDeals = byName(owned(await http(a, 'GET', `/api/v1/data/${DEAL}`, admin.token))) .filter((r) => r.name !== REAL_DEAL); - // Empty both seeded tables by id — not a purge, which would tell the heal - // the emptiness is wanted — so the next boot heals them. + // Empty both seeded tables by id, then, with boot 1 stopped, clear the + // database's landed-key record too. Not a purge, and not a person's + // deletion alone: both are emptiness the heal now leaves alone (a purge by + // its ledger flag; a deletion since #34405, because the heal honours the + // record and does not insert again a recorded key whose row is gone). The + // heal is for a database that lost the seeded rows AND their record under + // a kept ledger, so that is the state boot 2 finds; the users stay, so the + // installer the ledger records still resolves. Ruling 6670861426 (#30324) + // is about who owns the healed rows; the assertions below read that. rec.emptied = []; for (const object of [NOTE, DEAL]) { for (const row of owned(await http(a, 'GET', `/api/v1/data/${object}`, admin.token))) { @@ -312,6 +320,18 @@ beforeAll(async () => { } } await stopGroup(a.child); + // No `-d` and no project config: `os start` stores at `/data/objectstack.db`. + const dbFile = join(home, 'data', 'objectstack.db'); + const store = new Database(dbFile, { fileMustExist: true }); + try { + const recorded = store + .prepare('SELECT COUNT(*) AS n FROM sys_seed_landed_key WHERE object_name IN (?, ?)') + .get(DEAL, NOTE) as { n: number }; + if (recorded.n === 0) throw new Error(`precondition: ${dbFile} records no landed key for ${DEAL} or ${NOTE}`); + store.prepare('DELETE FROM sys_seed_landed_key').run(); + } finally { + store.close(); + } // ── boot 2: the same home; the rehydrate finds every seeded table empty ─── const b = await bootStart(cwd, home); 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 4a8f9db00fb..7344130221e 100644 --- a/packages/cloud-connection/src/marketplace-install-local-heal.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-heal.test.ts @@ -239,6 +239,24 @@ describe('rehydrate sample-data healing', () => { ); }); + // [#34405] Withheld rows (`skipped`, no error) are a settled heal, pinned on + // the real loader in marketplace-install-local-landed-keys.test.ts. A load + // that landed nothing and withheld nothing, or that errored, is still the + // empty install the banner escalates. + it.each([ + { case: 'nothing landed, nothing withheld', skipped: 0, errors: [] }, + { case: 'rows skipped beside an error', skipped: 2, errors: [{ message: 'database is locked' }] }, + ])('a heal run that lands no rows reports an empty install: $case', async ({ skipped, errors }) => { + seedResult = { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: skipped }, errors }; + const { ctx } = await rehydrateWith({}, { crm_x: [], crm_y: [] }); + expect(loadCalls).toHaveLength(1); + expect((ctx.logger.warn as any).mock.calls.some((c: any[]) => String(c[0]).includes(`sample-data heal for ${MANIFEST.id}`))).toBe(true); + expect(recordSeedOutcome).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ source: MANIFEST.id, marketplace: true, inserted: 0, updated: 0, rejected: errors.length, emptyInstall: true }), + ); + }); + it('purge → restart keeps the package empty (end to end through the endpoints)', async () => { // Install over an empty DB, with rows landing. seedResult = { summary: { totalInserted: 3, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; 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 new file mode 100644 index 00000000000..dc83594492f --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts @@ -0,0 +1,435 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34405, #31021] install-local's seed loads keep, and honour, the record of + * which seed rows landed in the organization they seed (`sys_seed_landed_key`). + * + * The loader's guard (`SeedLoaderService` option `landedKeys`) records every + * keyed row an `ignore` or `upsert` dataset lands and, in `'honour'` mode, does + * not insert again a recorded row that is now gone: a person removed it. In + * `'reseed'` mode it records the same and inserts every missing row. This door + * built its loader without the option, so it neither read nor wrote the + * record: a sample row a tenant deleted came back on the next reinstall, + * upgrade, restart heal or per-organization replay. + * + * Real here: `SeedLoaderService` (`@objectstack/runtime`), over a faithful + * in-memory engine that registers `sys_seed_landed_key` the way + * `@objectstack/platform-objects` does. Each pin runs on a flat bundle (one + * top-level `data`) and on a composed one (`packages[]`, the seed datasets in + * each package body), which must behave the same. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +// The first load of the runtime's dist paid at module top, never inside a +// clocked `it` (`scripts/check-test-source-alias.mjs`): the plugin reaches the +// seed loader through a dynamic `import()`. +import '@objectstack/runtime'; +import { assertEngineDeleteDispatch } from '@objectstack/metadata-core'; +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { INSTALLER_ORGANIZATION, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; + +type Row = Record; +type Handler = (c: any) => Promise; + +const ROUTE = '/api/v1/marketplace/install-local'; +const LEDGER = 'sys_seed_landed_key'; +const ORG = INSTALLER_ORGANIZATION.id; + +/** + * `where` as the seed loader spells it here: field equality only. A combinator + * or a value operator is REFUSED rather than answered, so a shape this double + * does not implement can never read as a match or a miss. + */ +function rowMatches(row: Row, where: Record = {}): boolean { + return Object.entries(where).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`engine double: unsupported combinator ${k}`); + if (v !== null && typeof v === 'object') { + throw new Error(`engine double: unsupported value operator on ${k}: ${JSON.stringify(v)}`); + } + return (row[k] ?? null) === (v ?? null); + }); +} + +/** + * A faithful in-memory engine: `where` filters, ids minted on insert. `store` + * outlives a boot. Every dataset here is `ignore` (create-only), and a + * person's deletion is a direct edit of `store`, so no load here writes + * anything but an insert (the owner stamp asks `update` and skips an engine + * without one; the rows have no owner column anyway). `delete` is the purge's: + * by primary key, under the real dispatch contract. + */ +function createEngine(store: Record) { + let next = 0; + const engine: any = { + syncSchemas: async () => undefined, + async find(object: string, query?: any) { + let rows = (store[object] ?? []).filter((r) => rowMatches(r, query?.where)); + if (typeof query?.limit === 'number') rows = rows.slice(0, query.limit); + return rows.map((r) => ({ ...r })); + }, + async insert(object: string, data: any) { + const mint = (d: Row) => ({ id: d.id ?? `gen_${object}_${++next}`, ...d }); + const rows = Array.isArray(data) ? data.map(mint) : [mint(data)]; + (store[object] ??= []).push(...rows); + return Array.isArray(data) ? rows.map((r) => ({ ...r })) : { ...rows[0] }; + }, + async delete(object: string, options?: any) { + const dispatch = assertEngineDeleteDispatch(options); + if (dispatch.kind !== 'by-id') throw new Error('engine double: the purge deletes by primary key only'); + const table = store[object] ?? []; + const at = table.findIndex((r) => r.id === String(dispatch.id)); + if (at < 0) return false; + table.splice(at, 1); + return true; + }, + async count(object: string, query?: any) { + return (await engine.find(object, query)).length; + }, + async aggregate() { + return []; + }, + }; + return engine; +} + +const objectDef = (name: string) => ({ name, label: name, fields: { name: { type: 'text', label: 'Name' } } }); + +/** The objects the metadata service answers: the packages' own, the organization and the landed-key record. */ +const METADATA_OBJECTS: Record = { + lk_account: objectDef('lk_account'), + lk_order: objectDef('lk_order'), + sys_organization: { name: 'sys_organization', systemFields: { tenant: false }, fields: { name: { type: 'text' }, slug: { type: 'text' } } }, + [LEDGER]: { + name: LEDGER, + fields: { + object_name: { type: 'text' }, + seed_key: { type: 'textarea' }, + organization_id: { type: 'lookup', reference: 'sys_organization' }, + }, + }, +}; + +const ACCOUNTS = (withUpgradeRow: boolean) => ({ + object: 'lk_account', + externalId: 'name', + records: [{ name: 'Acme' }, { name: 'Globex' }, ...(withUpgradeRow ? [{ name: 'Initech' }] : [])], +}); +const ORDERS = { object: 'lk_order', externalId: 'name', records: [{ name: 'SO-1' }, { name: 'SO-2' }] }; + +/** A flat bundle: one top-level `data`. v2 adds a row to the seed. */ +const flat = (version: '1.0.0' | '2.0.0') => ({ + id: 'com.example.lkflat', + name: 'Landed keys flat', + version, + type: 'app', + objects: [objectDef('lk_account'), objectDef('lk_order')], + data: [ACCOUNTS(version === '2.0.0'), ORDERS], +}); + +/** A composed bundle: `packages[]`, the datasets in each package body, no top-level `data`. v2 adds a row to the seed. */ +const composed = (version: '1.0.0' | '2.0.0') => ({ + id: 'com.example.lksuite', + name: 'Landed keys suite', + version, + type: 'app', + packages: [ + { + manifest: { + id: 'com.example.lksuite.o2c', name: 'o2c', version, type: 'module', + dependencies: { 'com.example.lksuite.core': '*' }, + objects: [objectDef('lk_order')], + data: [ORDERS], + }, + }, + { + manifest: { + id: 'com.example.lksuite.core', name: 'core', version, type: 'module', + objects: [objectDef('lk_account')], + data: [ACCOUNTS(version === '2.0.0')], + }, + }, + ], +}); + +function makeC(reqBody: any, manifestId?: string) { + const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })); + return { + req: { + url: `http://localhost:3000${ROUTE}`, + raw: new Request(`http://localhost:3000${ROUTE}`), + json: async () => reqBody, + param: (k: string) => (k === 'manifestId' ? manifestId : undefined), + header: () => undefined, + query: () => undefined, + }, + json, + }; +} + +let dir: string; +let store: Record; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'mil-landed-keys-')); + // The `single` posture's Default Organization, the sole one: the loads seed it. + store = { sys_organization: [{ id: ORG, slug: 'default', name: 'Default' }] }; +}); +afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); }); + +/** + * One runtime over the ledger directory and `store`: a fresh plugin, booted + * through `kernel:ready` (so a second boot is a restart over the same + * database, its rehydrate and heal included). `posture: 'isolated'` puts the + * organization wall in force, the session's active organization the one the + * install seeds. + */ +async function boot(opts: { posture?: 'single' | 'isolated' } = {}) { + const routes = new Map(); + const rawApp = { + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; + const auth = installerAuthService(); + const services: Record = { + manifest: { register: vi.fn() }, + auth: { + api: { + getSession: async () => ({ + ...(await auth.api.getSession()), + session: opts.posture === 'isolated' ? { activeOrganizationId: ORG } : {}, + }), + }, + }, + objectql: withInstallerGrants(createEngine(store)), + metadata: { + getObject: async (name: string) => METADATA_OBJECTS[name], + listObjects: async () => Object.values(METADATA_OBJECTS), + get: async (_type: string, name: string) => METADATA_OBJECTS[name], + list: async () => [], + }, + ...(opts.posture ? { tenancy: { posture: opts.posture } } : {}), + }; + const hooks = new Map(); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const ctx = { + hook: (e: string, h: any) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + const svc = services[name]; + if (svc === undefined) throw new Error(`no ${name}`); + return svc; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + logger, + }; + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + await plugin.start(ctx as any); + await hooks.get('kernel:ready')?.(); + const install = async (manifest: unknown) => { + const res = await routes.get(`POST ${ROUTE}`)!(makeC({ manifest })); + expect(res.status, JSON.stringify(res.payload)).toBe(200); + return res; + }; + const reseed = (manifestId: string) => routes.get(`POST ${ROUTE}/:manifestId/reseed-sample-data`)!(makeC({}, manifestId)); + const purge = (manifestId: string) => routes.get(`POST ${ROUTE}/:manifestId/purge-sample-data`)!(makeC({}, manifestId)); + /** The per-organization replayer this door registered (no other plugin registers one here). */ + const replayer = () => services['seed-replayer'] as (orgId: string, options?: { userId?: string; reseed?: boolean }) => Promise; + return { plugin, ctx, install, reseed, purge, replayer, logger }; +} + +/** The seed rows of `object` in `org`, by name. */ +const names = (object: string, org: string = ORG) => + (store[object] ?? []).filter((r) => r.organization_id === org).map((r) => r.name).sort(); +/** The landed-key record of `org`, as `object:name` pairs. */ +const landed = (org: string = ORG) => + (store[LEDGER] ?? []) + .filter((r) => r.organization_id === org) + .map((r) => `${r.object_name}:${(JSON.parse(r.seed_key) as Array<[string, string]>).map(([, v]) => v).join('|')}`) + .sort(); +/** A person deletes the seed row `name` of `object` in `org`. */ +const removeRow = (object: string, name: string, org: string = ORG) => { + store[object] = (store[object] ?? []).filter((r) => !(r.name === name && r.organization_id === org)); +}; + +/** + * What a boot's restart heal recorded for `manifestId` on the kernel's + * `seed-summary`: the outcome the boot banner, `objectstack:seed-settled`, + * `GET /ready` and `os verify` judge, an `emptyInstall` or a `rejected` row + * reading as a failed seed in each. + */ +const healOutcome = (rt: { ctx: any }, manifestId: string) => + (rt.ctx.getService('seed-summary') as Array>).find((s) => s.source === manifestId && s.marketplace === true); +/** The heal's own log lines for `manifestId` at `level`. */ +const healLines = (rt: { logger: Record }, level: 'info' | 'warn', manifestId: string) => + (rt.logger[level].mock.calls as unknown[][]) + .map((c) => String(c[0])) + .filter((line) => line.includes('[MarketplaceInstallLocal]') && line.includes(manifestId) && /heal/.test(line)); +/** The outcome a heal that withheld every row records: the real `skipped`, nothing flagged. */ +const withheldOutcome = (manifestId: string) => + ({ source: manifestId, marketplace: true, inserted: 0, updated: 0, skipped: 4, rejected: 0, droppedRefs: 0 }); + +const BUNDLES = [ + { kind: 'flat', id: 'com.example.lkflat', body: flat }, + { kind: 'composed', id: 'com.example.lksuite', body: composed }, +] as const; + +describe.each(BUNDLES)('$kind bundle: install-local keeps and honours the record of landed seed rows', ({ id, body }) => { + it('install writes sys_seed_landed_key for every row it lands, in the organization it seeds', async () => { + const rt = await boot(); + const res = await rt.install(body('1.0.0')); + expect(res.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 4, errors: 0 }); + expect(names('lk_account')).toEqual(['Acme', 'Globex']); + expect(names('lk_order')).toEqual(['SO-1', 'SO-2']); + expect(landed()).toEqual(['lk_account:Acme', 'lk_account:Globex', 'lk_order:SO-1', 'lk_order:SO-2']); + }); + + it('a seed row deleted after the install stays deleted across a reinstall and an upgrade; the row the upgrade adds lands', async () => { + const rt = await boot(); + await rt.install(body('1.0.0')); + removeRow('lk_account', 'Globex'); + + const reinstall = await rt.install(body('1.0.0')); + expect(names('lk_account')).toEqual(['Acme']); + expect(reinstall.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 0, errors: 0 }); + + const upgrade = await rt.install(body('2.0.0')); + expect(upgrade.payload.data.upgradedFrom, JSON.stringify(upgrade.payload)).toBeDefined(); + expect(names('lk_account')).toEqual(['Acme', 'Initech']); + expect(names('lk_order')).toEqual(['SO-1', 'SO-2']); + expect(upgrade.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 1, errors: 0 }); + expect(landed()).toContain('lk_account:Initech'); + }); + + it('under the organization wall, the install and the upgrade keep it in the caller\'s active organization', async () => { + // A second organization, so no sole organization stands in for the caller's. + store.sys_organization.push({ id: 'org_other', slug: 'other', name: 'Other' }); + const rt = await boot({ posture: 'isolated' }); + await rt.install(body('1.0.0')); + expect(landed()).toEqual(['lk_account:Acme', 'lk_account:Globex', 'lk_order:SO-1', 'lk_order:SO-2']); + expect(landed('org_other')).toEqual([]); + removeRow('lk_order', 'SO-2'); + + await rt.install(body('2.0.0')); + expect(names('lk_order')).toEqual(['SO-1']); + expect(names('lk_account')).toEqual(['Acme', 'Globex', 'Initech']); + }); + + it('reseed is the deliberate re-seed: it inserts every missing row and records it again', async () => { + const rt = await boot(); + await rt.install(body('1.0.0')); + removeRow('lk_account', 'Globex'); + removeRow('lk_order', 'SO-1'); + + const res = await rt.reseed(id); + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(res.payload).toEqual({ + success: true, + data: { manifestId: id, inserted: 2, updated: 0, skipped: 2, errors: 0, withSampleData: true }, + }); + expect(names('lk_account')).toEqual(['Acme', 'Globex']); + expect(names('lk_order')).toEqual(['SO-1', 'SO-2']); + // Recorded once per key: the re-seed does not duplicate the record. + expect(landed()).toEqual(['lk_account:Acme', 'lk_account:Globex', 'lk_order:SO-1', 'lk_order:SO-2']); + + // …and the record still stands for the next removal. + removeRow('lk_account', 'Globex'); + await rt.install(body('1.0.0')); + expect(names('lk_account')).toEqual(['Acme']); + }); + + it('a restart does not heal back the seed rows a person deleted, and still heals a database that never held them', async () => { + const first = await boot(); + await first.install(body('1.0.0')); + for (const r of ['Acme', 'Globex']) removeRow('lk_account', r); + for (const r of ['SO-1', 'SO-2']) removeRow('lk_order', r); + + // Every seeded object empty, the purge never run: the heal's own trigger. + const restart = await boot(); + expect(names('lk_account')).toEqual([]); + expect(names('lk_order')).toEqual([]); + // The withheld rows are the declared outcome, so the restart reports a + // settled seed: the real `skipped`, no `emptyInstall`, said at `info`. + expect(healOutcome(restart, id)).toEqual(withheldOutcome(id)); + expect(healLines(restart, 'warn', id)).toEqual([]); + expect(healLines(restart, 'info', id)).toHaveLength(1); + + // Control: a new database (no row, no record) is healed from the ledger body. + for (const object of Object.keys(store)) if (object !== 'sys_organization') delete store[object]; + const fresh = await boot(); + expect(names('lk_account')).toEqual(['Acme', 'Globex']); + expect(names('lk_order')).toEqual(['SO-1', 'SO-2']); + expect(healOutcome(fresh, id)).toEqual(expect.objectContaining({ inserted: 4, rejected: 0, healed: true })); + expect(healOutcome(fresh, id)).not.toHaveProperty('emptyInstall'); + }); + + it('a purge stays purged across a reinstall and a restart', async () => { + const first = await boot(); + await first.install(body('1.0.0')); + const purged = await first.purge(id); + expect(purged.status, JSON.stringify(purged.payload)).toBe(200); + expect(purged.payload.data).toMatchObject({ deleted: 4, errors: 0 }); + + // The reinstall withholds every recorded row (counted in `skipped`). + const reinstall = await first.install(body('1.0.0')); + expect(reinstall.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 0, errors: 0 }); + expect(names('lk_account')).toEqual([]); + expect(names('lk_order')).toEqual([]); + + // Every seeded object empty again: the restart's heal runs, and leaves it, + // reporting a settled seed rather than an empty install. + const restart = await boot(); + expect(names('lk_account')).toEqual([]); + expect(names('lk_order')).toEqual([]); + expect(healOutcome(restart, id)).toEqual(withheldOutcome(id)); + expect(healLines(restart, 'warn', id)).toEqual([]); + }); + + it('the per-organization replayer honours it per organization, and `{ reseed: true }` brings a removed row back', async () => { + const rt = await boot(); + await rt.install(body('1.0.0')); + const replay = rt.replayer(); + expect(typeof replay).toBe('function'); + + await replay('org_a'); + await replay('org_b'); + removeRow('lk_account', 'Acme', 'org_a'); + + const again = await replay('org_a'); + await replay('org_b'); + expect(again).toMatchObject({ inserted: 0, errors: [] }); + expect(names('lk_account', 'org_a')).toEqual(['Globex']); + expect(names('lk_account', 'org_b')).toEqual(['Acme', 'Globex']); + expect(landed('org_a')).toEqual(['lk_account:Acme', 'lk_account:Globex', 'lk_order:SO-1', 'lk_order:SO-2']); + + const reseeded = await replay('org_a', { reseed: true }); + expect(reseeded).toMatchObject({ inserted: 1, errors: [] }); + expect(names('lk_account', 'org_a')).toEqual(['Acme', 'Globex']); + }); +}); + +describe('an unmanaged copy\'s sample data: the install honours the record, the reseed re-seeds', () => { + it('a row deleted after the copy\'s first load is not loaded again by another install load; the reseed brings it back', async () => { + const rt = await boot(); + const seed = (door: 'install' | 'reseed') => (rt.plugin as any).seedUnmanagedCopy(makeC({}), rt.ctx, { + app: flat('1.0.0'), + appId: 'com.example.lkflat', + targetPackageId: 'com.example.lkflat-copy', + datasets: [ACCOUNTS(false)], + userId: null, + door, + }); + + expect(await seed('install')).toMatchObject({ mode: 'inline', inserted: 2, errors: 0 }); + expect(landed()).toEqual(['lk_account:Acme', 'lk_account:Globex']); + removeRow('lk_account', 'Acme'); + + expect(await seed('install')).toMatchObject({ mode: 'inline', inserted: 0, errors: 0 }); + expect(names('lk_account')).toEqual(['Globex']); + + expect(await seed('reseed')).toMatchObject({ mode: 'inline', inserted: 1, errors: 0 }); + expect(names('lk_account')).toEqual(['Acme', 'Globex']); + }); +}); diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index 124c88a63a1..ad402ab7651 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -1977,6 +1977,18 @@ export class MarketplaceInstallLocalPlugin implements Plugin { * install-time rows (or the user's own data) are still present, and * re-upserting would silently revert user edits on every boot. * + * [#34405] The load honours the landed-key record (`sys_seed_landed_key`), + * as the runtime's boot seed does: a seed row whose key landed in this + * organization before and whose row is gone was removed by a person, and is + * withheld (counted in `skipped`), not inserted again. A database that lost + * its rows and the record with them is healed whole. A heal that landed + * no rows but skipped some, with no error, is reported at `info` and + * recorded with its real `skipped`, never as an `emptyInstall`. The split + * reads the loader's `skipped`, which also counts an `update` row with no + * match, so a heal whose only skips are those records settled too. Only a + * load that landed nothing otherwise (nothing skipped, or an error) is the + * empty install the boot banner escalates. + * * `converted` is the entry's manifest as rehydrate converted it — the one the * package registered — so the heal seeds what registered, not the raw * ledger bytes. @@ -2018,7 +2030,11 @@ export class MarketplaceInstallLocalPlugin implements Plugin { try { // [#30281] No user starts a boot heal: the setting, then this // package's declared default locale. - const summary = await this.runInlineSeed(ctx, datasets, undefined, { app: converted }, await this.resolveRecordedInstaller(ctx, entry)); + // [#34405] Honouring the landed-key record, as the runtime's boot + // seed does: a new database holds no record and is healed whole, + // while seed rows a person deleted from every seeded object stay + // deleted. + const summary = await this.runInlineSeed(ctx, datasets, 'honour', undefined, { app: converted }, await this.resolveRecordedInstaller(ctx, entry)); const landed = (summary.inserted ?? 0) + (summary.updated ?? 0); if (landed > 0) { entry.withSampleData = true; @@ -2038,6 +2054,22 @@ export class MarketplaceInstallLocalPlugin implements Plugin { droppedRefs: summary.droppedRefs ?? 0, healed: true, }); + } else if ((summary.skipped ?? 0) > 0 && (summary.errors ?? 0) === 0) { + // [#34405] Rows skipped and none landed, no error: a seed a + // person emptied is withheld by the landed-key record and stays + // empty on every restart. `skipped` also counts an `update` row + // with no match, so a heal whose only skips are those lands here + // too. A settled seed, not a failed one, so no `emptyInstall`. + ctx.logger?.info?.(`[MarketplaceInstallLocal] sample-data heal for ${entry.manifestId} landed no rows: ${summary.skipped} seed row(s) skipped, none in error (a row withheld by the landed-key record, or an update-mode row with no match); the package's sample-data reseed brings withheld rows back`); + await this.recordSeedSummary(ctx, { + source: entry.manifestId, + marketplace: true, + inserted: 0, + updated: 0, + skipped: summary.skipped, + rejected: 0, + droppedRefs: summary.droppedRefs ?? 0, + }); } else { ctx.logger?.warn?.(`[MarketplaceInstallLocal] sample-data heal for ${entry.manifestId} landed no rows${summary.errorSample ? ` — first error: ${summary.errorSample}` : ''}`); // Installed package, seed datasets declared, yet 0 rows landed — @@ -2258,7 +2290,10 @@ export class MarketplaceInstallLocalPlugin implements Plugin { const empty = () => ({ inserted: 0, updated: 0, skipped: 0, errors: [] as any[] }); // [#30281] `options.userId` is the organization's founder when the // org-scoping middleware knows one — the AppPlugin replayer's shape. - return async (organizationId: string, options?: { userId?: string }) => { + // [#34405] `options.reseed` is the deliberate re-seed the AppPlugin + // replayer takes too: every missing row, whatever the landed-key record + // says. Every other replay honours that record. + return async (organizationId: string, options?: { userId?: string; reseed?: boolean }) => { if (!organizationId) return empty(); const datasetsNow = this.readSharedSeedDatasets(ctx); if (!Array.isArray(datasetsNow) || datasetsNow.length === 0) return empty(); @@ -2284,7 +2319,7 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // [#30324] The founder owns the rows: the organization's first // admin, the one person this door is handed. With none, the rows // keep no owner, as before. - const s = await this.runInlineSeed(ctx, datasetsNow, organizationId, { userId: options?.userId }, { + const s = await this.runInlineSeed(ctx, datasetsNow, options?.reseed === true ? 'reseed' : 'honour', organizationId, { userId: options?.userId }, { userId: options?.userId ?? null, door: 'per-organization seed replay', none: `the replay of organization ${organizationId} names no founder`, @@ -3455,6 +3490,8 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // the database (e.g. a reinstall/upgrade over live sample data) — the // install carries sample data either way. Leaving the flag false here // is what made older ledgers claim "no sample data" over a seeded DB. + // [#34405] A row the landed-key record keeps out (a person deleted it) + // is in `skipped` too; the listing reads the rows, not this flag. const seededRows = (seededSummary.seeded.inserted ?? 0) + (seededSummary.seeded.updated ?? 0) + (seededSummary.seeded.skipped ?? 0); if (seededSummary.seeded.mode === 'inline' && seededRows > 0) { entry.withSampleData = true; @@ -5584,7 +5621,7 @@ export class MarketplaceInstallLocalPlugin implements Plugin { organizationId = resolved; } try { - const s = await this.runInlineSeed(ctx, datasets, organizationId, { + const s = await this.runInlineSeed(ctx, datasets, door === 'reseed' ? 'reseed' : 'honour', organizationId, { ...(userId ? { userId } : {}), app, }, { @@ -7355,7 +7392,9 @@ export class MarketplaceInstallLocalPlugin implements Plugin { if (!multiTenant || organizationId) { // [#30281] The installing (or reseeding) user and this // package's own declared default locale. - const s = await this.runInlineSeed(ctx, datasets, organizationId, { + // [#34405] The reseed re-seeds; the install and the + // upgrade honour the landed-key record. + const s = await this.runInlineSeed(ctx, datasets, opts.door === 'reseed' ? 'reseed' : 'honour', organizationId, { userId: opts.userId, app: manifest, }, { @@ -7468,10 +7507,22 @@ export class MarketplaceInstallLocalPlugin implements Plugin { * A, maintainer, 2026-11-05: the install paths * pick datasets by locale). Nothing answers ⇒ no locale, and every dataset * loads as before. A dataset without `locale` loads whatever it answers. + * + * [#34405, #31021] `landedKeys` is the loader's own option, passed by every + * caller, never defaulted: each load keeps the record of which seed rows + * landed in the organization it seeds (`sys_seed_landed_key`). `'honour'` + * — the install, the upgrade, the restart heal, the per-organization + * replay and an unmanaged copy's first load — does not insert again a + * recorded row that is now gone, because a person removed it; a key never + * recorded still lands, so a row an upgrade adds is inserted. `'reseed'` — + * the sample-data reseed and the replayer's `{ reseed: true }` — is the + * deliberate re-seed: it inserts every missing row and records it again. + * A row the record keeps out is counted in `skipped`. */ private runInlineSeed = async ( ctx: PluginContext, datasets: any[], + landedKeys: 'honour' | 'reseed', organizationId?: string, localeFrom: { userId?: string; app?: unknown } = {}, owner: SeedOwnerOfLoad = { userId: null, door: 'seed', none: 'no person named' }, @@ -7492,7 +7543,7 @@ export class MarketplaceInstallLocalPlugin implements Plugin { appDefaultLocale: appDefaultSeedLocale(localeFrom.app), }); ctx.logger?.info?.(`[MarketplaceInstallLocal] seed locale${organizationId ? ` for org ${organizationId}` : ''}: ${describeSeedLocale(seedLocale)}`); - const seedLoader = new (SeedLoaderService as any)(ql, metadata, ctx.logger); + const seedLoader = new (SeedLoaderService as any)(ql, metadata, ctx.logger, { landedKeys }); const request = (SeedLoaderRequestSchema as any).parse({ // ADR-0036 / seed rename: the field is `seeds` (was `datasets`). seeds: datasets, diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index eb0ca78055f..a22f0ed9966 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -4851,7 +4851,7 @@ export class SeedLoaderService implements ISeedLoaderService { (ledger.withdrawnReferences > 0 ? ` ${ledger.withdrawnReferences} reference(s) to such rows were left as they are rather than reported unresolved.` : '') + - ` A deliberate re-seed brings them back: the seed-replayer service called with { reseed: true }.`, + ` A deliberate re-seed brings them back: the seed-replayer service called with { reseed: true }, or an installed package's sample-data reseed.`, { organizationId: ledger.organizationId, rows, diff --git a/packages/platform-objects/src/system/sys-seed-landed-key.object.ts b/packages/platform-objects/src/system/sys-seed-landed-key.object.ts index 30dcd8ca448..901808849dc 100644 --- a/packages/platform-objects/src/system/sys-seed-landed-key.object.ts +++ b/packages/platform-objects/src/system/sys-seed-landed-key.object.ts @@ -28,11 +28,14 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * Writer and reader: `SeedLoaderService` (`@objectstack/metadata-protocol`) * alone, under the seed write context, on the loads that ask for this record * (`landedKeys`): the boot seed, the per-organization replay and the dev - * hot-reload seeder of `@objectstack/runtime`'s AppPlugin. Internal state, + * hot-reload seeder of `@objectstack/runtime`'s AppPlugin, and the install, + * upgrade, restart heal, reseed and per-organization replay of + * `@objectstack/cloud-connection`'s install-local door. Internal state, * not a setting: ⛔ no data API, no settings key, no environment variable. * * Clearing it is never needed for a re-seed: the deliberate re-seed (the - * `seed-replayer` service called with `{ reseed: true }`) inserts every + * `seed-replayer` service called with `{ reseed: true }`, or install-local's + * sample-data reseed) inserts every * missing row whatever this table says and records them again, and a new * database starts with no rows. Deleting an organization deletes its rows. * diff --git a/packages/qa/dogfood/test/install-local-no-active-organization.dogfood.test.ts b/packages/qa/dogfood/test/install-local-no-active-organization.dogfood.test.ts index 39c2aaa5c44..5856c4db711 100644 --- a/packages/qa/dogfood/test/install-local-no-active-organization.dogfood.test.ts +++ b/packages/qa/dogfood/test/install-local-no-active-organization.dogfood.test.ts @@ -29,8 +29,11 @@ // organization; the reseed and the purge answer `403 PERMISSION_DENIED` // naming it; no seed row lands in either organization (nothing guessed). // 3. The SAME session once it selects organization B: reseed, purge and a -// reinstall all act in B, as they always have. One fact differs between -// 2 and 3: the active organization. +// reinstall all act in B, never in A. The reinstall after the purge +// honours B's landed-key record (the purge deletes the rows, not the +// record) and withholds every purged row; the reseed is the way back, in +// B (#34405, ruling 6929076086). One fact differs between 2 and 3: the +// active organization. // // Boots a walled fixture stack of its own, so it stays out of `SHARED_SHOWCASE`. @@ -96,11 +99,12 @@ describe('dogfood: install-local under an organization wall, with a session that let memberships: number; type Answer = { status: number; body: any }; const orgless: Record<'install' | 'reseed' | 'purge', Answer> = {} as never; - const inOrgB: Record<'reseed' | 'purge' | 'reinstall', Answer> = {} as never; + const inOrgB: Record<'reseed' | 'purge' | 'reinstall' | 'reseedBack', Answer> = {} as never; let rowsAfterOrgless: number; let orgBAfterReseed: number; let orgBAfterPurge: number; let orgBAfterReinstall: number; + let orgBAfterReseedBack: number; let orgAAtEnd: number; async function activeOrganization(): Promise { @@ -147,6 +151,8 @@ describe('dogfood: install-local under an organization wall, with a session that orgBAfterPurge = await countRows(ql, ORG_B); inOrgB.reinstall = await json(await stack.apiAs(token, 'POST', BASE, installBody())); orgBAfterReinstall = await countRows(ql, ORG_B); + inOrgB.reseedBack = await json(await stack.apiAs(token, 'POST', `${BASE}/${CRM}/reseed-sample-data`, {})); + orgBAfterReseedBack = await countRows(ql, ORG_B); orgAAtEnd = await countRows(ql, ORG_A); }, 300_000); @@ -191,7 +197,7 @@ describe('dogfood: install-local under an organization wall, with a session that expect(rowsAfterOrgless).toBe(0); }); - it('CONTROL: the same session with organization B active — reseed, purge and reinstall act in B, as before', () => { + it('CONTROL: the same session with organization B active — reseed, purge and reinstall act in B; the reinstall withholds the purged rows and the reseed brings them back', () => { expect(sessionOrgAfter).toBe(ORG_B); expect(inOrgB.reseed.status, JSON.stringify(inOrgB.reseed.body)).toBe(200); expect(inOrgB.reseed.body?.data).toMatchObject({ inserted: SEED_TOTAL, errors: 0, withSampleData: true }); @@ -200,8 +206,13 @@ describe('dogfood: install-local under an organization wall, with a session that expect(inOrgB.purge.body?.data).toMatchObject({ deleted: SEED_TOTAL, skipped: 0, errors: 0, withSampleData: false }); expect(orgBAfterPurge).toBe(0); expect(inOrgB.reinstall.status, JSON.stringify(inOrgB.reinstall.body)).toBe(200); - expect(inOrgB.reinstall.body?.data?.seeded).toMatchObject({ mode: 'inline', inserted: SEED_TOTAL }); - expect(orgBAfterReinstall).toBe(SEED_TOTAL); + // #34405, ruling 6929076086: the reinstall honours B's landed-key record, which the purge leaves in place, + // so it withholds every purged row (`skipped`); the reseed is the way back. + expect(inOrgB.reinstall.body?.data?.seeded).toMatchObject({ mode: 'inline', inserted: 0, skipped: SEED_TOTAL, errors: 0 }); + expect(orgBAfterReinstall).toBe(0); + expect(inOrgB.reseedBack.status, JSON.stringify(inOrgB.reseedBack.body)).toBe(200); + expect(inOrgB.reseedBack.body?.data).toMatchObject({ inserted: SEED_TOTAL, errors: 0, withSampleData: true }); + expect(orgBAfterReseedBack).toBe(SEED_TOTAL); expect(orgAAtEnd).toBe(0); }); }); diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index 9eecbf3d9f2..acfd2e15f12 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -177,19 +177,23 @@ export const SeedSchema = lazySchema(() => strictObject({ * (ruling 6631016988 on objectstack#30081, which measured exactly that on a * production boot and on both upgrade paths while the default was `upsert`). * - * A row a person deleted is not brought back by every replay. The loads - * AppPlugin (`@objectstack/runtime`) runs for an organization — the - * single-tenant boot seed, the per-organization replay (the `seed-replayer` - * service) and the dev hot reload, where the composition registers - * `sys_seed_landed_key` (`@objectstack/platform-objects`) — record, per - * organization, the key of every keyed row an `ignore` or `upsert` dataset - * landed, and do not insert again a recorded row that is now gone. A key - * never recorded still lands, so a row an upgrade adds to the seed is - * inserted. A seed publish and a package - * install or upgrade (`os package install`, the marketplace install) keep no - * record, so the row comes back on those. The deliberate re-seed, - * `seed-replayer(organizationId, { reseed: true })`, inserts every missing - * row whatever the record says. + * A row a person deleted is not brought back by every replay. The loads that + * seed an organization — AppPlugin's (`@objectstack/runtime`) single-tenant + * boot seed and dev hot reload, the per-organization replay (the + * `seed-replayer` service, AppPlugin's or the marketplace's fallback one), + * and the package install or upgrade (`os package install`, the marketplace + * install) with its restart heal, into the installing person's organization + * or the sole organization — record, per organization, where the + * composition registers `sys_seed_landed_key` + * (`@objectstack/platform-objects`), the key of every keyed row an `ignore` + * or `upsert` dataset landed, and do not insert again a recorded row that is + * now gone. A key never recorded still lands, so a row an upgrade adds to + * the seed is inserted. A seed publish keeps no record, nor does a load with + * no `config.organizationId` and no sole organization, so the row comes back + * on those. The deliberate re-seed — + * `seed-replayer(organizationId, { reseed: true })`, or the installed + * package's sample-data reseed — inserts every missing row whatever the + * record says. * * An author who wants a replay to refresh the rows — reference data the * package keeps current — declares `mode: 'upsert'`, and can still exempt @@ -212,10 +216,11 @@ export const SeedSchema = lazySchema(() => strictObject({ '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 AppPlugin runs for an ' + - 'organization (the boot seed, the seed-replayer replay, the dev hot reload), an `ignore` or `upsert` row ' + - 'that landed once and was later deleted is not inserted again; a publish or package install keeps no such ' + - 'record, and seed-replayer called with { reseed: true } inserts every missing row.', + '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.', ), /** diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 45d1cf202bd..3ac757e4a12 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -51,6 +51,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/cloud-connection/src/marketplace-install-local-landed-keys.test.ts", + "verb": "delete", + "pinned": 1 + }, { "file": "packages/cloud-connection/src/marketplace-install-local-sample-data-not-loaded.test.ts", "verb": "delete",