Skip to content

Commit 9b9faf4

Browse files
committed
feat(metadata-protocol,runtime,platform-objects): record which seed rows landed per organization and do not insert a removed one again (wip)
Claude-Session: https://claude.ai/code/session_017xRBcTJTE7kSbcMoJQ4Txf Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3f61e4f commit 9b9faf4

6 files changed

Lines changed: 556 additions & 12 deletions

File tree

‎packages/metadata-protocol/src/seed-loader.ts‎

Lines changed: 403 additions & 2 deletions
Large diffs are not rendered by default.

‎packages/platform-objects/src/plugin.test.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest';
1111
import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core';
1212
import { ObjectSchema, RECYCLE_BIN_ENTRY_FIELDS, RECYCLE_BIN_OBJECT } from '@objectstack/spec/data';
1313
import { PlatformObjectsPlugin } from './plugin.js';
14-
import { SysExchangeRate, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysTrustedKey } from './system/index.js';
14+
import { SysExchangeRate, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey } from './system/index.js';
1515

1616
/**
1717
* Hand-rolled fake PluginContext (mirrors the service-plugin tests) — this
@@ -47,7 +47,7 @@ function makeCtx() {
4747
}
4848

4949
describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4243, #4270)', () => {
50-
it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState and SysRecycleBin through the manifest service', async () => {
50+
it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => {
5151
const ctx = makeCtx();
5252
const manifests: any[] = [];
5353
ctx.registerService('manifest', { register: (m: any) => manifests.push(m) });
@@ -57,7 +57,7 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4
5757
const infra = manifests.find((m) => m.id === 'com.objectstack.platform-objects');
5858
expect(infra).toBeDefined();
5959
expect(infra.scope).toBe('system');
60-
expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin]);
60+
expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]);
6161
expect(infra.objects.map((o: any) => o.name)).toEqual([
6262
'sys_migration',
6363
// ADR-0119 D2 (#4617). Registered UNCONDITIONALLY, alongside the flag
@@ -81,8 +81,11 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4
8181
// delete for any business object, so it registers with the engine's
8282
// infrastructure rather than with any one capability plugin.
8383
'sys_recycle_bin',
84+
// [#31021] Which declared seed rows landed in each organization, read
85+
// and written only by the seed loader, beside the rows it describes.
86+
'sys_seed_landed_key',
8487
]);
85-
// ⛔ The seven above must NOT acquire the ledger's routing triple. They
88+
// ⛔ The eight above must NOT acquire the ledger's routing triple. They
8689
// ride the project database today; moving them is a different question.
8790
expect(infra.defaultDatasource).toBeUndefined();
8891
});

‎packages/platform-objects/src/plugin.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { SysExchangeRate } from './system/sys-exchange-rate.object.js';
1010
import { SysTrustedKey } from './system/sys-trusted-key.object.js';
1111
import { SysLifecycleState } from './system/sys-lifecycle-state.object.js';
1212
import { SysRecycleBin } from './system/sys-recycle-bin.object.js';
13+
import { SysSeedLandedKey } from './system/sys-seed-landed-key.object.js';
1314
import { attestFreshDatastore } from './system/migration-flag.js';
1415
import type {
1516
II18nService,
@@ -70,6 +71,11 @@ import { SEED_SETTLEMENT_SERVICE } from '@objectstack/spec/contracts';
7071
* engine, present in every composition, so it registers with the engine-
7172
* facing infrastructure, on the project database. A composition without it
7273
* keeps no snapshot, and the engine says so once per object.
74+
* - **`sys_seed_landed_key`** — which declared seed rows landed in each
75+
* organization (#31021), so a seed replay does not insert again a row a
76+
* person deleted. Its only reader and writer is the seed loader, on the
77+
* project database beside the rows it describes; a composition without it
78+
* keeps no record, and the loader says so once per load.
7379
* - **`sys_metadata_activation`** — the packaged-metadata activation
7480
* ledger (ADR-0126 §4). Same story a third time, and the ruling that
7581
* moved it here is recorded verbatim on #12359 (maintainer, 2026-08-26,
@@ -216,7 +222,7 @@ export class PlatformObjectsPlugin {
216222
version: this.version,
217223
type: 'plugin',
218224
scope: 'system',
219-
objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin],
225+
objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey],
220226
});
221227
ctx?.getService?.('manifest')?.register?.({
222228
...ACTIVATION_LEDGER_MANIFEST,

‎packages/platform-objects/src/system/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ export { SysMigrationJournal } from './sys-migration-journal.object.js';
2727
export { SysLifecycleState } from './sys-lifecycle-state.object.js';
2828
// [ADR-0148, #30237] The recycle bin: one entry per delete operation.
2929
export { SysRecycleBin } from './sys-recycle-bin.object.js';
30+
// [#31021] Which declared seed rows landed in an organization.
31+
export { SysSeedLandedKey } from './sys-seed-landed-key.object.js';
3032
// Multi-currency M1-1 (epic #8345): the dated rate table the write-time
3133
// home-currency projection reads.
3234
export {
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { ObjectSchema, Field } from '@objectstack/spec/data';
4+
5+
/**
6+
* sys_seed_landed_key — which declared seed rows have landed in an
7+
* organization, one row per seed key (#31021).
8+
*
9+
* A seed is replayed long after its first load: on every single-tenant boot,
10+
* and per organization whenever a host replays the seed union (a package
11+
* upgrade that changes it). The create-only rule (`SeedSchema.mode`'s
12+
* `ignore` default) inserts every declared row it does not find, so a row a
13+
* person deleted came back at the next replay under a new id. This table is
14+
* what tells "never landed here" from "landed here and since removed": the
15+
* seed loader records the key of every keyed row it lands — inserted, updated
16+
* or matched — under the organization it seeds, and does not insert a
17+
* recorded key again once its row is gone. A key never recorded still lands,
18+
* so a row an upgrade adds to the seed is inserted as before.
19+
*
20+
* Row identity: (organization_id, object_name, seed_key). `seed_key` is the
21+
* dataset's natural key — its `externalId` field names, each with the value
22+
* the loader matched the row by — JSON-encoded (`[["name","Acme"]]`), so a
23+
* composite key needs no separator byte and two datasets keyed on different
24+
* fields of one object never share a key. An `id` key is recorded under the
25+
* id the seed AUTHORED, not the per-organization id a replay may give the row
26+
* (#21665), so it reads the same in every organization.
27+
*
28+
* Writer and reader: `SeedLoaderService` (`@objectstack/metadata-protocol`)
29+
* alone, under the seed write context, on the loads that ask for this record
30+
* (`landedKeys`): the boot seed, the per-organization replay and the dev
31+
* hot-reload seeder of `@objectstack/runtime`'s AppPlugin. Internal state,
32+
* not a setting: ⛔ no data API, no settings key, no environment variable.
33+
*
34+
* Clearing it is never needed for a re-seed: the deliberate re-seed (the
35+
* `seed-replayer` service called with `{ reseed: true }`) inserts every
36+
* missing row whatever this table says and records them again, and a new
37+
* database starts with no rows. Deleting an organization deletes its rows.
38+
*
39+
* Lifecycle: **no `lifecycle` block on purpose** — durable. Reaping a row
40+
* would bring the seed row a person deleted back at the next replay.
41+
*
42+
* Registered by `PlatformObjectsPlugin` (`../plugin.ts`).
43+
*
44+
* @namespace sys
45+
*/
46+
export const SysSeedLandedKey = ObjectSchema.create({
47+
name: 'sys_seed_landed_key',
48+
label: 'Seed Landed Key',
49+
pluralLabel: 'Seed Landed Keys',
50+
icon: 'history',
51+
isSystem: true,
52+
managedBy: 'engine-owned',
53+
// Organization-owned: a key landed in one organization says nothing about
54+
// another. Who may read is object permission: the platform-only capability.
55+
requiredPermissions: ['manage_platform_settings'],
56+
description:
57+
'Which declared seed rows have landed in this organization, one row per seed key: a seed replay does not insert a recorded key again once its row is gone.',
58+
nameField: 'seed_key', // [ADR-0079] canonical primary-title pointer
59+
highlightFields: ['object_name', 'seed_key', 'created_at'],
60+
61+
fields: {
62+
id: Field.text({
63+
label: 'ID',
64+
readonly: true,
65+
}),
66+
67+
object_name: Field.text({
68+
label: 'Object',
69+
required: true,
70+
readonly: true,
71+
maxLength: 255,
72+
description: 'The seeded object the key belongs to.',
73+
}),
74+
75+
seed_key: Field.textarea({
76+
label: 'Seed Key',
77+
required: true,
78+
readonly: true,
79+
description:
80+
'The seed row\'s natural key: its dataset\'s externalId field names with the values the row was matched by, JSON-encoded (`[["name","Acme"]]`).',
81+
}),
82+
83+
organization_id: Field.lookup('sys_organization', {
84+
label: 'Organization',
85+
required: false,
86+
readonly: true,
87+
// The organization's delete takes its record with it.
88+
deleteBehavior: 'cascade',
89+
description: 'The organization the seed row landed in. Deleting the organization deletes its rows.',
90+
}),
91+
92+
created_at: Field.datetime({
93+
label: 'Landed At',
94+
readonly: true,
95+
description: 'When the seed loader first recorded the key in this organization.',
96+
}),
97+
},
98+
99+
indexes: [
100+
// The loader's one access path: the keys of one object in one organization.
101+
{ fields: ['organization_id', 'object_name'], unique: false },
102+
],
103+
104+
enable: {
105+
trackHistory: false,
106+
searchable: false,
107+
// Internal state — no data API at all. The seed loader reads and writes
108+
// it in process, under the seed write context.
109+
apiEnabled: false,
110+
apiMethods: [],
111+
},
112+
});

‎packages/runtime/src/app-plugin.ts‎

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,18 @@ const WITHHELD_FIELD_READERS_REPORTED = new WeakSet<object>();
7373
* through, resolved when a dataset loads. A kernel without
7474
* `@objectstack/service-storage` answers none, and the loader refuses a row
7575
* naming a seed file, by name, rather than write an object into a file field.
76+
*
77+
* [#31021] …and how the load treats the record of which seed rows landed in
78+
* the organization it seeds (`sys_seed_landed_key`). Every load this plugin
79+
* runs — the boot seed, the per-organization replay, the dev hot-reload
80+
* seeder — honours it, so a seed row a person deleted is not inserted again
81+
* by the next boot or replay; the replay's deliberate re-seed
82+
* (`{ reseed: true }`) inserts every missing row and records them again.
7683
*/
77-
function seedLoaderOptionsFor(ctx: PluginContext): { getFieldFiles: () => IFieldFileService | undefined } {
84+
function seedLoaderOptionsFor(
85+
ctx: PluginContext,
86+
landedKeys: 'honour' | 'reseed',
87+
): { getFieldFiles: () => IFieldFileService | undefined; landedKeys: 'honour' | 'reseed' } {
7888
return {
7989
getFieldFiles: () => {
8090
try {
@@ -83,6 +93,7 @@ function seedLoaderOptionsFor(ctx: PluginContext): { getFieldFiles: () => IField
8393
return undefined;
8494
}
8595
},
96+
landedKeys,
8697
};
8798
}
8899

@@ -1942,7 +1953,14 @@ export class AppPlugin implements Plugin {
19421953
// when the org-scoping middleware knows one (the insert's
19431954
// attributed user). The callable stays `(organizationId)` for
19441955
// every caller that has none.
1945-
const replayer = async (organizationId: string, options?: { userId?: string }) => {
1956+
//
1957+
// [#31021] `options.reseed` is the DELIBERATE re-seed — a
1958+
// host's "restore sample data" or reset action: every missing
1959+
// seed row is inserted, including the ones a person removed,
1960+
// and recorded as landed again. Without it the replay honours
1961+
// the organization's record of landed seed rows
1962+
// (`sys_seed_landed_key`) and does not insert those again.
1963+
const replayer = async (organizationId: string, options?: { userId?: string; reseed?: boolean }) => {
19461964
if (!organizationId) return { inserted: 0, updated: 0, skipped: 0, errors: [] as any[] };
19471965
const md = ctx.getService('metadata') as IMetadataService | undefined;
19481966
if (!md) {
@@ -1974,7 +1992,9 @@ export class AppPlugin implements Plugin {
19741992
appDefaultLocale: appSeedLocale,
19751993
});
19761994
loggerRef.info(`[seed-replayer] organization ${organizationId} seeds for locale ${describeSeedLocale(seedLocale)}`);
1977-
const seedLoader = new SeedLoaderService(ql, md, loggerRef, seedLoaderOptionsFor(ctx));
1995+
const seedLoader = new SeedLoaderService(
1996+
ql, md, loggerRef, seedLoaderOptionsFor(ctx, options?.reseed === true ? 'reseed' : 'honour'),
1997+
);
19781998
const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');
19791999
const request = SeedLoaderRequestSchema.parse({
19802000
seeds: datasetsNow,
@@ -2075,7 +2095,7 @@ export class AppPlugin implements Plugin {
20752095
try {
20762096
const metadata = ctx.getService('metadata') as IMetadataService | undefined;
20772097
if (metadata) {
2078-
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx));
2098+
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx, 'honour'));
20792099
const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');
20802100
// [#16595] `Seed.locale`'s producer on the DEFAULT boot
20812101
// path — see {@link resolveSeedLocale}.
@@ -2503,7 +2523,7 @@ export class AppPlugin implements Plugin {
25032523
ctx.logger.warn('[Seeder] hot-reload seed skipped — metadata service unavailable');
25042524
return;
25052525
}
2506-
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx));
2526+
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger, seedLoaderOptionsFor(ctx, 'honour'));
25072527
const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');
25082528
// [#16595] `Seed.locale`'s producer on the dev hot-reload
25092529
// path. Resolved from the BOOT bundle, not from `payload`: a

0 commit comments

Comments
 (0)