Skip to content

Commit 3585054

Browse files
committed
fix(core): the import dry run previews create rows in the commit's batches
The dry run asked the engine about each create row alone, so a child rule reading a parent roll-up (#25579) answered valid for a row the commit refuses. Create rows are now buffered like the commit's and previewed through one multi-row validate() per commit batch, in file order; update rows keep their per-row preview. The engine's multi-row preview now admits an insert row after the write's reference check, as insert() does. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5krDpBpMjEHKqjJ6u8
1 parent 1685a06 commit 3585054

4 files changed

Lines changed: 581 additions & 30 deletions

File tree

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26684] How the import dry run asks the engine for its verdicts: a create
5+
* row is previewed with the rows of the batch the commit would write it in,
6+
* in ONE `validateData` call, and an update row alone, as before.
7+
*
8+
* Driven against an `ImportProtocolLike` double that answers one verdict per
9+
* submitted row (the `ValidateDataResponse` contract) and records each call.
10+
* What the batch buys — a child rule reading a parent roll-up counting the
11+
* earlier rows — is pinned end to end over a real engine in
12+
* `packages/rest/src/import-dry-run-batch-parent-summary.test.ts`.
13+
*
14+
* Pinned here:
15+
* - the batches are the commit's: file order, the commit's checkpoints
16+
* (every `progressEvery` rows) and run length
17+
* (`Math.min(progressEvery, MAX_CREATE_BATCH_SIZE)`, 200);
18+
* - each row keeps its own report, at its own position, between update rows;
19+
* - an update row is asked alone, in `update` mode, as before;
20+
* - a batch the engine refuses outright is degraded as the commit degrades
21+
* one: each row alone, then the survivors together again.
22+
*/
23+
24+
import { describe, it, expect, vi } from 'vitest';
25+
import { runImport, type ImportProtocolLike } from './import-runner';
26+
import type { ExportFieldMeta } from './import-field-meta.js';
27+
28+
type ValidateArgs = Parameters<NonNullable<ImportProtocolLike['validateData']>>[0];
29+
30+
const OBJECT = 'contact';
31+
32+
const baseOpts = {
33+
objectName: OBJECT,
34+
metaMap: new Map<string, ExportFieldMeta>([['name', { name: 'name', type: 'text' }]]),
35+
writeMode: 'insert' as const,
36+
matchFields: [] as string[],
37+
dryRun: true,
38+
runAutomations: false,
39+
trimWhitespace: true,
40+
createMissingOptions: false,
41+
skipBlankMatchKey: false,
42+
};
43+
44+
const POSTURE = { valueShapeStrict: false, mediaValueShapeStrict: false };
45+
46+
/**
47+
* One verdict per submitted row; a row named `bad*` is refused. A batch that
48+
* holds a row named `boom` is refused outright, as the engine throws on an
49+
* undeclared field.
50+
*/
51+
function validatingProtocol(findData: ImportProtocolLike['findData'] = vi.fn(async () => [])) {
52+
const validateData = vi.fn(async (args: ValidateArgs) => {
53+
const rows = (Array.isArray(args.data) ? args.data : [args.data]) as Array<Record<string, unknown>>;
54+
if (rows.some((r) => r.name === 'boom')) throw Object.assign(new Error('boom is not a field'), { code: 'INVALID_FIELD' });
55+
const results = rows.map((r) => String(r.name).startsWith('bad')
56+
? { valid: false, errors: [{ field: 'name', code: 'rule_violation', message: `refused ${String(r.name)}` }], warnings: [] }
57+
: { valid: true, errors: [], warnings: [] });
58+
return { object: OBJECT, mode: args.mode ?? 'insert', valid: results.every((r) => r.valid), results, posture: POSTURE };
59+
});
60+
const p: ImportProtocolLike = { findData, createData: vi.fn(), updateData: vi.fn(), validateData };
61+
return { p, validateData };
62+
}
63+
64+
const names = (call: [ValidateArgs]) => {
65+
const data = call[0].data;
66+
return Array.isArray(data) ? data.map((r) => (r as Record<string, unknown>).name) : (data as Record<string, unknown>).name;
67+
};
68+
69+
describe('[#26684] the dry run previews create rows in the commit\'s batches', () => {
70+
it('the create rows of a small file are ONE insert-mode call, in file order, each row keeping its own verdict', async () => {
71+
const { p, validateData } = validatingProtocol();
72+
const s = await runImport({ ...baseOpts, p, rows: [{ name: 'a' }, { name: 'bad-b' }, { name: 'c' }] });
73+
74+
expect(validateData).toHaveBeenCalledTimes(1);
75+
expect(validateData.mock.calls[0]![0]).toMatchObject({ object: OBJECT, mode: 'insert' });
76+
expect(names(validateData.mock.calls[0] as [ValidateArgs])).toEqual(['a', 'bad-b', 'c']);
77+
expect(s).toMatchObject({ ok: 2, errors: 1, created: 2 });
78+
expect(s.results).toEqual([
79+
{ row: 1, ok: true, action: 'created' },
80+
{ row: 2, ok: false, action: 'failed', field: 'name', code: 'rule_violation', error: 'refused bad-b' },
81+
{ row: 3, ok: true, action: 'created' },
82+
]);
83+
});
84+
85+
it('a file of 450 rows is previewed in the commit\'s runs: 200, 200, 50', async () => {
86+
const { p, validateData } = validatingProtocol();
87+
const rows = Array.from({ length: 450 }, (_, n) => ({ name: `r${n + 1}` }));
88+
const s = await runImport({ ...baseOpts, p, rows });
89+
90+
expect(validateData.mock.calls.map((c) => (c[0].data as unknown[]).length)).toEqual([200, 200, 50]);
91+
expect(names(validateData.mock.calls[1] as [ValidateArgs])).toEqual(rows.slice(200, 400).map((r) => r.name));
92+
expect(s).toMatchObject({ ok: 450, created: 450 });
93+
expect(s.results.map((r) => r.row)).toEqual(rows.map((_, n) => n + 1));
94+
});
95+
96+
it('a caller progressEvery sets the checkpoints, and the run length follows it, as on the commit', async () => {
97+
const { p, validateData } = validatingProtocol();
98+
const rows = Array.from({ length: 7 }, (_, n) => ({ name: `r${n + 1}` }));
99+
const progress: number[] = [];
100+
await runImport({ ...baseOpts, p, rows, progressEvery: 3, onProgress: (pr) => { progress.push(pr.created); } });
101+
102+
expect(validateData.mock.calls.map((c) => names(c as [ValidateArgs]))).toEqual([
103+
['r1', 'r2', 'r3'], ['r4', 'r5', 'r6'], ['r7'],
104+
]);
105+
// Each checkpoint reports the rows previewed so far, as the commit reports the rows written.
106+
expect(progress).toEqual([3, 6, 7]);
107+
});
108+
109+
it('an update row is asked alone, in update mode, and the create rows around it keep their batch', async () => {
110+
const findData = vi.fn(async (args: any) => {
111+
const where = JSON.stringify(args ?? {});
112+
return where.includes('"u1"') ? [{ id: 'e1', name: 'u1' }] : [];
113+
});
114+
const { p, validateData } = validatingProtocol(findData as any);
115+
const s = await runImport({
116+
...baseOpts, p, writeMode: 'upsert', matchFields: ['name'],
117+
rows: [{ name: 'a' }, { name: 'u1' }, { name: 'bad-c' }],
118+
});
119+
120+
const update = validateData.mock.calls.find((c) => c[0].mode === 'update')!;
121+
expect(update[0].data).toEqual({ name: 'u1', id: 'e1' });
122+
const insert = validateData.mock.calls.filter((c) => c[0].mode !== 'update');
123+
expect(insert.map((c) => names(c as [ValidateArgs]))).toEqual([['a', 'bad-c']]);
124+
expect(s.results).toEqual([
125+
{ row: 1, ok: true, action: 'created' },
126+
{ row: 2, ok: true, action: 'updated', id: 'e1' },
127+
{ row: 3, ok: false, action: 'failed', field: 'name', code: 'rule_violation', error: 'refused bad-c' },
128+
]);
129+
});
130+
131+
it('a batch the engine refuses outright is asked row by row, then the survivors together again', async () => {
132+
const { p, validateData } = validatingProtocol();
133+
const s = await runImport({ ...baseOpts, p, rows: [{ name: 'a' }, { name: 'boom' }, { name: 'c' }] });
134+
135+
expect(validateData.mock.calls.map((c) => names(c as [ValidateArgs]))).toEqual([
136+
['a', 'boom', 'c'], ['a'], ['boom'], ['c'], ['a', 'c'],
137+
]);
138+
expect(s.results[0]).toEqual({ row: 1, ok: true, action: 'created' });
139+
expect(s.results[1]).toMatchObject({ row: 2, ok: false, action: 'failed', code: 'INVALID_FIELD' });
140+
expect(s.results[2]).toEqual({ row: 3, ok: true, action: 'created' });
141+
});
142+
143+
it('no validate-only operation: every create row is reported on its coercion verdict, as before', async () => {
144+
const p: ImportProtocolLike = { findData: vi.fn(async () => []), createData: vi.fn(), updateData: vi.fn() };
145+
const s = await runImport({ ...baseOpts, p, rows: [{ name: 'a' }, { name: 'b' }] });
146+
expect(s).toMatchObject({ ok: 2, created: 2, errors: 0 });
147+
expect(p.createData).not.toHaveBeenCalled();
148+
});
149+
});

‎packages/core/src/utils/import-runner.ts‎

Lines changed: 137 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -960,11 +960,11 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
960960
* with no validation at all, which is the false all-clear this card exists
961961
* to close.
962962
*/
963-
const previewVerdict = async (
964-
data: Record<string, any>,
963+
const previewVerdicts = async (
964+
data: Record<string, any> | Array<Record<string, any>>,
965965
mode: 'insert' | 'update',
966966
rowCtx: typeof writeCtx,
967-
): Promise<NonNullable<ValidateDataResponse['results']>[number] | null> => {
967+
): Promise<NonNullable<ValidateDataResponse['results']> | null> => {
968968
if (typeof p.validateData !== 'function') return null;
969969
const res = await p.validateData({
970970
object: objectName, data, mode,
@@ -975,7 +975,96 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
975975
context: rowCtx,
976976
...(environmentId ? { environmentId } : {}),
977977
});
978-
return res?.results?.[0] ?? null;
978+
return res?.results ?? [];
979+
};
980+
const previewVerdict = async (
981+
data: Record<string, any>,
982+
mode: 'insert' | 'update',
983+
rowCtx: typeof writeCtx,
984+
): Promise<PreviewVerdict | null> => {
985+
const verdicts = await previewVerdicts(data, mode, rowCtx);
986+
return verdicts === null ? null : (verdicts[0] ?? null);
987+
};
988+
989+
/**
990+
* [#26684] The dry run's verdicts for a run of CREATE rows, asked of the
991+
* engine as ONE multi-row insert preview, in file order — the batch the
992+
* commit's flush hands `insertManyData`. The engine's multi-row `validate()`
993+
* judges each row with the earlier rows of the same call that its rules
994+
* admitted (#25579: a child rule reading a parent roll-up counts them), so
995+
* the dry run refuses the rows the commit refuses. ⛔ Nothing here re-reads
996+
* or re-judges a rule: the accumulation is the engine's, as on the write.
997+
*
998+
* One context for the run, the union of its rows' kept option values, as
999+
* the commit's batch call carries (`ctxForRows`).
1000+
*
1001+
* A call that throws, or answers a verdict count other than one per row, is
1002+
* degraded as the commit's flush degrades a failed batch: each row is asked
1003+
* alone, so a row the engine refuses outright (an undeclared field) carries
1004+
* its own refusal, as `insertManyData` culls it per row; the rows that
1005+
* survive alone are then asked again together, so they still see each
1006+
* other.
1007+
*/
1008+
type PreviewVerdict = NonNullable<ValidateDataResponse['results']>[number];
1009+
type PreviewOutcome = { verdict: PreviewVerdict | null } | { thrown: unknown };
1010+
const previewCreateRun = async (run: ReadonlyArray<PendingCreate>): Promise<PreviewOutcome[]> => {
1011+
const ask = async (part: ReadonlyArray<PendingCreate>): Promise<PreviewOutcome[]> => {
1012+
const verdicts = await previewVerdicts(part.map((b) => b.data), 'insert', writeCtxFor(part.map((b) => b.kept)));
1013+
if (verdicts === null) return part.map(() => ({ verdict: null }));
1014+
if (verdicts.length !== part.length) {
1015+
throw Object.assign(
1016+
new Error(`validateData returned ${verdicts.length} verdict(s) for ${part.length} row(s)`),
1017+
{ code: 'ERR_BULK_RESULT_MISMATCH' },
1018+
);
1019+
}
1020+
return verdicts.map((verdict) => ({ verdict }));
1021+
};
1022+
try {
1023+
return await ask(run);
1024+
} catch (batchError) {
1025+
if (run.length === 1) return [{ thrown: batchError }];
1026+
const alone: PreviewOutcome[] = [];
1027+
for (const b of run) {
1028+
try { alone.push((await ask([b]))[0]!); } catch (e) { alone.push({ thrown: e }); }
1029+
}
1030+
const survivors = run.filter((_, k) => !('thrown' in alone[k]!));
1031+
if (survivors.length < 2 || survivors.length === run.length) return alone;
1032+
const together = await ask(survivors).catch(() => null);
1033+
if (!together) return alone;
1034+
let s = 0;
1035+
return alone.map((o) => ('thrown' in o ? o : together[s++]!));
1036+
}
1037+
};
1038+
1039+
/**
1040+
* One dry-run row's report from its engine verdict (#4633). `existing` is
1041+
* the matched record of an update-resolved row; a create-resolved row has
1042+
* none. `null` (no validate-only operation) reports the row on the coercion
1043+
* + resolution verdict the caller already has.
1044+
*/
1045+
const reportPreview = (
1046+
i: number, rowNo: number, verdict: PreviewVerdict | null, existing?: Record<string, any>,
1047+
): void => {
1048+
if (verdict && !verdict.valid) {
1049+
errCount++;
1050+
const first = verdict.errors[0];
1051+
results[i] = {
1052+
row: rowNo, ok: false, action: 'failed',
1053+
...(first?.field ? { field: first.field } : {}),
1054+
code: first?.code ?? 'VALIDATION_FAILED',
1055+
error: composeValidationMessage(verdict.errors),
1056+
};
1057+
return;
1058+
}
1059+
okCount++;
1060+
// A warn-first deployment ADMITS some findings; the row is ok
1061+
// because the write would store it, and the complaint rides
1062+
// along so "accepted for now" is visible rather than silent.
1063+
const admitted = verdict?.warnings?.length ? { warnings: verdict.warnings } : {};
1064+
// [#20701] What the write would strip from this row, from the same verdict.
1065+
const drops = rowDrops(verdict?.droppedFields);
1066+
if (existing) { updated++; results[i] = { row: rowNo, ok: true, action: 'updated', id: String(existing.id ?? '') || undefined, ...admitted, ...drops }; }
1067+
else { created++; results[i] = { row: rowNo, ok: true, action: 'created', ...admitted, ...drops }; }
9791068
};
9801069

9811070
/**
@@ -1011,7 +1100,11 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
10111100
// batch call, so a bad row never forces the whole-batch degradation that
10121101
// re-runs beforeInsert hooks on its siblings.
10131102
const canPartialCreate = typeof p.insertManyData === 'function';
1014-
const pendingCreates: Array<{ index: number; rowNo: number; data: Record<string, any>; kept: Record<string, string[]> }> = [];
1103+
type PendingCreate = { index: number; rowNo: number; data: Record<string, any>; kept: Record<string, string[]> };
1104+
const pendingCreates: PendingCreate[] = [];
1105+
// [#26684] A dry run's CREATE rows, buffered as the commit buffers them and
1106+
// previewed at the same checkpoints in the same runs (`flushPendingPreviews`).
1107+
const pendingPreviews: PendingCreate[] = [];
10151108
// bulkWrite is at-least-once: a retry (or a mismatch-driven degradation) may
10161109
// re-run a create whose prior attempt already committed. Every buffered
10171110
// CREATE row is therefore pre-assigned a client-generated id at flush time
@@ -1219,6 +1312,33 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
12191312
}
12201313
};
12211314

1315+
/**
1316+
* [#26684] The dry run's counterpart of {@link flushPendingCreates}: the
1317+
* buffered CREATE rows previewed in the commit's runs — the same checkpoints
1318+
* (every `progressEvery` rows, and the end) and the same run length
1319+
* (`Math.min(progressEvery, MAX_CREATE_BATCH_SIZE)`, the commit's
1320+
* `bulkWrite` batch size) — so each run is the batch the commit writes.
1321+
* Each row still gets its own verdict, reported as before.
1322+
*/
1323+
const flushPendingPreviews = async (): Promise<void> => {
1324+
if (pendingPreviews.length === 0) return;
1325+
const batch = pendingPreviews.splice(0, pendingPreviews.length);
1326+
const runLength = Math.min(progressEvery, MAX_CREATE_BATCH_SIZE);
1327+
for (let start = 0; start < batch.length; start += runLength) {
1328+
const run = batch.slice(start, start + runLength);
1329+
const outcomes = await previewCreateRun(run);
1330+
run.forEach((b, k) => {
1331+
const outcome = outcomes[k]!;
1332+
if ('thrown' in outcome) {
1333+
errCount++;
1334+
results[b.index] = toFailedResult(b.rowNo, outcome.thrown, objectName);
1335+
} else {
1336+
reportPreview(b.index, b.rowNo, outcome.verdict);
1337+
}
1338+
});
1339+
}
1340+
};
1341+
12221342
return (async () => {
12231343
const sharingKey = await rowsSharingKey();
12241344
for (let i = 0; i < rows.length; i++) {
@@ -1293,28 +1413,17 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
12931413
// patch, as the by-id update does. Nothing new crosses the
12941414
// protocol: the id is the address every update door already
12951415
// carries in the payload.
1296-
const verdict = willUpdate
1297-
? await previewVerdict({ ...updatePatch(data, matchedKeySet), id: (existing as Record<string, any>).id }, 'update', rowCtx)
1298-
: await previewVerdict(data, 'insert', rowCtx);
1299-
if (verdict && !verdict.valid) {
1300-
errCount++;
1301-
const first = verdict.errors[0];
1302-
results[i] = {
1303-
row: rowNo, ok: false, action: 'failed',
1304-
...(first?.field ? { field: first.field } : {}),
1305-
code: first?.code ?? 'VALIDATION_FAILED',
1306-
error: composeValidationMessage(verdict.errors),
1307-
};
1416+
//
1417+
// [#26684] A create is not asked alone: it is buffered like the
1418+
// commit's create and previewed with the rows of its batch
1419+
// (`flushPendingPreviews`), so a rule that counts the earlier
1420+
// rows of the batch judges it as the commit's write does. An
1421+
// update is asked alone, as it is written alone.
1422+
if (willUpdate) {
1423+
const target = existing as Record<string, any>;
1424+
reportPreview(i, rowNo, await previewVerdict({ ...updatePatch(data, matchedKeySet), id: target.id }, 'update', rowCtx), target);
13081425
} else {
1309-
okCount++;
1310-
// A warn-first deployment ADMITS some findings; the row is ok
1311-
// because the write would store it, and the complaint rides
1312-
// along so "accepted for now" is visible rather than silent.
1313-
const admitted = verdict?.warnings?.length ? { warnings: verdict.warnings } : {};
1314-
// [#20701] What the write would strip from this row, from the same verdict.
1315-
const drops = rowDrops(verdict?.droppedFields);
1316-
if (willUpdate) { updated++; results[i] = { row: rowNo, ok: true, action: 'updated', id: String((existing as any).id ?? '') || undefined, ...admitted, ...drops }; }
1317-
else { created++; results[i] = { row: rowNo, ok: true, action: 'created', ...admitted, ...drops }; }
1426+
pendingPreviews.push({ index: i, rowNo, data, kept: keptOptionValues });
13181427
}
13191428
} else if (willUpdate) {
13201429
const target = existing as Record<string, any>;
@@ -1366,6 +1475,7 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
13661475
if (processed % progressEvery === 0 || processed === rows.length) {
13671476
// Flush before reporting/cancelling so counts and `processed` reflect
13681477
// every row up to this checkpoint, not just decided-but-unwritten ones.
1478+
await flushPendingPreviews();
13691479
await flushPendingCreates();
13701480
if (onProgress) await onProgress(snapshot(processed));
13711481
}
@@ -1377,6 +1487,7 @@ export function runImport(opts: RunImportOptions): Promise<ImportRunSummary> {
13771487
}
13781488
}
13791489

1490+
await flushPendingPreviews();
13801491
await flushPendingCreates();
13811492
const compacted = results.filter((r): r is ImportRowResult => r !== undefined);
13821493

0 commit comments

Comments
 (0)