From 8790a540124f23a2c719a7fe1f28eac489f155ae Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:31:02 +0000 Subject: [PATCH 1/2] fix(units): raise the blank-unit debt of a unitField re-pointed at a new field; name unused code-keyed mapping entries; say a capped walk judged only the rows it examined Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As5bdhV5T4N9vpjmZzH --- .../src/protocol-write-face.ts | 27 ++++++++++++- .../protocol-destructive-unit-mode.test.ts | 35 ++++++++++++++--- .../objectql/src/unit-code-backfill.test.ts | 25 ++++++++++++ packages/objectql/src/unit-code-backfill.ts | 39 ++++++++++++++++++- 4 files changed, 118 insertions(+), 8 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-write-face.ts b/packages/metadata-protocol/src/protocol-write-face.ts index efd6ca37594..ec099fb4e9c 100644 --- a/packages/metadata-protocol/src/protocol-write-face.ts +++ b/packages/metadata-protocol/src/protocol-write-face.ts @@ -319,8 +319,33 @@ function detectDestructiveObjectChanges(prev: any, next: any): Array<{ // quantity among its declarers, the blanks beside it and the `""` // entry, so this one is not raised. Lifted by the same `force`, // reading no row. + // + // The same debt, raised under the same code: a stored `record`-mode + // quantity whose `unitField` is re-pointed at a field that held no + // stored unit before the save (new in it, or unstored before it). + // Every stored row then holds its quantity beside a blank there. The + // re-point onto a field that already was a unit code field converts + // nothing and strands no blank the save made, so it raises nothing: + // the sibling of `currency_field_repointed`, out of R1 (ADR-0158 Open + // item 9). The re-point onto a stored text field is + // `unit_code_field_declared`'s, under the same once-only rule. const unitField = recordUnitFieldOf(nextField); - if ( + const prevUnitField = recordUnitFieldOf(prevField); + const repointedOntoBlank = prevUnitField !== undefined + && unitField !== undefined + && prevUnitField !== unitField + && !prevUnitCodeFields.has(unitField); + if (repointedOntoBlank && isStored(prevField) && !declaredUnitCodeFields.has(unitField)) { + issues.push({ + code: 'unit_mode_to_record', + field: fname, + message: `Field '${fname}' re-pointed its unitField from '${prevUnitField}' to '${unitField}' — '${unitField}' held no ` + + `stored unit before this save (it is new, or was not stored), so every row already stored holds its quantity ` + + `beside a blank '${unitField}', and no longer reads the unit '${prevUnitField}' holds; editing the quantity there ` + + 'is refused until the row holds a unit code; once saved, write those blanks from a "" entry in the mapping of ' + + unitCodeBackfillRemedy(objectName, unitField), + }); + } else if ( isStored(prevField) && unitField !== undefined && unitModeOf(prevField) !== 'record' diff --git a/packages/objectql/src/protocol-destructive-unit-mode.test.ts b/packages/objectql/src/protocol-destructive-unit-mode.test.ts index 691fbad180b..d8fa65f370d 100644 --- a/packages/objectql/src/protocol-destructive-unit-mode.test.ts +++ b/packages/objectql/src/protocol-destructive-unit-mode.test.ts @@ -19,7 +19,9 @@ import { unitCodeSources } from './validation/unit-code-membership.js'; * blanks beside it, whatever its `unitField`'s history (already a unit code * field, or new in the same save), unless the same save raises * `unit_code_field_declared` on that `unitField`: that finding names the - * quantity, the blanks and the `""` entry, so each debt is reported once. The + * quantity, the blanks and the `""` entry, so each debt is reported once. So + * does a stored `record`-mode quantity whose `unitField` is re-pointed at a + * field that held no stored unit (new in the save, or unstored before it). The * save is answered with the 409 `DESTRUCTIVE_CHANGE`, whose finding names the * conversion run, CLI and REST; `force: true` lifts it. It reads no row. */ @@ -172,6 +174,22 @@ describe('ObjectStackProtocolImplementation - unit_code_field_declared and unit_ readNoRow('mat_gross'); }); + it("a stored record-mode quantity's unitField re-pointed at a field NEW in the same save raises unit_mode_to_record on the quantity, reading no row", async () => { + // Every stored row now holds its quantity beside a blank 'gross_uom': the same blank debt as a switch to 'record'. + const fields = { ...STORED.mat_gross, gross: RECORD('gross', 'gross_uom'), gross_uom: TEXT('gross_uom') }; + const err = await refusalOf(save('mat_gross', fields)); + expect(err).toMatchObject({ code: 'DESTRUCTIVE_CHANGE', status: 409, issues: [expect.objectContaining({ code: 'unit_mode_to_record', field: 'gross' })] }); + expect(err.issues).toHaveLength(1); + const { message } = err.issues[0]; + expect(message).toContain("Field 'gross' re-pointed its unitField from 'uom' to 'gross_uom'"); + expect(message).toContain("'gross_uom' held no stored unit before this save (it is new, or was not stored)"); + expect(message).toContain("every row already stored holds its quantity beside a blank 'gross_uom'"); + expect(message).toContain('write those blanks from a "" entry in the mapping of'); + for (const part of remedyOf('mat_gross', 'gross_uom')) expect(message).toContain(part); + readNoRow('mat_gross'); + expect(await findingsOf(save('mat_gross', fields, { force: true }))).toEqual([]); + }); + it('[S1] raises nothing for a field that already was a unit code field, however it is declared now', async () => { // A new quantity naming a field another quantity already names. expect(await findingsOf(save('mat_gross', { ...STORED.mat_gross, net: RECORD('net', 'uom') }))).toEqual([]); @@ -219,6 +237,8 @@ describe('ObjectStackProtocolImplementation - unit_code_field_declared and unit_ ['mat_bare', { ...STORED.mat_bare, title: CODE('title'), weight: RECORD('weight', 'uom'), uom: TEXT('uom') }], ['mat_plain', { ...STORED.mat_plain, weight: RECORD('weight', 'weight_uom'), weight_uom: TEXT('weight_uom') }], ['mat_fixed', { ...STORED.mat_fixed, weight: RECORD('weight', 'uom') }], + ['mat_gross', { ...STORED.mat_gross, gross: RECORD('gross', 'gross_uom'), gross_uom: TEXT('gross_uom') }], + ['mat_pair', { ...STORED.mat_pair, net: RECORD('net', 'uom'), gross: RECORD('gross', 'gross_uom'), gross_uom: TEXT('gross_uom') }], ] as Array<[string, Record]>)('on %s, the fields raised are those unitCodeSources newly names over a stored field, and each switched quantity\'s blanks are named once (%#)', async (object, next) => { const before = new Set(unitCodeSources(STORED[object]).map((s) => s.codeField)); const expected = unitCodeSources(next) @@ -233,12 +253,17 @@ describe('ObjectStackProtocolImplementation - unit_code_field_declared and unit_ .map((i) => i.field) .sort(); expect(raised).toEqual(expected); - // Every stored quantity this save switches to unitMode 'record' has its blank debt named exactly once: by - // unit_mode_to_record on the quantity, or by unit_code_field_declared on its unitField, which names it. + // Every stored quantity this save switches to unitMode 'record', or re-points at a field that was no unit + // code field before, has its blank debt named exactly once: by unit_mode_to_record on the quantity, or by + // unit_code_field_declared on its unitField, which names it. const issues = (err?.issues ?? []) as Array<{ code: string; field: string; message: string }>; for (const [name, field] of Object.entries(next) as Array<[string, any]>) { - const before = STORED[object][name] as any; - if (!before || before.unitConfig?.unitMode === 'record' || field?.unitConfig?.unitMode !== 'record') continue; + const prior = STORED[object][name] as any; + if (!prior || field?.unitConfig?.unitMode !== 'record') continue; + const priorPointer = prior.unitConfig?.unitMode === 'record' ? prior.unitConfig.unitField : undefined; + const owes = priorPointer === undefined + || (priorPointer !== field.unitConfig.unitField && !before.has(field.unitConfig.unitField)); + if (!owes) continue; const named = issues.filter((i) => (i.code === 'unit_mode_to_record' && i.field === name) || (i.code === 'unit_code_field_declared' && i.field === field.unitConfig.unitField && i.message.includes(`'${name}'`))); expect(named.map((i) => i.code), name).toHaveLength(1); diff --git a/packages/objectql/src/unit-code-backfill.test.ts b/packages/objectql/src/unit-code-backfill.test.ts index efe02c8b7dc..5611e9d9947 100644 --- a/packages/objectql/src/unit-code-backfill.test.ts +++ b/packages/objectql/src/unit-code-backfill.test.ts @@ -289,6 +289,31 @@ describe('backfillUnitCodes — free text stored before the field was a unit cod expect(d.finds.uom_material ?? 0).toBe(0); }); + it('a mapping entry whose key the rows store as a unit code, and that no row used, is named in the report', async () => { + const report = await run({ mapping: { ...MAPPING, KGM: 'LBR' } }); + expect(report.values.find((v) => v.value === 'KGM')).toEqual({ value: 'KGM', rows: 1, disposition: 'member', unusedEntry: 'LBR' }); + // The entries rows did use name nothing. + expect(report.values.filter((v) => v.unusedEntry !== undefined).map((v) => v.value)).toEqual(['KGM']); + expect(formatUnitCodeBackfillReport(report)).toContain( + '⚠ The mapping entry "KGM" → LBR was not used: the rows holding "KGM" store it as a unit code, which is never rewritten.'); + expect(formatUnitCodeBackfillReport(await run({ mapping: MAPPING })).some((l) => l.includes('was not used'))).toBe(false); + }); + + it('an apply run over a walk the cap cut short writes the rows examined, and the report says the rest were not judged', async () => { + // The cap stops after m1 and m2, both mapped: the unmatched 'kg ' and 'lbs' rows past it are not seen. + const report = await run({ mapping: { kg: 'KGM', '公斤': 'KGM' }, apply: true, maxRecords: 2 }); + expect(report).toMatchObject({ scannedRecords: 2, mapped: 2, written: 2, unmatched: 0, truncated: true, applied: true }); + expect(['m1', 'm2', 'm4', 'm8'].map(uom)).toEqual(['KGM', 'KGM', 'kg ', 'lbs']); + expect(unitCodeBackfillComplete(report)).toBe(false); + const lines = formatUnitCodeBackfillReport(report); + expect(lines).toContain('⚠ Walk incomplete — some rows were not examined; re-run without the cap to finish.'); + expect(lines).toContain(' The rows past the cap were not judged: any of them may hold a value with no mapping entry, which this ' + + 'run neither named nor refused, and it wrote the rows examined only.'); + // Without the cap, the same apply run is refused over the values it now sees. + const err = await refusal(run({ mapping: { kg: 'KGM', '公斤': 'KGM' }, apply: true })); + expect(err).toMatchObject({ code: 'VALIDATION_ERROR', status: 400, field: 'mapping' }); + }); + it('the dry-run report names each value, what it would write, and claims no row or table', async () => { const report = await run({ mapping: MAPPING }); expect(formatUnitCodeBackfillReport(report)).toEqual([ diff --git a/packages/objectql/src/unit-code-backfill.ts b/packages/objectql/src/unit-code-backfill.ts index acbe3cd1651..2269817a0ed 100644 --- a/packages/objectql/src/unit-code-backfill.ts +++ b/packages/objectql/src/unit-code-backfill.ts @@ -55,7 +55,16 @@ * sees each spelling before writing. * - An apply run counts first, read-only, and refuses before any write while a * non-blank value that is no unit code has no mapping entry, naming each one. So one - * apply run converts the whole field or nothing, and a re-run writes nothing. + * apply run converts the whole field or nothing, and a re-run writes nothing — + * over the rows it examines. A walk the `maxRecords` cap cuts short judges + * only those, as the currency backfill's does: an apply run still writes the + * rows it examined, and the report says that the rows past the cap were not + * judged, so any of them may hold a value with no mapping entry. A re-run + * without the cap finishes, and rewrites nothing already converted. + * - A mapping entry whose key a row stores as a unit code rewrites nothing + * there (above). Where no row used such an entry, the report names it + * (`unusedEntry` on the value), so an operator's entry never goes unused + * without a word. * * The walk reads each row and tallies and tests its value here, in the * application, never in a `GROUP BY` or an anti-join on `sys_unit`: matching is @@ -103,6 +112,12 @@ export interface UnitCodeBackfillValue { */ disposition: 'member' | 'retired' | 'other-dimension' | 'mapped' | 'unmatched'; code?: string; + /** + * On a value stored as a unit code (`member`, `retired`, `other-dimension`) + * that is also a mapping key no row used: the code that entry names, never + * written, since a unit code is never rewritten. + */ + unusedEntry?: string; } /** The counts of one organization's rows (`organizationId` null: rows that name none). */ @@ -487,6 +502,11 @@ async function walkUnitCodes( } } if (walk.truncated) report.truncated = true; + // A mapping key stored as a unit code, which no row was rewritten from: named, never silently unused. + const used = new Set([...values.values()].filter((v) => v.disposition === 'mapped').map((v) => v.value)); + for (const v of values.values()) { + if (v.disposition !== 'mapped' && v.disposition !== 'unmatched' && has(v.value) && !used.has(v.value)) v.unusedEntry = mapping[v.value]; + } report.values = [...values.values()].sort((a, b) => (a.value < b.value ? -1 : a.value > b.value ? 1 : 0)); report.organizations = [...organizations.values()].sort((a, b) => a.organizationId === b.organizationId ? 0 : a.organizationId === null ? 1 : b.organizationId === null ? -1 : a.organizationId < b.organizationId ? -1 : 1, @@ -573,13 +593,28 @@ export function formatUnitCodeBackfillReport(report: UnitCodeBackfillReport): st lines.push(`✗ ${report.unmatched} row(s) hold a value with no mapping entry: an apply run is refused until each value is ` + 'mapped or those rows are corrected.'); } + const unused = new Map(report.values.filter((v) => v.unusedEntry !== undefined).map((v) => [v.value, v.unusedEntry!])); + for (const [key, code] of unused) { + lines.push(`⚠ The mapping entry ${JSON.stringify(key)} → ${code} was not used: the rows holding ${JSON.stringify(key)} store ` + + 'it as a unit code, which is never rewritten.'); + } if (report.failures.length > 0) { lines.push(`✗ ${report.failures.length} row(s) could not be written:`); for (const f of report.failures.slice(0, MAX_SAMPLE_IDS)) lines.push(` • ${f.recordId}: ${f.error}`); if (report.failures.length > MAX_SAMPLE_IDS) lines.push(` … and ${report.failures.length - MAX_SAMPLE_IDS} more`); lines.push('Re-running is safe: a row holding a unit code is never rewritten.'); } - if (report.truncated) lines.push('⚠ Walk incomplete — some rows were not examined; re-run without the cap to finish.'); + if (report.truncated) { + lines.push('⚠ Walk incomplete — some rows were not examined; re-run without the cap to finish.'); + // The counts above, the unmatched check included, saw only the rows examined. + lines.push(' The rows past the cap were not judged: any of them may hold a value with no mapping entry, which this run ' + + (report.applied ? 'neither named nor refused, and it wrote the rows examined only.' : 'does not name, and an apply run would not refuse.')); + // An unscoped run judged "one organization" from the rows it examined, as the currency backfill's report says. + if (report.organizationId === null && !report.allOrganizations) { + lines.push(' The organization check saw only the rows examined: rows past the cap may belong to another ' + + 'organization, so name the organization (one run per organization) before writing.'); + } + } if (!report.applied && report.mapped > 0) lines.push('Dry run — no row or table was written. Re-run with --apply to convert.'); return lines; } From 0237272ee3f9eee0f4ed263f354ef3eb12dbb684 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 08:46:16 +0000 Subject: [PATCH 2/2] chore(changeset): unit re-point finding and backfill report gaps Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_011y7As5bdhV5T4N9vpjmZzH --- .changeset/35885-unit-repoint-backfill-gaps.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .changeset/35885-unit-repoint-backfill-gaps.md diff --git a/.changeset/35885-unit-repoint-backfill-gaps.md b/.changeset/35885-unit-repoint-backfill-gaps.md new file mode 100644 index 00000000000..553e106c3da --- /dev/null +++ b/.changeset/35885-unit-repoint-backfill-gaps.md @@ -0,0 +1,13 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/objectql': patch +--- + +fix(units): a `unitField` re-pointed at a new field raises its blank-unit debt; the unit-code backfill names unused mapping entries and says what a capped walk did not judge + +Clause-②: no +Metadata-protocol: none + +- A metadata save that re-points a stored `record`-mode quantity's `unitConfig.unitField` at a field that held no stored unit before the save (new in it, or unstored before it) is now answered 409 `DESTRUCTIVE_CHANGE` with `unit_mode_to_record` on the quantity: every stored row then holds its quantity beside a blank unit, and is refused at its next quantity edit until it holds a unit code. The finding names the `""` mapping entry of `os migrate unit-codes` that writes those blanks, reads no row, and is lifted by `force: true`. A re-point onto a stored text field still raises `unit_code_field_declared` alone, and a re-point onto a field that already was a unit code field still raises nothing. +- `os migrate unit-codes` and `POST /api/v1/meta/_migrate-unit-codes`: a mapping entry whose key the rows store as a unit code, which is never rewritten, and that no row used is now named, as `unusedEntry` on that value in the report and as a line of the printed report. +- When the walk stops at `maxRecords`, the printed report now says that the rows past the cap were not judged, so any of them may hold a value with no mapping entry, and that an apply run wrote the rows examined only, as the record-currency backfill's report does; an unscoped run also says its organization check saw only the rows examined. An apply run over such a walk still writes the rows it examined, as before.