diff --git a/.changeset/33812-seed-depends-on.md b/.changeset/33812-seed-depends-on.md new file mode 100644 index 00000000000..0248b84c970 --- /dev/null +++ b/.changeset/33812-seed-depends-on.md @@ -0,0 +1,22 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +'@objectstack/runtime': minor +'@objectstack/cli': minor +--- + +feat(spec, metadata-protocol): a seed dataset can declare `dependsOn`, the objects it loads after, for an order no lookup field gives + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: follow-up #34277 — `skills/objectstack-data/references/seeds.md` (its relationship section and its best-practice table tell the author to order seeds parent before child in the exported array, which orders nothing; `dependsOn` is not taught) + +The seed loader orders a load's datasets by the `lookup`, `master_detail` and `user` fields between their objects; the order of the stack's `data` array only breaks ties. A dataset whose `beforeInsert` hook reads another seeded object had no way to say so, and its hook ran against whatever that object held at the moment, which an unrelated dataset could change. A rating scored from seeded bands, ordered by its one lookup to its rule, was written a wave before the bands and scored every row as if none existed. + +- **`Seed.dependsOn: string[]` names objects.** Each name adds an edge to the same dependency graph the lookup fields feed, so the dataset's object loads after the named object's rows: `defineSeed(CustomerRating, { dependsOn: ['crm_rating_band'], records })`. The edges of several datasets of one object are pooled onto that object, and the returned `dependencyGraph.nodes[].dependsOn` lists them beside the lookup edges. +- **A load that declares none keeps its order exactly.** Nothing changes for an app that does not write the key. +- **A declaration the load cannot honour refuses the whole load, before any row is written.** The load answers `success: false` with one `errors[]` entry per refused declaration (`field: 'dependsOn'`, `sourceObject` the declaring object, `targetObject` the named one), and every caller reports it the way it reports any failed load. Three cases: a name that is the dataset's own object; a name no other dataset of the same load seeds (a misspelling, or an object whose datasets `env` or `locale` scoped out of this load, which the message says); and a declared edge that closes a cycle with the other edges, lookups included, with the cycle spelled out object by object. A cycle made of lookup fields alone still loads in deferred passes, as before. +- **A refused boot seed reads as a failed seed.** The single-tenant boot seed (`AppPlugin`) counts each error of a load refused before any dataset ran as a rejected row in the outcome it records, so `os dev` / `os serve` print the source with a warning on the banner's `Seeds:` line and the `objectstack:seed-settled` message answers `ok: false`; before, a refused load wrote nothing and read clean on both. +- **`defineSeed` refuses a dataset that names its own object** when it runs. The other two cases need the whole load, so only the loader can judge them. + +A seed published on its own (a draft publish) is its own load, so a published seed whose `dependsOn` names an object seeded by another item is refused until the two are published together. diff --git a/content/docs/data-modeling/seed-data.mdx b/content/docs/data-modeling/seed-data.mdx index 42ef9ffcf5b..7e084283195 100644 --- a/content/docs/data-modeling/seed-data.mdx +++ b/content/docs/data-modeling/seed-data.mdx @@ -457,7 +457,7 @@ const contactsSeed = defineSeed(Contact, { ], }); -// Export in dependency order — parents before children +// The loader puts accounts first because `contact.account` looks them up export const SeedData = [accountsSeed, contactsSeed]; ``` @@ -539,6 +539,56 @@ duplicates on every replay boot ([#3434](https://github.com/objectstack-ai/objec --- +## Load Order — `dependsOn` + +A load orders its datasets by the relationships between their objects: a `lookup`, +`master_detail` or `user` field makes its object load after the object it points +at, however the datasets are listed. The order of your `data` array only breaks +ties between objects that are ready at the same moment. + +Some dependencies are not fields. A `beforeInsert` hook that **reads** another +seeded object while a row is written (a rating scored from seeded bands, a price +computed from a seeded rate table) needs those rows to be there first, and no +lookup says so. Declare it with `dependsOn`, naming the objects: + +```typescript +export const ratingBandsSeed = defineSeed(RatingBand, { + externalId: 'code', + records: [/* … */], +}); + +// The rating's beforeInsert hook scores each row from crm_rating_band rows, +// so this dataset must load after them. +export const customerRatingsSeed = defineSeed(CustomerRating, { + dependsOn: ['crm_rating_band'], + records: [/* … */], +}); +``` + +Each name adds an edge to the same dependency graph the lookup fields feed. A +dataset that declares no `dependsOn` loads exactly where its lookups put it. + +The loader refuses the **whole load**, writing no row, and reports why, when a +`dependsOn`: + +- names the dataset's own object (`defineSeed` also refuses this when it runs); +- names an object no other dataset of the same load seeds: a misspelling, or a + dataset that `env` or `locale` scoped out of this load. A seed published on its + own is its own load, so publish it together with the seeds it depends on. Two + more loads carry only part of an app's seeds and refuse the same way: the dev + hot-reload seeder loads only the datasets of objects first seen in that reload, + so restart the dev server after adding a seed that depends on an object seeded + earlier, and a marketplace install loads one package's datasets, so name only + objects your own package seeds; +- closes a cycle with the other edges, lookups included: `crm_rating_rule` + declaring `dependsOn: ['crm_customer_rating']` while the rating looks up its + rule. No order can keep that edge. + +A cycle made only of lookup fields is still loaded in several passes (each row is +written first and its missing reference filled in afterwards), as before. + +--- + ## File Fields — `seedFile(path)` A `file`, `image`, `avatar`, `video` or `audio` field stores the id of a stored @@ -705,11 +755,11 @@ import { contactsSeed } from './contacts.seed'; import { leadsSeed } from './leads.seed'; import { productsSeed } from './products.seed'; -/** All seed datasets — order determines load sequence */ +/** All seed datasets — the loader orders them by their lookups and dependsOn */ export const SeedData = [ accountsSeed, // no dependencies productsSeed, // no dependencies - contactsSeed, // depends on accounts + contactsSeed, // looks up accounts, so it loads after them leadsSeed, // no dependencies ]; ``` @@ -753,10 +803,12 @@ when the use case requires it — `upsert` for reference data the package keeps (with `applyOn: 'create'` on the columns the customer or a job owns), or `replace` for ephemeral cache tables. -### Seed in dependency order +### Declare a dependency no field expresses -Always export parent datasets before child datasets. If `contact` has a lookup to -`account`, `accountsSeed` must appear before `contactsSeed` in the exported array. +Lookup fields order the load for you: if `contact` has a lookup to `account`, +accounts load first wherever `accountsSeed` sits in the array. Listing parents +first keeps the file readable, but it orders nothing. When a hook reads another +seeded object, declare it with `dependsOn` (see "Load Order"). ### Keep records realistic @@ -783,6 +835,7 @@ function defineSeed< columns?: { [field: string]: { applyOn?: 'create' | 'always' } }; // per-column write policy; default: 'always' env?: Array<'prod' | 'dev' | 'test'>; // default: ['prod','dev','test'] locale?: string[]; // BCP-47 tags; omitted = every locale + dependsOn?: string[]; // objects this dataset loads after (see "Load Order") records: Array>; // declared fields + injectable system columns } ): Seed diff --git a/content/docs/references/api/package-api.mdx b/content/docs/references/api/package-api.mdx index 4ad925bdc96..bc04716fe5b 100644 --- a/content/docs/references/api/package-api.mdx +++ b/content/docs/references/api/package-api.mdx @@ -247,6 +247,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **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 | +| **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | @@ -355,6 +356,7 @@ Package manifest installed through POST /api/v1/packages (AUTHORING stage; scope | **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 | +| **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | diff --git a/content/docs/references/data/seed-loader.mdx b/content/docs/references/data/seed-loader.mdx index 09230fd0892..864c98dd13e 100644 --- a/content/docs/references/data/seed-loader.mdx +++ b/content/docs/references/data/seed-loader.mdx @@ -234,6 +234,7 @@ Seed loader request with datasets and configuration | **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 | +| **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | diff --git a/content/docs/references/data/seed.mdx b/content/docs/references/data/seed.mdx index 10834427e5c..58c14a8869a 100644 --- a/content/docs/references/data/seed.mdx +++ b/content/docs/references/data/seed.mdx @@ -34,6 +34,7 @@ const result = SeedSchema.parse(data); | **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 | +| **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | diff --git a/content/docs/references/kernel/manifest.mdx b/content/docs/references/kernel/manifest.mdx index cd1fcaf1df9..dd385376dd2 100644 --- a/content/docs/references/kernel/manifest.mdx +++ b/content/docs/references/kernel/manifest.mdx @@ -101,6 +101,7 @@ Install mode: managed (registered as code, upgradeable, sealed) | unmanaged (cop | **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 | +| **dependsOn** | `string[]` | optional | Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert hook that reads another seeded object. Each name adds an edge to the load's dependency graph. The load is refused, writing nothing, when a name is the dataset's own object, is not seeded by another dataset of the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone. | | **records** | `Record[]` | ✅ | Data records | | **files** | `Record` | optional | Bytes of the package files the records name with `seedFile(path)`, keyed by path. Written by `os build`, which reads each path relative to the package root; the loader stores each one as a file the written record owns. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | diff --git a/packages/cli/src/commands/serve-seed-refused-load-33812.test.ts b/packages/cli/src/commands/serve-seed-refused-load-33812.test.ts new file mode 100644 index 00000000000..664d0fca3e9 --- /dev/null +++ b/packages/cli/src/commands/serve-seed-refused-load-33812.test.ts @@ -0,0 +1,166 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { AppPlugin } from '@objectstack/runtime'; +import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { composeSeedSettledMessage } from '../utils/seed-settled-message.js'; +import { printSeedResultAfterBanner } from '../utils/format.js'; + +/** + * A boot seed whose load is REFUSED (a `Seed.dependsOn` the loader cannot + * honour) must read as a failed seed on the two channels built to say so: the + * banner's `Seeds:` line and the `objectstack:seed-settled` message. + * + * A refused load writes no row and answers `success: false` with its refusal + * in `errors[]` and every row counter at zero. The single-tenant boot seed + * records its outcome for those channels (`recordSeedOutcome`), and from the + * counters alone a source that wrote nothing and rejected nothing is dropped + * from the `Seeds:` line and leaves `ok: true` — a clean-looking boot that + * seeded nothing. Driven here end to end: AppPlugin's real boot seed and + * SeedLoaderService over an in-memory engine, then the `seed-summary` service as the + * CLI reads it, the settled message and the banner line. The control + * is the same boot with a load that succeeds. + */ + +function rowMatches(row: any, 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); + }); +} + +function createEngine() { + const store: Record = {}; + let next = 0; + const engine: any = { + store, + 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 findOne(object: string, query?: any) { + assertEngineFindOnePredicate(object, query); + return (await engine.find(object, { ...query, limit: 1 }))[0] ?? null; + }, + async insert(object: string, data: any) { + const mint = (d: any) => ({ id: d.id ?? `gen_${++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 update(object: string, data: any, options?: any) { + assertEngineUpdateDispatch(data, options); + const row = (store[object] ?? []).find((r) => r.id === data.id); + if (row) Object.assign(row, data); + return row ? { ...row } : null; + }, + async count(object: string, query?: any) { + return (await engine.find(object, query)).length; + }, + async aggregate() { + return []; + }, + }; + return engine; +} + +const OBJECTS: Record = { + crm_case: { name: 'crm_case', fields: { name: { type: 'text' } } }, +}; + +const metadataService = { + getObject: vi.fn(async (name: string) => OBJECTS[name]), + listObjects: vi.fn(async () => Object.values(OBJECTS)), + get: vi.fn(async (_type: string, name: string) => OBJECTS[name]), + list: vi.fn(async () => []), + register: vi.fn(async () => {}), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), +}; + +const bundle = (dataset: Record = {}) => ({ + id: 'refused_load_app', + data: [{ object: 'crm_case', externalId: 'name', records: [{ name: 'CASE-1' }, { name: 'CASE-2' }], ...dataset }], +}); + +/** Boot AppPlugin's inline seed on a context with a real service map; answer the map. */ +async function boot(dataset?: Record) { + const engine = createEngine(); + const services = new Map(); + const ctx: any = { + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + registerService: vi.fn((name: string, svc: unknown) => { + if (services.has(name)) throw new Error(`service '${name}' already registered`); + services.set(name, svc); + }), + getService: vi.fn((name: string) => { + if (name === 'objectql') return engine; + if (name === 'metadata') return metadataService; + return services.get(name); + }), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + }; + await new AppPlugin(bundle(dataset) as any).start(ctx); + // What the CLI reads back after `runtime.start()` (`runtimeSeedSettlementChannels`). + const recorded = services.get('seed-summary'); + return { engine, summary: Array.isArray(recorded) && recorded.length > 0 ? (recorded as any[]) : undefined }; +} + +describe('a boot seed refused by dependsOn reads as a failed seed (banner and settled message)', () => { + const OLD_BUDGET = process.env.OS_INLINE_SEED_BUDGET_MS; + const OLD_MULTI = process.env.OS_MULTI_ORG_ENABLED; + let lines: string[]; + let spy: ReturnType; + + beforeEach(() => { + delete process.env.OS_MULTI_ORG_ENABLED; + process.env.OS_INLINE_SEED_BUDGET_MS = '8000'; + lines = []; + spy = vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + lines.push(args.join(' ')); + }); + }); + afterEach(() => { + spy.mockRestore(); + if (OLD_BUDGET === undefined) delete process.env.OS_INLINE_SEED_BUDGET_MS; + else process.env.OS_INLINE_SEED_BUDGET_MS = OLD_BUDGET; + if (OLD_MULTI === undefined) delete process.env.OS_MULTI_ORG_ENABLED; + else process.env.OS_MULTI_ORG_ENABLED = OLD_MULTI; + }); + + it('the refused load: nothing written, the source is a problem on the Seeds line, and the settled message is not ok', async () => { + const { engine, summary } = await boot({ dependsOn: ['no_such_object'] }); + + expect(engine.store.crm_case ?? []).toHaveLength(0); + expect(summary).toEqual([expect.objectContaining({ source: 'refused_load_app', inserted: 0 })]); + expect(summary![0]!.rejected).toBeGreaterThan(0); + + expect(composeSeedSettledMessage(undefined, summary).ok).toBe(false); + + printSeedResultAfterBanner(summary ?? []); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain('⚠ Seeds:'); + expect(lines[0]).toContain('refused_load_app'); + }); + + it('control: the same boot with a load that succeeds reads ok, with its rows on the Seeds line', async () => { + const { engine, summary } = await boot(); + + expect(engine.store.crm_case).toHaveLength(2); + expect(summary).toEqual([expect.objectContaining({ source: 'refused_load_app', inserted: 2, rejected: 0 })]); + + expect(composeSeedSettledMessage(undefined, summary).ok).toBe(true); + + printSeedResultAfterBanner(summary ?? []); + expect(lines).toHaveLength(1); + expect(lines[0]).not.toContain('⚠'); + expect(lines[0]).toContain('refused_load_app 2 rows'); + }); +}); diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 04ad3e458e9..650c35111b8 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -76,6 +76,7 @@ import { type SeedSuppressionReason, } from '@objectstack/spec/contracts'; import { missingProviderMessage } from '../utils/capability-preflight.js'; +import { composeSeedSettledMessage } from '../utils/seed-settled-message.js'; // The deployment's product name, for `AuthPlugin` — the same resolver the email // capability's template context reads (`resolveEmailCapabilityArg`), so the two // cannot disagree. Both moved to `@objectstack/plugin-email` beside the mail @@ -908,19 +909,9 @@ export function seedingHasSettled(snapshot: SeedSettlementSnapshot | undefined): return !snapshot || snapshot.inFlight === 0; } -/** Build the message from the two things the kernel already knows. */ -export function composeSeedSettledMessage( - snapshot: SeedSettlementSnapshot | undefined, - sources: SeedSourceSummary[] | undefined, -): SeedSettledMessage { - const list = sources ?? []; - return { - type: 'objectstack:seed-settled', - ok: list.every((s) => s.rejected === 0 && (s.droppedRefs ?? 0) === 0 && !s.emptyInstall), - suppressed: snapshot ? [...snapshot.suppressed] : [], - sources: list, - }; -} +// Built in its own module so a test can drive the verdict without loading +// this file's composition graph; re-exported here, where it always lived. +export { composeSeedSettledMessage }; /** What {@link createSeedSettlementAnnouncer} needs from its host. */ export interface SeedSettlementChannels { diff --git a/packages/cli/src/utils/seed-settled-message.ts b/packages/cli/src/utils/seed-settled-message.ts new file mode 100644 index 00000000000..9c304558e64 --- /dev/null +++ b/packages/cli/src/utils/seed-settled-message.ts @@ -0,0 +1,26 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SeedSettlementSnapshot } from '@objectstack/spec/contracts'; +import type { SeedSourceSummary } from './format.js'; +import type { SeedSettledMessage } from '../commands/serve.js'; + +/** + * Build the `objectstack:seed-settled` message ({@link SeedSettledMessage}) + * from the two things the kernel already knows: the settlement tally and the + * per-source seed summary the banner's `Seeds:` row renders. + * + * Kept apart from `serve.ts`, which re-exports it, so a test of the verdict + * does not load the whole boot composition `serve.ts` imports. + */ +export function composeSeedSettledMessage( + snapshot: SeedSettlementSnapshot | undefined, + sources: SeedSourceSummary[] | undefined, +): SeedSettledMessage { + const list = sources ?? []; + return { + type: 'objectstack:seed-settled', + ok: list.every((s) => s.rejected === 0 && (s.droppedRefs ?? 0) === 0 && !s.emptyInstall), + suppressed: snapshot ? [...snapshot.suppressed] : [], + sources: list, + }; +} diff --git a/packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts b/packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts new file mode 100644 index 00000000000..a149fa232cd --- /dev/null +++ b/packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts @@ -0,0 +1,282 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, vi } from 'vitest'; +import { SeedLoaderService } from './seed-loader.js'; +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; +import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate, type EngineFindOneQueryInput } from '@objectstack/metadata-core'; + +/** + * `Seed.dependsOn` — a dataset declares the seeded objects its insert-time + * lifecycle hook reads, and the loader orders it after them. + * + * Before the key existed, a dataset's place in the load came from lookup / + * master_detail / user edges alone; authored order only broke ties inside the + * Kahn queue. A dataset whose `beforeInsert` hook READS another seeded object + * had no way to say so, so its hook ran against whatever that object happened + * to hold — here, a rating scored against bands that had not landed yet. + * + * The fixture is the reported shape: `customer_rating` looks up `rating_rule` + * only, and `rating_band` sits two master_detail hops below the rule, so the + * rating is ready one wave before the bands. The fake engine plays the hook: + * every `customer_rating` row is stamped, at insert time, with the number of + * `rating_band` rows the store holds at that moment. + * + * What the ruling binds, each pinned below: + * - `dependsOn` names objects; each name is an edge in the same graph the + * lookups feed, so the declaring dataset lands after the named object. + * - An app that declares no `dependsOn` keeps today's order exactly. + * - A declared edge that closes a cycle refuses the load, and so does a name + * that is not a seeded object of the same load. A refused load writes no + * row. A cycle of lookup edges alone keeps today's deferred passes. + */ + +function createLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +function createEngine() { + const store: Record = {}; + const insertOrder: string[] = []; + let idCounter = 0; + + /** The "hook": a rating is scored against the bands present when it is inserted. */ + const stamp = (objectName: string, row: any) => + objectName === 'customer_rating' ? { ...row, bands_seen: (store.rating_band ?? []).length } : row; + + const engine = { + find: vi.fn(async (objectName: string, query?: any) => { + let records = store[objectName] || []; + if (query?.where) { + records = records.filter((r) => + Object.entries(query.where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); return r[k] === v; }), + ); + } + if (typeof query?.limit === 'number') records = records.slice(0, query.limit); + return records; + }), + findOne: vi.fn(async (object: string, query?: EngineFindOneQueryInput) => { assertEngineFindOnePredicate(object, query); return null; }), + insert: vi.fn(async (objectName: string, data: any) => { + if (!store[objectName]) store[objectName] = []; + insertOrder.push(objectName); + if (Array.isArray(data)) { + const records = data.map((d) => ({ id: `gen-${++idCounter}`, ...stamp(objectName, d) })); + store[objectName].push(...records); + return records; + } + const record = { id: `gen-${++idCounter}`, ...stamp(objectName, data) }; + store[objectName].push(record); + return record; + }), + update: vi.fn(async (_o: string, data: any, options?: any) => { + assertEngineUpdateDispatch(data, options); + return data; + }), + delete: vi.fn(async (_objectName: string, options?: any) => { + assertEngineDeleteDispatch(options); + return { deleted: 1 }; + }), + count: vi.fn(async (objectName: string) => (store[objectName] || []).length), + aggregate: vi.fn(async () => []), + } as unknown as IDataEngine; + + return { engine, store, insertOrder }; +} + +const OBJECTS: Record = { + rating_rule: { name: 'rating_rule', fields: { name: { type: 'text' } } }, + rating_item: { name: 'rating_item', fields: { name: { type: 'text' }, rule: { type: 'master_detail', reference: 'rating_rule' } } }, + rating_band: { name: 'rating_band', fields: { name: { type: 'text' }, item: { type: 'master_detail', reference: 'rating_item' } } }, + customer_rating: { + name: 'customer_rating', + fields: { name: { type: 'text' }, rule: { type: 'lookup', reference: 'rating_rule' }, bands_seen: { type: 'number' } }, + }, + // A lookup cycle of its own (x ↔ y), and an object hanging off it. + cyc_x: { name: 'cyc_x', fields: { name: { type: 'text' }, y: { type: 'lookup', reference: 'cyc_y' } } }, + cyc_y: { name: 'cyc_y', fields: { name: { type: 'text' }, x: { type: 'lookup', reference: 'cyc_x' } } }, + cyc_child: { name: 'cyc_child', fields: { name: { type: 'text' }, x: { type: 'lookup', reference: 'cyc_x' } } }, + cyc_reader: { name: 'cyc_reader', fields: { name: { type: 'text' } } }, +}; + +function createMetadata(): IMetadataService { + return { + getObject: vi.fn(async (name: string) => OBJECTS[name]), + listObjects: vi.fn(async () => Object.values(OBJECTS)), + register: vi.fn(async () => {}), + get: vi.fn(async () => undefined), + list: vi.fn(async () => []), + unregister: vi.fn(async () => {}), + exists: vi.fn(async () => false), + listNames: vi.fn(async () => []), + } as unknown as IMetadataService; +} + +const BASE_CONFIG = { + dryRun: false, + haltOnError: false, + multiPass: true, + defaultMode: 'upsert', + batchSize: 1000, + transaction: false, + env: 'prod', +} as any; + +const ds = (object: string, records: Record[], extra: Record = {}) => ({ + object, + externalId: 'name', + mode: 'upsert', + env: ['prod', 'dev', 'test'], + records, + ...extra, +}); + +/** The reported book: the bands authored BEFORE the ratings, which was never enough. */ +const book = (ratingExtra: Record = {}) => [ + ds('rating_rule', [{ name: 'R1' }]), + ds('rating_item', [{ name: 'I1', rule: 'R1' }]), + ds('rating_band', [{ name: 'B1', item: 'I1' }, { name: 'B2', item: 'I1' }]), + ds('customer_rating', [{ name: 'C1', rule: 'R1' }], ratingExtra), +]; + +async function run(seeds: any[], config: Record = {}) { + const { engine, store, insertOrder } = createEngine(); + const logger = createLogger(); + const loader = new SeedLoaderService(engine, createMetadata(), logger as any); + const result = await loader.load({ seeds, config: { ...BASE_CONFIG, ...config } } as any); + return { result, store, insertOrder, logger, engine }; +} + +describe('Seed.dependsOn orders a dataset after the objects its hook reads', () => { + it('the card: a rating declaring dependsOn its bands is inserted after them, and its hook sees them', async () => { + const { result, store, insertOrder } = await run(book({ dependsOn: ['rating_band'] })); + + expect(result.success, JSON.stringify(result.errors)).toBe(true); + expect(insertOrder.indexOf('rating_band')).toBeLessThan(insertOrder.indexOf('customer_rating')); + expect(store.customer_rating?.[0]?.bands_seen).toBe(2); + // The declared edge is in the graph the lookups feed. + const node = result.dependencyGraph.nodes.find((n) => n.object === 'customer_rating'); + expect(node?.dependsOn).toEqual(expect.arrayContaining(['rating_rule', 'rating_band'])); + }); + + it('control: with no dependsOn the load keeps today\'s order exactly — the rating lands a wave before the bands', async () => { + const { result, store, insertOrder } = await run(book()); + + expect(result.success).toBe(true); + expect(result.dependencyGraph.insertOrder).toEqual(['rating_rule', 'rating_item', 'customer_rating', 'rating_band']); + expect(insertOrder).toEqual(['rating_rule', 'rating_item', 'customer_rating', 'rating_band']); + expect(store.customer_rating?.[0]?.bands_seen).toBe(0); + }); + + it('several datasets of one object: their declarations are pooled onto the object', async () => { + const seeds = [ + ...book(), + ds('customer_rating', [{ name: 'C2', rule: 'R1' }], { dependsOn: ['rating_band'] }), + ]; + const { result, store } = await run(seeds); + + expect(result.success, JSON.stringify(result.errors)).toBe(true); + expect(store.customer_rating?.map((r) => r.bands_seen)).toEqual([2, 2]); + }); + + it('a lookup cycle elsewhere: a dataset downstream of it still lands after the object it declares', async () => { + // cyc_x ↔ cyc_y never reach in-degree 0, so cyc_child (lookup → cyc_x) and + // cyc_reader (dependsOn cyc_child) are both appended after the Kahn pass. + // Authored with the reader first, the append must still honour the edge. + const seeds = [ + ds('cyc_reader', [{ name: 'R' }], { dependsOn: ['cyc_child'] }), + ds('cyc_x', [{ name: 'X', y: 'Y' }]), + ds('cyc_y', [{ name: 'Y', x: 'X' }]), + ds('cyc_child', [{ name: 'C', x: 'X' }]), + ]; + const { result, insertOrder } = await run(seeds); + + expect(result.success, JSON.stringify(result.errors)).toBe(true); + expect(result.dependencyGraph.circularDependencies.length).toBeGreaterThan(0); + expect(insertOrder.indexOf('cyc_child')).toBeLessThan(insertOrder.indexOf('cyc_reader')); + }); +}); + +describe('Seed.dependsOn refusals: the load writes nothing and names the declaration', () => { + /** Refused, nothing written, and the declaration named by its two objects. */ + const expectRefused = (r: Awaited>, object: string, target: string) => { + expect(r.result.success).toBe(false); + expect(r.result.results).toEqual([]); + expect(r.result.summary.totalInserted).toBe(0); + expect(r.engine.insert).not.toHaveBeenCalled(); + expect(r.result.errors.every((e) => e.field === 'dependsOn')).toBe(true); + expect(r.result.errors).toEqual(expect.arrayContaining([ + expect.objectContaining({ sourceObject: object, targetObject: target, field: 'dependsOn' }), + ])); + const error = r.result.errors.find((e) => e.sourceObject === object && e.targetObject === target)!; + expect(error.message).toContain(`'${object}'`); + return error; + }; + + it('a declared edge that closes a cycle with lookup edges refuses the load', async () => { + // customer_rating looks up rating_rule, so the rule lands first; a rule + // that declares it reads the ratings asks for the opposite. + const seeds = book(); + seeds[0] = ds('rating_rule', [{ name: 'R1' }], { dependsOn: ['customer_rating'] }); + const r = await run(seeds); + + const error = expectRefused(r, 'rating_rule', 'customer_rating'); + // The subject is the cycle itself, named object by object. + expect(error.message).toContain('rating_rule → customer_rating → rating_rule'); + }); + + it('two declared edges that close a cycle between themselves refuse the load', async () => { + const seeds = [ + ds('cyc_reader', [{ name: 'R' }], { dependsOn: ['rating_rule'] }), + ds('rating_rule', [{ name: 'R1' }], { dependsOn: ['cyc_reader'] }), + ]; + const r = await run(seeds); + + expectRefused(r, 'cyc_reader', 'rating_rule'); + expectRefused(r, 'rating_rule', 'cyc_reader'); + }); + + it('a dataset that declares its own object refuses the load', async () => { + const r = await run(book({ dependsOn: ['customer_rating'] })); + + expectRefused(r, 'customer_rating', 'customer_rating'); + }); + + it('a name that no dataset of this load seeds refuses the load', async () => { + const r = await run(book({ dependsOn: ['crm_rating_bnad'] })); + + const error = expectRefused(r, 'customer_rating', 'crm_rating_bnad'); + expect(error.message).toContain("'crm_rating_bnad'"); + expect(error.message).not.toContain('scoped out'); + }); + + it('a name whose datasets this load scoped out (env) refuses the load and says why', async () => { + const seeds = book({ dependsOn: ['rating_band'] }); + seeds[2] = ds('rating_band', [{ name: 'B1', item: 'I1' }], { env: ['dev'] }); + const r = await run(seeds, { env: 'prod' }); + + const error = expectRefused(r, 'customer_rating', 'rating_band'); + expect(error.message).toContain('scoped out'); + }); + + it('a dataset this load scoped out is not judged', async () => { + const seeds = [...book(), ds('cyc_reader', [{ name: 'R' }], { env: ['dev'], dependsOn: ['no_such_object'] })]; + const r = await run(seeds, { env: 'prod' }); + + expect(r.result.success, JSON.stringify(r.result.errors)).toBe(true); + }); + + it('control: a cycle of lookup edges alone is still loaded by deferred passes, not refused', async () => { + const seeds = [ds('cyc_x', [{ name: 'X', y: 'Y' }]), ds('cyc_y', [{ name: 'Y', x: 'X' }])]; + const r = await run(seeds); + + expect(r.result.success, JSON.stringify(r.result.errors)).toBe(true); + expect(r.result.dependencyGraph.circularDependencies.length).toBeGreaterThan(0); + expect(r.result.summary.totalInserted).toBe(2); + }); + + it('a dry run reports the same refusal', async () => { + const r = await run(book({ dependsOn: ['crm_rating_bnad'] }), { dryRun: true }); + + expect(r.result.success).toBe(false); + expect(r.result.errors.map((e) => e.message).join('\n')).toContain("'crm_rating_bnad'"); + }); +}); diff --git a/packages/metadata-protocol/src/seed-loader.ts b/packages/metadata-protocol/src/seed-loader.ts index 811047510bd..eb0ca78055f 100644 --- a/packages/metadata-protocol/src/seed-loader.ts +++ b/packages/metadata-protocol/src/seed-loader.ts @@ -1199,9 +1199,17 @@ export class SeedLoaderService implements ISeedLoaderService { return this.buildEmptyResult(config, Date.now() - startTime); } - // 2. Build dependency graph + // 2. Build dependency graph. `Seed.dependsOn` adds its declared edges to + // the ones the lookup fields give; a declaration this load cannot honour + // (a name it does not seed, an edge that closes a cycle) refuses the + // whole load before any row is written. const objectNames = datasets.map(d => d.object); - const graph = await this.buildDependencyGraph(objectNames); + const declared = this.collectDeclaredDependencies(datasets, request.seeds); + const graph = await this.buildDependencyGraph(objectNames, declared.edges); + const dependsOnRefusals = [...declared.refusals, ...this.findDeclaredEdgeCycles(graph.nodes, declared.edges)]; + if (dependsOnRefusals.length > 0) { + return this.refuseDeclaredDependencies(config, graph, dependsOnRefusals, Date.now() - startTime); + } this.logger.info('[SeedLoader] Dependency graph built', { objects: objectNames.length, @@ -1310,7 +1318,18 @@ export class SeedLoaderService implements ISeedLoaderService { return this.buildResult(config, graph, allResults, allErrors, durationMs); } - async buildDependencyGraph(objectNames: string[]): Promise { + /** + * Object dependency graph of a load: one node per object, an edge per + * `lookup` / `master_detail` / `user` field that points at another object of + * the load, plus — when `declared` is given — an edge per `Seed.dependsOn` + * name (object → the objects it loads after). The declared names are + * expected to be objects of the load: {@link collectDeclaredDependencies} + * holds them to it before this runs. + */ + async buildDependencyGraph( + objectNames: string[], + declared?: ReadonlyMap>, + ): Promise { const nodes: ObjectDependencyNodeParsed[] = []; const objectSet = new Set(objectNames); @@ -1374,11 +1393,17 @@ export class SeedLoaderService implements ISeedLoaderService { } } + // [Seed.dependsOn] The declared edges join the same node, after the + // ones the fields gave. + for (const target of declared?.get(objectName) ?? []) { + if (objectSet.has(target) && !dependsOn.includes(target)) dependsOn.push(target); + } + nodes.push({ object: objectName, dependsOn, references }); } // Topological sort - const { insertOrder, circularDependencies } = this.topologicalSort(nodes); + const { insertOrder, circularDependencies } = this.topologicalSort(nodes, declared); return { nodes, insertOrder, circularDependencies }; } @@ -3983,6 +4008,7 @@ export class SeedLoaderService implements ISeedLoaderService { */ private topologicalSort( nodes: ObjectDependencyNodeParsed[], + declared?: ReadonlyMap>, ): { insertOrder: string[]; circularDependencies: string[][] } { const inDegree = new Map(); const adjacency = new Map(); @@ -4035,10 +4061,16 @@ export class SeedLoaderService implements ISeedLoaderService { const cycles = this.findCycles(remaining); circularDependencies.push(...cycles); - // Add remaining objects to insertOrder (they'll need multi-pass) - for (const node of remaining) { - if (!insertOrder.includes(node.object)) { - insertOrder.push(node.object); + // Add remaining objects to insertOrder (they'll need multi-pass). + // [Seed.dependsOn] Their lookup edges are left to the deferred passes, + // as before, but a DECLARED edge is an order the load must keep: a + // dataset depending on an object that sits behind a lookup cycle is + // left over too, and is appended after that object. The declared edges + // never form a cycle here (the load refuses one before it writes), and + // with none declared the append order is the node order, as before. + for (const object of this.orderByDeclaredEdges(remaining.map(n => n.object), declared)) { + if (!insertOrder.includes(object)) { + insertOrder.push(object); } } } @@ -4046,6 +4078,171 @@ export class SeedLoaderService implements ISeedLoaderService { return { insertOrder, circularDependencies }; } + /** + * [Seed.dependsOn] `objects`, stably reordered so each lands after every + * object of the list it declared a dependency on: repeatedly the first + * object whose declared dependencies are all placed. An object caught on a + * declared cycle (which the load refuses before using this order) keeps its + * place at the end rather than being lost. + */ + private orderByDeclaredEdges( + objects: string[], + declared: ReadonlyMap> | undefined, + ): string[] { + if (!declared || declared.size === 0) return objects; + const pending = [...new Set(objects)]; + const inList = new Set(pending); + const placed: string[] = []; + const isPlaced = new Set(); + while (pending.length > 0) { + const next = pending.findIndex(object => + [...(declared.get(object) ?? [])].every(dep => dep === object || !inList.has(dep) || isPlaced.has(dep))); + const [object] = pending.splice(next === -1 ? 0 : next, 1); + placed.push(object); + isPlaced.add(object); + } + return placed; + } + + /** + * [Seed.dependsOn] The declared edges of a load, pooled per object across + * its datasets, and the declarations the load cannot honour: a dataset that + * names its own object, or a name no dataset of the load seeds — told apart + * from a name whose datasets `env` / `locale` scoped out of this load. + * Only datasets this load seeds are judged. + */ + private collectDeclaredDependencies( + datasets: Seed[], + requested: Seed[], + ): { edges: Map>; refusals: DeclaredDependencyRefusal[] } { + const edges = new Map>(); + const refusals: DeclaredDependencyRefusal[] = []; + const loaded = new Set(datasets.map(d => d.object)); + const scopedOut = new Set(requested.map(d => d.object).filter(object => !loaded.has(object))); + for (const dataset of datasets) { + for (const target of dataset.dependsOn ?? []) { + if (target === dataset.object) { + refusals.push({ + object: dataset.object, + target, + message: + `Seed dataset '${dataset.object}' declares dependsOn its own object: a dataset cannot load after ` + + 'itself. List the other seeded objects its hooks read, or drop the entry. The seed load was refused ' + + 'and no row was written.', + }); + continue; + } + if (!loaded.has(target)) { + refusals.push({ + object: dataset.object, + target, + message: scopedOut.has(target) + ? `Seed dataset '${dataset.object}' declares dependsOn '${target}', whose datasets are all scoped out ` + + 'of this load by their env or locale, so its rows would not be there when this dataset loads. ' + + `Scope '${dataset.object}' the same way, or widen '${target}'. The seed load was refused and no row ` + + 'was written.' + : `Seed dataset '${dataset.object}' declares dependsOn '${target}', which no dataset of this load ` + + 'seeds. dependsOn names objects that other datasets of the same load seed; check the spelling, or ' + + `load '${target}'s dataset together with this one. The seed load was refused and no row was written.`, + }); + continue; + } + let set = edges.get(dataset.object); + if (!set) edges.set(dataset.object, set = new Set()); + set.add(target); + } + } + return { edges, refusals }; + } + + /** + * [Seed.dependsOn] Every declared edge that closes a cycle of the combined + * graph. The rule: a declared edge `A dependsOn B` is refused when B already + * depends on A, directly or through any chain of edges — lookup or declared + * (self-references excluded, as the sort excludes them). Equivalently, the + * edge lies on a cycle, which is the one case where no order keeps it. A + * cycle made of lookup edges alone is not this rule's: those still load in + * deferred passes. + */ + private findDeclaredEdgeCycles( + nodes: ObjectDependencyNodeParsed[], + declared: ReadonlyMap>, + ): DeclaredDependencyRefusal[] { + if (declared.size === 0) return []; + const dependsOnOf = new Map(); + for (const node of nodes) { + const deps = dependsOnOf.get(node.object) ?? []; + for (const dep of node.dependsOn) if (dep !== node.object && !deps.includes(dep)) deps.push(dep); + dependsOnOf.set(node.object, deps); + } + /** A dependency chain from `from` to `to` (both ends included), or undefined. */ + const chain = (from: string, to: string): string[] | undefined => { + const previous = new Map(); + const queue = [from]; + const seen = new Set([from]); + while (queue.length > 0) { + const current = queue.shift()!; + if (current === to) { + const path = [to]; + while (path[0] !== from) path.unshift(previous.get(path[0])!); + return path; + } + for (const dep of dependsOnOf.get(current) ?? []) { + if (seen.has(dep)) continue; + seen.add(dep); + previous.set(dep, current); + queue.push(dep); + } + } + return undefined; + }; + const refusals: DeclaredDependencyRefusal[] = []; + for (const [object, targets] of declared) { + for (const target of targets) { + const back = chain(target, object); + if (!back) continue; + const cycle = [object, ...back].join(' → '); + refusals.push({ + object, + target, + message: + `Seed dataset '${object}' declares dependsOn '${target}', and that edge closes a cycle: ${cycle} ` + + '(each arrow reads "loads after", from a lookup field or a dependsOn). No load order keeps it. Drop the ' + + 'entry, or the dependency that runs the other way. The seed load was refused and no row was written.', + }); + } + } + return refusals; + } + + /** + * [Seed.dependsOn] The answer of a load refused for its declarations: + * nothing written, `success: false`, one error per refused declaration + * (`field: 'dependsOn'`). Returned rather than thrown, so every caller + * reports it the way it reports any failed load, and none falls back to + * writing the rows some other way. + */ + private refuseDeclaredDependencies( + config: SeedLoaderConfigParsed, + graph: ObjectDependencyGraphParsed, + refusals: DeclaredDependencyRefusal[], + durationMs: number, + ): SeedLoaderResultParsed { + const errors: ReferenceResolutionError[] = refusals.map(refusal => ({ + sourceObject: refusal.object, + field: 'dependsOn', + targetObject: refusal.target, + targetField: '(dataset)', + attemptedValue: refusal.target, + // The declaration is the dataset's, not a row's; no row was attempted. + recordIndex: 0, + message: refusal.message, + })); + // No log line of its own: the refusal is handed to the caller, which + // reports a failed load's errors (AGENTS.md, degradation log levels). + return this.buildResult(config, graph, [], errors, durationMs); + } + private findCycles(nodes: ObjectDependencyNodeParsed[]): string[][] { const cycles: string[][] = []; const nodeMap = new Map(nodes.map(n => [n.object, n])); @@ -4834,6 +5031,13 @@ export class SeedLoaderService implements ISeedLoaderService { // Internal Types // ========================================================================== +/** [Seed.dependsOn] One declaration a load refuses: `object` named `target`. */ +interface DeclaredDependencyRefusal { + readonly object: string; + readonly target: string; + readonly message: string; +} + /** * Structural view of objectql's `SummaryRecomputeError` (framework#3147). * diff --git a/packages/qa/dogfood/test/seed-depends-on-33812.dogfood.test.ts b/packages/qa/dogfood/test/seed-depends-on-33812.dogfood.test.ts new file mode 100644 index 00000000000..40d89cd1adb --- /dev/null +++ b/packages/qa/dogfood/test/seed-depends-on-33812.dogfood.test.ts @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// `Seed.dependsOn`, end to end: a stack's seed datasets, booted through the +// real composition (AppPlugin's boot seed → SeedLoaderService → ObjectQL → +// the sandboxed `beforeInsert` hook → the driver), read back over REST. +// +// ## What was broken +// +// The seed loader orders datasets by the lookup / master_detail / user edges +// between their objects, and the authored `data` order only breaks ties. A +// dataset whose insert-time hook READS another seeded object had no way to say +// so. Here a rating looks up its rule only, while the bands it is scored from +// sit two master_detail hops below the rule, so the rating is ready a wave +// before the bands: its hook ran against an empty band table, and every +// seeded rating scored as if no band existed — though `data` lists the bands +// first. +// +// ## What these cases pin +// +// Two rating objects with the same hook and the same lookup, seeded by the +// same boot. The one whose dataset declares `dependsOn: ['dod_band']` is +// written after the bands, and its hook counts both; the one that declares +// nothing keeps the order the lookups give, before the bands, and counts none +// (an app that declares no `dependsOn` keeps today's order). The loader's +// refusals (a name the load does not seed, an edge that closes a cycle) are +// pinned in-process: `packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts`. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { ObjectSchema, Field, defineSeed } from '@objectstack/spec/data'; + +const SCORE_SOURCE = + "const bands = await ctx.api.object('dod_band').find({}); ctx.input.bands_seen = bands.length;"; + +const DodRule = ObjectSchema.create({ + name: 'dod_rule', + label: 'Rule', + sharingModel: 'public_read_write', + fields: { name: Field.text({ label: 'Name', required: true }) }, +}); +const DodItem = ObjectSchema.create({ + name: 'dod_item', + label: 'Item', + sharingModel: 'public_read_write', + fields: { name: Field.text({ label: 'Name', required: true }), rule: Field.masterDetail('dod_rule', { label: 'Rule' }) }, +}); +const DodBand = ObjectSchema.create({ + name: 'dod_band', + label: 'Band', + sharingModel: 'public_read_write', + fields: { name: Field.text({ label: 'Name', required: true }), item: Field.masterDetail('dod_item', { label: 'Item' }) }, +}); +const rating = (name: string, label: string) => ObjectSchema.create({ + name, + label, + sharingModel: 'public_read_write', + fields: { + name: Field.text({ label: 'Name', required: true }), + rule: Field.lookup('dod_rule', { label: 'Rule' }), + bands_seen: Field.number({ label: 'Bands seen' }), + }, +}); +const DodRating = rating('dod_rating', 'Rating'); +const DodRatingPlain = rating('dod_rating_plain', 'Rating (no dependsOn)'); + +const scoreHook = (name: string, object: string) => ({ + name, + object, + events: ['beforeInsert'], + body: { language: 'js', source: SCORE_SOURCE, capabilities: ['api.read'] }, +}); + +const dodStack = defineStack({ + manifest: { + id: 'com.dogfood.seed-depends-on', + namespace: 'dod', + version: '0.0.0', + type: 'app', + name: 'Seed dependsOn Fixture', + description: 'A seeded rating whose insert hook reads seeded bands that no lookup orders it after.', + }, + objects: [DodRule, DodItem, DodBand, DodRating, DodRatingPlain], + hooks: [scoreHook('dod_rating_score', 'dod_rating'), scoreHook('dod_rating_plain_score', 'dod_rating_plain')], + // Authored bands-first, which on its own never ordered anything. + data: [ + defineSeed(DodRule, { records: [{ name: 'R1' }] }), + defineSeed(DodItem, { records: [{ name: 'I1', rule: 'R1' }] }), + defineSeed(DodBand, { records: [{ name: 'B1', item: 'I1' }, { name: 'B2', item: 'I1' }] }), + defineSeed(DodRating, { dependsOn: ['dod_band'], records: [{ name: 'C1', rule: 'R1' }] }), + defineSeed(DodRatingPlain, { records: [{ name: 'P1', rule: 'R1' }] }), + ], +} as any); + +describe('dogfood: Seed.dependsOn orders a seeded dataset after the objects its hook reads', () => { + let stack: VerifyStack; + let token: string; + + beforeAll(async () => { + stack = await bootStack(dodStack as never, {}); + token = await stack.signIn(); + }, 240_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + const rows = async (object: string): Promise => { + const res = await stack.apiAs(token, 'GET', `/data/${object}`); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(200); + return body.records ?? body.data ?? []; + }; + + it('the bands were seeded', async () => { + expect((await rows('dod_band')).map((r) => r.name).sort()).toEqual(['B1', 'B2']); + }); + + it('the card: the rating that declares dependsOn its bands is written after them, and its hook sees both', async () => { + const [row] = await rows('dod_rating'); + expect(row?.name).toBe('C1'); + expect(row?.bands_seen).toBe(2); + }); + + it('control: the rating that declares nothing keeps the lookup order — written before the bands, it sees none', async () => { + const [row] = await rows('dod_rating_plain'); + expect(row?.name).toBe('P1'); + expect(row?.bands_seen).toBe(0); + }); +}); diff --git a/packages/runtime/src/app-plugin.ts b/packages/runtime/src/app-plugin.ts index 8cfc804d00a..d8a3078d1c7 100644 --- a/packages/runtime/src/app-plugin.ts +++ b/packages/runtime/src/app-plugin.ts @@ -2194,12 +2194,21 @@ export class AppPlugin implements Plugin { // that, at every level; framework#4012 fixed that half, but // the level gate below is what still hides these.) One // labelled entry per config app. + // + // A load the loader REFUSED before any dataset ran (a + // `Seed.dependsOn` it cannot honour) wrote no row, so + // every row counter is zero and the refusal lives only in + // `errors[]`. Counted as rejected, one per error — the + // shape the marketplace sample-data heal records + // (`rejected: summary.errors`) — so the banner's `Seeds:` + // row and the settled message say the seed failed. + const refusedLoad = !result.success && result.results.length === 0 ? result.errors.length : 0; recordSeedOutcome(ctx, { source: String(appId), inserted: totalInserted, updated: totalUpdated, skipped: totalSkipped, - rejected: totalErrored, + rejected: totalErrored + refusedLoad, droppedRefs: totalRefsDropped, }); if (result.success) { diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index e325f1c326f..f99d4facb2d 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -942,6 +942,7 @@ "data/Seed:_packageVersion", "data/Seed:_provenance", "data/Seed:columns", + "data/Seed:dependsOn", "data/Seed:env", "data/Seed:externalId", "data/Seed:files", diff --git a/packages/spec/liveness/seed.json b/packages/spec/liveness/seed.json index 9f300d11695..1eddc78372e 100644 --- a/packages/spec/liveness/seed.json +++ b/packages/spec/liveness/seed.json @@ -52,6 +52,13 @@ "producer": "packages/runtime/src/app-plugin.ts#resolveSeedLocale (AppPlugin resolves the load-time locale ITSELF off the app's declared `i18n.defaultLocale` — the same ENVELOPE key, read the same way `loadTranslations` reads it for `setDefaultLocale` — and threads it into all THREE `SeedLoaderRequest`s this plugin builds: the inline boot seed, the per-org replayer registered for tenant provisioning, and the dev hot-reload seeder. A blank or undeclared `defaultLocale` sends NO `locale` key rather than an `'en'` default, because absence is the loader's unrestricted spelling and a default would have turned a wiring change into a data change)", "note": "FLIPPED experimental → live 2026-09-09 by #16595, which supplied the missing PRODUCER. The consumer half (#16510 / PR #16592) was always closed and tested; what was missing was the second input the effect depends on, `SeedLoaderConfig.locale`, which no first-party call site passed — so `filterByLocale` returned its input on its first line and `dataset.locale` was never read at all on the default boot path. That is the same shape `Seed.env` was in before framework#4704, which is why this row was recorded as `experimental` instead of published `live` on a correct-but-insufficient consumer pointer (#4837). EVIDENCE FOR THE FLIP, and it is a NEGATIVE leg rather than a green suite: `packages/runtime/src/app-plugin.seed-locale-producer.test.ts` asserts on the rows that reach the engine, not on the request object, and an ablation that neutralises `resolveSeedLocale` (returning `undefined`) turns 5 of its 7 cases red in the inert direction — a `locale: ['zh-CN']` dataset loads on an `en` stack. All three of this plugin's call sites go red, so the pin covers each one. ⚠️ WHAT THIS `live` ASSERTS, AND WHAT IT DOES NOT — read this before citing the row. It ASSERTS the ledger's own criterion and nothing wider: authoring `locale` changes runtime behaviour, on the boot path a `defineStack()` app actually boots through, and the `producer` field names the code that makes that true. ⛔ It does NOT assert that every path which can reach `SeedLoaderService.load()` supplies a locale — two do not, they are named below, and a reader who takes `live` as \"the axis is honoured everywhere\" is reading something this row does not say. That is the distinction between this row and the #4837 specimen one entry up: `Seed.env` was `live` while ZERO of six call sites supplied it, so authoring the key changed nothing anywhere and the verdict was false in the only sense the criterion has. Here it is true, and bounded, and the bound is written down. ⚠️ THE SCOPE OF THIS `live`, stated rather than left to be discovered: this repo has SIX request builders, the same six the `env` row one entry up enumerates. FOUR supply a locale, each named by the function that builds its request: (1) packages/runtime/src/app-plugin.ts#start, the inline boot seed (single-tenant boot) — the app's declared `i18n.defaultLocale`, read by `resolveSeedLocale`; (2) packages/runtime/src/app-plugin.ts#registerHotReloadSeeder, the dev hot-reload seeder — the same `resolveSeedLocale`, off the boot bundle; (3) packages/runtime/src/app-plugin.ts#start, the per-organization replayer it registers as `seed-replayer` for tenant provisioning — `resolveSeedLocaleForLoad` (packages/runtime/src/seed-locale.ts), resolved per organization at replay time: the organization's `localization.locale` setting when somebody set it (a `source: 'default'` answer does not count), then the founder's `sys_user.locale`, then the app's `i18n.defaultLocale`; (4) packages/cloud-connection/src/marketplace-install-local-plugin.ts#runInlineSeed, one builder behind four paths, all through `resolveSeedLocaleForLoad` — the marketplace install and the sample-data reseed (`applySideEffects`: the setting, then the installing or reseeding user's `sys_user.locale`, then the package's declared `i18n.defaultLocale`), the restart heal (`maybeHealSampleData`: no organization and no user, so the setting as read for a load naming no organization, then the package's default) and this plugin's own per-organization replayer (`buildSeedReplayer`, registered only where no `AppPlugin` replayer already is: the setting, then the founder, and no app-default rung, because its shared list is every installed package's datasets). #16595 wired (1)–(3) in `packages/runtime/src/app-plugin.ts` — the default boot path, which is what makes authoring `locale` change runtime behaviour and therefore what makes this row `live` — and PR #30346 (`Fixes #30281`, merged 2026-11-05) moved (3) onto `resolveSeedLocaleForLoad`, keeping `resolveSeedLocale` as its last rung, and wired (4). A builder whose source answers nothing sends no `locale` key, never an `'en'` guess. TWO are publish-time paths and still pass no locale: (5) packages/runtime/src/domains/packages.ts#applyPublishedSeeds (package apply) and (6) packages/metadata-protocol/src/protocol-publish-batch.ts#applySeedBodies (draft publish — the body `packages/metadata-protocol/src/protocol.ts#applySeedBodies` delegates to; the request moved out of `protocol.ts` with it). Neither is handed the stack config, and neither passes `env` either, so this is the SAME frontier the `live` `env` row already sits behind rather than a new one — but `env` crosses it because `resolveEnvConfig` can read an ambient `NODE_ENV` inside `load()`, and a locale has no ambient source inside `load()`, so it cannot be closed the same way: the four builders that supply one resolve it at the call site. RULED 2026-09-10 on #17011 (director seat, one-class self-adjudication, option A 「不扩散」): publish and install are locale-neutral acts, so this bound is the CONTRACT rather than an open defect — 「无违约、非缺陷」, because `content/docs/data-modeling/seed-data.mdx` already declared that these three paths load every dataset and warn. What the ruling ordered was wording, not wiring: `SeedSchema.locale`'s describe and that docs page now state the bound, and ⛔ no behaviour changed on the three sites — making them pass a locale (option B) and turning the warning into a refusal (option C) were both explicitly ⛔ not ruled. So this line is a DECISION, not a to-do. ⚠️ NARROWED 2026-11-05 — the ruling above is kept as it was recorded, and its \"three paths\" and \"three sites\" are the 2026-09-10 set, marketplace install included. A maintainer ruling on #30281 (2026-11-05, option A, reversing #17011's install-path bound) ordered the install paths to pick datasets by locale, on HotCRM's request for zh-CN demo data rather than through the measurement the premise below names; PR #30346 (`Fixes #30281`, merged 2026-11-05) carried it out and moved the marketplace-install path, builder (4) above, across that bound. The ruling's bound now covers package apply and draft publish only — builders (5) and (6) — and `SeedSchema.locale`'s describe (PR #30604) and that docs page state it narrowed the same way. ⚠️ THE RULING'S LOAD-BEARING PREMISE, and the one thing that reopens it: real first-party seed data using `locale`, measured repo-wide, is ZERO — re-derived 2026-09-22 against 1f53b0b685 by a structural scan of all 49 `defineSeed` call sites (24 of them real app data in `examples/`, none declaring `locale`), self-lit because the same scan does find the two `locale`-declaring call sites on the docs page. That reach is THIS repo only; cloud / hotcrm / external customer apps stay unmeasured. A measured use of `locale`-scoped seed data in any of them reopens this as option B. ⚠️ AND THEREFORE `SeedLoaderService#warnOnUnresolvedLocaleScope` STAYS (the judgement #16595 was asked to make, decided with its reason recorded here rather than deleted silently): it is not a signpost for an unwired state that has now gone away. It is the live diagnostic for the two call sites above that pass none (package apply, draft publish), for any embedding host that builds its own request, for a stack that declares no `i18n` block (the boot seed and the dev hot-reload seeder have no other source), and, since 2026-11-05, for an install, reseed, heal or replay on which no rung of `resolveSeedLocaleForLoad` answers — all of which still reach `load()` with locale-scoped datasets and no `config.locale`. Deleting it would make exactly those paths silently inert, which is the property this row spent a release being. REPOINTED while flipping: the pre-flip text of this note named four call sites (the three in app-plugin.ts plus draft publish) and called the `protocol.ts` one unconfirmed. Re-derived against `main` at bb7d91f19f: the `protocol.ts` site is REAL — the earlier negative came from grepping `seedLoader.load`, and that call site names its local `loader` — and the enumeration was short by two (package apply, marketplace install). The full set is the six named above, found by scanning `SeedLoaderRequestSchema` rather than a variable name. RE-COUNTED 2026-11-05 against b8929f48 by the same scan of production `SeedLoaderRequestSchema` parses: still SIX builders, the six named above, with the draft-publish request now built in `protocol-publish-batch.ts`. A control scan of every `new SeedLoaderService(` finds no seventh: its three other constructions, in the marketplace plugin's sample-data scope, purge and count reads (`sampleDataInScope`, `handlePurge`, `handleSampleDataCount`), call only `buildDependencyGraph` and never `load()`." }, + "dependsOn": { + "status": "live", + "verifiedAt": "2026-11-16", + "evidenceScope": "in-repo", + "evidence": "packages/metadata-protocol/src/seed-loader.ts#collectDeclaredDependencies (`dataset.dependsOn ?? []` — the one read of the key, once per load: each name becomes a declared edge pooled per object, or a refusal when it names the dataset's own object or an object no dataset of the load seeds); packages/metadata-protocol/src/seed-loader.ts#buildDependencyGraph (the declared edges join the node's `dependsOn` beside the lookup edges, so `topologicalSort` and `orderDatasets` order the dataset after the named objects); packages/metadata-protocol/src/seed-loader.ts#findDeclaredEdgeCycles (a declared edge that closes a cycle of the combined graph refuses the load before any row is written)", + "note": "Seeded 2026-11-16 (maintainer ruling recorded on the card, option 「新增 dependsOn 显式声明」, with review edits E1/E2). Names OBJECTS, not datasets, because the graph node is the object (`orderDatasets` keys on `dataset.object`). An app that declares none keeps the order the lookup edges give, byte for byte (the control case of the pins below). RUNTIME PROOF (ADR-0054): packages/qa/dogfood/test/seed-depends-on-33812.dogfood.test.ts boots a stack whose seeded rating's sandboxed `beforeInsert` hook counts seeded bands that no lookup orders it after, and reads the rows back over REST: the dataset declaring `dependsOn` sees both bands, the same dataset without it sees none. The ledger's `proof` field is not set: that form needs a `@proof:` tag registered in packages/spec/scripts/liveness/proof-registry.mts, whose classes are the ADR-0054 §2a high-risk list, and this key belongs to none of them. In-process pins of the refusals (unknown name, scoped-out name, own object, declared cycle; a lookup-only cycle still deferred): packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts. `defineSeed` refuses the own-object case when it runs (packages/spec/src/data/seed.zod.ts#assertSeedNotDependingOnItself)." + }, "records": { "status": "live", "verifiedAt": "2026-08-28", diff --git a/packages/spec/liveness/state-counts/seed.md b/packages/spec/liveness/state-counts/seed.md index 76912db6bb8..c6d098c3ec4 100644 --- a/packages/spec/liveness/state-counts/seed.md +++ b/packages/spec/liveness/state-counts/seed.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `seed` | 18 | 0 | 0 | 0 | 0 | 18 | +| `seed` | 19 | 0 | 0 | 0 | 0 | 19 | diff --git a/packages/spec/src/data/seed-loader.zod.ts b/packages/spec/src/data/seed-loader.zod.ts index fea17a62106..0cd7da1ec4c 100644 --- a/packages/spec/src/data/seed-loader.zod.ts +++ b/packages/spec/src/data/seed-loader.zod.ts @@ -72,14 +72,16 @@ export type ReferenceResolutionParsed = z.infer z.object({ /** Object machine name */ object: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Object name (snake_case)'), /** - * Objects that this object depends on (via lookup/master_detail fields). + * Objects that this object depends on: via its lookup / master_detail / + * user fields, plus the objects its datasets declare in `Seed.dependsOn`. * These must be loaded before this object. */ dependsOn: z.array(z.string()).describe('Objects this object depends on'), diff --git a/packages/spec/src/data/seed.test.ts b/packages/spec/src/data/seed.test.ts index 64b890581b1..4760d92f3c5 100644 --- a/packages/spec/src/data/seed.test.ts +++ b/packages/spec/src/data/seed.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { SeedSchema, SeedMode, SeedColumnSchema, type Seed } from './seed.zod'; +import { SeedSchema, SeedMode, SeedColumnSchema, defineSeed, type Seed } from './seed.zod'; import { ColumnApplyOnSchema } from './column-apply-on.zod'; import { FieldMappingEntrySchema } from '../api/export.zod'; @@ -373,3 +373,54 @@ describe('SeedSchema', () => { expect(largeDataset.records).toHaveLength(1000); }); }); + +/** + * `Seed.dependsOn` — the objects a dataset loads after. The schema holds each + * name to an object machine name; `defineSeed` refuses the one declaration it + * can judge alone (the dataset's own object). The refusals that need the whole + * load (a name the load does not seed, an edge that closes a cycle) are the + * seed loader's, pinned in `@objectstack/metadata-protocol` + * (`seed-loader-depends-on-33812.test.ts`). + */ +const Rating = { + name: 'crm_customer_rating', + fields: { name: { type: 'text' }, total_score: { type: 'number' } }, +} as const; + +describe('SeedSchema.dependsOn', () => { + it('is an authorable key: a list of object names parses and is kept', () => { + const parsed = SeedSchema.safeParse({ object: 'crm_customer_rating', records: [], dependsOn: ['crm_rating_band'] }); + expect(parsed.success).toBe(true); + expect(parsed.success && parsed.data.dependsOn).toEqual(['crm_rating_band']); + }); + + it('is optional, with no default: a seed without it parses to no key', () => { + const parsed = SeedSchema.safeParse({ object: 'crm_customer_rating', records: [] }); + expect(parsed.success).toBe(true); + expect(parsed.success && 'dependsOn' in parsed.data).toBe(false); + }); + + it('refuses a name that is not an object machine name', () => { + const parsed = SeedSchema.safeParse({ object: 'crm_customer_rating', records: [], dependsOn: ['CrmRatingBand'] }); + expect(parsed.success).toBe(false); + expect(!parsed.success && parsed.error.issues[0]?.path).toEqual(['dependsOn', 0]); + }); + + it('refuses a single string where the list belongs', () => { + const parsed = SeedSchema.safeParse({ object: 'crm_customer_rating', records: [], dependsOn: 'crm_rating_band' }); + expect(parsed.success).toBe(false); + expect(!parsed.success && parsed.error.issues[0]?.path).toEqual(['dependsOn']); + }); +}); + +describe('defineSeed: dependsOn', () => { + it('carries the declared objects onto the seed', () => { + const seed = defineSeed(Rating, { dependsOn: ['crm_rating_band'], records: [{ name: 'Acme' }] }); + expect(seed.dependsOn).toEqual(['crm_rating_band']); + }); + + it('refuses a dataset that names its own object, naming it', () => { + expect(() => defineSeed(Rating, { dependsOn: ['crm_customer_rating'], records: [{ name: 'Acme' }] })) + .toThrow(/defineSeed\('crm_customer_rating'\).*dependsOn/); + }); +}); diff --git a/packages/spec/src/data/seed.zod.ts b/packages/spec/src/data/seed.zod.ts index 4aa3958ab90..9eecbf3d9f2 100644 --- a/packages/spec/src/data/seed.zod.ts +++ b/packages/spec/src/data/seed.zod.ts @@ -312,6 +312,39 @@ export const SeedSchema = lazySchema(() => strictObject({ locale: z.array(LocaleSchema).min(1).optional() .describe('Applicable locales (BCP-47 tags); omitted applies to every locale. The boot seed filters on the app\'s i18n.defaultLocale; the marketplace install, sample-data reseed, restart heal and per-organization replay filter on the locale resolved for the load (the localization.locale setting when set, then the locale of the installing, reseeding or founding user, then the app\'s i18n.defaultLocale where the load names one); package apply and draft publish do not filter by locale — they load every dataset and warn'), + /** + * Load-Order Dependencies + * + * The objects this dataset must be loaded after, by object name — for a + * dependency no field expresses: most often a lifecycle hook on this object + * (`beforeInsert`) that reads another seeded object while the row is + * written, e.g. a rating scored from seeded bands: + * `defineSeed(CustomerRating, { dependsOn: ['crm_rating_band'], records })`. + * + * A load orders its datasets by the dependency graph of their objects: + * a `lookup` / `master_detail` / `user` field already makes its object load + * after the one it points at, and the order the datasets are written in + * only breaks ties between objects ready at the same moment. Each name here + * adds one more edge to that same graph, so this dataset's object lands + * after the named object's rows. A dataset that declares none keeps the + * order the fields alone give. + * + * Every name must be an object another dataset of the same load seeds. The + * loader refuses the whole load, writing no row, when a name is this + * dataset's own object, when no dataset of the load seeds it (a misspelling, + * or a dataset that `env` / `locale` scoped out of this load), or when the + * edge closes a cycle with the other edges (lookup fields included). A cycle + * made of lookup fields alone is still loaded in several passes, as before. + * `defineSeed` refuses a dataset that names its own object when it runs. + */ + dependsOn: z.array(z.string().regex(/^[a-z_][a-z0-9_]*$/)).optional() + .describe( + 'Objects (by name) this dataset loads after, for an order no lookup field gives — e.g. a beforeInsert ' + + 'hook that reads another seeded object. Each name adds an edge to the load\'s dependency graph. The load ' + + 'is refused, writing nothing, when a name is the dataset\'s own object, is not seeded by another dataset of ' + + 'the same load, or closes a cycle with the other edges. Omitted, the order comes from lookup fields alone.', + ), + /** * The Payload * Array of raw JSON objects matching the Object Schema. @@ -541,6 +574,9 @@ function assertSeedFilesOnFileFields( * The keys of {@link SeedSchema.shape.columns} are held to the same set, both * times ({@link SeedColumns}). * + * A `dependsOn` that names the dataset's own object is refused when it runs + * ({@link SeedSchema.shape.dependsOn}). + * * A `seedFile(path)` value is refused when it runs on a field that is not a * file field (`file`, `image`, `avatar`, `video`, `audio`) — see * {@link SeedSchema.shape.files} for how the bytes reach the loader. @@ -573,5 +609,24 @@ export function defineSeed< const seed = SeedSchema.parse({ ...config, object: objectDef.name }); assertSeedKeysDeclared(objectDef, seed.records, seed.columns); assertSeedFilesOnFileFields(objectDef, seed.records); + assertSeedNotDependingOnItself(objectDef, seed.dependsOn); return seed; } + +/** + * The call-time half of the load's `dependsOn` refusals: the one a dataset + * can be judged on alone. A dataset that names its own object asks to load + * after itself, which no order satisfies. The other two refusals (a name no + * dataset of the load seeds, an edge that closes a cycle) need the whole load, + * so only the seed loader can make them. + */ +function assertSeedNotDependingOnItself( + objectDef: { name: string }, + dependsOn: readonly string[] | undefined, +): void { + if (!dependsOn?.includes(objectDef.name)) return; + throw new Error( + `defineSeed('${objectDef.name}'): dependsOn names the dataset's own object '${objectDef.name}'. ` + + 'A dataset cannot load after itself: list the other seeded objects its hooks read, or drop the entry.', + ); +} diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 7013c2223f8..59ec53804c2 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -11,6 +11,16 @@ "verb": "delete", "pinned": 1 }, + { + "file": "packages/cli/src/commands/serve-seed-refused-load-33812.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/cli/src/commands/serve-seed-refused-load-33812.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/cli/src/utils/organization-ownership-apply.test.ts", "verb": "delete", @@ -2421,6 +2431,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/seed-loader-depends-on-33812.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/seed-loader-driver-text.test.ts", "verb": "delete",