From c04c6526ff112994b0415319bca2990d0b0ccf5a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:38:13 +0000 Subject: [PATCH 1/3] feat: say a translation fault on the answer, and guard the three unguarded bundle builders An i18n service that resolves but cannot read its translations now leaves a trace on every answer it touches: the /meta list and by-name reads on both HTTP hosts, the MCP list_objects and describe_object tools on both bridges, and query_dataset carry an optional translationWarning naming the reason, present only on such a fault. The object save refuses 503 SERVICE_UNAVAILABLE instead of storing a body whose translated echoes it could not tell from typed text; the analytics option-label pass and the upload page serve the authored labels with one warn line. Claude-Session: https://claude.ai/code/session_01L6bhgVdouXCTCCcBVLaYW5 Co-authored-by: Claude --- .changeset/35707-translation-fault-warning.md | 23 +++++++++ content/docs/references/ai/dataset-tools.mdx | 1 + content/docs/references/api/app-bundle.mdx | 15 ++++-- content/docs/references/api/protocol.mdx | 2 + packages/mcp/src/mcp-http-tools.ts | 7 ++- packages/mcp/src/metadata-completeness.ts | 6 +++ .../stdio-data-bridge.dataset-locale.test.ts | 10 ++++ ...io-data-bridge.object-locale-34872.test.ts | 34 +++++++++++++ packages/mcp/src/stdio-data-bridge.ts | 51 ++++++++++++++----- .../src/protocol-discovery-and-bases.ts | 41 +++++++++++++-- .../protocol-meta-effective-schema.test.ts | 45 ++++++++++++++++ packages/rest/src/meta-item-read-gate.ts | 49 ++++++++++++++++-- .../src/meta-translation-fault-34993.test.ts | 19 ++++--- packages/rest/src/rest-server.ts | 16 ++++-- .../domains/mcp-object-locale-34872.test.ts | 49 ++++++++++++++++++ packages/runtime/src/domains/mcp.ts | 41 ++++++++++----- .../meta-list-projection-parity.test.ts | 49 +++++++++++++++++- packages/runtime/src/domains/meta.ts | 10 +++- .../src/mcp-dataset-tools-bridge.test.ts | 16 ++++++ .../picklist-dimension-label-i18n.test.ts | 26 +++++++++- .../service-analytics/src/dataset-tools.ts | 18 ++++++- .../services/service-analytics/src/plugin.ts | 25 +++++++-- .../record-file-access.integration.test.ts | 28 +++++++++- .../service-storage/src/record-file-access.ts | 22 ++++++-- packages/spec/authorable-surface/ai.json | 1 + packages/spec/authorable-surface/api.json | 2 + packages/spec/src/ai/dataset-tools.zod.ts | 7 +++ packages/spec/src/api/protocol.zod.ts | 14 +++++ 28 files changed, 562 insertions(+), 65 deletions(-) create mode 100644 .changeset/35707-translation-fault-warning.md diff --git a/.changeset/35707-translation-fault-warning.md b/.changeset/35707-translation-fault-warning.md new file mode 100644 index 00000000000..6668fcdc5a8 --- /dev/null +++ b/.changeset/35707-translation-fault-warning.md @@ -0,0 +1,23 @@ +--- +'@objectstack/spec': patch +'@objectstack/rest': patch +'@objectstack/runtime': patch +'@objectstack/mcp': patch +'@objectstack/metadata-protocol': patch +'@objectstack/service-analytics': patch +'@objectstack/service-storage': patch +--- + +feat: an answer whose translations could not be read says so, as `translationWarning` + +Clause-②: yes (widening) — `GetMetaItemsResponseSchema`, `GetMetaItemResponseSchema` and `QueryDatasetOutputSchema` gain the optional string `translationWarning`; the MCP `list_objects` and `describe_object` answers gain the same optional member, and `DiagnosedObjectListing` and the dataset tools' `DatasetToolSource` gain the optional `translationWarning` they carry it in +Metadata-protocol: none + +When the deployment's i18n service resolves but its translations cannot be read (its `getLocales` or `getTranslations` throws), the metadata and dataset answers are served in the authored language, untranslated. Until now only `list_datasets` told the caller why; every other answer looked exactly like one for a locale with no translation. These answers now carry `translationWarning`, the server's sentence naming the reason, beside what they serve: `GET /meta/:type` and `GET /meta/:type/:name` on both HTTP hosts (the REST server and the runtime dispatcher), the MCP `list_objects` and `describe_object` tools on both transports, and `query_dataset`. It is present only on such a fault, so an answer whose translations were read is byte for byte what it was. `list_datasets` keeps the `partial` and `warning` it already serves for the same fault. A list answered as a bare array (a protocol that answers without the `{ type, items }` envelope) has no member to carry it; the server log says the fault either way. + +Three more places read the i18n service's whole catalog with no guard, so the same fault failed them with an unhandled error: + +- An object save reads the catalog to tell a translated label a Studio session sends back from one the author typed. It now refuses the save as 503 `SERVICE_UNAVAILABLE`, naming the reason, and stores nothing; retrying once the translations read again saves the same body. Saving without the catalog would have stored translated labels as the authored ones. +- A dataset query's select-option labels and the upload page's object and field labels are now served as declared, with one `warn` line saying the translations could not be read. + +Nothing to migrate. diff --git a/content/docs/references/ai/dataset-tools.mdx b/content/docs/references/ai/dataset-tools.mdx index ed3d7eab128..0459bf1ec17 100644 --- a/content/docs/references/ai/dataset-tools.mdx +++ b/content/docs/references/ai/dataset-tools.mdx @@ -341,6 +341,7 @@ const result = DatasetNextStepSchema.parse(data); | **totalGroups** | `integer` | optional | How many groups the selection formed before `offset` and `limit` cut them: the rows the same selection answers with no window. The same name and meaning as `aggregate_records`' `totalGroups`. Never paid for with a read. Where the window is pushed into the one SQL statement that grouped the answer, the database counts the groups with a window count in that statement. Where the window is applied in memory, it is the length of the grid before the window: an order by a display label (the tool's own order when none is sent sorts every selected dimension, so any select or reference dimension brings it in; an order by measures alone does not), a grid assembled from several queries (a measure with its own filter, a derived measure, `compareTo`), and a query the engine's aggregate serves, such as a date bucket, a field-to-field filter, an external object or a driver with no raw SQL. That grid is counted only when every read that built it came back whole: a grid that any cap or row guard cut before the window answers no count. Equals `rowCount` when the answer was not cut. Absent otherwise, which is when: the window was pushed down and the SQL dialect is not one the tool knows, or a selected member is itself named `__os_group_count`, or the page came back empty after an `offset`; a read was served by a strategy that does not vouch for its grid, such as one a host adds, or was cut by a cap under it; or the dataset's object is missing and the answer is the empty one served for it | | **delegationNarrowed** | `true` | optional | Present, and `true`, when the caller acts as an agent whose authority narrows what it may read on the dataset's object; `warning` states the narrowing (ADR-0090 D10) | | **warning** | `string` | optional | The narrowing statement; present exactly when `delegationNarrowed` is | +| **translationWarning** | `string` | optional | Present only when the translations this answer is labelled with could not be read (the deployment's i18n service failed while they were read): the dataset, member and option labels are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale. Independent of `warning`, which states a delegation narrowing only | ### Nested Shape: `QueryDatasetOutput.fields[number]` diff --git a/content/docs/references/api/app-bundle.mdx b/content/docs/references/api/app-bundle.mdx index 186be795fe9..d42dbd79e88 100644 --- a/content/docs/references/api/app-bundle.mdx +++ b/content/docs/references/api/app-bundle.mdx @@ -73,11 +73,11 @@ const result = AppMetadataBundleResponseSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **app** | `{ type: string; name: string; item: any; sortability?: object; … }` | ✅ | The app, as `GET /meta/app/{appId}` answers it to this caller (its navigation pruned to what the caller may open). | -| **objects** | `{ type: string; name: string; item: any; sortability?: object; … }[]` | ✅ | The objects the app's navigation reaches and the objects whose relationship fields reference them, in the object list's order, each as `GET /meta/object/{name}` answers it. An object the caller may not read is absent. | -| **views** | `{ type: string; name: string; item: any; sortability?: object; … }[]` | ✅ | The views the navigation names and the views bound to the bundled objects, each as `GET /meta/view/{name}` answers it. A view the caller may not read is absent. | -| **pages** | `{ type: string; name: string; item: any; sortability?: object; … }[]` | ✅ | The pages the navigation names and the pages bound to the bundled objects, each as `GET /meta/page/{name}` answers it. A page the caller may not read is absent. | -| **dashboards** | `{ type: string; name: string; item: any; sortability?: object; … }[]` | ✅ | The dashboards the navigation names, each as `GET /meta/dashboard/{name}` answers it. A dashboard the caller may not read is absent. | +| **app** | `{ type: string; name: string; item: any; translationWarning?: string; … }` | ✅ | The app, as `GET /meta/app/{appId}` answers it to this caller (its navigation pruned to what the caller may open). | +| **objects** | `{ type: string; name: string; item: any; translationWarning?: string; … }[]` | ✅ | The objects the app's navigation reaches and the objects whose relationship fields reference them, in the object list's order, each as `GET /meta/object/{name}` answers it. An object the caller may not read is absent. | +| **views** | `{ type: string; name: string; item: any; translationWarning?: string; … }[]` | ✅ | The views the navigation names and the views bound to the bundled objects, each as `GET /meta/view/{name}` answers it. A view the caller may not read is absent. | +| **pages** | `{ type: string; name: string; item: any; translationWarning?: string; … }[]` | ✅ | The pages the navigation names and the pages bound to the bundled objects, each as `GET /meta/page/{name}` answers it. A page the caller may not read is absent. | +| **dashboards** | `{ type: string; name: string; item: any; translationWarning?: string; … }[]` | ✅ | The dashboards the navigation names, each as `GET /meta/dashboard/{name}` answers it. A dashboard the caller may not read is absent. | ### Nested Shape: `AppMetadataBundleResponse.app` @@ -86,6 +86,7 @@ const result = AppMetadataBundleResponseSchema.parse(data); | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | | **item** | `any` | ✅ | Metadata item definition | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | | **sortability** | `{ fields: Record }` | optional | Per-column sortability projection — present exactly when `type` is `object`, on every serving branch. Computed at serve time from the served document via the spec's own storage predicates; consumers render sort affordances from this signal and never re-derive it from field `type`. See `ObjectSortabilitySchema` for the closed category set. | | **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Resolved lock verdict for this item (ADR-0010 §3.3). `none` means unlocked; `no-overlay` / `no-delete` / `full` mean the write doors refuse the corresponding write with 403. Joins two refusals: the document's own `_lock` (`ITEM_LOCKED`; the packaged artifact wins over any overlay), and the locked packaged base — an item a code package ships, on a type with no per-org overlay channel (`NOT_OVERRIDABLE`, or `ITEM_LOCKED` when the write names the read-only package). | | **lockReason** | `string` | optional | Human-readable explanation shown next to a refused write. Present only when the resolved item declares `_lockReason`. | @@ -110,6 +111,7 @@ const result = AppMetadataBundleResponseSchema.parse(data); | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | | **item** | `any` | ✅ | Metadata item definition | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | | **sortability** | `{ fields: Record }` | optional | Per-column sortability projection — present exactly when `type` is `object`, on every serving branch. Computed at serve time from the served document via the spec's own storage predicates; consumers render sort affordances from this signal and never re-derive it from field `type`. See `ObjectSortabilitySchema` for the closed category set. | | **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Resolved lock verdict for this item (ADR-0010 §3.3). `none` means unlocked; `no-overlay` / `no-delete` / `full` mean the write doors refuse the corresponding write with 403. Joins two refusals: the document's own `_lock` (`ITEM_LOCKED`; the packaged artifact wins over any overlay), and the locked packaged base — an item a code package ships, on a type with no per-org overlay channel (`NOT_OVERRIDABLE`, or `ITEM_LOCKED` when the write names the read-only package). | | **lockReason** | `string` | optional | Human-readable explanation shown next to a refused write. Present only when the resolved item declares `_lockReason`. | @@ -134,6 +136,7 @@ const result = AppMetadataBundleResponseSchema.parse(data); | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | | **item** | `any` | ✅ | Metadata item definition | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | | **sortability** | `{ fields: Record }` | optional | Per-column sortability projection — present exactly when `type` is `object`, on every serving branch. Computed at serve time from the served document via the spec's own storage predicates; consumers render sort affordances from this signal and never re-derive it from field `type`. See `ObjectSortabilitySchema` for the closed category set. | | **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Resolved lock verdict for this item (ADR-0010 §3.3). `none` means unlocked; `no-overlay` / `no-delete` / `full` mean the write doors refuse the corresponding write with 403. Joins two refusals: the document's own `_lock` (`ITEM_LOCKED`; the packaged artifact wins over any overlay), and the locked packaged base — an item a code package ships, on a type with no per-org overlay channel (`NOT_OVERRIDABLE`, or `ITEM_LOCKED` when the write names the read-only package). | | **lockReason** | `string` | optional | Human-readable explanation shown next to a refused write. Present only when the resolved item declares `_lockReason`. | @@ -158,6 +161,7 @@ const result = AppMetadataBundleResponseSchema.parse(data); | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | | **item** | `any` | ✅ | Metadata item definition | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | | **sortability** | `{ fields: Record }` | optional | Per-column sortability projection — present exactly when `type` is `object`, on every serving branch. Computed at serve time from the served document via the spec's own storage predicates; consumers render sort affordances from this signal and never re-derive it from field `type`. See `ObjectSortabilitySchema` for the closed category set. | | **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Resolved lock verdict for this item (ADR-0010 §3.3). `none` means unlocked; `no-overlay` / `no-delete` / `full` mean the write doors refuse the corresponding write with 403. Joins two refusals: the document's own `_lock` (`ITEM_LOCKED`; the packaged artifact wins over any overlay), and the locked packaged base — an item a code package ships, on a type with no per-org overlay channel (`NOT_OVERRIDABLE`, or `ITEM_LOCKED` when the write names the read-only package). | | **lockReason** | `string` | optional | Human-readable explanation shown next to a refused write. Present only when the resolved item declares `_lockReason`. | @@ -182,6 +186,7 @@ const result = AppMetadataBundleResponseSchema.parse(data); | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | | **item** | `any` | ✅ | Metadata item definition | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | | **sortability** | `{ fields: Record }` | optional | Per-column sortability projection — present exactly when `type` is `object`, on every serving branch. Computed at serve time from the served document via the spec's own storage predicates; consumers render sort affordances from this signal and never re-derive it from field `type`. See `ObjectSortabilitySchema` for the closed category set. | | **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Resolved lock verdict for this item (ADR-0010 §3.3). `none` means unlocked; `no-overlay` / `no-delete` / `full` mean the write doors refuse the corresponding write with 403. Joins two refusals: the document's own `_lock` (`ITEM_LOCKED`; the packaged artifact wins over any overlay), and the locked packaged base — an item a code package ships, on a type with no per-org overlay channel (`NOT_OVERRIDABLE`, or `ITEM_LOCKED` when the write names the read-only package). | | **lockReason** | `string` | optional | Human-readable explanation shown next to a refused write. Present only when the resolved item declares `_lockReason`. | diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 49fae8703c1..1f0da178272 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1581,6 +1581,7 @@ This schema accepts one of the following structures: | **type** | `string` | ✅ | Metadata type name | | **name** | `string` | ✅ | Item name | | **item** | `any` | ✅ | Metadata item definition | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | | **sortability** | `{ fields: Record }` | optional | Per-column sortability projection — present exactly when `type` is `object`, on every serving branch. Computed at serve time from the served document via the spec's own storage predicates; consumers render sort affordances from this signal and never re-derive it from field `type`. See `ObjectSortabilitySchema` for the closed category set. | | **lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Resolved lock verdict for this item (ADR-0010 §3.3). `none` means unlocked; `no-overlay` / `no-delete` / `full` mean the write doors refuse the corresponding write with 403. Joins two refusals: the document's own `_lock` (`ITEM_LOCKED`; the packaged artifact wins over any overlay), and the locked packaged base — an item a code package ships, on a type with no per-org overlay channel (`NOT_OVERRIDABLE`, or `ITEM_LOCKED` when the write names the read-only package). | | **lockReason** | `string` | optional | Human-readable explanation shown next to a refused write. Present only when the resolved item declares `_lockReason`. | @@ -1663,6 +1664,7 @@ One changed key path of the pending draft, and the last write that changed it. | **registrations** | `Record` | optional | The automation engine's verdict on each listed flow, keyed by the item's `name`: one entry per listed item that is not a pending draft. Present only on a `flow` list answered by a process that runs an automation service; absent otherwise, and absence means no engine judged them, never `registered`. The verdict is the answering process's engine. Beside the items, never inside one: an item's `status` stays what its author declared. | | **disabledActions** | `Record` | optional | For each listed object, keyed by the item's `name`: the names in its `actions` that this deployment's activation ledger switches off, so a call to any of them is refused 409 `ACTION_DISABLED` (the item read's `disabledActions`). One entry per listed object that is not a pending draft, `[]` when none of its actions is switched off. Present only on an `object` list answered by a process whose data engine has an activation ledger attached; absent otherwise, and absence means no ledger answered, never that nothing is switched off. Beside the items, never inside one: each item's `actions` is served as declared. | | **changedAt** | `Record` | optional | When each listed item last changed, keyed by the item's `name`: the `updated_at` of the stored row whose content the list serves for that item, an ISO-8601 instant in UTC written with `Z`. One entry per listed item served from a stored row; an item the list serves from code (a code-shipped or file-loaded definition) has no recorded change time and no entry, never a stand-in such as the read time. Where an item has several stored layers in scope (its package's own row, the package-less row, the package's declared override, environment-wide or scoped to one package), the time is the effective layer's: the row whose content is the listed item. On a `?preview=draft` list an item whose pending draft is served (`_draft: true`) has the draft row's time, since the draft is its content. Where several listed items share a name (a name two or more packages ship, the members of a bundle), the latest of their times. Only the names of items in this answer are keyed, and a door that leaves out some item of a name (the per-caller read gate, a query filter) answers no entry for that name, since the entry may be the time of the item it left out. A view a stored view container expands is not served from a row of its own name and has no entry. Absent when no listed item is served from a stored row. Beside the items, never inside one: an item's body is served as stored. | +| **translationWarning** | `string` | optional | Present only when this answer's translations could not be read (the deployment's i18n service failed while they were read): the labels and descriptions are then served as authored, untranslated, and this is the server's sentence saying why. Absent on every answer whose translations were read, including one that found no translation for the caller's locale, so its absence never means "translated". A non-empty string, never an empty one. Beside the served documents, never inside one. | ### Nested Shape: `GetMetaItemsResponse.registrations[string][state='registered']` diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 11f20e499ed..aa762a692fa 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -3991,8 +3991,12 @@ export function registerObjectTools( const visible = allowSystem ? diagnosed.objects : await filterAsync(diagnosed.objects, async (o) => !isSystemObject(o.name) || await attestsAiRead(o.name)); + // [#35707] A translation fault: the labels are untranslated, and the answer says why. + const untranslated = typeof diagnosed.translationWarning === 'string' && diagnosed.translationWarning.length > 0 + ? { translationWarning: diagnosed.translationWarning } + : {}; if (!diagnosed.degraded) { - return textResult({ objects: visible, totalCount: visible.length }); + return textResult({ objects: visible, totalCount: visible.length, ...untranslated }); } return textResult({ objects: visible, @@ -4001,6 +4005,7 @@ export function registerObjectTools( warning: metadataPartialListingSentence('objects', visible.length), code: METADATA_UNAVAILABLE_CODE, status: 503, + ...untranslated, }); } catch (err) { return metaDoorErrorResult(err, 'list_objects', undefined, faultLogger); diff --git a/packages/mcp/src/metadata-completeness.ts b/packages/mcp/src/metadata-completeness.ts index 3374268c8f8..9283bc6ec03 100644 --- a/packages/mcp/src/metadata-completeness.ts +++ b/packages/mcp/src/metadata-completeness.ts @@ -61,6 +61,12 @@ export interface DiagnosedObjectListing { objects: T[]; degraded: boolean; errors: string[]; + /** + * [#35707] The sentence of a translation fault: the listing's labels and + * descriptions are served untranslated because the translations could not + * be read. Absent on a listing whose translations were read. + */ + translationWarning?: string; } /** diff --git a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts index 9a504dfdb76..4843fc5e31e 100644 --- a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts +++ b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts @@ -252,6 +252,16 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i const answer = await bridge.queryDataset!({ datasetName: 'opp_metrics', selection: { measures: ['total_amount'] } }, { maxRows: 10 }); expect(answer.rowCount).toBe(1); expect(answer.provenance.dataset).toEqual({ name: 'opp_metrics', label: 'Opportunity Metrics' }); + // [#35707] …and says why the labels are untranslated; `warning` stays the narrowing's alone. + expect(answer.translationWarning).toEqual(expect.stringContaining(message)); + expect(answer).not.toHaveProperty('warning'); + }); + + it('[#35707] control: query_dataset over reads that answer carries no translationWarning', async () => { + const bridge = await bridgeOverRealExecutor(() => i18nService('zh-CN')); + const answer = await bridge.queryDataset!({ datasetName: 'opp_metrics', selection: { measures: ['total_amount'] } }, { maxRows: 10 }); + expect(answer.provenance.dataset).toEqual({ name: 'opp_metrics', label: '商机指标' }); + expect(answer).not.toHaveProperty('translationWarning'); }); it.each(CASES)('$read throwing: the object tools serve the authored labels', async ({ read, message }) => { diff --git a/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts index 9ba18b96123..2d0b9c1d414 100644 --- a/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts +++ b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts @@ -198,11 +198,45 @@ describe('[#34872] stdio list_objects and describe_object serve labels and descr expect(described.json).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); const listed = (await session.call('list_objects', {})).json; expect(listed.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + // [#35707] No service is no fault: nothing failed to read, so nothing is said. + expect(described.json).not.toHaveProperty('translationWarning'); + expect(listed).not.toHaveProperty('translationWarning'); } finally { await session.close(); } } }); + + // [#35707] A service that resolves but whose reads throw is a translation + // fault: both tools answer the authored text and say why, as + // `translationWarning`; a healthy answer carries no such member. + it.each(['getLocales', 'getTranslations'] as const)('[#35707] %s throwing: describe_object and list_objects answer the authored text with translationWarning', async (failing) => { + const faulting = () => ({ ...i18nService('zh-CN'), [failing]: () => { throw new Error('bundle offline'); } }); + const session = await connect({ i18n: faulting }); + try { + const described = await session.call('describe_object', { objectName: OBJ }); + expect(described.isError).toBe(false); + expect(described.json).toMatchObject({ name: OBJ, label: 'Deal', translationWarning: expect.stringContaining('bundle offline') }); + const listed = (await session.call('list_objects', {})).json; + expect(listed.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal' }); + expect(listed).toMatchObject({ totalCount: 2, translationWarning: expect.stringContaining('bundle offline') }); + } finally { + await session.close(); + } + }); + + it('[#35707] CONTROL — the reads answering under a zh-CN default: translated, and no translationWarning on either tool', async () => { + const session = await connect({ i18n: () => i18nService('zh-CN') }); + try { + const described = (await session.call('describe_object', { objectName: OBJ })).json; + expect(described.label).toBe('交易'); + expect(described).not.toHaveProperty('translationWarning'); + const listed = (await session.call('list_objects', {})).json; + expect(Object.keys(listed).sort()).toEqual(['objects', 'totalCount']); + } finally { + await session.close(); + } + }); }); describe('[#34995] the stdio object resources serve labels in the locale the object tools speak', () => { diff --git a/packages/mcp/src/stdio-data-bridge.ts b/packages/mcp/src/stdio-data-bridge.ts index 934fbbcbb29..9b2c37f228a 100644 --- a/packages/mcp/src/stdio-data-bridge.ts +++ b/packages/mcp/src/stdio-data-bridge.ts @@ -367,7 +367,7 @@ export interface StdioDataBridgeDeps { */ export interface StdioDatasetToolsService { datasetTools(deps: { - loadDatasets: (context: unknown) => Promise; + loadDatasets: (context: unknown) => Promise; translationLocale?: (context: unknown) => Promise; diagnoseDelegation?: (object: string, context: unknown) => Promise<{ narrowed: boolean; statement?: string } | undefined>; maxQueryLimit?: number; @@ -838,6 +838,12 @@ export interface ServedLocaleSources { i18n?: () => unknown; /** The `protocol` service: an object's packaged base and a declared override's pair translations. */ protocol?: () => StdioProtocolObjectReads | undefined; + /** + * [#35707] Told the sentence of a translation fault (the read served the + * text untranslated), for a tool that says it on its answer. Optional: the + * server log says it either way. + */ + reportTranslationFault?: (warning: string) => void; } /** @@ -874,7 +880,10 @@ function defaultLocaleSources(i18n: (() => unknown) | undefined, resolveProtocol async function inServedLocale(sources: ServedLocaleSources, served: readonly ObjectDef[]): Promise { if (served.length === 0) return [...served]; const translated = await translateMetaList( - defaultLocaleSources(sources.i18n, async () => sources.protocol?.()), + { + ...defaultLocaleSources(sources.i18n, async () => sources.protocol?.()), + ...(sources.reportTranslationFault ? { reportTranslationFault: sources.reportTranslationFault } : {}), + }, 'object', [...served], ); @@ -1546,6 +1555,21 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // from, through the wrapper `plugin.ts` puts on the view the // `objectstack://objects` resources read, so the two answer alike. const localizedView = servedLocaleObjectView(servedView, { i18n: deps.i18n, protocol }); + /** + * [#35707] The same view for one tool call that says a translation fault on + * its answer: `report` is told the fault's sentence. + */ + const localizedViewReporting = (report: (warning: string) => void) => + servedLocaleObjectView(servedView, { i18n: deps.i18n, protocol, reportTranslationFault: report }); + + /** The `list_objects` summaries of `view`'s objects. */ + const summariesOf = async (view: McpObjectView): Promise => + ((await view.listObjects()) as ObjectDef[]).map((o) => ({ + name: o.name, + label: o.label ?? o.name, + ...authoredDescription(o), + fieldCount: o.fields ? Object.keys(o.fields).length : undefined, + })); /** * `describe_object`'s answer for the principal: the object as they are @@ -1559,13 +1583,17 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge * exactly the ones this answer lists. */ const describeForPrincipal = async (name: string): Promise | null> => { - const { served: def, declared } = await readObjectWithDeclaration(localizedView, name); + // [#35707] A translation fault is said on the answer, as `translationWarning`. + let translationWarning: string | undefined; + const view = localizedViewReporting((warning) => { translationWarning = warning; }); + const { served: def, declared } = await readObjectWithDeclaration(view, name); if (!def) return null; // The field list is an ARRAY here, not the stored map: `validate_expression` // reads `Array.isArray(def.fields)` off this very value, and the HTTP // bridge projects the same shape. A map would type-check and silently // leave that tool with zero fields in scope. - return describeServedObject(def as ServedObjectDef, declared as ServedObjectDef); + const described = describeServedObject(def as ServedObjectDef, declared as ServedObjectDef); + return translationWarning === undefined ? described : { ...described, translationWarning }; }; const bridge: McpDataBridge = { @@ -1575,12 +1603,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge // fields that exist for them ({@link callerObjectView}). // [#34721] …and the object's authored `description`, as the HTTP twin serves it. // [#34872] …in the locale this transport speaks ({@link servedLocaleObjectView}). - return ((await localizedView.listObjects()) as ObjectDef[]).map((o) => ({ - name: o.name, - label: o.label ?? o.name, - ...authoredDescription(o), - fieldCount: o.fields ? Object.keys(o.fields).length : undefined, - })); + return summariesOf(localizedView); }, /** @@ -1594,9 +1617,11 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge * is the correct one. */ async listObjectsDiagnosed(): Promise> { - const objects = await bridge.listObjects(); + // [#35707] `listObjects`' summaries, with a translation fault said as `translationWarning`. + let translationWarning: string | undefined; + const objects = await summariesOf(localizedViewReporting((warning) => { translationWarning = warning; })); const { degraded, errors } = await diagnoseObjectListRead(metadataService); - return { objects, degraded, errors }; + return { objects, degraded, errors, ...(translationWarning === undefined ? {} : { translationWarning }) }; }, // [#32442, ruling A] The read opt-in of a system object, judged by @@ -1951,7 +1976,7 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge items, ); const rows = Array.isArray(translated) ? translated : items; - return warning === undefined ? rows : { items: rows, warning }; + return warning === undefined ? rows : { items: rows, translationWarning: warning }; }; const translationLocale = async () => { const sources = defaultLocaleSources(deps.i18n, async () => undefined); diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index a7c7c574312..8e39fd2e2fa 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -1239,6 +1239,17 @@ export class ProtocolDiscoveryAndBasesFacet { * (`locale -> data`), or `undefined` when no service or no locale is * registered — the bundle the `/meta` read exits translate with * (`translationBundleOf` in `@objectstack/rest`, built the same way). + * + * [#35707] Its one reader is the object SAVE (the echo restore above and + * {@link restoreInjectedColumnEchoes}), so a service whose `getLocales` or + * `getTranslations` throws refuses the save as a 503 + * ({@link translationsUnreadableForSaveError}) instead of answering + * `undefined` the way the read doors do: without the bundle the save + * cannot tell a label a translated read served back from one the author + * typed, and storing the echo would make the translation the authored + * text — the "storing a body this door could not judge" the stored-row + * read refuses for the same reason. The refusal is handed to the caller, + * never logged here. */ static registeredTranslationBundle(host: Pick): TranslationBundle | undefined { const service: any = host.getServicesRegistry?.().get('i18n'); @@ -1246,9 +1257,13 @@ export class ProtocolDiscoveryAndBasesFacet { return undefined; } const bundle: Record = {}; - for (const locale of service.getLocales() as string[]) { - const data = service.getTranslations(locale); - if (data && typeof data === 'object') bundle[locale] = data; + try { + for (const locale of service.getLocales() as string[]) { + const data = service.getTranslations(locale); + if (data && typeof data === 'object') bundle[locale] = data; + } + } catch (error) { + throw translationsUnreadableForSaveError(error); } return Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined; } @@ -1298,3 +1313,23 @@ export class ProtocolDiscoveryAndBasesFacet { return undefined; } } + +/** + * [#35707] The refusal an object save answers when the registered i18n + * service cannot read its translations + * ({@link ProtocolDiscoveryAndBasesFacet.registeredTranslationBundle}): 503 + * `SERVICE_UNAVAILABLE`, the code the metadata store's own unavailable read + * answers, with the service's reason kept as `cause`. Retrying once the + * translations read again saves the same body. + */ +function translationsUnreadableForSaveError(cause: unknown): Error { + const reason = cause instanceof Error ? cause.message : String(cause); + const err = new Error( + `The translations could not be read (${reason}), so this save cannot tell a translated label served back ` + + 'from one written by hand; nothing was saved. Retry once the translations can be read.', + ) as Error & { code?: string; status?: number; cause?: unknown }; + err.code = 'SERVICE_UNAVAILABLE'; + err.status = 503; + err.cause = cause; + return err; +} diff --git a/packages/objectql/src/protocol-meta-effective-schema.test.ts b/packages/objectql/src/protocol-meta-effective-schema.test.ts index 9e2410155e7..ba98b6ee490 100644 --- a/packages/objectql/src/protocol-meta-effective-schema.test.ts +++ b/packages/objectql/src/protocol-meta-effective-schema.test.ts @@ -737,3 +737,48 @@ describe('[#33952] a zh-CN read of a patched field label, echoed back, is stored expect(stored.fields.name.label).toBe('Account Name'); }); }); + +/** + * [#35707] The object save reads the registered i18n service's whole catalog + * to tell a translated echo from typed text. A service whose `getLocales` or + * `getTranslations` throws leaves it unable to tell, so the save is refused + * 503 `SERVICE_UNAVAILABLE` and nothing is stored — never a body whose + * translated labels became the authored ones. The control saves the same body + * over a service that reads. + */ +describe('[#35707] an object save over translations that cannot be read is refused, and stores nothing', () => { + const body = () => ({ + name: 'crm_note', label: 'Note', sharingModel: 'private', + fields: { title: { name: 'title', type: 'text', label: 'Title' } }, + }); + const i18nOf = (failing?: 'getLocales' | 'getTranslations') => ({ + getLocales: () => { + if (failing === 'getLocales') throw new Error('bundle offline'); + return ['en', 'zh-CN']; + }, + getTranslations: (locale: string) => { + if (failing === 'getTranslations') throw new Error('bundle offline'); + return locale === 'zh-CN' ? { objects: { crm_note: { label: '笔记' } } } : {}; + }, + }); + const saveOver = async (i18n: unknown) => { + const host = makeHost(false); + const protocol: any = new ObjectStackProtocolImplementation(host.engine, () => new Map([['i18n', i18n]])); + const outcome = await protocol.saveMetaItem({ type: 'object', name: 'crm_note', item: body(), mode: 'publish' } as any) + .then(() => null, (e: unknown) => e); + return { outcome, stored: Array.from(host.rows.values()).some((r) => r.name === 'crm_note') }; + }; + + it('control: the translations reading, the save stores the body', async () => { + expect(await saveOver(i18nOf())).toEqual({ outcome: null, stored: true }); + }); + + for (const failing of ['getLocales', 'getTranslations'] as const) { + it(`${failing} throwing: 503 SERVICE_UNAVAILABLE naming the reason, and no row`, async () => { + const { outcome, stored } = await saveOver(i18nOf(failing)); + expect(outcome).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect((outcome as Error).message).toContain('bundle offline'); + expect(stored).toBe(false); + }); + } +}); diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 946fd74f68d..7352e14661e 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -4232,13 +4232,49 @@ export async function translateMetaEnvelope( && runtimeDocument && typeof runtimeDocument === 'object' && !Array.isArray(runtimeDocument) ? { sortability: resolveObjectSortability(runtimeDocument) } : {}; + let translationWarning: string | undefined; + const item = await translateMetaDocument( + { + ...sources, + reportTranslationFault: (warning) => { + translationWarning = warning; + sources.reportTranslationFault?.(warning); + }, + }, + metaType, + document, + ); return { ...envelope, ...sortability, - item: await translateMetaDocument(sources, metaType, document), + item, + ...withTranslationWarningOf(translationWarning), }; } +/** + * [#35707] The `translationWarning` member of a `/meta` answer + * (`GetMetaItemsResponseSchema`, `GetMetaItemResponseSchema`): the sentence + * {@link translationBundleOf} reported for this answer's translation, or + * nothing. Only a fault reports one, so a healthy answer is the body it was. + */ +function withTranslationWarningOf(warning: string | undefined): { translationWarning?: string } { + return typeof warning === 'string' && warning.length > 0 ? { translationWarning: warning } : {}; +} + +/** + * [#35707] A list answer with its `translationWarning` beside the items: on + * the `{ type, items }` envelope the spec declares. A bare array (a protocol + * that answers the list without its envelope) has no member to carry it and is + * answered as it came; the server log says the fault either way. + */ +function withListTranslationWarning(data: unknown, warning: string | undefined): unknown { + const member = withTranslationWarningOf(warning); + if (member.translationWarning === undefined) return data; + if (!data || typeof data !== 'object' || Array.isArray(data)) return data; + return { ...(data as Record), ...member }; +} + // ── The object mask's answer ────────────────────────────────────────────────── /** [ADR-0106 D6 tier 2] The cache posture a schema served under an UNDETERMINED field visibility carries. */ @@ -4525,8 +4561,12 @@ export interface MetaListAnswerSources extends MetaItemReadGateSources { * The translation step: {@link translateMetaList} over this transport's * I/O, handed the folded `metaType`. A port rather than a call so each * transport keeps ONE entry into it (`RestServer.translateMetaItems`). + * + * [#35707] `reportTranslationFault` is handed on as the translation's + * {@link MetaListTranslationSources.reportTranslationFault}, so the chain + * serves the fault's sentence as the answer's `translationWarning`. */ - translateList(metaType: string, items: unknown): Promise; + translateList(metaType: string, items: unknown, reportTranslationFault?: (warning: string) => void): Promise; /** * [#5224] The endpoint matcher this request's `api` face asks — the * `metadata` service occupying the slot, or `undefined`. It is PROBED here @@ -4992,7 +5032,10 @@ export function createMetaListAnswer( visible = withChangedAtOfListedNames(raw, visible); // 9. The translation step ({@link translateMetaList}, through the transport's entry). - const data = await sources.translateList(metaType, visible); + // [#35707] A translation fault is said on the answer, as `translationWarning`. + let translationWarning: string | undefined; + const translated = await sources.translateList(metaType, visible, (warning) => { translationWarning = warning; }); + const data = withListTranslationWarning(translated, translationWarning); // 10. [#27627] The validator of what is served — over `data`, the // list after every step above, never an earlier stage of it. return { ok: true, data, ...metaRepresentationCaching(data, cacheControl) }; diff --git a/packages/rest/src/meta-translation-fault-34993.test.ts b/packages/rest/src/meta-translation-fault-34993.test.ts index e2369d710b5..17d0b655e15 100644 --- a/packages/rest/src/meta-translation-fault-34993.test.ts +++ b/packages/rest/src/meta-translation-fault-34993.test.ts @@ -5,8 +5,10 @@ * but whose `getLocales` / `getTranslations` throws. The shared translator * (`translationBundleOf`) answers it as no bundle, so the list and the by-name * read serve the authored text (200, not 500), and the server log says so at - * `warn` — this door carries no warning on its answer. The control serves the - * bundle label over the same harness, so the authored text is the fault's doing. + * `warn`. [#35707] Both answers say it too, as `translationWarning` beside the + * served documents; a healthy answer carries no such member. The control + * serves the bundle label over the same harness, so the authored text is the + * fault's doing. */ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; @@ -35,7 +37,8 @@ function restOver(i18n: unknown) { const protocol = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), getMetaTypes: vi.fn().mockResolvedValue([]), - getMetaItems: vi.fn(async ({ type }: any) => (type === 'object' ? [ACCOUNT] : [])), + // The `{ type, items }` envelope the protocol answers, the member `translationWarning` rides beside. + getMetaItems: vi.fn(async ({ type }: any) => ({ type, items: type === 'object' ? [ACCOUNT] : [] })), getMetaItem: vi.fn(async ({ type, name }: any) => ({ type, name, item: ACCOUNT, lock: 'none', editable: true })), findData: vi.fn().mockResolvedValue([]), }; @@ -58,7 +61,7 @@ async function read(rest: RestServer, path: string, params: Record { vi.stubEnv('OS_REST_LOG', 'info'); }); @@ -67,7 +70,9 @@ afterAll(() => { vi.unstubAllEnvs(); }); describe('[#34993] REST /meta serves the authored text on a translation fault', () => { it('control: the reads answering, the list serves the bundle label', async () => { expect(await read(restOver(i18nWhoseReadThrows(undefined)), '/api/v1/meta/:type', { type: 'object' })) - .toEqual({ status: 200, label: '客户', field: '行业' }); + .toEqual({ status: 200, label: '客户', field: '行业', translationWarning: undefined }); + expect(await read(restOver(i18nWhoseReadThrows(undefined)), '/api/v1/meta/:type/:name', { type: 'object', name: 'showcase_account' })) + .toEqual({ status: 200, label: '客户', field: '行业', translationWarning: undefined }); }); it.each(['getLocales', 'getTranslations'] as const)('%s throwing: list and by-name read answer 200 untranslated, and the log says why', async (failing) => { @@ -75,9 +80,9 @@ describe('[#34993] REST /meta serves the authored text on a translation fault', try { const rest = restOver(i18nWhoseReadThrows(failing)); expect(await read(rest, '/api/v1/meta/:type', { type: 'object' })) - .toEqual({ status: 200, label: 'Account', field: 'Industry' }); + .toEqual({ status: 200, label: 'Account', field: 'Industry', translationWarning: expect.stringContaining('bundle offline') }); expect(await read(rest, '/api/v1/meta/:type/:name', { type: 'object', name: 'showcase_account' })) - .toEqual({ status: 200, label: 'Account', field: 'Industry' }); + .toEqual({ status: 200, label: 'Account', field: 'Industry', translationWarning: expect.stringContaining('bundle offline') }); expect(warn.mock.calls.map((c) => String(c[0]))).toEqual( expect.arrayContaining([expect.stringContaining('bundle offline')]), ); diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 5cd1517d870..60b18481da2 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -4715,9 +4715,18 @@ export class RestServer { * transports run, reached here through {@link metaListAnswerSources}; this * method folds the spelling and hands in this transport's I/O. */ - private async translateMetaItems(req: any, type: string, environmentId: string | undefined, items: any): Promise { + private async translateMetaItems( + req: any, + type: string, + environmentId: string | undefined, + items: any, + reportTranslationFault?: (warning: string) => void, + ): Promise { return metaReadGate.translateMetaList( - this.metaListTranslationSources(environmentId, req), + { + ...this.metaListTranslationSources(environmentId, req), + ...(reportTranslationFault ? { reportTranslationFault } : {}), + }, RestServer.metaTypeSingular(type), items, ); @@ -4760,7 +4769,8 @@ export class RestServer { return { ...this.metaItemReadGateSources(environmentId, req, p), requestLocale: (i18n) => this.extractLocale(req, i18n), - translateList: (_metaType, items) => this.translateMetaItems(req, req.params.type, environmentId, items), + translateList: (_metaType, items, reportTranslationFault) => + this.translateMetaItems(req, req.params.type, environmentId, items, reportTranslationFault), resolveEndpointMatcher: () => this.resolveEndpointMatchAuthority(environmentId, req), notifyMissingEndpointMatcher: (surface) => this.notifyMissingEndpointAuthority(surface), resolveObjectMasker: () => this.resolveObjectMasker(environmentId, req, 'object'), diff --git a/packages/runtime/src/domains/mcp-object-locale-34872.test.ts b/packages/runtime/src/domains/mcp-object-locale-34872.test.ts index 34fd1acfcbb..5789e03e972 100644 --- a/packages/runtime/src/domains/mcp-object-locale-34872.test.ts +++ b/packages/runtime/src/domains/mcp-object-locale-34872.test.ts @@ -253,4 +253,53 @@ describe('[#34872] HTTP MCP list_objects and describe_object serve labels and de expect(noI18n).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); expect(field(noI18n, 'subject')).toMatchObject({ label: 'Subject' }); }); + + // [#35707] A translation fault: an i18n service that resolves but whose + // reads throw. The answers are the authored text, never a refusal, and the + // two the object tools render carry `translationWarning` naming the + // reason; a healthy answer carries no such member. + const throwingI18n = (failing: 'getLocales' | 'getTranslations') => ({ + ...i18nService, + [failing]: () => { throw new Error('bundle offline'); }, + }); + + it.each(['getLocales', 'getTranslations'] as const)('[#35707] %s throwing: describe_object and list_objects answer the authored text and say why', async (failing) => { + const bridge = await bridgeAs(PERSONAS.staff, 'zh-CN', { i18n: throwingI18n(failing) }); + const described = await bridge.describeObject(OBJ); + expect(described).toMatchObject({ name: OBJ, label: 'Deal', description: OBJECT_TEXT }); + expect(field(described, 'amount')).toMatchObject({ label: 'Amount', description: AMOUNT_TEXT }); + expect(described.translationWarning).toEqual(expect.stringContaining('bundle offline')); + const listing = await bridge.listObjectsDiagnosed(); + expect(listing.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); + expect(listing.translationWarning).toEqual(expect.stringContaining('bundle offline')); + }); + + it('[#35707] CONTROL — the reads answering: the same answers are translated and carry no translationWarning', async () => { + const bridge = await bridgeAs(PERSONAS.staff, 'zh-CN'); + const described = await bridge.describeObject(OBJ); + expect(described.label).toBe('交易'); + expect(described).not.toHaveProperty('translationWarning'); + const listing = await bridge.listObjectsDiagnosed(); + expect(listing.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: '交易' }); + expect(listing).not.toHaveProperty('translationWarning'); + }); + + // [#35707] A host that hands the dispatcher its own request object, its + // query already parsed (`request.query`), not a Fetch `Request`: the + // locale is read from that query. The URL names another locale, so an + // answer read from the URL instead could not pass. + it('[#35707] a host request whose query is already parsed: `?locale=` is read from `request.query`', async () => { + const dispatcher = new HttpDispatcher(kernelOver(services), undefined, { enforceProjectMembership: false }); + const hostRequest = { method: 'POST', url: '/api/v1/mcp?locale=fr-FR', headers: {}, query: { locale: 'zh-CN' } }; + const bridge = dispatcher.buildMcpBridge({ + request: hostRequest, response: {}, environmentId: undefined, executionContext: { ...PERSONAS.staff }, + } as any); + const described = await bridge.describeObject(OBJ); + expect(described).toMatchObject({ name: OBJ, label: '交易', description: '一笔销售交易,从首次接触到签单。' }); + // CONTROL — the same host request without a parsed query reads its URL: `fr-FR` has no entry. + const fromUrl = dispatcher.buildMcpBridge({ + request: { ...hostRequest, query: undefined }, response: {}, environmentId: undefined, executionContext: { ...PERSONAS.staff }, + } as any); + expect(await fromUrl.describeObject(OBJ)).toMatchObject({ label: 'Deal' }); + }); }); diff --git a/packages/runtime/src/domains/mcp.ts b/packages/runtime/src/domains/mcp.ts index ec8fe99d149..a76b7036b73 100644 --- a/packages/runtime/src/domains/mcp.ts +++ b/packages/runtime/src/domains/mcp.ts @@ -1136,9 +1136,17 @@ export function buildMcpBridge( * No locale, or a key the bundle does not carry, leaves the authored text; * names never change. */ - const inCallerLocale = async (served: readonly any[]): Promise => { + const inCallerLocale = async (served: readonly any[], reportTranslationFault?: (warning: string) => void): Promise => { if (served.length === 0) return [...served]; - const translated = await translateMetaList(metaTranslationSources(deps, context, getProtocol), 'object', [...served]); + const translated = await translateMetaList( + { + ...metaTranslationSources(deps, context, getProtocol), + // [#35707] Handed back to the tool that says the fault on its answer. + ...(reportTranslationFault ? { reportTranslationFault } : {}), + }, + 'object', + [...served], + ); return Array.isArray(translated) ? translated : [...served]; }; @@ -1148,7 +1156,7 @@ export function buildMcpBridge( return def ? await servedToCaller(def) : def; }; - const listObjectSummaries = async (): Promise => { + const listObjectSummaries = async (reportTranslationFault?: (warning: string) => void): Promise => { const objs = await readServedObjects(); const served: any[] = []; // [ADR-0106 D5(2)] Every listed object as this caller is served it, @@ -1162,7 +1170,7 @@ export function buildMcpBridge( } const out: any[] = []; // [#34872] …in the caller's locale, the page translated in one call. - for (const o of await inCallerLocale(served)) { + for (const o of await inCallerLocale(served, reportTranslationFault)) { out.push({ name: o.name, label: o.label ?? o.name, @@ -1188,12 +1196,15 @@ export function buildMcpBridge( const def: any = declared ? await servedToCaller(declared) : declared; if (!def) return null; // `declared` is read for the `readonly` verdict alone, which no translation touches. - const [localized] = await inCallerLocale([def]); - return describeServedObject(localized, declared); + // [#35707] A translation fault is said on the answer, as `translationWarning`. + let translationWarning: string | undefined; + const [localized] = await inCallerLocale([def], (warning) => { translationWarning = warning; }); + const described = describeServedObject(localized, declared); + return translationWarning === undefined ? described : { ...described, translationWarning }; }; const bridge = { - listObjects: listObjectSummaries, + listObjects: () => listObjectSummaries(), /** * [#6504] The HTTP transport's half of the `list_objects` completeness * fix — the stdio bridge (`packages/mcp/src/stdio-data-bridge.ts`) @@ -1218,10 +1229,13 @@ export function buildMcpBridge( * that cannot manufacture a claim. */ listObjectsDiagnosed: async () => { - const objects = await listObjectSummaries(); + // [#35707] A translation fault rides the listing as `translationWarning`. + let translationWarning: string | undefined; + const objects = await listObjectSummaries((warning) => { translationWarning = warning; }); + const said = translationWarning === undefined ? {} : { translationWarning }; const meta: any = await getMeta(); if (!meta || typeof meta.listDiagnosed !== 'function') { - return { objects, degraded: false, errors: [] }; + return { objects, degraded: false, errors: [], ...said }; } try { const diagnosed: any = await meta.listDiagnosed('object'); @@ -1229,9 +1243,10 @@ export function buildMcpBridge( objects, degraded: diagnosed?.degraded === true, errors: Array.isArray(diagnosed?.errors) ? diagnosed.errors : [], + ...said, }; } catch { - return { objects, degraded: false, errors: [] }; + return { objects, degraded: false, errors: [], ...said }; } }, // [#25120] Answered from the listing `list_objects` serves @@ -1878,7 +1893,7 @@ function recordContextMembers( */ export interface McpDatasetToolsService { datasetTools(deps: { - loadDatasets: (context: unknown) => Promise; + loadDatasets: (context: unknown) => Promise; translationLocale?: (context: unknown) => Promise; diagnoseDelegation?: (object: string, context: unknown) => Promise<{ narrowed: boolean; statement?: string } | undefined>; maxQueryLimit?: number; @@ -2023,7 +2038,7 @@ function metaTranslationSources( * the REST door localizes a saved dataset. A throwing read is left to throw: * the executor answers it as a degraded read (`partial` / 503), never as an * empty catalogue. [#34993] A translation fault is no failed read: the rows - * are handed over untranslated, with the fault's sentence as their `warning`. + * are handed over untranslated, with the fault's sentence as their `translationWarning` (#35707). * - [#35083] `translationLocale` is the locale that translation read, so the * executor's labels and its sentences speak one language. * - The narrowing probe is the bridge's own `diagnoseDelegation` read, asked @@ -2050,7 +2065,7 @@ function datasetToolMembers( items, ); const rows = Array.isArray(translated) ? translated : items; - return warning === undefined ? rows : { items: rows, warning }; + return warning === undefined ? rows : { items: rows, translationWarning: warning }; }; const translationLocale = async () => { const sources = metaTranslationSources(deps, context, getProtocol); diff --git a/packages/runtime/src/domains/meta-list-projection-parity.test.ts b/packages/runtime/src/domains/meta-list-projection-parity.test.ts index 9ea53946260..8da9a6be4b7 100644 --- a/packages/runtime/src/domains/meta-list-projection-parity.test.ts +++ b/packages/runtime/src/domains/meta-list-projection-parity.test.ts @@ -385,6 +385,8 @@ const itemsOf = (data: any): any[] | undefined => interface Boot { withI18n?: boolean; + /** [#35707] The i18n service in place of {@link i18nDouble}. */ + i18n?: unknown; /** [#20478] A protocol with no layered read (`getMetaItemLayered` absent). */ withoutLayered?: boolean; } @@ -397,7 +399,7 @@ function bootDispatcher(callerName: CallerName, opts: Boot = {}) { protocol, security: securityFor(caller), metadata: endpointMatcher, - ...(opts.withI18n === false ? {} : { i18n: i18nDouble }), + ...(opts.withI18n === false ? {} : { i18n: opts.i18n ?? i18nDouble }), }; const get = (n: string) => services[n] ?? null; const kernel: any = { context: { getService: get }, getService: get, getServiceAsync: async (n: string) => get(n) }; @@ -455,7 +457,7 @@ function bootRest(callerName: CallerName, opts: Boot = {}) { rest.securityServiceProvider = async () => securityFor(caller); rest.serviceExistsProvider = (name: string) => name !== 'tenancy'; rest.metadataServiceProvider = async () => endpointMatcher; - if (opts.withI18n !== false) rest.i18nServiceProvider = async () => i18nDouble; + if (opts.withI18n !== false) rest.i18nServiceProvider = async () => opts.i18n ?? i18nDouble; rest.registerRoutes(); const META = '/api/v1/meta'; const routeOf = (path: string) => { @@ -1391,3 +1393,46 @@ describe('[#20408] an undetermined field visibility (ADR-0106 D6 tier 2) serves } } }); + +/** + * [#35707] A translation fault — an i18n service that resolves but whose + * `getLocales` throws — on the list and the by-name read: both transports + * answer 200 with the authored text and the same `translationWarning` beside + * the served documents. The control, over the readable double, carries no + * such member on either transport. + */ +describe('[#35707] a translation fault is said as translationWarning, the same on both transports', () => { + const faulting = { ...i18nDouble, getLocales: () => { throw new Error('bundle offline'); } }; + const ZH = { 'accept-language': 'zh-CN' }; + /** + * A booted transport whose list read answers the `{ type, items }` + * envelope the real protocol answers: the double's bare array has no + * member to carry the warning, and is answered as it came. + */ + const enveloped = (boot: T): T => { + const bare = boot.protocol.getMetaItems.getMockImplementation(); + boot.protocol.getMetaItems.mockImplementation(async (request: any) => ({ type: request.type, items: await bare(request) })); + return boot; + }; + for (const path of ['/meta/object', '/meta/object/invoice']) { + it(`GET ${path} under zh-CN`, async () => { + const dispatcher = await enveloped(bootDispatcher('holder', { i18n: faulting })).read(path, {}, ZH); + const rest = await enveloped(bootRest('holder', { i18n: faulting })).read(path, {}, ZH); + const list = path === '/meta/object'; + for (const answer of [dispatcher, rest]) { + expect(answer.status).toBe(200); + const doc = list ? answer.items?.find((o: any) => o?.name === 'invoice') : answer.item; + expect(doc?.label).toBe('Invoice'); + } + const warningOf = (answer: Answer, onDispatcher: boolean) => (onDispatcher ? answer.body?.data : answer.body)?.translationWarning; + expect(warningOf(rest, false)).toEqual(expect.stringContaining('bundle offline')); + expect(warningOf(dispatcher, true)).toBe(warningOf(rest, false)); + // CONTROL — the readable double: translated, and no member on either transport. + const healthyDispatcher = await enveloped(bootDispatcher('holder')).read(path, {}, ZH); + const healthyRest = await enveloped(bootRest('holder')).read(path, {}, ZH); + expect(list ? healthyRest.items?.find((o: any) => o?.name === 'invoice')?.label : healthyRest.item?.label).toBe('发票'); + expect(warningOf(healthyRest, false)).toBeUndefined(); + expect(warningOf(healthyDispatcher, true)).toBeUndefined(); + }); + } +}); diff --git a/packages/runtime/src/domains/meta.ts b/packages/runtime/src/domains/meta.ts index 905863dda3e..64b7273472b 100644 --- a/packages/runtime/src/domains/meta.ts +++ b/packages/runtime/src/domains/meta.ts @@ -745,8 +745,14 @@ async function answerMetaList( // which cache posture the page owes. resolveObjectMasker: () => resolveObjectMasker(deps, context, 'object'), requestLocale, - translateList: (metaType, items) => translateMetaList( - metaTranslationSources(deps, context, protocol, requestLocale), metaType, items, + // [#35707] The fault's sentence is handed back, so the chain serves it as `translationWarning`. + translateList: (metaType, items, reportTranslationFault) => translateMetaList( + { + ...metaTranslationSources(deps, context, protocol, requestLocale), + ...(reportTranslationFault ? { reportTranslationFault } : {}), + }, + metaType, + items, ), }; try { diff --git a/packages/runtime/src/mcp-dataset-tools-bridge.test.ts b/packages/runtime/src/mcp-dataset-tools-bridge.test.ts index e16ba478689..bd71d2f6863 100644 --- a/packages/runtime/src/mcp-dataset-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-dataset-tools-bridge.test.ts @@ -223,6 +223,22 @@ describe('[ADR-0149 D2] the HTTP dataset tools when the i18n service resolves bu const answer = await bridge.queryDataset!({ datasetName: 'sales_analysis', selection: { measures: ['revenue'] } }, { maxRows: 10 }); expect(answer.rowCount).toBe(1); expect(answer.provenance.dataset).toEqual({ name: 'sales_analysis', label: 'Sales analysis' }); + // [#35707] …and says why the labels are untranslated; `warning` stays the + // narrowing's alone (this harness's security double narrows every object). + expect(answer.translationWarning).toEqual(expect.stringContaining(message)); + expect(answer).toMatchObject({ delegationNarrowed: true, warning: 'narrowed on crm_opportunity' }); + }); + + it('[#35707] control: query_dataset over reads that answer carries no translationWarning', async () => { + const answering = { + getLocales: () => ['zh-CN', 'en'], + getTranslations: (locale: string) => (locale === 'zh-CN' ? ZH_CN : {}), + getDefaultLocale: () => 'zh-CN', + }; + const bridge = await bridgeOverRealExecutor(answering); + const answer = await bridge.queryDataset!({ datasetName: 'sales_analysis', selection: { measures: ['revenue'] } }, { maxRows: 10 }); + expect(answer.provenance.dataset).toEqual({ name: 'sales_analysis', label: '销售分析' }); + expect(answer).not.toHaveProperty('translationWarning'); }); /** diff --git a/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts b/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts index 6b2641e36a4..43cea933f19 100644 --- a/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts +++ b/packages/services/service-analytics/src/__tests__/picklist-dimension-label-i18n.test.ts @@ -47,7 +47,7 @@ * service as `i18n`. */ -import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { DatasetSchema } from '@objectstack/spec/ui'; @@ -341,6 +341,30 @@ describe('[#22178] a picklist-bound select dimension renders its labels in the r expect(await labelsOf(face, 'type', 'en')).toEqual(EXPECTED['zh-CN'].type); }); }); + + // [#35707] A translation fault is no failed query: the bundle the option + // labels translate through is answered as none, so the rows carry the + // authored labels, and one warn line says why. + for (const failing of ['getLocales', 'getTranslations'] as const) { + it(`#35707: ${failing} throwing — zh-CN rows answer the authored labels, and the log says the translations could not be read`, async () => { + const warn = vi.spyOn(quiet, 'warn'); + try { + await withI18n({ [failing]: () => { throw new Error('bundle offline'); } }, async () => { + expect(await labelsOf(face, 'industry', 'zh-CN')).toEqual(AUTHORED.industry); + expect(await labelsOf(face, 'type', 'zh-CN')).toEqual(AUTHORED.type); + }); + const said = warn.mock.calls.map((c) => String((c as unknown[])[0])).filter((m) => m.startsWith('[Analytics]')); + expect(said.length).toBeGreaterThan(0); + expect(said[0]).toContain('bundle offline'); + } finally { + warn.mockRestore(); + } + }); + } + + it('#35707 CONTROL — the same reads answering again, zh-CN rows answer the translated labels', async () => { + expect(await labelsOf(face, 'type', 'zh-CN')).toEqual(EXPECTED['zh-CN'].type); + }); }); } }); diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index d635869776a..96c1b93508c 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -177,10 +177,19 @@ export function getDatasetToolDefinitions(): readonly AIToolDefinition[] { * [#34993] A `warning` without `partial` is a whole read the host says * something about (a translation fault: every row, its text untranslated): * `list_datasets` says it, and `query_dataset` still answers. + * [#35707] `translationWarning` is that translation fault named as one: the + * rows are whole, their text untranslated. `list_datasets` says it as it says + * `warning`, and `query_dataset` serves it as its answer's + * `translationWarning`. */ export type DatasetToolSource = | readonly unknown[] - | { readonly items: readonly unknown[]; readonly partial?: true; readonly warning?: string }; + | { + readonly items: readonly unknown[]; + readonly partial?: true; + readonly warning?: string; + readonly translationWarning?: string; + }; /** The ADR-0090 D10 narrowing probe, in `McpDataBridge.diagnoseDelegation`'s shape. */ export type DatasetToolDelegationProbe = ( @@ -315,6 +324,8 @@ interface LoadedDatasets { readonly holdings: ReadonlyArray<{ readonly packageId: string | null; readonly name: unknown; readonly dataset?: Dataset }>; readonly partial: boolean; readonly warning?: string; + /** [#35707] The host's translation-fault sentence ({@link DatasetToolSource}). */ + readonly translationWarning?: string; } /** @@ -419,6 +430,7 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { const items = Array.isArray(source) ? source : (source as { items?: readonly unknown[] }).items ?? []; const degraded = !Array.isArray(source) && (source as { partial?: unknown }).partial === true; const said = Array.isArray(source) ? undefined : (source as { warning?: unknown }).warning; + const untranslated = Array.isArray(source) ? undefined : (source as { translationWarning?: unknown }).translationWarning; const datasets: Dataset[] = []; const holdings: Array = []; for (const item of items) { @@ -437,6 +449,7 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { holdings, partial: degraded, ...(degraded ? { warning: String(said ?? 'The dataset read was degraded.') } : typeof said === 'string' ? { warning: said } : {}), + ...(typeof untranslated === 'string' && untranslated.length > 0 ? { translationWarning: untranslated } : {}), }; } @@ -507,6 +520,7 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { const warnings: string[] = []; if (loaded.warning) warnings.push(loaded.warning); + if (loaded.translationWarning) warnings.push(loaded.translationWarning); if (unresolved) { warnings.push('Some datasets or members could not be checked against this caller\'s permissions and are left out.'); } @@ -638,6 +652,8 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { ...(narrowing?.narrowed && narrowing.statement ? { delegationNarrowed: true as const, warning: narrowing.statement } : {}), + // [#35707] The labels above were read through translations that failed: say so. + ...(loaded.translationWarning ? { translationWarning: loaded.translationWarning } : {}), } as QueryDatasetOutput; } diff --git a/packages/services/service-analytics/src/plugin.ts b/packages/services/service-analytics/src/plugin.ts index c3ed4e445ad..fb1912aa6d6 100644 --- a/packages/services/service-analytics/src/plugin.ts +++ b/packages/services/service-analytics/src/plugin.ts @@ -1173,13 +1173,28 @@ export class AnalyticsServicePlugin implements Plugin { // "translate a select option label" implementation: the actual lookup // stays exactly one function, `translateObject` below, imported rather // than reimplemented. + // + // [#35707] A service whose `getLocales` or `getTranslations` throws is a + // translation fault, answered as `translationBundleOf` (`packages/rest`) + // answers it: no bundle, so the option labels stay authored, and one + // `warn` line saying why (a functional degradation — the labels are + // served, untranslated). The dataset tools tell their caller through the + // same service's catalogue read (`translationWarning`). const buildTranslationBundle = (i18n: II18nService): TranslationBundle | undefined => { - const locales = i18n.getLocales(); - if (!locales.length) return undefined; const bundle: TranslationBundle = {}; - for (const locale of locales) { - const data = i18n.getTranslations(locale); - if (data && typeof data === 'object') (bundle as Record)[locale] = data; + try { + const locales = i18n.getLocales(); + if (!locales.length) return undefined; + for (const locale of locales) { + const data = i18n.getTranslations(locale); + if (data && typeof data === 'object') (bundle as Record)[locale] = data; + } + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + ctx.logger.warn( + `[Analytics] The translations could not be read (${reason}), so dimension option labels are served untranslated.`, + ); + return undefined; } return Object.keys(bundle).length ? bundle : undefined; }; diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index b2a651b01da..3bf6daf337a 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -125,6 +125,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o /** [#32712] The workspace's default locale, as the `localization` settings answer it; none unless a case sets one. */ let workspaceLocale: string | undefined; const localizationChanged: Array<() => void> = []; + /** [#35707] The plugin's logger, so a case can read what a degradation said. */ + const pluginLogger = silentLogger(); const setWorkspaceLocale = (locale: string | undefined) => { workspaceLocale = locale; for (const fn of localizationChanged) fn(); @@ -159,7 +161,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const phases = new Map unknown>>(); const mount = (m: string) => (path: string, handler: RouteHandler) => { routes.set(`${m}:${path}`, handler); }; const ctx = { - logger: silentLogger(), + logger: pluginLogger, registerService: (name: string, svc: unknown) => { services.set(name, svc); }, getService: (name: string): T => { if (!services.has(name)) throw new Error(`service '${name}' not registered`); @@ -1047,6 +1049,30 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o }); }); + it.each(['getLocales', 'getTranslations'] as const)('#35707: %s throwing — the page still serves, with the labels as declared, and the log says why', async (failing) => { + const id = await titledClaim(); + const grant = await files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never); + const i18n = { + getLocales: () => { + if (failing === 'getLocales') throw new Error('bundle offline'); + return ['zh-CN']; + }, + getTranslations: (locale: string) => { + if (failing === 'getTranslations') throw new Error('bundle offline'); + return locale === 'zh-CN' ? { objects: { claim: { label: '报销单', fields: { policy: { label: '保单' } } } } } : {}; + }, + }; + pluginLogger.warn.mockClear(); + await withServices({ i18n }, async () => { + const page = await openIn(tokenOf(grant.path), ZH); + expect(page._status).toBe(200); + expect(String(page._sent)).toContain(`${row(zh.recordRow, zh.recordTitled('Claim', TITLE))}${row(zh.goesIntoRow, zh.intoField('Policy'))}`); + }); + const said = pluginLogger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[RecordFileAccess]')); + expect(said.length).toBeGreaterThan(0); + expect(said[0]).toContain('bundle offline'); + }); + it('#33634: with sourceLocale en declared over a zh-CN default, an English page names the inline labels and a Chinese one the pack', async () => { const id = await titledClaim(); const grant = await files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never); diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index 296b810b5ab..caa870bc2af 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -711,12 +711,24 @@ function titleOf(value: unknown, recordId: string): string | undefined { * shape `translateObject` reads (the glue `RestServer.buildTranslationBundle` * and the analytics service's label pass build the same way); `undefined` * when it holds none. + * + * [#35707] A service whose `getLocales` or `getTranslations` throws is a + * translation fault, answered as `translationBundleOf` in `packages/rest` + * answers it: `undefined`, so the page's labels are served as declared, and + * one `warn` line on `logger` saying why (a functional degradation — the page + * still serves, in the authored language). */ -function translationBundleOf(i18n: UploadLinkLabelI18n): TranslationBundle | undefined { +function translationBundleOf(i18n: UploadLinkLabelI18n, logger: RecordFileAccessDeps['logger']): TranslationBundle | undefined { const bundle: Record = {}; - for (const locale of i18n.getLocales()) { - const data = i18n.getTranslations(locale); - if (data && typeof data === 'object') bundle[locale] = data; + try { + for (const locale of i18n.getLocales()) { + const data = i18n.getTranslations(locale); + if (data && typeof data === 'object') bundle[locale] = data; + } + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + logger.warn(`[RecordFileAccess] The translations could not be read (${reason}), so the upload page's labels are served untranslated.`); + return undefined; } return Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined; } @@ -1341,7 +1353,7 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo fields: field !== undefined ? { [field]: { name: field, ...(fieldLabel !== undefined ? { label: fieldLabel } : {}) } } : {}, }; const i18n = this.deps.getI18n?.(); - const bundle = i18n ? translationBundleOf(i18n) : undefined; + const bundle = i18n ? translationBundleOf(i18n, this.deps.logger) : undefined; if (!i18n || !bundle) return { objectLabel, fieldLabel }; const fallback = typeof i18n.getFallbackLocale === 'function' ? i18n.getFallbackLocale() : undefined; // [#33634] The authored language: the declared `sourceLocale`, else the diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 7e2f2eb3d8e..f5d1964962c 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -443,6 +443,7 @@ "ai/QueryDatasetOutput:sourceLine", "ai/QueryDatasetOutput:totalGroups", "ai/QueryDatasetOutput:totals", + "ai/QueryDatasetOutput:translationWarning", "ai/QueryDatasetOutput:truncated", "ai/QueryDatasetOutput:warning", "ai/RecordCitation:anchor", diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 7f0627aa9b0..42d9b4c04ea 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -927,6 +927,7 @@ "api/GetMetaItemResponse:registration", "api/GetMetaItemResponse:resettable", "api/GetMetaItemResponse:sortability", + "api/GetMetaItemResponse:translationWarning", "api/GetMetaItemResponse:type", "api/GetMetaItemResponse:version", "api/GetMetaItemsRequest:names", @@ -937,6 +938,7 @@ "api/GetMetaItemsResponse:disabledActions", "api/GetMetaItemsResponse:items", "api/GetMetaItemsResponse:registrations", + "api/GetMetaItemsResponse:translationWarning", "api/GetMetaItemsResponse:type", "api/GetMetaTypesResponse:entries", "api/GetMetaTypesResponse:types", diff --git a/packages/spec/src/ai/dataset-tools.zod.ts b/packages/spec/src/ai/dataset-tools.zod.ts index a259c2dae37..b89d98cda76 100644 --- a/packages/spec/src/ai/dataset-tools.zod.ts +++ b/packages/spec/src/ai/dataset-tools.zod.ts @@ -462,6 +462,13 @@ export const QueryDatasetOutputSchema = lazySchema(() => AnalyticsResultResponse + 'dataset\'s object; `warning` states the narrowing (ADR-0090 D10)', ), warning: z.string().optional().describe('The narrowing statement; present exactly when `delegationNarrowed` is'), + translationWarning: z.string().min(1).optional().describe( + 'Present only when the translations this answer is labelled with could not be read (the deployment\'s ' + + 'i18n service failed while they were read): the dataset, member and option labels are then served as ' + + 'authored, untranslated, and this is the server\'s sentence saying why. Absent on every answer whose ' + + 'translations were read, including one that found no translation for the caller\'s locale. Independent ' + + 'of `warning`, which states a delegation narrowing only', + ), })); // ========================================== diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 64a887dd905..8785d89c0da 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -357,6 +357,18 @@ export const FlowRegistrationSchema = lazySchema(() => z.discriminatedUnion('sta }), ])); +/** + * [#35707] The one description of the `translationWarning` slot a `/meta` + * answer carries, shared by the list and the by-name read so the two say it in + * the same words. + */ +const META_TRANSLATION_WARNING_DESCRIPTION = + 'Present only when this answer\'s translations could not be read (the deployment\'s i18n service failed ' + + 'while they were read): the labels and descriptions are then served as authored, untranslated, and this ' + + 'is the server\'s sentence saying why. Absent on every answer whose translations were read, including one ' + + 'that found no translation for the caller\'s locale, so its absence never means "translated". A ' + + 'non-empty string, never an empty one. Beside the served documents, never inside one.'; + /** * Get Metadata Items Response * @@ -415,6 +427,7 @@ export const GetMetaItemsResponseSchema = lazySchema(() => z.object({ + 'row of its own name and has no entry. Absent when no listed item is served from a stored row. ' + 'Beside the items, never inside one: an item\'s body is served as stored.', ), + translationWarning: z.string().min(1).optional().describe(META_TRANSLATION_WARNING_DESCRIPTION), })); /** @@ -795,6 +808,7 @@ export const GetMetaItemResponseSchema = lazySchema(() => z.object({ type: z.string().describe('Metadata type name'), name: z.string().describe('Item name'), item: z.unknown().describe('Metadata item definition'), + translationWarning: z.string().min(1).optional().describe(META_TRANSLATION_WARNING_DESCRIPTION), sortability: ObjectSortabilitySchema.optional().describe( 'Per-column sortability projection — present exactly when `type` ' + 'is `object`, on every serving branch. Computed at serve time from the ' From 141dfb3ed11a839755a4eb2d009b0f27bae5cff8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:12:14 +0000 Subject: [PATCH 2/3] fix: declare the protocol change, name both catalog readers, and serve fixed warning sentences - The changeset declares `Metadata-protocol: added` and grades `@objectstack/spec` minor: the response schemas' new key moves the authorable-surface shards. - `registeredTranslationBundle` has two readers, the object save and the stored-metadata migration (preview and apply). Both are refused the same way on a translation fault; the docblock and the sentence name both, and a migration pin covers the two passes. - The refusal is declared (`refusal: true`) with one fixed sentence, so the HTTP caller reads it instead of the generic 5xx sentence; the i18n error rides as `cause` and is logged at warn. Pinned at the REST save route. - `translationWarning`, `list_datasets`' translation warning and its catalogue-unreadable warning are fixed sentences; the original error goes to the server log only (`DatasetToolsDeps.logger`, bound by `AnalyticsService.datasetTools`). Claude-Session: https://claude.ai/code/session_01L6bhgVdouXCTCCcBVLaYW5 Co-authored-by: Claude --- .changeset/35707-translation-fault-warning.md | 10 +- .../stdio-data-bridge.dataset-locale.test.ts | 8 +- ...io-data-bridge.object-locale-34872.test.ts | 6 +- .../src/protocol-discovery-and-bases.ts | 65 ++++--- .../protocol-meta-effective-schema.test.ts | 74 +++++++- packages/rest/src/meta-item-read-gate.ts | 18 +- .../meta-save-translation-fault-35707.test.ts | 173 ++++++++++++++++++ .../src/meta-translation-fault-34993.test.ts | 4 +- .../domains/mcp-object-locale-34872.test.ts | 11 +- .../meta-list-projection-parity.test.ts | 3 +- .../src/mcp-dataset-tools-bridge.test.ts | 8 +- .../src/__tests__/dataset-tools.test.ts | 10 +- .../src/analytics-service.ts | 5 +- .../service-analytics/src/dataset-tools.ts | 15 +- scripts/engine-double-contract.pinned.json | 15 ++ 15 files changed, 360 insertions(+), 65 deletions(-) create mode 100644 packages/rest/src/meta-save-translation-fault-35707.test.ts diff --git a/.changeset/35707-translation-fault-warning.md b/.changeset/35707-translation-fault-warning.md index 6668fcdc5a8..c53422ebcf3 100644 --- a/.changeset/35707-translation-fault-warning.md +++ b/.changeset/35707-translation-fault-warning.md @@ -1,5 +1,5 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/rest': patch '@objectstack/runtime': patch '@objectstack/mcp': patch @@ -10,14 +10,14 @@ feat: an answer whose translations could not be read says so, as `translationWarning` -Clause-②: yes (widening) — `GetMetaItemsResponseSchema`, `GetMetaItemResponseSchema` and `QueryDatasetOutputSchema` gain the optional string `translationWarning`; the MCP `list_objects` and `describe_object` answers gain the same optional member, and `DiagnosedObjectListing` and the dataset tools' `DatasetToolSource` gain the optional `translationWarning` they carry it in -Metadata-protocol: none +Clause-②: yes (widening) — `GetMetaItemsResponseSchema`, `GetMetaItemResponseSchema` and `QueryDatasetOutputSchema` gain the optional string `translationWarning`; the MCP `list_objects` and `describe_object` answers gain the same optional member, and `DiagnosedObjectListing` and the dataset tools' `DatasetToolSource` gain the optional `translationWarning` they carry it in; `DatasetToolsDeps` gains an optional `logger` +Metadata-protocol: added -When the deployment's i18n service resolves but its translations cannot be read (its `getLocales` or `getTranslations` throws), the metadata and dataset answers are served in the authored language, untranslated. Until now only `list_datasets` told the caller why; every other answer looked exactly like one for a locale with no translation. These answers now carry `translationWarning`, the server's sentence naming the reason, beside what they serve: `GET /meta/:type` and `GET /meta/:type/:name` on both HTTP hosts (the REST server and the runtime dispatcher), the MCP `list_objects` and `describe_object` tools on both transports, and `query_dataset`. It is present only on such a fault, so an answer whose translations were read is byte for byte what it was. `list_datasets` keeps the `partial` and `warning` it already serves for the same fault. A list answered as a bare array (a protocol that answers without the `{ type, items }` envelope) has no member to carry it; the server log says the fault either way. +When the deployment's i18n service resolves but its translations cannot be read (its `getLocales` or `getTranslations` throws), the metadata and dataset answers are served in the authored language, untranslated. Until now only `list_datasets` told the caller why; every other answer looked exactly like one for a locale with no translation. These answers now carry `translationWarning`, one fixed sentence saying the translations could not be read, beside what they serve: `GET /meta/:type` and `GET /meta/:type/:name` on both HTTP hosts (the REST server and the runtime dispatcher), the MCP `list_objects` and `describe_object` tools on both transports, and `query_dataset`. It is present only on such a fault, so an answer whose translations were read is byte for byte what it was. `list_datasets` keeps the `partial` and `warning` it already serves for the same fault. Every warning sentence here, and `list_datasets`' warning when the dataset catalogue itself cannot be read, is now the platform's client-facing failure text: a fixed sentence, with the original error in the server log only. A list answered as a bare array (a protocol that answers without the `{ type, items }` envelope) has no member to carry it; the server log says the fault either way. Three more places read the i18n service's whole catalog with no guard, so the same fault failed them with an unhandled error: -- An object save reads the catalog to tell a translated label a Studio session sends back from one the author typed. It now refuses the save as 503 `SERVICE_UNAVAILABLE`, naming the reason, and stores nothing; retrying once the translations read again saves the same body. Saving without the catalog would have stored translated labels as the authored ones. +- An object save and the stored-metadata migration (its preview and its apply pass, from the REST route, the runtime dispatcher and `os migrate meta`) read the catalog to tell a translated label a Studio session sent back from one the author typed. Both are now refused as 503 `SERVICE_UNAVAILABLE`, a declared refusal whose fixed sentence reaches the HTTP caller ("The translations could not be read, … nothing was saved or migrated. Retry once the translations can be read."), and nothing is stored; the i18n error is logged on the server. Retrying once the translations read again saves the same body. Going on without the catalog would have stored translated labels as the authored ones, or counted an echoed stored row as canonical. - A dataset query's select-option labels and the upload page's object and field labels are now served as declared, with one `warn` line saying the translations could not be read. Nothing to migrate. diff --git a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts index 4843fc5e31e..900ee55d7f1 100644 --- a/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts +++ b/packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts @@ -240,11 +240,12 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i expect(answer.datasets.map((d) => [d.name, d.label])).toEqual([['opp_metrics', '商机指标']]); }); - it.each(CASES)('$read throwing: list_datasets keeps the dataset untranslated, partial, naming the i18n error', async ({ read, message }) => { + it.each(CASES)('$read throwing: list_datasets keeps the dataset untranslated, partial, with the fixed sentence and no i18n error text', async ({ read, message }) => { const bridge = await bridgeOverRealExecutor(() => i18nWhoseReadThrows(read, message)); const answer = await bridge.listDatasets!({ terms: TERMS }); expect(answer.datasets.map((d) => [d.name, d.label])).toEqual([['opp_metrics', 'Opportunity Metrics']]); - expect(answer).toMatchObject({ partial: true, warning: expect.stringContaining(message) }); + expect(answer).toMatchObject({ partial: true, warning: 'The translations could not be read, so labels and descriptions are served untranslated.' }); + expect(JSON.stringify(answer)).not.toContain(message); }); it.each(CASES)('$read throwing: query_dataset answers, in the authored labels', async ({ read, message }) => { @@ -253,7 +254,8 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i expect(answer.rowCount).toBe(1); expect(answer.provenance.dataset).toEqual({ name: 'opp_metrics', label: 'Opportunity Metrics' }); // [#35707] …and says why the labels are untranslated; `warning` stays the narrowing's alone. - expect(answer.translationWarning).toEqual(expect.stringContaining(message)); + expect(answer.translationWarning).toBe('The translations could not be read, so labels and descriptions are served untranslated.'); + expect(JSON.stringify(answer)).not.toContain(message); expect(answer).not.toHaveProperty('warning'); }); diff --git a/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts index 2d0b9c1d414..d6b289f6adc 100644 --- a/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts +++ b/packages/mcp/src/stdio-data-bridge.object-locale-34872.test.ts @@ -216,10 +216,12 @@ describe('[#34872] stdio list_objects and describe_object serve labels and descr try { const described = await session.call('describe_object', { objectName: OBJ }); expect(described.isError).toBe(false); - expect(described.json).toMatchObject({ name: OBJ, label: 'Deal', translationWarning: expect.stringContaining('bundle offline') }); + expect(described.json).toMatchObject({ name: OBJ, label: 'Deal', translationWarning: 'The translations could not be read, so labels and descriptions are served untranslated.' }); + expect(JSON.stringify(described.json)).not.toContain('bundle offline'); const listed = (await session.call('list_objects', {})).json; expect(listed.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal' }); - expect(listed).toMatchObject({ totalCount: 2, translationWarning: expect.stringContaining('bundle offline') }); + expect(listed).toMatchObject({ totalCount: 2, translationWarning: 'The translations could not be read, so labels and descriptions are served untranslated.' }); + expect(JSON.stringify(listed)).not.toContain('bundle offline'); } finally { await session.close(); } diff --git a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts index 8e39fd2e2fa..a7456e3ab50 100644 --- a/packages/metadata-protocol/src/protocol-discovery-and-bases.ts +++ b/packages/metadata-protocol/src/protocol-discovery-and-bases.ts @@ -1240,16 +1240,21 @@ export class ProtocolDiscoveryAndBasesFacet { * registered — the bundle the `/meta` read exits translate with * (`translationBundleOf` in `@objectstack/rest`, built the same way). * - * [#35707] Its one reader is the object SAVE (the echo restore above and - * {@link restoreInjectedColumnEchoes}), so a service whose `getLocales` or - * `getTranslations` throws refuses the save as a 503 - * ({@link translationsUnreadableForSaveError}) instead of answering - * `undefined` the way the read doors do: without the bundle the save - * cannot tell a label a translated read served back from one the author - * typed, and storing the echo would make the translation the authored - * text — the "storing a body this door could not judge" the stored-row - * read refuses for the same reason. The refusal is handed to the caller, - * never logged here. + * [#35707] It has two readers, and neither may go on without it: the + * object SAVE (the echo restore above and + * {@link restoreInjectedColumnEchoes}) and the stored-row MIGRATION + * (`migrateStoredMetadata`'s translated-echo notices, read for every + * stored object row on the preview pass and the apply pass alike). So a + * service whose `getLocales` or `getTranslations` throws refuses either + * as a 503 ({@link translationsUnreadableError}) instead of answering + * `undefined` the way the read doors do: without the bundle neither can + * tell a label a translated read served back from one the author typed. + * The save would store the echo as the authored text — the "storing a + * body this door could not judge" the stored-row read refuses for the + * same reason — and the migration would count an echoed row `canonical`. + * The refusal is handed to the caller with a fixed sentence; the + * service's own error is logged here at `warn`, because the route doors + * do not log a declared refusal. */ static registeredTranslationBundle(host: Pick): TranslationBundle | undefined { const service: any = host.getServicesRegistry?.().get('i18n'); @@ -1263,7 +1268,9 @@ export class ProtocolDiscoveryAndBasesFacet { if (data && typeof data === 'object') bundle[locale] = data; } } catch (error) { - throw translationsUnreadableForSaveError(error); + const reason = error instanceof Error ? error.message : String(error); + console.warn(`[metadata] The translations could not be read (${reason}), so the object save or migration is refused.`); + throw translationsUnreadableError(error); } return Object.keys(bundle).length > 0 ? (bundle as TranslationBundle) : undefined; } @@ -1315,21 +1322,37 @@ export class ProtocolDiscoveryAndBasesFacet { } /** - * [#35707] The refusal an object save answers when the registered i18n - * service cannot read its translations + * [#35707] The one sentence {@link translationsUnreadableError} says, fixed + * and worded for both of its doors (the object save and the stored-row + * migration). The platform's client-facing failure text: the i18n service's + * own error is never quoted to the caller; it rides as `cause` and is + * logged where it is caught. + */ +const TRANSLATIONS_UNREADABLE_MESSAGE = + 'The translations could not be read, so a label a translated read served back cannot be told from one ' + + 'written by hand; nothing was saved or migrated. Retry once the translations can be read.'; + +/** + * [#35707] The refusal an object save or a stored-row migration answers when + * the registered i18n service cannot read its translations * ({@link ProtocolDiscoveryAndBasesFacet.registeredTranslationBundle}): 503 * `SERVICE_UNAVAILABLE`, the code the metadata store's own unavailable read - * answers, with the service's reason kept as `cause`. Retrying once the - * translations read again saves the same body. + * answers (`metadataStoreUnavailableError`), with the service's error kept + * as `cause` alone. Declared a refusal (`refusal: true`), so the route error + * doors hand the caller {@link TRANSLATIONS_UNREADABLE_MESSAGE} rather than + * the generic 5xx sentence. Retrying once the translations read again saves + * the same body. */ -function translationsUnreadableForSaveError(cause: unknown): Error { - const reason = cause instanceof Error ? cause.message : String(cause); - const err = new Error( - `The translations could not be read (${reason}), so this save cannot tell a translated label served back ` - + 'from one written by hand; nothing was saved. Retry once the translations can be read.', - ) as Error & { code?: string; status?: number; cause?: unknown }; +function translationsUnreadableError(cause: unknown): Error { + const err = new Error(TRANSLATIONS_UNREADABLE_MESSAGE) as Error & { + code?: string; + status?: number; + refusal?: boolean; + cause?: unknown; + }; err.code = 'SERVICE_UNAVAILABLE'; err.status = 503; + err.refusal = true; err.cause = cause; return err; } diff --git a/packages/objectql/src/protocol-meta-effective-schema.test.ts b/packages/objectql/src/protocol-meta-effective-schema.test.ts index ba98b6ee490..7115f4a3b63 100644 --- a/packages/objectql/src/protocol-meta-effective-schema.test.ts +++ b/packages/objectql/src/protocol-meta-effective-schema.test.ts @@ -40,7 +40,7 @@ * `packages/metadata-protocol/src/protocol.injected-system-columns.test.ts`. */ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; // [#5619] The producer's OWN write-verb dispatch decisions, so the fake engine // below cannot accept a call ObjectQL refuses. @@ -742,11 +742,17 @@ describe('[#33952] a zh-CN read of a patched field label, echoed back, is stored * [#35707] The object save reads the registered i18n service's whole catalog * to tell a translated echo from typed text. A service whose `getLocales` or * `getTranslations` throws leaves it unable to tell, so the save is refused - * 503 `SERVICE_UNAVAILABLE` and nothing is stored — never a body whose - * translated labels became the authored ones. The control saves the same body - * over a service that reads. + * 503 `SERVICE_UNAVAILABLE` (a declared refusal with one fixed sentence; the + * service's error rides as `cause`) and nothing is stored — never a body whose + * translated labels became the authored ones. The stored-row migration reads + * the same catalog and is refused the same way. The controls run over a + * service that reads. */ -describe('[#35707] an object save over translations that cannot be read is refused, and stores nothing', () => { +const TRANSLATIONS_UNREADABLE = + 'The translations could not be read, so a label a translated read served back cannot be told from one ' + + 'written by hand; nothing was saved or migrated. Retry once the translations can be read.'; + +describe('[#35707] an object save or migration over translations that cannot be read is refused, and stores nothing', () => { const body = () => ({ name: 'crm_note', label: 'Note', sharingModel: 'private', fields: { title: { name: 'title', type: 'text', label: 'Title' } }, @@ -774,11 +780,59 @@ describe('[#35707] an object save over translations that cannot be read is refus }); for (const failing of ['getLocales', 'getTranslations'] as const) { - it(`${failing} throwing: 503 SERVICE_UNAVAILABLE naming the reason, and no row`, async () => { - const { outcome, stored } = await saveOver(i18nOf(failing)); - expect(outcome).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); - expect((outcome as Error).message).toContain('bundle offline'); - expect(stored).toBe(false); + it(`${failing} throwing: a declared 503 SERVICE_UNAVAILABLE refusal with the fixed sentence, and no row`, async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const { outcome, stored } = await saveOver(i18nOf(failing)); + expect(outcome).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, refusal: true }); + expect((outcome as Error).message).toBe(TRANSLATIONS_UNREADABLE); + expect(((outcome as Error).cause as Error).message).toBe('bundle offline'); + expect(stored).toBe(false); + } finally { + warn.mockRestore(); + } + }); + } + + /** + * The catalog's other reader: the stored-row migration reads it for every + * stored object row, on the preview pass and the apply pass alike. Without + * it an echoed row would be counted `canonical`, so both passes are + * refused the same way and the stored row is untouched. + */ + const migrateOver = async (i18n: unknown, apply: boolean) => { + const host = makeHost(false); + const protocol: any = new ObjectStackProtocolImplementation(host.engine, () => new Map([['i18n', i18n]])); + await host.engine.insert('sys_metadata', { + type: 'object', name: 'crm_note', organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(body()), + }); + const before = JSON.stringify(Array.from(host.rows.values())); + const outcome = await protocol.migrateStoredMetadata({ types: ['object'], ...(apply ? { apply: true } : {}) }) + .then((r: any) => r, (e: unknown) => e); + return { outcome, unchanged: JSON.stringify(Array.from(host.rows.values())) === before }; + }; + + it('control: the translations reading, the migration preview and apply answer, and the row is untouched', async () => { + for (const apply of [false, true]) { + const { outcome, unchanged } = await migrateOver(i18nOf(), apply); + expect(outcome).not.toBeInstanceOf(Error); + expect(Array.isArray(outcome.rows)).toBe(true); + expect(unchanged).toBe(true); + } + }); + + for (const apply of [false, true]) { + it(`a throwing read refuses the migration ${apply ? 'apply' : 'preview'} pass the same way, and the row is untouched`, async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const { outcome, unchanged } = await migrateOver(i18nOf('getTranslations'), apply); + expect(outcome).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, refusal: true }); + expect((outcome as Error).message).toBe(TRANSLATIONS_UNREADABLE); + expect(unchanged).toBe(true); + } finally { + warn.mockRestore(); + } }); } }); diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index 7352e14661e..7c858bfc364 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -3343,11 +3343,13 @@ export async function isTranslatableMetaType(type: string): Promise { /** * [#34993] The sentence a translation fault is said in, on every door that * says one: the i18n service resolved, but its translations could not be read. + * + * [#35707] A fixed sentence, the platform's client-facing failure text: the + * caught error is never quoted to the caller. Its text goes to the server + * log alone ({@link translationBundleOf}). */ -export function metaTranslationFaultWarning(error: unknown): string { - const reason = error instanceof Error ? error.message : String(error); - return `The translations could not be read (${reason}), so labels and descriptions are served untranslated.`; -} +export const META_TRANSLATION_FAULT_WARNING = + 'The translations could not be read, so labels and descriptions are served untranslated.'; /** * Build a `TranslationBundle` (`Record`) from an @@ -3359,7 +3361,7 @@ export function metaTranslationFaultWarning(error: unknown): string { * translation fault, not a failed read: the answer is `undefined` (the text is * served untranslated, as with no bundle), the server log says so at `warn` * (a functional degradation), and `reportFault` hands the same sentence - * ({@link metaTranslationFaultWarning}) to a door that carries a warning on + * ({@link META_TRANSLATION_FAULT_WARNING}) to a door that carries a warning on * its answer. One locale failing fails the whole bundle, so an answer never * mixes the locales that read with the fallback for the one that did not. */ @@ -3377,9 +3379,9 @@ export function translationBundleOf(i18n: unknown, reportFault?: (warning: strin if (data && typeof data === 'object') bundle[locale] = data; } } catch (error) { - const warning = metaTranslationFaultWarning(error); - logWarn(`[meta] ${warning}`); - reportFault?.(warning); + const reason = error instanceof Error ? error.message : String(error); + logWarn(`[meta] The translations could not be read (${reason}), so labels and descriptions are served untranslated.`); + reportFault?.(META_TRANSLATION_FAULT_WARNING); return undefined; } return Object.keys(bundle).length ? bundle : undefined; diff --git a/packages/rest/src/meta-save-translation-fault-35707.test.ts b/packages/rest/src/meta-save-translation-fault-35707.test.ts new file mode 100644 index 00000000000..68c75da5d7c --- /dev/null +++ b/packages/rest/src/meta-save-translation-fault-35707.test.ts @@ -0,0 +1,173 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35707] An object save over translations that cannot be read, at the HTTP + * door. + * + * The save reads the registered i18n service's whole catalog to tell a label a + * translated read served back from one the author typed. When the service's + * `getLocales` or `getTranslations` throws, the protocol refuses the save as + * 503 `SERVICE_UNAVAILABLE`, declared a refusal, with one fixed sentence. The + * route error door withholds the prose of an undeclared 5xx, so this file pins + * what the caller actually receives: the status, the code, that fixed sentence + * (never the generic 5xx one), none of the i18n service's own error text, and + * an unchanged store. The control saves the same body over a service that + * reads. + * + * The real `ObjectStackProtocolImplementation` over a `sys_metadata`-backed + * engine, as `meta-compound-save-mode-parity.test.ts` boots it. That import + * resolves to `@objectstack/metadata-protocol`'s `dist/`: rebuild it before + * reading a result here after touching the protocol. + */ + +import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'; +// Paid at collection: `rest-server.ts` reaches `@objectstack/objectql` by a +// dynamic import inside a route handler (`check:test-source-alias`). +import '@objectstack/objectql'; +import { RestServer } from './rest-server.js'; +import { assertEngineUpdateDispatch, assertEngineDeleteDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; + +const SINGLE_PATH = '/api/v1/meta/:type/:name'; +const NAME = 'crm_note'; +const LIVE_LABEL = 'Live label'; +const SUBMITTED_LABEL = 'Edited label'; +const FAULT_TEXT = 'bundle offline at 10.0.0.7'; +const SENTENCE = + 'The translations could not be read, so a label a translated read served back cannot be told from one ' + + 'written by hand; nothing was saved or migrated. Retry once the translations can be read.'; + +const objectBody = (label: string) => ({ + name: NAME, + label, + sharingModel: 'private', + fields: Object.fromEntries(['a', 'b'].map((f) => [f, { name: f, type: 'text', label: f }])), +}); + +function mockServer() { + return { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), + use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), + }; +} + +function mockRes() { + const res: any = { + statusCode: 200, + json: vi.fn(function (this: any, body: any) { this._body = body; return this; }), + send: vi.fn(), + status: vi.fn(function (this: any, code: number) { this.statusCode = code; return this; }), + header: vi.fn(), + }; + return res; +} + +const i18nOf = (failing?: 'getLocales' | 'getTranslations') => ({ + getLocales: () => { + if (failing === 'getLocales') throw new Error(FAULT_TEXT); + return ['en', 'zh-CN']; + }, + getTranslations: (locale: string) => { + if (failing === 'getTranslations') throw new Error(FAULT_TEXT); + return locale === 'zh-CN' ? { objects: { [NAME]: { label: '笔记' } } } : {}; + }, +}); + +function boot(i18n: unknown) { + const rows = new Map(); + rows.set('row_live', { + id: 'row_live', type: 'object', name: NAME, + organization_id: null, package_id: null, state: 'active', + metadata: JSON.stringify(objectBody(LIVE_LABEL)), + checksum: 'sha256_35707_fixture', version: 1, + }); + const match = (r: any, where: Record): boolean => { + for (const k of Object.keys(where ?? {})) { + if (k.startsWith('$')) throw new Error(`fake engine: unsupported logical operator ${k}`); + } + return Object.entries(where ?? {}).every(([k, v]) => + v === null || v === undefined ? r[k] === null || r[k] === undefined : r[k] === v); + }; + const engine: any = { + async find(table: string, o?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + const found = [...rows.values()].filter((r) => match(r, o?.where ?? {})); + return typeof o?.limit === 'number' ? found.slice(0, o.limit) : found; + }, + async findOne(table: string, o: { where: Record }) { + assertEngineFindOnePredicate(table, o); + if (table !== 'sys_metadata') return null; + for (const r of rows.values()) if (match(r, o?.where ?? {})) return r; + return null; + }, + async insert(table: string, data: Record) { + if (table === 'sys_metadata') { + const r = { ...(data as any), id: String(data.id ?? `r_${rows.size}`) }; + rows.set(r.id, r); + } + return { id: String(data.id ?? 'r_new') }; + }, + async update(_t: string, data: Record, opts?: Record) { + assertEngineUpdateDispatch(data, opts); + const id = (opts as any)?.where?.id; + const existing = id ? rows.get(String(id)) : undefined; + if (existing) rows.set(String(id), { ...existing, ...(data as any) }); + return { id: id ?? null }; + }, + async delete(_t: string, opts?: Record) { + assertEngineDeleteDispatch(opts); + return { deleted: 0 }; + }, + registry: { + registerItem: () => {}, registerObject: () => {}, listItems: () => [], + getItem: () => undefined, getArtifactItem: () => undefined, + removeRuntimeShadow: () => false, removeOverlayEntry: () => {}, uninstallPackage: () => {}, + }, + }; + const protocol: any = new ObjectStackProtocolImplementation(engine, () => new Map([['i18n', i18n]])); + const rest = new RestServer(mockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => ({ userId: 'u_author', systemPermissions: ['manage_metadata'] }); + rest.registerRoutes(); + const route = (rest as any).getRoutes().find((r: any) => r.method === 'PUT' && r.path === SINGLE_PATH); + + return { + put: async () => { + const res = mockRes(); + await route.handler({ params: { type: 'object', name: NAME }, query: {}, headers: {}, body: objectBody(SUBMITTED_LABEL) }, res); + return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] }; + }, + liveLabel: () => JSON.parse([...rows.values()].find((r) => r.name === NAME && r.state === 'active')!.metadata).label, + }; +} + +// The REST log is loud here, so the server-log assertion reads what a real +// deployment logs. +beforeAll(() => { vi.stubEnv('OS_REST_LOG', 'info'); }); +afterAll(() => { vi.unstubAllEnvs(); }); + +describe('[#35707] PUT /meta/object/:name over translations that cannot be read', () => { + it('control: the translations reading, the save answers 200 and stores the body', async () => { + const server = boot(i18nOf()); + const { status } = await server.put(); + expect(status).toBe(200); + expect(server.liveLabel()).toBe(SUBMITTED_LABEL); + }); + + for (const failing of ['getLocales', 'getTranslations'] as const) { + it(`${failing} throwing: 503 SERVICE_UNAVAILABLE with the fixed sentence, no i18n error text, store unchanged`, async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const server = boot(i18nOf(failing)); + const { status, body } = await server.put(); + expect(status).toBe(503); + expect(body).toMatchObject({ error: SENTENCE, code: 'SERVICE_UNAVAILABLE' }); + expect(JSON.stringify(body)).not.toContain(FAULT_TEXT); + expect(server.liveLabel()).toBe(LIVE_LABEL); + // The i18n service's own error reaches the server log. + expect(warn.mock.calls.some((c) => String(c[0]).includes(FAULT_TEXT))).toBe(true); + } finally { + warn.mockRestore(); + } + }); + } +}); diff --git a/packages/rest/src/meta-translation-fault-34993.test.ts b/packages/rest/src/meta-translation-fault-34993.test.ts index 17d0b655e15..cc961c5fa0e 100644 --- a/packages/rest/src/meta-translation-fault-34993.test.ts +++ b/packages/rest/src/meta-translation-fault-34993.test.ts @@ -80,9 +80,9 @@ describe('[#34993] REST /meta serves the authored text on a translation fault', try { const rest = restOver(i18nWhoseReadThrows(failing)); expect(await read(rest, '/api/v1/meta/:type', { type: 'object' })) - .toEqual({ status: 200, label: 'Account', field: 'Industry', translationWarning: expect.stringContaining('bundle offline') }); + .toEqual({ status: 200, label: 'Account', field: 'Industry', translationWarning: 'The translations could not be read, so labels and descriptions are served untranslated.' }); expect(await read(rest, '/api/v1/meta/:type/:name', { type: 'object', name: 'showcase_account' })) - .toEqual({ status: 200, label: 'Account', field: 'Industry', translationWarning: expect.stringContaining('bundle offline') }); + .toEqual({ status: 200, label: 'Account', field: 'Industry', translationWarning: 'The translations could not be read, so labels and descriptions are served untranslated.' }); expect(warn.mock.calls.map((c) => String(c[0]))).toEqual( expect.arrayContaining([expect.stringContaining('bundle offline')]), ); diff --git a/packages/runtime/src/domains/mcp-object-locale-34872.test.ts b/packages/runtime/src/domains/mcp-object-locale-34872.test.ts index 5789e03e972..0bc178eec2f 100644 --- a/packages/runtime/src/domains/mcp-object-locale-34872.test.ts +++ b/packages/runtime/src/domains/mcp-object-locale-34872.test.ts @@ -256,8 +256,9 @@ describe('[#34872] HTTP MCP list_objects and describe_object serve labels and de // [#35707] A translation fault: an i18n service that resolves but whose // reads throw. The answers are the authored text, never a refusal, and the - // two the object tools render carry `translationWarning` naming the - // reason; a healthy answer carries no such member. + // two the object tools render carry `translationWarning`, the fixed + // sentence (the i18n error's own text never reaches the caller); a healthy + // answer carries no such member. const throwingI18n = (failing: 'getLocales' | 'getTranslations') => ({ ...i18nService, [failing]: () => { throw new Error('bundle offline'); }, @@ -268,10 +269,12 @@ describe('[#34872] HTTP MCP list_objects and describe_object serve labels and de const described = await bridge.describeObject(OBJ); expect(described).toMatchObject({ name: OBJ, label: 'Deal', description: OBJECT_TEXT }); expect(field(described, 'amount')).toMatchObject({ label: 'Amount', description: AMOUNT_TEXT }); - expect(described.translationWarning).toEqual(expect.stringContaining('bundle offline')); + expect(described.translationWarning).toBe('The translations could not be read, so labels and descriptions are served untranslated.'); + expect(JSON.stringify(described)).not.toContain('bundle offline'); const listing = await bridge.listObjectsDiagnosed(); expect(listing.objects.find((o: any) => o.name === OBJ)).toMatchObject({ label: 'Deal', description: OBJECT_TEXT }); - expect(listing.translationWarning).toEqual(expect.stringContaining('bundle offline')); + expect(listing.translationWarning).toBe('The translations could not be read, so labels and descriptions are served untranslated.'); + expect(JSON.stringify(listing)).not.toContain('bundle offline'); }); it('[#35707] CONTROL — the reads answering: the same answers are translated and carry no translationWarning', async () => { diff --git a/packages/runtime/src/domains/meta-list-projection-parity.test.ts b/packages/runtime/src/domains/meta-list-projection-parity.test.ts index 8da9a6be4b7..06128397712 100644 --- a/packages/runtime/src/domains/meta-list-projection-parity.test.ts +++ b/packages/runtime/src/domains/meta-list-projection-parity.test.ts @@ -1425,7 +1425,8 @@ describe('[#35707] a translation fault is said as translationWarning, the same o expect(doc?.label).toBe('Invoice'); } const warningOf = (answer: Answer, onDispatcher: boolean) => (onDispatcher ? answer.body?.data : answer.body)?.translationWarning; - expect(warningOf(rest, false)).toEqual(expect.stringContaining('bundle offline')); + expect(warningOf(rest, false)).toBe('The translations could not be read, so labels and descriptions are served untranslated.'); + expect(JSON.stringify(rest.body)).not.toContain('bundle offline'); expect(warningOf(dispatcher, true)).toBe(warningOf(rest, false)); // CONTROL — the readable double: translated, and no member on either transport. const healthyDispatcher = await enveloped(bootDispatcher('holder')).read(path, {}, ZH); diff --git a/packages/runtime/src/mcp-dataset-tools-bridge.test.ts b/packages/runtime/src/mcp-dataset-tools-bridge.test.ts index bd71d2f6863..a70f2670d1b 100644 --- a/packages/runtime/src/mcp-dataset-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-dataset-tools-bridge.test.ts @@ -211,11 +211,12 @@ describe('[ADR-0149 D2] the HTTP dataset tools when the i18n service resolves bu expect(answer.datasets.map((d: { name: string; label: string }) => [d.name, d.label])).toEqual([['sales_analysis', '销售分析']]); }); - it.each(CASES)('$read throwing: list_datasets keeps the dataset untranslated, partial, naming the i18n error', async ({ read, message }) => { + it.each(CASES)('$read throwing: list_datasets keeps the dataset untranslated, partial, with the fixed sentence and no i18n error text', async ({ read, message }) => { const bridge = await bridgeOverRealExecutor(i18nWhoseReadThrows(read, message)); const answer = await bridge.listDatasets!({}); expect(answer.datasets.map((d: { name: string; label: string }) => [d.name, d.label])).toEqual([['sales_analysis', 'Sales analysis']]); - expect(answer).toMatchObject({ partial: true, warning: expect.stringContaining(message) }); + expect(answer).toMatchObject({ partial: true, warning: 'The translations could not be read, so labels and descriptions are served untranslated.' }); + expect(JSON.stringify(answer)).not.toContain(message); }); it.each(CASES)('$read throwing: query_dataset answers, in the authored labels', async ({ read, message }) => { @@ -225,7 +226,8 @@ describe('[ADR-0149 D2] the HTTP dataset tools when the i18n service resolves bu expect(answer.provenance.dataset).toEqual({ name: 'sales_analysis', label: 'Sales analysis' }); // [#35707] …and says why the labels are untranslated; `warning` stays the // narrowing's alone (this harness's security double narrows every object). - expect(answer.translationWarning).toEqual(expect.stringContaining(message)); + expect(answer.translationWarning).toBe('The translations could not be read, so labels and descriptions are served untranslated.'); + expect(JSON.stringify(answer)).not.toContain(message); expect(answer).toMatchObject({ delegationNarrowed: true, warning: 'narrowed on crm_opportunity' }); }); diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index 2b5fb08df43..b3d5a627ce4 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -333,10 +333,14 @@ describe('list_datasets — the catalogue asks the query\'s own gates', () => { status: 400, }); - const failing = service.datasetTools({ loadDatasets: async () => { throw new Error('metadata loader down'); } }); + // [#35707] The caller is told the catalogue could not be read, in a fixed + // sentence; the loader's own error text goes to the server log alone. + const warn = vi.fn(); + const failing = service.datasetTools({ loadDatasets: async () => { throw new Error('metadata loader down'); }, logger: { warn } }); const failed = await failing.listDatasets({}, ME); - expect(failed).toMatchObject({ datasets: [], partial: true }); - expect(failed.warning).toContain('metadata loader down'); + expect(failed).toMatchObject({ datasets: [], partial: true, warning: 'The dataset catalogue could not be read, so no dataset is listed.' }); + expect(JSON.stringify(failed)).not.toContain('metadata loader down'); + expect(warn.mock.calls.map((c) => String(c[0]))).toEqual([expect.stringContaining('metadata loader down')]); const degraded = service.datasetTools({ loadDatasets: async () => ({ items: [PIPELINE], partial: true as const, warning: 'one source unavailable' }), diff --git a/packages/services/service-analytics/src/analytics-service.ts b/packages/services/service-analytics/src/analytics-service.ts index 8ff884be3b5..15480a097e4 100644 --- a/packages/services/service-analytics/src/analytics-service.ts +++ b/packages/services/service-analytics/src/analytics-service.ts @@ -2980,10 +2980,11 @@ export class AnalyticsService implements IAnalyticsService { * service, so neither host imports this package. `createDatasetTools` with * `analytics` set to this service; `definitions` on the answer is * {@link getDatasetToolDefinitions}. Refuses at every call unless - * {@link hasPluginWiredAdmission}. + * {@link hasPluginWiredAdmission}. [#35707] The executor logs through this + * service's logger unless `deps` names one. */ datasetTools(deps: Omit): DatasetTools { - return createDatasetTools({ ...deps, analytics: this }); + return createDatasetTools({ logger: this.logger, ...deps, analytics: this }); } /** diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index 96c1b93508c..d0beb90ceef 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -235,6 +235,13 @@ export interface DatasetToolsDeps { * on a bridge that omits it. A throw is read as "cannot say". */ readonly diagnoseDelegation?: DatasetToolDelegationProbe; + /** + * [#35707] Where a failure the answer says in a fixed sentence is logged + * with its own text: the caller is told the catalogue could not be read, + * never why. {@link AnalyticsService.datasetTools} binds the service's + * logger; absent, the text is not logged. + */ + readonly logger?: { warn(message: string): void }; } /** A tool call in the `ToolCallPart` shape's two members the executor reads. */ @@ -405,6 +412,9 @@ function text(label: unknown, locale: string | undefined, fallback?: string): st } /** Create the dataset tools' executor over a host's service and metadata. */ +/** [#35707] What `list_datasets` says when the catalogue read throws. */ +const DATASET_CATALOGUE_UNREADABLE_WARNING = 'The dataset catalogue could not be read, so no dataset is listed.'; + export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { const maxRows = typeof deps.maxQueryLimit === 'number' && deps.maxQueryLimit > 0 ? Math.floor(deps.maxQueryLimit) @@ -468,10 +478,13 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { const nextStep = terms !== undefined ? composeDatasetNextStep({ terms, datasets: [], candidates: [], partial: true, locales: sentence }) : undefined; + // [#35707] The platform's client-facing failure text: a fixed sentence, + // the caught error's own text to the server log alone. + deps.logger?.warn(`[Analytics] list_datasets: the dataset catalogue could not be read: ${e instanceof Error ? e.message : String(e)}`); return { datasets: [], partial: true, - warning: `The dataset catalogue could not be read: ${e instanceof Error ? e.message : String(e)}`, + warning: DATASET_CATALOGUE_UNREADABLE_WARNING, ...(nextStep ? { nextStep } : {}), }; } diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 1ef3abcf564..75bf6d08460 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -5211,6 +5211,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/rest/src/meta-save-translation-fault-35707.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/rest/src/meta-save-translation-fault-35707.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/rest/src/meta-save-translation-fault-35707.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/rest/src/meta-view-label-not-invented.test.ts", "verb": "findOne", From 2468a0c13d1c7b84b95a3b1fce142b3bd470f657 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 12:53:19 +0000 Subject: [PATCH 3/3] fix: query_dataset's 503 for a failed dataset read says a fixed sentence The refusal is the REST door's own sentence for the same fault; the read's error rides as `cause` and goes to the server log through the dataset tools' logger, never into the answer. Claude-Session: https://claude.ai/code/session_01L6bhgVdouXCTCCcBVLaYW5 Co-authored-by: Claude --- .changeset/35707-translation-fault-warning.md | 2 +- .../src/__tests__/dataset-tools.test.ts | 19 +++++++++++++++---- .../service-analytics/src/dataset-tools.ts | 16 +++++++++++----- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/.changeset/35707-translation-fault-warning.md b/.changeset/35707-translation-fault-warning.md index c53422ebcf3..82fc9de13e2 100644 --- a/.changeset/35707-translation-fault-warning.md +++ b/.changeset/35707-translation-fault-warning.md @@ -13,7 +13,7 @@ feat: an answer whose translations could not be read says so, as `translationWar Clause-②: yes (widening) — `GetMetaItemsResponseSchema`, `GetMetaItemResponseSchema` and `QueryDatasetOutputSchema` gain the optional string `translationWarning`; the MCP `list_objects` and `describe_object` answers gain the same optional member, and `DiagnosedObjectListing` and the dataset tools' `DatasetToolSource` gain the optional `translationWarning` they carry it in; `DatasetToolsDeps` gains an optional `logger` Metadata-protocol: added -When the deployment's i18n service resolves but its translations cannot be read (its `getLocales` or `getTranslations` throws), the metadata and dataset answers are served in the authored language, untranslated. Until now only `list_datasets` told the caller why; every other answer looked exactly like one for a locale with no translation. These answers now carry `translationWarning`, one fixed sentence saying the translations could not be read, beside what they serve: `GET /meta/:type` and `GET /meta/:type/:name` on both HTTP hosts (the REST server and the runtime dispatcher), the MCP `list_objects` and `describe_object` tools on both transports, and `query_dataset`. It is present only on such a fault, so an answer whose translations were read is byte for byte what it was. `list_datasets` keeps the `partial` and `warning` it already serves for the same fault. Every warning sentence here, and `list_datasets`' warning when the dataset catalogue itself cannot be read, is now the platform's client-facing failure text: a fixed sentence, with the original error in the server log only. A list answered as a bare array (a protocol that answers without the `{ type, items }` envelope) has no member to carry it; the server log says the fault either way. +When the deployment's i18n service resolves but its translations cannot be read (its `getLocales` or `getTranslations` throws), the metadata and dataset answers are served in the authored language, untranslated. Until now only `list_datasets` told the caller why; every other answer looked exactly like one for a locale with no translation. These answers now carry `translationWarning`, one fixed sentence saying the translations could not be read, beside what they serve: `GET /meta/:type` and `GET /meta/:type/:name` on both HTTP hosts (the REST server and the runtime dispatcher), the MCP `list_objects` and `describe_object` tools on both transports, and `query_dataset`. It is present only on such a fault, so an answer whose translations were read is byte for byte what it was. `list_datasets` keeps the `partial` and `warning` it already serves for the same fault. Every warning sentence here, `list_datasets`' warning when the dataset catalogue itself cannot be read, and `query_dataset`'s 503 refusal when the dataset read fails, are now the platform's client-facing failure text: a fixed sentence, with the original error in the server log only. A list answered as a bare array (a protocol that answers without the `{ type, items }` envelope) has no member to carry it; the server log says the fault either way. Three more places read the i18n service's whole catalog with no guard, so the same fault failed them with an unhandled error: diff --git a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts index b3d5a627ce4..059179b049e 100644 --- a/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts +++ b/packages/services/service-analytics/src/__tests__/dataset-tools.test.ts @@ -534,10 +534,21 @@ describe('query_dataset', () => { it('answers 503 when the dataset read itself fails, never NOT_FOUND', async () => { const { service } = await bootWired(); - const tools = service.datasetTools({ loadDatasets: async () => { throw new Error('loader down'); } }); - await expect( - tools.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'] } }, ME), - ).rejects.toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + // [#35707] A fixed sentence (the REST door's own); the read's error rides + // as `cause` and reaches the logger, never the answer. + const warn = vi.fn(); + const failure = new Error('loader down'); + const tools = service.datasetTools({ loadDatasets: async () => { throw failure; }, logger: { warn } }); + const refused = await tools.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'] } }, ME) + .then(() => undefined, (e: unknown) => e as Error & { cause?: unknown }); + expect(refused).toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + message: 'The dataset "pipeline" could not be resolved: the dataset read failed. This is a server-side fault, not a missing dataset.', + }); + expect(refused!.message).not.toContain('loader down'); + expect(refused!.cause).toBe(failure); + expect(warn.mock.calls.map((c) => String(c[0]))).toEqual([expect.stringContaining('loader down')]); }); // A selection naming no measure has nothing to project. The spec selection diff --git a/packages/services/service-analytics/src/dataset-tools.ts b/packages/services/service-analytics/src/dataset-tools.ts index d0beb90ceef..3dd9742e7d6 100644 --- a/packages/services/service-analytics/src/dataset-tools.ts +++ b/packages/services/service-analytics/src/dataset-tools.ts @@ -237,8 +237,8 @@ export interface DatasetToolsDeps { readonly diagnoseDelegation?: DatasetToolDelegationProbe; /** * [#35707] Where a failure the answer says in a fixed sentence is logged - * with its own text: the caller is told the catalogue could not be read, - * never why. {@link AnalyticsService.datasetTools} binds the service's + * with its own text: the caller is told the catalogue or the dataset could + * not be read, never why. {@link AnalyticsService.datasetTools} binds the service's * logger; absent, the text is not logged. */ readonly logger?: { warn(message: string): void }; @@ -567,12 +567,18 @@ export function createDatasetTools(deps: DatasetToolsDeps): DatasetTools { try { loaded = await load(service, context); } catch (e) { - throw refusal( + // [#35707] The platform's client-facing failure text: a fixed sentence + // (the REST door's own for the same fault), the caught error on `cause` + // and in the server log alone. + deps.logger?.warn(`[Analytics] query_dataset: the dataset read failed for "${datasetName}": ${e instanceof Error ? e.message : String(e)}`); + const refused = refusal( 'SERVICE_UNAVAILABLE', 503, - `The dataset "${datasetName}" could not be resolved: the dataset read failed ` - + `(${e instanceof Error ? e.message : String(e)}). This is a server-side fault, not a missing dataset.`, + `The dataset "${datasetName}" could not be resolved: the dataset read failed. ` + + 'This is a server-side fault, not a missing dataset.', ); + (refused as { cause?: unknown }).cause = e; + throw refused; } const notFound = () => refusal('NOT_FOUND', 404, `Dataset "${datasetName}" not found.`); // Admitted exactly as `list_datasets` lists it, holder by holder, BEFORE