Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/34993-translation-fault-untranslated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/rest': patch
'@objectstack/runtime': patch
'@objectstack/mcp': patch
'@objectstack/service-analytics': patch
---

Clause-②: yes (widening)
Metadata-protocol: none

fix(i18n, mcp): a translation fault serves the untranslated text and the fault is logged, instead of failing the read; `list_datasets` is flagged `partial` with a `warning`, while REST `/meta`, the MCP object tools and `query_dataset` log only

When the i18n service resolves but its `getLocales` or `getTranslations` throws, the shared `/meta` translator (`translationBundleOf`, `@objectstack/rest`) now answers it as no bundle: the text is served untranslated and the server log says so at `warn` (`The translations could not be read (…), so labels and descriptions are served untranslated.`). Before, the translation rejected, so `GET /meta/:type` and `GET /meta/:type/:name` answered 500, the MCP object tools failed, `list_datasets` answered `datasets: []` with `partial: true`, and `query_dataset` refused 503 on both MCP transports.

Now `list_datasets` keeps every dataset, in its authored text, with `partial: true` and that sentence as its `warning`; `query_dataset` answers. A dataset host's `loadDatasets` may return `{ items, warning }` without `partial`: a whole read the tools say something about, which `query_dataset` does not refuse. The translator's sources take an optional `reportTranslationFault(warning)` to carry the sentence on an answer.

fix(mcp): `?locale=` reaches the MCP labels, and the dataset tools answer in one language

The HTTP MCP door now reads a `?locale=` query parameter as the `/meta` doors do (after `Accept-Language`, before the i18n default), for the object and dataset labels and the app-docs tools; it read headers only, though its docblock promised both. The dataset executor (`createDatasetTools`) takes an optional `translationLocale` dependency, the locale its `loadDatasets` translated the rows for, and reads labels and composes `nextStep` and `sourceLine` in it first. Both MCP transports pass it, so a call with no `Accept-Language` (common for MCP clients, and every stdio call) no longer mixes labels in the i18n default with sentences in the workspace locale.
102 changes: 61 additions & 41 deletions packages/mcp/src/stdio-data-bridge.dataset-locale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@
* - an i18n service the host cannot resolve (its resolver throws), or none:
* the untranslated list, never an error;
* - an i18n service that resolves but whose `getLocales` / `getTranslations`
* throws, over the REAL executor: a degraded read on both dataset tools
* (seat ruling A, its own describe below).
* throws, over the REAL executor: the datasets untranslated, with a warning,
* on both dataset tools and the object tools (#34993, its own describe below);
* - a header-less call answers labels and sentences in one language (#35083).
*/

import { describe, it, expect } from 'vitest';
Expand All @@ -35,7 +36,12 @@ import {
type AnalyticsService,
type MatchableMember,
} from '@objectstack/service-analytics';
import { createStdioDataBridge, type StdioDataBridgeDeps, type StdioDatasetToolsService } from './stdio-data-bridge.js';
import {
createStdioDataBridge,
servedLocaleObjectView,
type StdioDataBridgeDeps,
type StdioDatasetToolsService,
} from './stdio-data-bridge.js';

const PRINCIPAL = { userId: 'u_key', tenantId: 'org_1' };

Expand Down Expand Up @@ -151,21 +157,16 @@ describe('[ADR-0149 D2] stdio list_datasets is localized for the workspace defau
});

/**
* [ADR-0149 D2] An i18n service that RESOLVES but whose reads throw is not the
* unresolvable service above. `translationBundleOf` calls `getLocales` and
* `getTranslations` unguarded, so `translateMetaList` rejects with the i18n
* error, and `loadDatasets` leaves that rejection to throw. The executor here
* is the REAL one (the analytics service `AnalyticsServicePlugin` registers,
* admission wired), so the answer is the executor's own degraded-read
* contract: `list_datasets` lists nothing, says `partial` and names the error;
* `query_dataset` refuses 503 `SERVICE_UNAVAILABLE` for a server-side fault.
* The control case lists the dataset over the same harness, so the empty
* catalogue is the failed read's doing, not the harness's.
* [ADR-0149 D2 · #34993] An i18n service that RESOLVES but whose reads throw
* is a translation fault, which the shared translator (`translationBundleOf`)
* answers as no bundle and says. The executor here is the REAL one (the
* analytics service `AnalyticsServicePlugin` registers, admission wired):
* `list_datasets` keeps the dataset, in its authored text, `partial` with the
* fault's warning; `query_dataset` answers; the object tools serve the
* authored labels. The control case lists the dataset in the bundle labels.
*
* Pinned on purpose under seat ruling A: the catalogue degrades and says so.
* A follow-up (B: serve the untranslated text on a translation fault, inside
* the shared translator) would flip these expectations deliberately, on both
* transports at once.
* Flipped on purpose by #34993 (seat ruling B) from #34876's ruling-A pin
* (`datasets: []` + `partial`, and a 503), on both transports at once.
*/
describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but its reads throw', () => {
/**
Expand Down Expand Up @@ -216,12 +217,12 @@ describe('[ADR-0149 D2] stdio dataset tools when the i18n service resolves but i
};
}

async function bridgeOverRealExecutor(i18n: () => unknown) {
async function bridgeOverRealExecutor(i18n: () => unknown, principal: object = PRINCIPAL) {
return createStdioDataBridge({
engine: {} as any,
metadataService: { list: async () => [] } as any,
protocol: () => ({ getMetaItems: async () => ({ items: [METRICS] }) }) as any,
resolvePrincipal: async () => PRINCIPAL as any,
resolvePrincipal: async () => principal as any,
datasetTools: await wiredAnalytics(),
i18n,
});
Expand All @@ -239,32 +240,51 @@ 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 lists nothing, says partial and names the i18n error', async ({ read, message }) => {
it.each(CASES)('$read throwing: list_datasets keeps the dataset untranslated, partial, naming the i18n error', async ({ read, message }) => {
const bridge = await bridgeOverRealExecutor(() => i18nWhoseReadThrows(read, message));
const answer = await bridge.listDatasets!({ terms: TERMS });
// [#34919] Terms were sent, so the degraded answer also carries `nextStep`:
// nothing listed reads `no_measure` for every word, and the note says the
// catalogue was incomplete and to repeat the warning.
expect(answer).toEqual({
datasets: [],
partial: true,
warning: expect.stringContaining(message),
nextStep: { decision: 'no_measure', terms: TERMS, note: expect.stringContaining('warning') },
});
expect(answer.warning).toMatch(/^The dataset catalogue could not be read: /);
expect(answer.datasets.map((d) => [d.name, d.label])).toEqual([['opp_metrics', 'Opportunity Metrics']]);
expect(answer).toMatchObject({ partial: true, warning: expect.stringContaining(message) });
});

it.each(CASES)('$read throwing: query_dataset refuses 503 SERVICE_UNAVAILABLE, naming the failed read', async ({ read, message }) => {
it.each(CASES)('$read throwing: query_dataset answers, in the authored labels', async ({ read, message }) => {
const bridge = await bridgeOverRealExecutor(() => i18nWhoseReadThrows(read, message));
const refused = await bridge
.queryDataset!({ datasetName: 'opp_metrics', selection: { measures: ['total_amount'] } }, { maxRows: 10 })
.then(
() => undefined,
(e: unknown) => e as { code?: unknown; status?: unknown; message?: unknown },
);
expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
// The failed read's own 503 (naming the i18n error), not the executor's
// "not available on this deployment" one.
expect(refused?.message).toContain(`the dataset read failed (${message})`);
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' });
});

it.each(CASES)('$read throwing: the object tools serve the authored labels', async ({ read, message }) => {
const deal = { name: 'crm_opportunity', label: 'Opportunity', fields: { stage: { type: 'text', label: 'Stage' } } };
const view = servedLocaleObjectView(
{ listObjects: async () => [deal], getObject: async () => deal } as any,
{ i18n: () => i18nWhoseReadThrows(read, message) },
);
const [listed] = (await view.listObjects()) as Array<typeof deal>;
expect([listed.label, listed.fields.stage.label]).toEqual(['Opportunity', 'Stage']);
expect(((await view.getObject('crm_opportunity')) as typeof deal).label).toBe('Opportunity');
});

/**
* [#35083] A header-less stdio call, an i18n default of zh-CN and a
* workspace of `en`: the labels AND the executor's sentences answer what a
* zh-CN principal is answered — one language, the labels'.
*/
it('a header-less call answers labels and sentences in one language', async () => {
const ask = async (principal: object, defaultLocale = 'zh-CN') => {
const bridge = await bridgeOverRealExecutor(() => i18nService(defaultLocale), principal);
return {
list: await bridge.listDatasets!({ terms: ['total_amount'] }),
query: await bridge.queryDataset!({ datasetName: 'opp_metrics', selection: { measures: ['total_amount'] } }, { maxRows: 10 }),
};
};
const headerless = await ask({ ...PRINCIPAL, workspaceLocale: 'en' });
const zh = await ask({ ...PRINCIPAL, locale: 'zh-CN' });
const en = await ask({ ...PRINCIPAL, locale: 'en' }, 'en');
expect(headerless.list.datasets[0].label).toBe('商机指标');
expect(headerless.list.nextStep).toEqual(zh.list.nextStep);
expect(headerless.query.sourceLine).toBe(zh.query.sourceLine);
// Control: the two languages' sentences differ, so the equalities above are the locale's doing.
expect(en.query.sourceLine).not.toBe(zh.query.sourceLine);
});
});
29 changes: 21 additions & 8 deletions packages/mcp/src/stdio-data-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,8 @@ export interface StdioDataBridgeDeps {
*/
export interface StdioDatasetToolsService {
datasetTools(deps: {
loadDatasets: (context: unknown) => Promise<readonly unknown[]>;
loadDatasets: (context: unknown) => Promise<readonly unknown[] | { items: readonly unknown[]; warning?: string }>;
translationLocale?: (context: unknown) => Promise<string | undefined>;
diagnoseDelegation?: (object: string, context: unknown) => Promise<{ narrowed: boolean; statement?: string } | undefined>;
maxQueryLimit?: number;
}): {
Expand Down Expand Up @@ -1703,12 +1704,14 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge
// carries no request, so the locale is the i18n service's default (what
// `metaRequestLocale` answers with no header), the workspace default the
// stdio principal speaks. An i18n service this host cannot resolve leaves the
// list untranslated, as there. The stdio bridge has no delegation probe (an
// API key is not delegated), so none is passed, as `query_records` here
// carries none.
// list untranslated, as there. [#34993] So does a translation fault, whose
// sentence the rows carry as their `warning`. [#35083] `translationLocale`
// is that one locale, so the executor's sentences speak the labels' language.
// The stdio bridge has no delegation probe (an API key is not delegated), so
// none is passed, as `query_records` here carries none.
if (deps.datasetTools) {
const service = deps.datasetTools;
const loadDatasets = async (): Promise<readonly unknown[]> => {
const loadDatasets = async () => {
const protocolService = protocol?.();
let merged: StdioProtocolObjectReads | undefined;
let items: readonly unknown[];
Expand All @@ -1718,11 +1721,21 @@ export function createStdioDataBridge(deps: StdioDataBridgeDeps): McpDataBridge
} else {
items = (await metadataService.list('dataset')) ?? [];
}
const translated = await translateMetaList(defaultLocaleSources(deps.i18n, async () => merged), 'dataset', items);
return Array.isArray(translated) ? translated : items;
let warning: string | undefined;
const translated = await translateMetaList(
{ ...defaultLocaleSources(deps.i18n, async () => merged), reportTranslationFault: (w: string) => { warning = w; } },
'dataset',
items,
);
const rows = Array.isArray(translated) ? translated : items;
return warning === undefined ? rows : { items: rows, warning };
};
const translationLocale = async () => {
const sources = defaultLocaleSources(deps.i18n, async () => undefined);
return sources.requestLocale(await sources.resolveI18nService());
};
const executor = (maxQueryLimit?: number) =>
service.datasetTools({ loadDatasets, ...(maxQueryLimit !== undefined ? { maxQueryLimit } : {}) });
service.datasetTools({ loadDatasets, translationLocale, ...(maxQueryLimit !== undefined ? { maxQueryLimit } : {}) });
bridge.listDatasets = async (input) => executor().listDatasets(input, await resolvePrincipal());
bridge.queryDataset = async (input, opts) => executor(opts.maxRows).queryDataset(input, await resolvePrincipal());
bridge.datasetToolDefinitions = () => executor().definitions;
Expand Down
45 changes: 37 additions & 8 deletions packages/rest/src/meta-item-read-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3250,23 +3250,47 @@ export async function isTranslatableMetaType(type: string): Promise<boolean> {
return translatableMetaTypes.has(type);
}

/**
* [#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.
*/
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.`;
}

/**
* Build a `TranslationBundle` (`Record<locale, TranslationData>`) from an
* `II18nService` instance. `undefined` when no locales are registered, so
* callers can avoid translation work. (`RestServer.buildTranslationBundle`
* delegates here.)
*
* [#34993] A service whose `getLocales` or `getTranslations` throws is a
* 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
* 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.
*/
export function translationBundleOf(i18n: unknown): any | undefined {
export function translationBundleOf(i18n: unknown, reportFault?: (warning: string) => void): any | undefined {
const service: any = i18n;
if (!service || typeof service.getLocales !== 'function' || typeof service.getTranslations !== 'function') {
return undefined;
}
const locales: string[] = service.getLocales();
if (!locales.length) return undefined;
const bundle: Record<string, any> = {};
for (const locale of locales) {
const data = service.getTranslations(locale);
if (data && typeof data === 'object') bundle[locale] = data;
try {
const locales: string[] = service.getLocales();
if (!locales.length) return undefined;
for (const locale of locales) {
const data = service.getTranslations(locale);
if (data && typeof data === 'object') bundle[locale] = data;
}
} catch (error) {
const warning = metaTranslationFaultWarning(error);
logWarn(`[meta] ${warning}`);
reportFault?.(warning);
return undefined;
}
return Object.keys(bundle).length ? bundle : undefined;
}
Expand Down Expand Up @@ -3579,6 +3603,11 @@ export interface MetaListTranslationSources {
* last fallback; without it, only the request's own preference counts.
*/
requestLocale(i18n?: unknown): string | undefined;
/**
* [#34993] Told the sentence of a translation fault ({@link translationBundleOf}),
* for a door that says it on its answer. Optional: the server log says it either way.
*/
reportTranslationFault?(warning: string): void;
}

/**
Expand Down Expand Up @@ -3611,7 +3640,7 @@ export async function translateMetaList(
: (raw && typeof raw === 'object' && Array.isArray(raw.items) ? raw.items : null);
if (!arr) return items;
const i18n = await sources.resolveI18nService();
const bundle = translationBundleOf(i18n);
const bundle = translationBundleOf(i18n, (warning) => sources.reportTranslationFault?.(warning));
const locale = sources.requestLocale(i18n);
if (!locale) return items;
const { translateMetadataDocument } = await import('@objectstack/spec/system');
Expand Down Expand Up @@ -3687,7 +3716,7 @@ export async function translateMetaDocument(
if (!document || typeof document !== 'object') return document;
if (!(await isTranslatableMetaType(metaType))) return document;
const i18n = await sources.resolveI18nService();
const bundle = translationBundleOf(i18n);
const bundle = translationBundleOf(i18n, (warning) => sources.reportTranslationFault?.(warning));
const locale = sources.requestLocale(i18n);
if (!locale) return document;
if (metaType === 'view') {
Expand Down
Loading
Loading