// `seedGraph(entities, { tenants, perTable, seed })`: rows for every table, in an order every foreign // key accepts, each child pointing at a parent of its OWN tenant, every value storable and every // declared rule kept. Pure: it returns the plan, `insertSeedGraph` writes it. Same seed, same bytes. import { finiteCount, finiteOption, fnv1a, systemClock } from '@ultimat3/core'; import type { ReferenceDescription } from '@ultimat3/entity'; import { DEFAULT_SEED, seededUuid } from './determinism'; import { seedGraphUnsatisfied } from './seed-graph-error'; import { edgeKey, insertOrder } from './seed-graph-order'; import { partitionWindow, valuesInWindow } from './seed-graph-partition'; import { declaredPatterns } from './seed-graph-patterns'; import type { SeedCanary, SeedGraph, SeedGraphOptions, SeedRow, SeedUpdate, } from './seed-graph-plan'; import { type RowProblem, solveRow, uniqueKey } from './seed-graph-row'; import { type EntityShape, type SeedEntity, shapeOf } from './seed-graph-shape'; import { candidatesFor, storable } from './seed-graph-values'; interface Placed { readonly tenant: string | null; readonly row: Record; readonly index: number; } const streamSeed = (seed: number, name: string): number => fnv1a(`${seed}:${name}`) || 1; const rotate = (values: readonly T[], by: number): T[] => values.map((_, i) => values[(i + by) % values.length] as T); const keyOf = (entity: SeedEntity, row: Readonly>) => Object.fromEntries(entity.$primaryKey.map((property) => [property, row[property]])); /** * Every entity whose rows belong to one tenant: a tenant column, a tenant root, or — with neither — * a reference path to one that is not cut by `shared`. The last kind is seeded per tenant under * its own tenant's parent, so the tenant proof has a row of each instance to attack it through. */ function ownedByTenant( shapes: ReadonlyMap, roots: ReadonlyMap, ): ReadonlySet { const owned = new Set(); for (const shape of shapes.values()) { if (roots.has(shape.name) || shape.entity.$tenantColumn !== null) owned.add(shape.name); } // A fixpoint over references: a grandchild is owned through its owned child. for (let grew = true; grew; ) { grew = false; for (const shape of shapes.values()) { if (owned.has(shape.name) || shape.entity.$describe().shared !== undefined) continue; const reaches = [...shape.references.values()].some( (reference) => reference.targetEntity !== shape.name && owned.has(reference.targetEntity), ); if (reaches) { owned.add(shape.name); grew = true; } } } return owned; } /** * Every untenanted entity (`shared`, or of no tenant) a tenant-owned table points at through a key * unique across the TABLE — a unique set holding the reference and not the tenant column. Each * tenant's children then take parent rows no other tenant may reuse, so the parent seeds * `perTable` rows per tenant: `perTable` alone ran out before tenant 2 (`X_SEED_GRAPH_UNSATISFIED`). */ function fannedOut( shapes: ReadonlyMap, scoped: (name: string) => boolean, ): ReadonlySet { const out = new Set(); for (const shape of shapes.values()) { if (!scoped(shape.name)) continue; const tenantColumn = shape.entity.$tenantColumn; const tableWide = [...shape.uniques, ...shape.partialUniques].filter( (set) => tenantColumn === null || !set.includes(tenantColumn), ); for (const reference of shape.references.values()) { if (scoped(reference.targetEntity) || reference.targetEntity === shape.name) continue; if (tableWide.some((set) => set.includes(reference.property))) { out.add(reference.targetEntity); } } } return out; } export function seedGraph( entities: Readonly>, options: SeedGraphOptions = {}, ): SeedGraph { const seed = finiteOption('seedGraph', 'seed', options.seed ?? DEFAULT_SEED); const tenantCount = finiteCount('seedGraph', 'tenants', options.tenants ?? 2, 1); const perTable = finiteCount('seedGraph', 'perTable', options.perTable ?? 3, 1); const anchor = options.now ?? systemClock.now(); // A view entity is a relation Postgres derives: no row is ever written to it, so it is no part of // the graph (`X_ENTITY_VIEW_READ_ONLY` otherwise) — the tables it reads from carry the rows. A // history table is the same from this side: its trigger writes every row, from the parent's. // A `readOnly` table is the app's own statement that it writes no row there (a trigger refuses // every INSERT): seeded like a view, never — a reference into one is null or refused below. const closed = new Map( Object.values(entities).flatMap((entity) => { const reason = entity.$describe().readOnly; return reason === undefined ? [] : [[entity.$name, reason] as const]; }), ); const tables = Object.values(entities).filter((entity) => { const described = entity.$describe(); return ( described.view === undefined && described.historyOf === undefined && !closed.has(entity.$name) ); }); const shapes = new Map(tables.map((entity) => [entity.$name, shapeOf(entity)])); const { order, deferred } = insertOrder( [...shapes.values()].map((shape) => ({ name: shape.name, references: [...shape.references.values()], updatable: shape.entity.$describe().appendOnly !== true, })), ); const tenantStream = seededUuid(streamSeed(seed, '$tenants')); const tenants = Array.from({ length: tenantCount }, () => tenantStream()); // The entity a tenant column points at holds ONE row per tenant, keyed by the tenant itself. const roots = new Map(); for (const shape of shapes.values()) { const tenantColumn = shape.entity.$tenantColumn; const reference = tenantColumn === null ? undefined : shape.references.get(tenantColumn); if (reference !== undefined && reference.targetEntity !== shape.name) { roots.set(reference.targetEntity, reference.targetProperty); } } const owned = ownedByTenant(shapes, roots); const scoped = (name: string): boolean => owned.has(name); const fanned = fannedOut(shapes, scoped); for (const factory of Object.values(options.factories ?? {})) factory.reset(); const besideNext = options.beside?.next ?? {}; const next: Record = { ...besideNext }; const placed = new Map(); // The same rows by tenant: a pool read per row was a filter of the whole parent table, so a pass // seeding a tenant pair per primitive planned in primitives² time. const placedIn = new Map>(); /** * `memo`: one table's insert loop, where no placed row changes. A shared pool's rotation is the * same for every tenant's row at one index, and copying the whole pool per row was the second * quadratic of a pass seed (6 s of an adopter's 36 at 1,188 tenants). */ const parentValues = ( reference: ReferenceDescription, tenant: string | null, index: number, memo?: Map, ): unknown[] => { if (!shapes.has(reference.targetEntity)) return reference.nullable ? [null] : []; const own = tenant === null || !scoped(reference.targetEntity) ? null : tenant; const pool = own === null ? (placed.get(reference.targetEntity) ?? []) : (placedIn.get(reference.targetEntity)?.get(own) ?? []); // The length too: a table's own pool grows under its own loop. const key = `${reference.targetEntity}\u0000${reference.targetProperty}\u0000${String(reference.nullable)}\u0000${own ?? ''}\u0000${index}\u0000${pool.length}`; const known = memo?.get(key); if (known !== undefined) return known; const values = pool.length === 0 ? [] : rotate(pool, index).map((p) => p.row[reference.targetProperty]); const answer = reference.nullable ? [...values, null] : values; memo?.set(key, answer); return answer; }; const refuseEmpty = (shape: EntityShape, property: string, tenant: string | null): never => { const reference = shape.references.get(property); const reason = reference === undefined ? undefined : closed.get(reference.targetEntity); if (reference !== undefined && reason !== undefined) { throw seedGraphUnsatisfied({ entity: shape.name, what: `${property} references ${reference.targetEntity}, which is readOnly (${reason}): no row of it is seeded and ${property} is not nullable, so no ${shape.name} row can be written`, columns: [property], fix: `entity('${shape.name}', { readOnly: '' }) # when the app never writes ${shape.name} either — else ${property}: .nullable(), then x db gen "${shape.entity.$table} ${property} nullable"`, }); } throw seedGraphUnsatisfied({ entity: shape.name, what: reference === undefined ? `no generated value is storable in ${property} — its column refuses every one` : !shapes.has(reference.targetEntity) ? `${property} references ${reference.targetEntity}, which is not in the set seeded — pass it too` : `${property} references ${reference.targetEntity}, which has no row${tenant === null ? '' : ' in the same tenant'} to point at`, columns: [property], }); }; const inserts: SeedRow[] = []; const canaries: SeedCanary[] = []; for (const name of order) { const shape = shapes.get(name) as EntityShape; const entity = shape.entity; const stream = seededUuid(streamSeed(seed, name)); const factory = options.factories?.[name]; const rows: Placed[] = []; placed.set(name, rows); const byTenant = new Map(); placedIn.set(name, byTenant); const allUniques = [...shape.uniques, ...shape.partialUniques]; const taken = allUniques.map(() => new Set()); // A one-property set's string values beside its keys: the solver's skip list (`takenStrings`). const takenStrings = allUniques.map((set) => set.length === 1 ? new Set() : undefined, ); const rootProperty = roots.get(name); // Read once per table: each `matches(/…/)` an invariant holds a column to, sampled from. const patterns = declaredPatterns(entity); // A `partitionBy` column takes values from the bucket the migration made first (`anchor`'s). const description = entity.$describe(); const window = partitionWindow(description.partition, anchor); const partitioned = description.columns.find( (column) => column.column === description.partition?.column, ); const buckets: readonly (string | null)[] = scoped(name) ? tenants : [null]; // Positions continue past the graph written before this one: a reset factory rebuilt that // graph's first values, and a unique column refused the second copy. const start = besideNext[name] ?? 0; // Only a unique column needs the continued position. Every other value is drawn from the row's // place in THIS graph, so the scale sweep's 8-row graph opens on the 2-row graph's values and a // branch on the handed row takes one path at both sizes (`scale-sweep-branch.test.ts`). const uniqueColumns = new Set(allUniques.flat()); const pools = new Map(); for (let skipped = 0; factory !== undefined && skipped < start; skipped += 1) factory.build(); let ordinal = start; for (const [bucket, tenant] of buckets.entries()) { const size = rootProperty !== undefined ? 1 : fanned.has(name) ? perTable * tenantCount : perTable; for (let index = 0; index < size; index += 1) { ordinal += 1; next[name] = ordinal; const canary = stream().replace(/-/g, '').slice(0, 10); const built: Readonly> = factory === undefined ? {} : { ...factory.build() }; const columns = shape.columns.map(([property, column], position) => { const reference = shape.references.get(property); // The tenant key points at a root row only when the root is in the set: refused like any // other reference to an entity this graph does not seed. const candidates = property === entity.$tenantColumn && reference !== undefined && !shapes.has(reference.targetEntity) ? [] : property === entity.$tenantColumn || property === rootProperty ? [tenant] : property === shape.softDelete && !Object.hasOwn(built, property) ? [null] : reference !== undefined ? deferred.has(edgeKey(name, property)) ? [null] : parentValues(reference, tenant, index, pools) : Object.hasOwn(built, property) ? storable(column, [built[property]]) : window !== null && property === partitioned?.property ? storable( column, valuesInWindow(partitioned.kind, window, ordinal, position), ) : candidatesFor(property, column, { ordinal: uniqueColumns.has(property) ? ordinal : ordinal - start, canary, position, patterns: patterns.get(property), uuid: stream, }); return [ property, candidates.length === 0 ? refuseEmpty(shape, property, tenant) : candidates, ] as const; }); // A partial unique whose every column the factory built is the database's to judge. const held = allUniques .map((set, i) => [set, taken[i] as Set, takenStrings[i]] as const) .filter( ([set], i) => i < shape.uniques.length || !set.every((property) => Object.hasOwn(built, property)), ); const problem: RowProblem = { columns, checks: shape.checks, uniques: held.map(([set]) => set), taken: held.map(([, set]) => set), takenStrings: held.map(([, , values]) => values), derive: factory?.derive?.bind(factory), }; const solved = solveRow(problem); if (!solved.ok) { // A table whose unique values run out is full, not broken — as long as EVERY tenant holds a // row: a tenant left empty would leave its own children no parent to point at. if (solved.capacity && index > 0) break; throw seedGraphUnsatisfied({ entity: name, what: solved.capacity && rows.length > 0 ? `${solved.broken.join(', ')} runs out of values before tenant ${bucket + 1} of ${buckets.length} holds a row — it is unique across the table, not per tenant` : `no generated row keeps ${solved.broken.join(', ')}`, columns: solved.properties, }); } const row = { ...solved.row }; allUniques.forEach((set, i) => { const key = uniqueKey(row, set); if (key === undefined) return; taken[i]?.add(key); const value = row[set[0] as string]; if (typeof value === 'string') takenStrings[i]?.add(value); }); const one = { tenant, row, index }; rows.push(one); const bucketRows = byTenant.get(tenant); if (bucketRows === undefined) byTenant.set(tenant, [one]); else bucketRows.push(one); inserts.push({ entity: name, table: entity.$table, tenant, row: { ...row } }); canaries.push({ entity: name, tenant, key: keyOf(entity, row), marker: canary, columns: Object.keys(row).filter( (p) => typeof row[p] === 'string' && String(row[p]).includes(canary), ), }); } } } const updates: SeedUpdate[] = []; for (const name of order) { const shape = shapes.get(name) as EntityShape; // An appendOnly row is never updated (its trigger refuses): a key deferred there stays null. if (shape.entity.$describe().appendOnly === true) continue; const later = shape.columns.filter(([property]) => deferred.has(edgeKey(name, property))); if (later.length === 0) continue; for (const { tenant, row, index } of placed.get(name) ?? []) { const columns = shape.columns.map(([property]) => { const reference = shape.references.get(property); return reference !== undefined && deferred.has(edgeKey(name, property)) ? ([property, parentValues(reference, tenant, index)] as const) : ([property, [row[property]]] as const); }); const solved = solveRow({ columns, checks: shape.checks, uniques: [], taken: [] }); if (!solved.ok) { throw seedGraphUnsatisfied({ entity: name, what: `the key set after insert to close a cycle breaks ${solved.broken.join(', ')}`, columns: solved.properties, }); } const patch = Object.fromEntries( later.flatMap(([property]) => solved.row[property] === null ? [] : [[property, solved.row[property]]], ), ); if (Object.keys(patch).length === 0) continue; Object.assign(row, patch); updates.push({ entity: name, tenant, key: keyOf(shape.entity, row), patch }); } } return { seed, tenants, order, inserts, updates, canaries, next }; }