Skip to content

Commit f02c522

Browse files
committed
wip(spec,metadata-protocol): seed dataset column applyOn create-only
Claude-Session: https://claude.ai/code/session_018HE4VY52U3L5Bfzz51dsFv Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5f5f0b4 commit f02c522

5 files changed

Lines changed: 236 additions & 21 deletions

File tree

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

Lines changed: 90 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,22 @@ function seedValuesInStoredForm(record: Record<string, unknown>, definition: unk
480480
}
481481
}
482482

483+
/**
484+
* [#25761] The columns a dataset writes only when it CREATES the row — those
485+
* its `columns` map declares `applyOn: 'create'` — minus the fields of its
486+
* `externalId`. A key field is what a matched row was found by, so it stays in
487+
* that row's write whatever it declares, as an import's match key stays
488+
* (`FieldMappingEntry.applyOn`, the same policy at the import door).
489+
*/
490+
function createOnlySeedColumns(dataset: Seed, externalId: string | string[]): ReadonlySet<string> {
491+
const keyFields = new Set(Array.isArray(externalId) ? externalId : [externalId]);
492+
const createOnly = new Set<string>();
493+
for (const [column, policy] of Object.entries(dataset.columns ?? {})) {
494+
if (policy?.applyOn === 'create' && !keyFields.has(column)) createOnly.add(column);
495+
}
496+
return createOnly;
497+
}
498+
483499
/**
484500
* [#24562] Field name → storage kind, for every field the definition declares
485501
* `datetime`, `date` or `time` — the fields a replay compares in their STORED
@@ -1080,6 +1096,9 @@ export class SeedLoaderService implements ISeedLoaderService {
10801096
const objectName = dataset.object;
10811097
const mode = dataset.mode || config.defaultMode;
10821098
const externalId = dataset.externalId || 'name';
1099+
// [#25761] Left out of every write to a row this dataset MATCHED — see
1100+
// `matchesExistingRow` in the record loop below.
1101+
const createOnlyColumns = createOnlySeedColumns(dataset, externalId);
10831102

10841103
let inserted = 0;
10851104
let updated = 0;
@@ -1333,6 +1352,7 @@ export class SeedLoaderService implements ISeedLoaderService {
13331352
// judge, and nothing here refuses a row for an owner it cannot prove.
13341353
const objectDefinition = await this.resolveObjectDefinition(objectName);
13351354
const rowsCarryOrganization = objectDefinition == null || seedRowNeedsOrganization(objectDefinition);
1355+
this.warnOnUndeclaredSeedColumns(dataset, objectDefinition);
13361356
// How a replay compares each field (`isNoOpReplay`): [#24562] a temporal
13371357
// field in its stored form, [#24624] a field the read path masks never by
13381358
// its set value.
@@ -1572,14 +1592,43 @@ export class SeedLoaderService implements ISeedLoaderService {
15721592
});
15731593
}
15741594

1575-
const recordRefs: Array<
1595+
/**
1596+
* [#25761] Is this row one the load MATCHED — an existing row this
1597+
* dataset writes over? The create-only policy is the only thing that
1598+
* asks. The same lookup {@link SeedLoaderService.decideWriteAction}
1599+
* makes: the record's natural key, as resolved so far, against the rows
1600+
* pre-loaded for the modes that match one (`upsert`, `update`,
1601+
* `ignore`). A dry run and the `insert` / `replace` modes pre-load
1602+
* nothing, so every row they see is one they create.
1603+
*/
1604+
const matchesExistingRow = (): boolean =>
1605+
existingRecords?.has(this.externalIdKey(record, externalId)) === true;
1606+
1607+
const allRecordRefs: Array<
15761608
Pick<ReferenceResolutionParsed, 'field' | 'targetObject' | 'targetField'> & { multiple?: boolean }
15771609
> = derivedPointerRefs.length === 0 ? objectRefs : [...objectRefs, ...derivedPointerRefs];
1610+
// [#25761] Create-only references resolve LAST, so a reference column of
1611+
// the externalId has been resolved by the time one asks
1612+
// `matchesExistingRow`. Every other dataset keeps its order.
1613+
const recordRefs = createOnlyColumns.size === 0
1614+
? allRecordRefs
1615+
: [
1616+
...allRecordRefs.filter((ref) => !createOnlyColumns.has(ref.field)),
1617+
...allRecordRefs.filter((ref) => createOnlyColumns.has(ref.field)),
1618+
];
15781619
for (const ref of recordRefs) {
15791620
// Never re-resolve the tenant stamp we just wrote (see above). A seed
15801621
// that authors `organization_id` ITSELF still goes through resolution,
15811622
// so naming an org by its natural key keeps working.
15821623
if (stampedTenantOrg && ref.field === 'organization_id') continue;
1624+
// [#25761] A create-only reference on a row the load matched is no
1625+
// part of that row's write: not resolved, not dropped for failing to
1626+
// resolve, and not deferred — pass 2's back-fill would write it after
1627+
// all, the one place the policy could leak.
1628+
if (createOnlyColumns.has(ref.field) && matchesExistingRow()) {
1629+
delete record[ref.field];
1630+
continue;
1631+
}
15831632
const fieldValue = record[ref.field];
15841633
// A blank reference is NO reference: the engine's blank rule
15851634
// (`isMissing` — `undefined`, `null`, `''`, whitespace-only) is the one
@@ -1809,6 +1858,15 @@ export class SeedLoaderService implements ISeedLoaderService {
18091858
continue;
18101859
}
18111860

1861+
// [#25761] The create-only columns leave a matched row's write here, so
1862+
// every write path below sees the same record: the no-op replay check
1863+
// compares without them (a value a job has changed since is not a
1864+
// difference the seed means to undo), and the update writes without
1865+
// them. A row the load creates keeps them all.
1866+
if (createOnlyColumns.size > 0 && matchesExistingRow()) {
1867+
for (const column of createOnlyColumns) delete record[column];
1868+
}
1869+
18121870
// [commit 1cba33f16] EARLY SIGNAL — emitted here, before this row reaches the
18131871
// engine, for the deferrals it took on columns the write contract
18141872
// requires on INSERT.
@@ -3162,6 +3220,37 @@ export class SeedLoaderService implements ISeedLoaderService {
31623220
);
31633221
}
31643222

3223+
/**
3224+
* [#25761] Say so, once per dataset, when its `columns` map names a column
3225+
* the object does not have.
3226+
*
3227+
* Such a policy governs nothing, and nothing else reports it: no row writes
3228+
* the named column, so the engine never refuses it the way it refuses an
3229+
* unknown record key. The column it was meant for (a misspelt `status`)
3230+
* keeps `always`, and every replay re-asserts it. `defineSeed` refuses the
3231+
* key when it runs; this is the same check for a seed that did not come
3232+
* through it (stored `seed` metadata, a package body). Judged against the
3233+
* set `defineSeed` uses — the declared fields plus the system columns the
3234+
* platform injects on this object — and only when the definition resolved
3235+
* with a field map: no opinion without one.
3236+
*/
3237+
private warnOnUndeclaredSeedColumns(dataset: Seed, definition: unknown): void {
3238+
const columns = Object.keys(dataset.columns ?? {});
3239+
if (columns.length === 0) return;
3240+
const fields = (definition as { fields?: unknown } | null | undefined)?.fields;
3241+
if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return;
3242+
const known = new Set<string>([...Object.keys(fields), ...resolveInjectedSystemColumns(definition).names]);
3243+
const undeclared = columns.filter((column) => !known.has(column));
3244+
if (undeclared.length === 0) return;
3245+
this.logger.warn(
3246+
`[SeedLoader] The ${dataset.object} seed declares a write policy for ${undeclared.map((c) => `\`${c}\``).join(', ')}, ` +
3247+
`which ${undeclared.length === 1 ? 'is not a column' : 'are not columns'} of ${dataset.object}: the policy governs ` +
3248+
`nothing, and a column it was meant for keeps \`applyOn: 'always'\`, re-asserted on every replay. Name a ` +
3249+
`field ${dataset.object} declares, or a system column the platform injects on it, as the \`columns\` key.`,
3250+
{ object: dataset.object, undeclaredColumns: undeclared },
3251+
);
3252+
}
3253+
31653254
/**
31663255
* Drop datasets that do not apply to this load, on every scope axis.
31673256
*

‎packages/spec/src/api/export.zod.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { z } from 'zod';
44
import { BaseResponseSchema } from './contract.zod';
55
import { ValidateDataIssueSchema } from './protocol.zod';
66
import { DroppedFieldsEventSchema } from '../data/data-engine.zod';
7+
import { ColumnApplyOnSchema } from '../data/column-apply-on.zod';
78

89
/**
910
* Data Export & Import Protocol
@@ -170,7 +171,7 @@ export const FieldMappingEntrySchema = lazySchema(() => z.object({
170171
.describe('Default value if source field is null/empty'),
171172
required: z.boolean().default(false)
172173
.describe('Whether this field is required (import validation)'),
173-
applyOn: z.enum(['create', 'always']).default('always')
174+
applyOn: ColumnApplyOnSchema.default('always')
174175
.describe(
175176
'When an import writes this column. `always` (default) writes it on every row the import ' +
176177
'creates or updates. `create` writes it only when the row is created: an `upsert` that ' +
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { z } from 'zod';
4+
5+
/**
6+
* Column Apply-On Policy — when a write door that matches rows by a natural
7+
* key writes a column.
8+
*
9+
* - `always` writes the column on every row the door creates or updates.
10+
* - `create` writes it only when the door creates the row. On a row the door
11+
* matched, the column is left out of the update, so the value the row holds
12+
* (one a job or a person wrote since) stays.
13+
*
14+
* One vocabulary for both doors that upsert by a natural key, so a column means
15+
* the same thing whichever door loads it: an import mapping entry
16+
* (`FieldMappingEntry.applyOn`, #25577) and a seed dataset column
17+
* (`SeedColumn.applyOn`, #25761). Each door declares its own default on its own
18+
* key (`always` on both), and neither spells the values a second time.
19+
*/
20+
export const ColumnApplyOnSchema = z.enum(['create', 'always'])
21+
.describe('When a matched-row write door writes a column: `always` on create and update, `create` on create only');
22+
23+
export type ColumnApplyOn = z.infer<typeof ColumnApplyOnSchema>;

‎packages/spec/src/data/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,10 @@ export * from './driver.zod';
231231
export * from './driver-sql.zod';
232232
export * from './driver-nosql.zod';
233233

234+
// [#25761] The one `create` / `always` vocabulary of a column's apply-on
235+
// policy, shared by the seed dataset column (`seed.zod`) and the import
236+
// mapping entry (`api/export.zod`), so neither door spells it twice.
237+
export * from './column-apply-on.zod';
234238
export * from './seed.zod';
235239

236240
// Form Layouts

0 commit comments

Comments
 (0)