Skip to content

Commit 2749517

Browse files
committed
fix(objectql): the validate() preview refuses a blank record-currency code; Clause-② declared as a widening
The insert and by-id update previews now judge the write's blank-code refusal on the write's own image (the insert row, or the stored row with the patch over it) and answer it as the row's ERR_CURRENCY_CODE_REQUIRED finding, so a dry run no longer passes a row the write refuses (changeset 26684's parity). The changeset declares Clause-②: yes (widening): the ledger gains a registered code and the formula rider widens the exported FormulaReturnDeclaration. The ledger comment says the write is never asked, not the driver. Claude-Session: https://claude.ai/code/session_01Utp6CboxRwQPbQZnhxyuzt Co-authored-by: Claude <noreply@anthropic.com>
1 parent cf5be50 commit 2749517

4 files changed

Lines changed: 58 additions & 6 deletions

File tree

‎.changeset/27186-record-currency-guards.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
feat(objectql): a record-currency amount is refused without its code, refused in an ungrouped raw aggregate, and refused under a summary roll-up
88

9-
Clause-②: no
9+
Clause-②: yes (widening)
1010
Metadata-protocol: none
1111

12-
- **A `record`-mode amount is stored with its currency code (ADR-0144 D8 rule 4).** An insert or update that would store a value in a `currency` field declaring `currencyConfig: { currencyMode: 'record', currencyField }` while that code field is blank (absent, `null` or white space) is refused `ERR_CURRENCY_CODE_REQUIRED` / 400, with `field` naming the code field and `amountField` the amount. The server never fills a currency in. On an update, only a write that carries the amount or its code is judged, against the stored row with the payload laid over it, so an edit of another field never meets it. The code is registered under `@objectstack/objectql` in the ADR-0112 error-code ledger.
12+
- **A `record`-mode amount is stored with its currency code (ADR-0144 D8 rule 4).** An insert or update that would store a value in a `currency` field declaring `currencyConfig: { currencyMode: 'record', currencyField }` while that code field is blank (absent, `null` or white space) is refused `ERR_CURRENCY_CODE_REQUIRED` / 400, with `field` naming the code field and `amountField` the amount. The server never fills a currency in. On an update, only a write that carries the amount or its code is judged, against the stored row with the payload laid over it, so an edit of another field never meets it. The `validate()` preview (`validateData`) answers the same refusal as the row's finding for an insert and for a by-id update, so a dry run does not pass a row the write refuses. The code is registered under `@objectstack/objectql` in the ADR-0112 error-code ledger.
1313
- **A raw aggregate over a `record`-mode amount groups by its code field (ADR-0144 D6).** `sum`, `avg`, `min` and `max` over such a field through `engine.aggregate` are refused `INVALID_FIELD` / 400 unless `groupBy` names the code field; grouped, each currency totals on its own. `count` and `count_distinct` are not judged. Before, USD 100 and EUR 100 summed to 200 under one label.
1414
- **A `summary` roll-up over a `record`-mode amount is refused at registration (ADR-0144 D6).** `sum` / `avg` / `min` / `max` of such a child field is refused `INVALID_METADATA` / 422 (`RecordCurrencySummaryRefusedError`) at whichever object's registration completes the pair. Before, child rows of USD 100 and JPY 15000 rolled up to 15100. Use `count`, or roll up a stored home-currency amount.
1515
- **`inferFormulaReturn` carries a record currency (`@objectstack/formula`).** A formula over a `record`-mode amount now declares `returnType: 'currency'` with `currencyConfig: { currencyMode: 'record', currencyField }`, the code field its sources name, instead of a tenant-default (`dynamic`) amount. Two record-mode amounts naming different code fields, or a record-mode amount meeting a `fixed` or `dynamic` one, are not one currency and are not stamped as money.

‎packages/objectql/src/engine-validate.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
5050
import { validateRecordInScope, normalizeBlankTypedValues, normalizeNumericStringValues, ValidationError, valueShapeStrictEffective, mediaStrictEffective } from './validation/record-validator.js';
5151
import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js';
5252
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
53+
import { assertRecordCurrencyCodes, RecordCurrencyCodeRequiredError } from './validation/record-currency-code.js';
5354
import { resolveEngineUpdateDispatch, type EngineUpdateDispatchData } from './engine-update-dispatch.js';
5455
import {
5556
droppedFieldEvents,
@@ -393,11 +394,15 @@ export async function validate(
393394
// `undefined` = no stored row: the row is judged on the patch alone, as
394395
// it was before these reads existed.
395396
const storedRows: Array<Record<string, unknown> | undefined> = [];
397+
// The by-id address each stored row was read from, for a refusal that names the record.
398+
const storedIds: unknown[] = [];
396399
for (const submitted of submittedRows) {
397400
let stored: Record<string, unknown> | undefined;
401+
let storedId: unknown;
398402
if (mode === 'update' && submitted && typeof submitted === 'object') {
399403
const dispatch = resolveEngineUpdateDispatch(submitted as EngineUpdateDispatchData, undefined);
400404
if (dispatch.kind === 'by-id') {
405+
storedId = dispatch.id;
401406
const visible = await this.findOne(object, {
402407
where: { id: dispatch.id },
403408
context: { ...(options?.context ?? {}), [RAW_FILE_VALUES_CONTEXT_KEY]: true },
@@ -417,6 +422,7 @@ export async function validate(
417422
}
418423
}
419424
storedRows.push(stored);
425+
storedIds.push(storedId);
420426
}
421427
// The merged view each rule evaluates, and the one the reference reads
422428
// below key on: the write reads a traversed FK off the same merge
@@ -543,6 +549,21 @@ export async function validate(
543549
// preview admits exactly what the write would.
544550
keptOptionValues: options?.context?.keptOptionValues,
545551
});
552+
// [ADR-0144 D8 rule 4] The write's blank-code refusal, at the write's
553+
// step and on the write's image: the insert row as stored, or the stored
554+
// row with the patch over it (`judgedViews`, the by-id update's
555+
// `priorRecord ⊕ payload`), judging only the pairs the patch touches.
556+
// An update with no stored row here (a predicate dispatch, an id this
557+
// caller cannot read) is not judged: the image the write judges is a
558+
// row the preview does not hold. A code column the read door withholds
559+
// from this caller is absent from the stored row, so the preview reads
560+
// it as blank — stricter than the write, never laxer.
561+
if (mode === 'insert' || storedRows[i]) {
562+
assertRecordCurrencyCodes(
563+
object, (schemaForValidation as { fields?: unknown } | undefined)?.fields,
564+
mode === 'insert' ? row : judgedViews[i], mode, mode === 'insert' ? undefined : row, storedIds[i],
565+
);
566+
}
546567
warnings.push(...evaluateValidationRules(schemaForValidation as any, row, mode, {
547568
// [#22445] The stored row, when this row named one: the by-id
548569
// update's `previous: priorRecord`. Absent, the record is the patch.
@@ -571,6 +592,10 @@ export async function validate(
571592
if (e instanceof ValidationError) {
572593
return { valid: false, errors: e.fields.map((f) => ({ ...f })), warnings };
573594
}
595+
// The write throws this refusal whole; the preview answers it as the row's finding.
596+
if (e instanceof RecordCurrencyCodeRequiredError) {
597+
return { valid: false, errors: [{ field: e.field, code: e.code, message: e.message }], warnings };
598+
}
574599
throw e;
575600
}
576601
batchSummaries?.accept(row);

‎packages/objectql/src/record-currency-guards.test.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313
// The fixture is the measurement round's `fx_invoice` (epic #8345, comment
1414
// 6041378776), with the sibling code field DECLARED as the record currency.
1515
// Every refusal here precedes the driver, so the driver is the rows-shaped
16-
// in-memory double the roll-up suite uses; the same probes on driver-memory and
17-
// on SqlDriver over better-sqlite3 are packages/qa/dogfood's
18-
// `record-currency-probes.dogfood.test.ts`.
16+
// in-memory double the roll-up suite uses; the same probes on SqlDriver over
17+
// better-sqlite3 and on SqliteWasmDriver are packages/qa/dogfood's
18+
// `test/record-currency-probes.test.ts`. The write's blank-code refusal is
19+
// also the `validate()` preview's finding (changeset 26684's parity).
1920

2021
import { describe, it, expect, beforeEach } from 'vitest';
2122
import type { EngineAggregateOptions, EngineUpdateOptions } from '@objectstack/spec/data';
@@ -195,6 +196,32 @@ describe('a record-mode amount is stored with its currency code (ERR_CURRENCY_CO
195196
await engine.update('fx_invoice', { amount: 9, currency_code: 'EUR' }, BATCH);
196197
expect(storeFor('fx_invoice').get(b.id)).toMatchObject({ amount: 9, currency_code: 'EUR' });
197198
});
199+
it('validate(): the insert and by-id update previews refuse what the write refuses, as the row\'s finding', async () => {
200+
const insertPreview = await engine.validate('fx_invoice', [
201+
{ title: 'p1', amount: 100 },
202+
{ title: 'p2', amount: 100, currency_code: 'USD' },
203+
{ title: 'p3' },
204+
]);
205+
expect(insertPreview.valid).toBe(false);
206+
expect(insertPreview.results?.map((r) => r.valid)).toEqual([false, true, true]);
207+
expect(insertPreview.results?.[0]?.errors).toEqual([
208+
{ field: 'currency_code', code: 'ERR_CURRENCY_CODE_REQUIRED', message: expect.stringContaining("'currency_code' is blank") },
209+
]);
210+
211+
const withCode = await engine.insert('fx_invoice', { title: 'i1', amount: 100, currency_code: 'USD' });
212+
storeFor('fx_invoice').set('legacy', { id: 'legacy', title: 'old', amount: 100, currency_code: null });
213+
const cleared = await engine.validate('fx_invoice', { id: withCode.id, currency_code: null }, { mode: 'update' });
214+
expect(cleared.valid).toBe(false);
215+
expect(cleared.results?.[0]?.errors).toEqual([
216+
{ field: 'currency_code', code: 'ERR_CURRENCY_CODE_REQUIRED', message: expect.stringContaining(`(record ${withCode.id})`) },
217+
]);
218+
219+
// The controls, answered as the write answers them: the stored code covers
220+
// a new amount, and a codeless legacy row's unrelated edit is not judged.
221+
expect((await engine.validate('fx_invoice', { id: withCode.id, amount: 250 }, { mode: 'update' })).valid).toBe(true);
222+
expect((await engine.validate('fx_invoice', { id: 'legacy', title: 'renamed' }, { mode: 'update' })).valid).toBe(true);
223+
expect(storeFor('fx_invoice').get(withCode.id)).toMatchObject({ amount: 100, currency_code: 'USD' });
224+
});
198225
});
199226

200227
describe('a raw aggregate over a record-mode amount groups by its code field (PROBE-A, PROBE-C)', () => {

‎packages/spec/src/api/error-code-ledger.zod.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,7 @@ export const ERROR_CODE_LEDGER = {
786786
'ERR_CROSS_DATASOURCE_TRANSACTION_WRITE',
787787
// [ADR-0144 D8 rule 4, Open item 9] A write would store a `record`-mode
788788
// currency amount beside a blank currency code — a number in no currency.
789-
// 400, refused before the driver is asked (`RecordCurrencyCodeRequiredError`,
789+
// 400; the driver is never asked to write the row (`RecordCurrencyCodeRequiredError`,
790790
// `validation/record-currency-code.ts`); `field` names the code field to
791791
// fill. The server never fills a currency in.
792792
'ERR_CURRENCY_CODE_REQUIRED',

0 commit comments

Comments
 (0)