Skip to content

Commit 09da8c7

Browse files
fix(objectql): the duplicate refusal reads in the writer's locale and names a declared composite unique index's fields (#33348)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DXuamRUC67fx2TTYrFfyuSH)_ Fixes #33213 Clause-②: yes (widening) Metadata-protocol: none ## Maintainer quick read - What changes: the 409 `UNIQUE_VIOLATION` sentence is now composed by the engine in the writer's language from the platform operation-message catalog, and a composite unique index names its fields by label when that can be established. - Why: a downstream app writing a duplicate of a "Plant + Carbon Grade + Cost Week" unique index under `Accept-Language: zh-CN` got the English "A record with this value already exists" and could not tell which fields collided. - Risk and rollback: the wire shape is unchanged (`code`, 409 and the meaning of `field` stay), only the `error` text moves; the English single-field and no-field sentences are byte-identical. Rollback is a revert of this PR. - Read first: `packages/objectql/src/duplicate-record-error.ts` (`declaredCompositeIndex` and `buildEndUserMessage`), `packages/types/src/unique-violation.ts` (new `uniqueViolationColumns`; the two existing functions answer as before), `packages/spec/src/system/operation-message.ts` (three new catalog keys). - Two-minute check: `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-duplicate-record-label-sentence.test.ts`; expect all green, including the zh-CN composite case asserting `已存在「工厂」、「牌号」、「成本周次」均相同的记录`. - Needed from you: nothing; the seat lands it. ## What changes - **The sentence is composed where the locale and the schema are.** `DuplicateRecordError` (`@objectstack/objectql`) now renders its end-user sentence from the platform operation-message catalog (`renderOperationMessage`, the catalog `DELETE_RESTRICTED` already renders from) in the write's message context, so a deployment's `errors.duplicate_record*` translation overrides it. It is carried in-process as `endUserMessage`, and the `DUPLICATE_RECORD` arm of `classifyDataError` (`@objectstack/types`) ships it as the 409 body's `error`. That arm holds neither a locale nor a schema, which is why it composed fixed English before. - **Three catalog keys**, every platform locale (`en`, `zh-CN`, `ja-JP`, `es-ES`): `duplicate_record` (names nothing), `duplicate_record_field` (`{{field}}`, one label), `duplicate_record_fields` (`{{fields}}`, a list spelled by the locale's existing `field_label_quoted` / `field_label_list_separator` rules). The English `duplicate_record` and `duplicate_record_field` are byte-identical to the fixed text the HTTP doors answered, so an English deployment reads no change for one field or none. - **A composite unique index is named only on a declared match.** `uniqueViolationColumns(error)` (new, `@objectstack/types`) reads the composite key's columns from the SQLite and Postgres texts the existing readers already parse, organization part set aside as `uniqueViolationField` sets it aside. The engine names them only when that set equals the `fields` of a unique index (`'global'` or `'organization'`) the object declares, and the user's sentence names them only when every one has a label (translation, else declared `label`). Anything short of that names nothing: driver text alone cannot tell a `tenancy.tenantField` column from an authored one, and a wrong field name is worse than none. `uniqueViolationColumn` / `uniqueViolationField` answer exactly as before (the shared reader was generalised over a reduction, not changed). - **The wire shape does not move.** `code` stays `UNIQUE_VIOLATION`, the status 409, `field` keeps its single-column contract (absent for a composite), and no key is added. The composite's labels also enter the engine's `message` (relayed as `developerMessage`) and its API names enter the in-process `developerMessage`. - Why not `userMessage`: that name on a thrown error is the ApiError contract's producer-marked channel, which `withDeclaredUserMessage` promotes to its own wire key. Whether this refusal joins that channel is a contract decision this fix does not make, so the property is `endUserMessage` and the wire is unchanged (pinned: `not.toHaveProperty('userMessage')`). ## Tests Pins added (zh-CN and en, single-field and multi-field, plus the fallbacks): - `packages/objectql/src/engine-duplicate-record-label-sentence.test.ts` — new top-level `describe` in the existing harness, through the real write doors (`insert`, `update` by id) and the real `mapDataError`: a declared `unique: 'organization'` index over `plant + carbon_grade + cost_week` named in en (`A record with the same “Plant”, “Carbon Grade”, “Cost Week” already exists`) and zh-CN (`已存在「工厂」、「牌号」、「成本周次」均相同的记录`), the Postgres DETAIL shape, an uncatalogued locale (`de-DE`) falling back to the en sentence, a deployment `errors.duplicate_record_fields` override; five controls that must name nothing (no matching declared index, a non-unique match, no indexes, one unlabelled field, a MySQL index-only refusal), each asserting the unnamed sentence in zh-CN and en; a single unlabelled field in zh-CN. The two existing zh-CN single-field pins now expect `已存在相同客户名称的记录` (they pinned the English sentence around a Chinese label — the reported defect). - `packages/rest/src/rest-duplicate-record-arm.test.ts` — a real `ObjectQL` on real better-sqlite3 with a declared `'global'` composite index: the exact 409 body in en and zh-CN, no `field`, no value. - `packages/spec/src/system/operation-message.test.ts` — the three keys in every locale with exactly their own placeholder, en byte-identity with the previous wire text, zh-CN / base-language / unknown-locale rendering, the `errors.` override. - `packages/types/src/unique-violation.test.ts` — `uniqueViolationColumns` on SQLite and Postgres composites, no overlap with `uniqueViolationField`, and `undefined` for index names, expression parts and a NOT NULL refusal. <details><summary>Runs (heads 330e619 and af12b05)</summary> - At 330e619: `pnpm --filter @objectstack/types test` — Test Files 39 passed (39), Tests 907 passed (907). - `pnpm --filter @objectstack/spec test` — Test Files 839 passed, 1 skipped (840); Tests 26834 passed, 1 skipped, 1 todo. - `pnpm --filter @objectstack/objectql test` — 594 passed, 1 failed: `federated-injected-column-readers.test.ts` flagged an `organization_id` literal the first cut used in the matcher. Fixed in af12b05 by comparing the declared index as written (no literal); re-run at af12b05: that file plus the three duplicate-record files, Test Files 4 passed (4), Tests 119 passed (119). The full objectql suite was not re-run at af12b05 (lock contention); CI runs it. - `pnpm --filter @objectstack/rest exec vitest run` on `rest-duplicate-record-arm`, `import-runner-unique-violation-row`, `import-row-report-field-20701`, `error-response-structured-arm-door-parity`, `error-response-generic-passthrough-object-parity` at af12b05 — Test Files 5 passed (5), Tests 135 passed (135). - `pnpm --filter @objectstack/types typecheck`, `@objectstack/objectql typecheck`, `@objectstack/spec typecheck` — exit 0 at 330e619 (the af12b05 objectql source change passed its tsup DTS build in the rest closure build). </details> <details><summary>Ablation (one-shot, not kept)</summary> `node scripts/ablation-replace.mjs --file packages/objectql/src/duplicate-record-error.ts --anchor "this.endUserMessage = buildEndUserMessage(...);" --replacement "this.endUserMessage = '';"` under the verify lock, running `engine-duplicate-record-label-sentence.test.ts` (the subject resolves from `src`, so no rebuild leg): mutation landed (anchor 1 -> 0, blob 55cc407 -> be7c0e75), Tests 24 failed / 37 passed (61) — red, the expected direction; restored (blob == HEAD 55cc407, `git diff HEAD` empty). </details> ## Acceptance notes - **MySQL still names no field, single or composite.** Its duplicate-entry text names an index (`for key 'idx_…'`), never columns; mapping a physical index name to a declared index is the wider schema-lookup contract `uniqueViolationColumn`'s doc already defers. The sentence is still in the writer's locale there. - **A legacy hand-written global index that lists `organization_id` itself** (`fields: ['organization_id', 'a', 'b']`) matches nothing and gets the unnamed (localized) sentence: the declared side is compared as written. The spec already steers new code to `unique: 'organization'`, which matches. - **A bare `unique: true` index** (refused at parse since protocol 18, converted on stored rows) is not treated as unique by the matcher. The existing real-driver pin in `rest-duplicate-record-arm.test.ts` §2 registers such an object straight into the registry and keeps its unnamed sentence for that reason; the new real-driver pin declares `'global'`. - **The raw driver unique arm** further down `classifyDataError` (a unique error that did not pass through the engine envelope) keeps its fixed English sentence: that module holds no locale. Every engine write door wraps first, so the reported path is the envelope. - The `envelope without endUserMessage` fallback in the arm keeps the previous sentence for an envelope built by an older engine; every envelope this engine builds carries the sentence. - Locale ladder: like every `renderOperationMessage` refusal, this takes the one `ExecutionContext.locale` value, so a request locale the catalog lacks reads `en`, not the workspace default (the limitation `ApiErrorSchema.userMessage` "Language" already records for the operation refusals). ## Verification - Local gate families: `node scripts/pm/dispatch-gates.mjs --commands` derived 87 families for this diff at af12b05; all 87 run, 80 exit 0. Seven exited 3 = PREREQUISITE NOT MET, read as NOT MEASURED (they read built output that predates the source or needs a deeper clone): `check-plugin-teardown-shape --self-test` (shallow clone), spec `check:api-surface`, `check:dual-source-exports`, `check:entry-nameability`, `check:exported-any` (spec `dist` predates a test-file edit), `check:dual-build-cjs-loads`, `check:type-check-debt` (closure not built). CI runs all of them on a clean build. `--ran` reconciliation: 87 derived, 87 run, 0 unrun. - No control bytes in any changed file (`grep -naP` over the diff: no match). - The branch sits on e540baf; `origin/main` has since moved 21 commits, none touching a file of this diff (`git merge-tree` clean). ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4cz2MxDkQYCC4U8indM --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent df9fe94 commit 09da8c7

9 files changed

Lines changed: 623 additions & 40 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/types': patch
4+
'@objectstack/objectql': patch
5+
---
6+
7+
fix(objectql): the duplicate refusal (`409 UNIQUE_VIOLATION`) now reads in the writer's language and names the fields of a composite unique index
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
A write refused by a unique constraint used to answer the fixed English sentence "A record with this value already exists" as the 409 body's `error`, whatever the request's `Accept-Language`, and never named the fields of a unique index over several columns, so the user could not tell which combination collided. The engine now composes that sentence in the writer's locale from the platform's operation message catalog, the catalog the `DELETE_RESTRICTED` refusal already uses, so a `zh-CN` request reads `已存在「工厂」、「牌号」、「成本周次」均相同的记录` where it read English. A composite key is named only when the columns the database reported match, as a set, a unique index the object declares, and only when every one of those fields has a label; otherwise the sentence names nothing, because a wrong field name is worse than none. The wire shape does not change: `code` stays `UNIQUE_VIOLATION`, the status stays 409, and `field` still names one column only when the database named exactly one. An English deployment reads the same sentences as before for a single field or none.
13+
14+
Three additions ride along. `BUILTIN_OPERATION_MESSAGES` (`@objectstack/spec/system`) gains `duplicate_record`, `duplicate_record_field` and `duplicate_record_fields` in every platform locale, so a deployment can override them with an `errors.duplicate_record*` translation. `@objectstack/types` exports `uniqueViolationColumns(error)`, the columns of a composite unique key the driver named, with the organization part set aside. `DuplicateRecordError` carries the composed sentence as `endUserMessage`. A MySQL refusal names an index and not its columns, so it still names no field.

‎packages/objectql/src/duplicate-record-error.ts‎

Lines changed: 149 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
import { isUniqueViolationError, uniqueViolationField } from '@objectstack/types';
3+
import { renderOperationMessage } from '@objectstack/spec/system';
4+
import { isUniqueViolationError, uniqueViolationColumns, uniqueViolationField } from '@objectstack/types';
45
import { objectDisplayLabel } from './engine-validation-messages.js';
56
import { resolveFieldLabel, type ValidationMessageContext } from './validation/record-validator.js';
67

@@ -97,6 +98,32 @@ import { resolveFieldLabel, type ValidationMessageContext } from './validation/r
9798
* a write made in `zh-CN` against a translated object reads its labels in
9899
* `zh-CN`. With no message context (a bare-kernel caller) they are the
99100
* declared labels, exactly as before.
101+
* - **`endUserMessage`** — the end user's sentence, composed in the writer's
102+
* locale from the platform's operation catalog (`duplicate_record*`,
103+
* `renderOperationMessage` in `@objectstack/spec/system`, the catalog the
104+
* `DELETE_RESTRICTED` refusal renders from), so a deployment's
105+
* `errors.duplicate_record*` translation overrides it. The HTTP doors ship
106+
* it as the 409 body's `error`; before, they composed a fixed English
107+
* sentence there, so a `zh-CN` writer read English beside a Chinese
108+
* object label. It names the conflicting field by label (one field), the
109+
* fields of a composite unique index by their labels (see `uniqueFields`
110+
* below), or nothing. ⛔ It is deliberately NOT spelled `userMessage`:
111+
* that name is the ApiError contract's producer-marked channel, which every
112+
* boundary promotes to a wire key of its own (`withDeclaredUserMessage`),
113+
* and whether this refusal joins that channel is a contract decision this
114+
* sentence does not make. The wire shape is unchanged: only the text of
115+
* `error` moves.
116+
* - **The fields of a composite unique index** — named in `endUserMessage`
117+
* and in `message` ONLY when the columns the store named
118+
* (`uniqueViolationColumns`, organization part set aside) match, as a set,
119+
* the `fields` of a unique index the object DECLARES. Driver text alone is evidence, not a verdict: a
120+
* `tenancy.tenantField` column prints beside the authored ones and cannot
121+
* be told from them, so anything short of a declared match names nothing —
122+
* the rule `field` follows, for the reason it does. `field` itself keeps
123+
* its single-column contract and stays absent for a composite; the
124+
* composite's API names open `developerMessage`. And the user's sentence
125+
* names them only when every one has a label — never an API name, the
126+
* rule `field_edit_denied` set for its list of fields.
100127
*
101128
* ## ⛔ What this deliberately does NOT do
102129
*
@@ -111,8 +138,24 @@ export const DUPLICATE_RECORD_CODE = 'DUPLICATE_RECORD' as const;
111138
/** The conflict status the engine's sibling 409 refusals declare. */
112139
const DUPLICATE_RECORD_STATUS = 409 as const;
113140

114-
/** The declared labels of the refused write's object and conflicting field. */
115-
type DuplicateRecordLabels = { readonly object?: string; readonly field?: string };
141+
/**
142+
* What the user-facing sentences name: the display labels of the refused
143+
* write's object and conflicting field, the composite unique index's fields
144+
* when one was matched, and the writer's locale to render the end user's
145+
* sentence in.
146+
*/
147+
type DuplicateRecordLabels = {
148+
readonly object?: string;
149+
readonly field?: string;
150+
/**
151+
* The fields of the declared unique index the store's composite key matched,
152+
* in the index's declared order, each with its display label (absent where
153+
* the field has none). Absent when no declared index matched.
154+
*/
155+
readonly uniqueFields?: ReadonlyArray<{ readonly name: string; readonly label?: string }>;
156+
/** The writer's locale and the deployment's translation hook; absent ⇒ `en`. */
157+
readonly messages?: Pick<ValidationMessageContext, 'locale' | 'translate'>;
158+
};
116159

117160
export class DuplicateRecordError extends Error {
118161
readonly code = DUPLICATE_RECORD_CODE;
@@ -137,6 +180,12 @@ export class DuplicateRecordError extends Error {
137180
* See the module header.
138181
*/
139182
readonly fieldLabel?: string;
183+
/**
184+
* The end user's sentence, in the writer's locale, from the platform's
185+
* operation catalog — what the HTTP doors ship as the 409 body's `error`.
186+
* See the module header, and on why it is not `userMessage`.
187+
*/
188+
readonly endUserMessage: string;
140189

141190
constructor(
142191
/** The object the refused write targeted. */
@@ -147,13 +196,21 @@ export class DuplicateRecordError extends Error {
147196
/** The display labels the user-facing `message` names them by; absent ⇒ the API name. */
148197
labels?: DuplicateRecordLabels,
149198
) {
150-
super(buildDuplicateMessage(labels?.object || object, field && (labels?.field || field)));
199+
const uniqueFields = field ? undefined : labels?.uniqueFields;
200+
super(
201+
buildDuplicateMessage(
202+
labels?.object || object,
203+
field ? [labels?.field || field] : uniqueFields?.map((f) => f.label || f.name),
204+
),
205+
);
151206
this.name = 'DuplicateRecordError';
152207
this.cause = cause;
153208
if (field && labels?.field) this.fieldLabel = labels.field;
209+
this.endUserMessage = buildEndUserMessage(field ? labels?.field : undefined, uniqueFields, labels?.messages);
154210
this.developerMessage =
155211
`Duplicate record refused on object '${object}'` +
156212
(field ? `, field '${field}'` : '') +
213+
(uniqueFields ? `, unique index fields ${uniqueFields.map((f) => `'${f.name}'`).join(', ')}` : '') +
157214
`. The driver refused this write as a unique-constraint violation. Its own error is attached ` +
158215
`as \`cause\`. Branch on the platform code (ADR-0112), never on a dialect's code or message, ` +
159216
`so the handling survives a change of store: over the HTTP API this refusal is reported as ` +
@@ -173,16 +230,45 @@ export class DuplicateRecordError extends Error {
173230
* message opening "Insert on 'x' …" would be thrown away by a guard written
174231
* against leaked driver statements. Measured, not guessed.
175232
*/
176-
function buildDuplicateMessage(object: string, field?: string): string {
233+
function buildDuplicateMessage(object: string, fields?: readonly string[]): string {
177234
return (
178235
`Duplicate record refused on '${object}': ` +
179-
(field
180-
? `a unique constraint on '${field}' already holds this value. `
181-
: 'a unique constraint already holds these values. ') +
236+
(fields?.length === 1
237+
? `a unique constraint on '${fields[0]}' already holds this value. `
238+
: fields && fields.length > 1
239+
? `a unique constraint on ${fields.map((f) => `'${f}'`).join(', ')} already holds these values. `
240+
: 'a unique constraint already holds these values. ') +
182241
'No record was written.'
183242
);
184243
}
185244

245+
/**
246+
* The end user's sentence, rendered from the operation catalog in the writer's
247+
* locale: the one field's label, the composite index's labels as a list
248+
* spelled by the locale's `field_label_quoted` / `field_label_list_separator`
249+
* rules, or nothing named. A composite is named only when EVERY field has a
250+
* label — never an API name in this sentence.
251+
*/
252+
function buildEndUserMessage(
253+
fieldLabel: string | undefined,
254+
uniqueFields: DuplicateRecordLabels['uniqueFields'],
255+
messages: DuplicateRecordLabels['messages'],
256+
): string {
257+
const opts = { locale: messages?.locale, translate: messages?.translate };
258+
if (fieldLabel) {
259+
return renderOperationMessage({ messageKey: 'duplicate_record_field', params: { field: fieldLabel } }, opts);
260+
}
261+
const labels = uniqueFields?.map((f) => f.label);
262+
if (labels && labels.length > 1 && labels.every((l): l is string => typeof l === 'string' && l.length > 0)) {
263+
const separator = renderOperationMessage({ messageKey: 'field_label_list_separator' }, opts);
264+
const list = labels
265+
.map((label) => renderOperationMessage({ messageKey: 'field_label_quoted', params: { label } }, opts))
266+
.join(separator);
267+
return renderOperationMessage({ messageKey: 'duplicate_record_fields', params: { fields: list } }, opts);
268+
}
269+
return renderOperationMessage({ messageKey: 'duplicate_record' }, opts);
270+
}
271+
186272
/**
187273
* A write door's driver-error exit — `insert` (#14095) and `update` (commit 9d7f7259f),
188274
* by-id and predicate alike: the platform envelope for a unique violation, or
@@ -210,7 +296,61 @@ export function envelopeUniqueViolation(
210296
if (error instanceof DuplicateRecordError) return error;
211297
if (!isUniqueViolationError(error)) return error;
212298
const field = uniqueViolationField(error);
213-
return new DuplicateRecordError(object, error, field, displayLabels(schema, object, field, messages));
299+
const uniqueFields = field ? undefined : declaredCompositeIndex(schema, uniqueViolationColumns(error));
300+
return new DuplicateRecordError(object, error, field, {
301+
...displayLabels(schema, object, field, messages),
302+
...(uniqueFields ? { uniqueFields: uniqueFields.map((name) => ({ name, label: fieldDisplayLabel(schema, object, name, messages) })) } : {}),
303+
...(messages ? { messages: { locale: messages.locale, translate: messages.translate } } : {}),
304+
});
305+
}
306+
307+
/**
308+
* The `fields` of the unique index the object DECLARES whose field set equals
309+
* the composite key the store named — in the index's declared order — or
310+
* `undefined` when none matches exactly. The store's side arrives with the
311+
* organization key part already set aside (`uniqueViolationColumns`), which
312+
* is what a `unique: 'organization'` index lists: only its authored fields.
313+
* The declared side is compared as written, so a legacy hand-written global
314+
* index that lists the organization column itself matches nothing and names
315+
* nothing — the conservative answer. A non-unique index never matches: it
316+
* refuses nothing.
317+
*/
318+
function declaredCompositeIndex(schema: unknown, columns: readonly string[] | undefined): readonly string[] | undefined {
319+
if (!columns || columns.length < 2) return undefined;
320+
const indexes = (schema as { indexes?: unknown } | undefined)?.indexes;
321+
if (!Array.isArray(indexes)) return undefined;
322+
const wanted = new Set(columns);
323+
if (wanted.size !== columns.length) return undefined;
324+
for (const raw of indexes) {
325+
const index = raw as { fields?: unknown; unique?: unknown } | null;
326+
if (!index || typeof index !== 'object') continue;
327+
if (index.unique !== 'global' && index.unique !== 'organization') continue;
328+
if (!Array.isArray(index.fields) || !index.fields.every((f): f is string => typeof f === 'string')) continue;
329+
const declared = index.fields;
330+
if (declared.length === wanted.size && new Set(declared).size === declared.length && declared.every((f) => wanted.has(f))) {
331+
return declared;
332+
}
333+
}
334+
return undefined;
335+
}
336+
337+
/**
338+
* One field's display label in the writer's locale — a translation, else its
339+
* declared `label` — or `undefined` when it has neither (the API name is never
340+
* returned as a label). The ladder {@link displayLabels} climbs for `field`.
341+
*/
342+
function fieldDisplayLabel(
343+
schema: unknown,
344+
object: string,
345+
field: string,
346+
messages: ValidationMessageContext | undefined,
347+
): string | undefined {
348+
const s = schema as { fields?: Record<string, { label?: unknown } | undefined> } | undefined;
349+
const declared = typeof s?.fields?.[field]?.label === 'string' && (s.fields[field]!.label as string).trim() !== ''
350+
? (s.fields[field]!.label as string).trim()
351+
: undefined;
352+
const label = resolveFieldLabel(field, { label: declared }, messages && { ...messages, objectName: object });
353+
return label === field && declared === undefined ? undefined : label;
214354
}
215355

216356
/**

0 commit comments

Comments
 (0)