Skip to content

Commit dd86154

Browse files
committed
feat(analytics): list_datasets answers nextStep and query_dataset answers sourceLine
The executor composes both finished sentences from the answer it serves: the per-term decision under the ADR-0149 D3 rule, the precedence among mixed cases (several_measures, one_measure, candidates_only, no_measure), the partial-answer closing sentence, and the source line from provenance, in the caller's language by the user-text ladder. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzfR33NbV51QQU6R6bm
1 parent d304f1b commit dd86154

3 files changed

Lines changed: 706 additions & 15 deletions

File tree

‎packages/services/service-analytics/src/__tests__/dataset-tools.test.ts‎

Lines changed: 291 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,19 @@
1818
* - `query_dataset`: one NOT_FOUND for missing and hidden; `provenance`
1919
* composed from what ran, which the model's input cannot set; the row cap
2020
* and `truncated`; the delegation statement; no `sql`.
21+
* - [#34919] `nextStep` and `sourceLine` (ADR-0149 M1 note): the decision for
22+
* each term, the precedence among mixed cases, the partial-answer rule, the
23+
* sentence's language, and that neither sentence names a member the caller
24+
* was not admitted to — on a mirror of `examples/app-crm`'s dataset.
2125
*/
2226

2327
import { describe, it, expect, vi } from 'vitest';
24-
import { ListDatasetsOutputSchema, getDatasetToolJsonSchemas } from '@objectstack/spec/ai';
28+
import { ListDatasetsOutputSchema, QueryDatasetOutputSchema, getDatasetToolJsonSchemas } from '@objectstack/spec/ai';
2529
import type { ExecutionContext } from '@objectstack/spec/kernel';
2630
import { AnalyticsServicePlugin } from '../plugin.js';
2731
import { AnalyticsService } from '../analytics-service.js';
2832
import { createDatasetTools, getDatasetToolDefinitions } from '../dataset-tools.js';
33+
import { composeDatasetSourceLine, datasetToolSentenceLocale } from '../dataset-next-step.js';
2934

3035
const ME = { userId: 'u_me', tenantId: 'org_a', locale: 'zh-CN' } as ExecutionContext;
3136
const ADMIN = { userId: 'u_admin', tenantId: 'org_a' } as ExecutionContext;
@@ -43,6 +48,19 @@ const OBJECTS: Record<string, { enable?: unknown; fields: Record<string, Record<
4348
},
4449
crm_locked: { fields: { id: { type: 'text' }, amount: { type: 'number' } } },
4550
crm_closed: { enable: { apiEnabled: false }, fields: { id: { type: 'text' }, amount: { type: 'number' } } },
51+
// [#34919] app-crm's two pipeline objects, as `examples/app-crm/src/objects` declares the fields its datasets read.
52+
crm_opportunity: {
53+
fields: {
54+
id: { type: 'text' },
55+
stage: { type: 'select' },
56+
account: { type: 'text' },
57+
close_date: { type: 'date' },
58+
amount: { type: 'currency' },
59+
},
60+
},
61+
crm_opportunity_line_item: {
62+
fields: { id: { type: 'text' }, product: { type: 'text' }, quantity: { type: 'number' }, amount: { type: 'currency' } },
63+
},
4664
};
4765

4866
const PIPELINE = {
@@ -105,18 +123,22 @@ function fakeEngine(rows: Record<string, unknown>[]) {
105123
};
106124
}
107125

108-
/** The security double: u_me may not read `crm_locked` nor the `margin` field; u_admin reads everything. */
126+
/**
127+
* The security double: u_me may not read `crm_locked` nor the `margin` field;
128+
* [#34919] u_rep may not read the `amount` field of app-crm's two objects;
129+
* u_admin reads everything.
130+
*/
131+
function fieldsFor(object: string, ctx?: ExecutionContext): string[] {
132+
const all = Object.keys(OBJECTS[object]?.fields ?? {});
133+
if (ctx?.userId === 'u_me') return all.filter((f) => f !== 'margin');
134+
if (ctx?.userId === 'u_rep' && object.startsWith('crm_opportunity')) return all.filter((f) => f !== 'amount');
135+
return all;
136+
}
109137
const security = {
110138
getReadFilter: async () => undefined,
111139
canReadObject: (object: string, ctx?: ExecutionContext) => !(ctx?.userId === 'u_me' && object === 'crm_locked'),
112-
getReadableFields: async (object: string, ctx?: ExecutionContext) => {
113-
const all = Object.keys(OBJECTS[object]?.fields ?? {});
114-
return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all;
115-
},
116-
getQueryableFields: async (object: string, ctx?: ExecutionContext) => {
117-
const all = Object.keys(OBJECTS[object]?.fields ?? {});
118-
return ctx?.userId === 'u_me' ? all.filter((f) => f !== 'margin') : all;
119-
},
140+
getReadableFields: async (object: string, ctx?: ExecutionContext) => fieldsFor(object, ctx),
141+
getQueryableFields: async (object: string, ctx?: ExecutionContext) => fieldsFor(object, ctx),
120142
};
121143

122144
async function bootWired(rows: Record<string, unknown>[] = [{ stage: 'won', revenue: 100 }]) {
@@ -827,3 +849,262 @@ describe('[#34763] list_datasets candidates — only what this caller may read,
827849
}
828850
});
829851
});
852+
853+
/**
854+
* [#34919] `examples/app-crm`'s `crm_opportunity_metrics`
855+
* (`src/datasets/opportunity.dataset.ts`), member for member with its labels
856+
* and synonyms, beside a second dataset over app-crm's line items. app-crm
857+
* declares one dataset, and the D1 rule refuses a word that answers to two
858+
* members of one dataset, so "a word with two matches" needs a second dataset:
859+
* `deal value` is `total_amount`'s synonym there and `line_amount`'s here.
860+
*/
861+
const CRM_OPPORTUNITY_METRICS = {
862+
name: 'crm_opportunity_metrics',
863+
label: 'Opportunity Metrics',
864+
description: 'Semantic layer for sales-pipeline counts and amounts',
865+
object: 'crm_opportunity',
866+
dimensions: [
867+
{ name: 'stage', label: 'Stage', field: 'stage', type: 'string', synonyms: ['sales stage', 'deal stage', 'pipeline stage', '销售阶段', '商机阶段', '漏斗阶段'] },
868+
{ name: 'account', label: 'Account', field: 'account', type: 'string', synonyms: ['customer', 'client', 'company', '客户', '公司', '客户名称'] },
869+
{ name: 'close_date', label: 'Close Date', field: 'close_date', type: 'date', dateGranularity: 'month', synonyms: ['closing month', 'expected close date', '成交日期', '预计成交日期', '成交月份'] },
870+
],
871+
measures: [
872+
{ name: 'opp_count', label: 'Opportunities', aggregate: 'count', synonyms: ['deal count', 'number of deals', '商机数', '商机数量', '机会数'] },
873+
{ name: 'total_amount', label: 'Total Amount', aggregate: 'sum', field: 'amount', format: '0,0', synonyms: ['deal value', 'opportunity amount', '商机金额', '金额合计'] },
874+
{ name: 'avg_amount', label: 'Avg Deal Size', aggregate: 'avg', field: 'amount', format: '0,0', synonyms: ['average deal value', 'average opportunity amount', '平均商机金额'] },
875+
],
876+
};
877+
const CRM_LINE_ITEM_METRICS = {
878+
name: 'crm_line_item_metrics',
879+
label: 'Line Item Metrics',
880+
object: 'crm_opportunity_line_item',
881+
dimensions: [{ name: 'product', label: 'Product', field: 'product', type: 'string' }],
882+
measures: [
883+
{ name: 'line_amount', label: 'Line Amount', aggregate: 'sum', field: 'amount', synonyms: ['deal value', '明细金额'] },
884+
{ name: 'quantity_total', label: 'Quantity', aggregate: 'sum', field: 'quantity' },
885+
],
886+
};
887+
const loadCrm = async () => [CRM_OPPORTUNITY_METRICS, CRM_LINE_ITEM_METRICS];
888+
const REP = { userId: 'u_rep', tenantId: 'org_a' } as ExecutionContext;
889+
/** The members u_rep may not read (each over `amount`), by every word a sentence could name them with. */
890+
const WITHHELD_WORDS = ['Total Amount', 'total_amount', 'Avg Deal Size', 'avg_amount', 'Line Amount', 'line_amount'];
891+
892+
type ListOut = Awaited<ReturnType<ReturnType<AnalyticsService['datasetTools']>['listDatasets']>>;
893+
894+
/**
895+
* The invariants `DatasetNextStepSchema` names and cannot refuse: the answer
896+
* parses; `nextStep` is present exactly when terms were sent; every term it
897+
* names was sent; a `candidates_only` term has entries in `candidates`; a
898+
* measure case's terms have measure entries in `matches`.
899+
*/
900+
function expectNextStepInvariants(out: ListOut, sent: readonly string[] | undefined) {
901+
expect(ListDatasetsOutputSchema.safeParse(out).success).toBe(true);
902+
if (sent === undefined || sent.length === 0) {
903+
expect('nextStep' in out).toBe(false);
904+
return;
905+
}
906+
const step = out.nextStep!;
907+
expect(step).toBeDefined();
908+
for (const term of step.terms) {
909+
expect(sent).toContain(term);
910+
// Distinct members: a word sent twice repeats its entries in `matches`.
911+
const measureHits = [...new Set(out.datasets.flatMap((d) => (d.matches ?? [])
912+
.filter((m) => m.term === term && m.member.startsWith('measures.'))
913+
.map((m) => `${d.name}.${m.member}`)))];
914+
const offered = (out.candidates ?? []).filter((c) => c.term === term);
915+
if (step.decision === 'one_measure') expect(measureHits).toHaveLength(1);
916+
if (step.decision === 'several_measures') expect(measureHits.length).toBeGreaterThan(1);
917+
if (step.decision === 'candidates_only') expect([measureHits.length, offered.length > 0]).toEqual([0, true]);
918+
if (step.decision === 'no_measure') expect([measureHits.length, offered.length]).toEqual([0, 0]);
919+
}
920+
expect(new Set(step.terms).size).toBe(step.terms.length);
921+
}
922+
923+
describe('[#34919] list_datasets nextStep on examples/app-crm — the decision each word gets', () => {
924+
async function ask(terms: string[] | undefined, ctx: ExecutionContext = ADMIN) {
925+
const { service } = await bootWired();
926+
const out = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets(terms === undefined ? {} : { terms }, ctx);
927+
expectNextStepInvariants(out, terms);
928+
return out;
929+
}
930+
931+
it('a word with one match ⇒ one_measure, naming the measure, its dataset and the names to query', async () => {
932+
const out = await ask(['商机数']);
933+
expect(out.nextStep).toMatchObject({ decision: 'one_measure', terms: ['商机数'] });
934+
expect(out.nextStep!.note).toContain('Opportunities (dataset: Opportunity Metrics)');
935+
expect(out.nextStep!.note).toContain('"crm_opportunity_metrics"');
936+
expect(out.nextStep!.note).toContain('"opp_count"');
937+
});
938+
939+
it('a word with two matches ⇒ several_measures, the note naming each by its label and its dataset\'s label', async () => {
940+
const out = await ask(['deal value']);
941+
expect(out.nextStep).toMatchObject({ decision: 'several_measures', terms: ['deal value'] });
942+
expect(out.nextStep!.note).toContain('Total Amount (dataset: Opportunity Metrics)');
943+
expect(out.nextStep!.note).toContain('Line Amount (dataset: Line Item Metrics)');
944+
});
945+
946+
it('a near-miss word ⇒ candidates_only, the note naming each offered member by its label and its dataset\'s label', async () => {
947+
const out = await ask(['金额']);
948+
expect(out.nextStep).toMatchObject({ decision: 'candidates_only', terms: ['金额'] });
949+
expect(out.candidates!.map((c) => c.member)).toEqual(['measures.total_amount', 'measures.avg_amount', 'measures.line_amount']);
950+
for (const named of ['Total Amount (dataset: Opportunity Metrics)', 'Avg Deal Size (dataset: Opportunity Metrics)', 'Line Amount (dataset: Line Item Metrics)']) {
951+
expect(out.nextStep!.note).toContain(named);
952+
}
953+
});
954+
955+
it('an unknown word ⇒ no_measure, and the note sends the reader to the object tools', async () => {
956+
const out = await ask(['库存周转']);
957+
expect(out.nextStep).toMatchObject({ decision: 'no_measure', terms: ['库存周转'] });
958+
expect(out.nextStep!.note).toContain('query_records');
959+
});
960+
961+
it('a word equal only to a dimension ⇒ no_measure, naming the grouping, and asks for the number instead of falling back', async () => {
962+
const out = await ask(['销售阶段']);
963+
expect(out.nextStep).toMatchObject({ decision: 'no_measure', terms: ['销售阶段'] });
964+
expect(out.nextStep!.note).toContain('Stage (dataset: Opportunity Metrics)');
965+
expect(out.nextStep!.note).not.toContain('query_records');
966+
});
967+
968+
it('no terms, or an empty list, ⇒ no nextStep', async () => {
969+
await ask(undefined);
970+
await ask([]);
971+
});
972+
973+
it('a withheld member appears in no decision and no sentence (N5)', async () => {
974+
// u_rep reads no `amount`: total_amount, avg_amount and line_amount are withheld.
975+
for (const terms of [['deal value'], ['金额'], ['商机金额', '销售阶段'], ['商机数', 'deal value', '金额']]) {
976+
const out = await ask(terms, REP);
977+
const text = JSON.stringify(out.nextStep);
978+
for (const word of WITHHELD_WORDS) expect(text, `${terms.join('+')} ⇒ ${word}`).not.toContain(word);
979+
}
980+
// What the same words read as for u_rep: the withheld equalities are gone, so nothing is a measure.
981+
expect((await ask(['deal value'], REP)).nextStep).toMatchObject({ decision: 'no_measure', terms: ['deal value'] });
982+
expect((await ask(['金额'], REP)).nextStep).toMatchObject({ decision: 'no_measure', terms: ['金额'] });
983+
// The control: the same words name those members for a caller who reads `amount`.
984+
expect((await ask(['deal value'])).nextStep!.note).toContain('Total Amount');
985+
});
986+
});
987+
988+
describe('[#34919] list_datasets nextStep — the precedence among mixed cases', () => {
989+
async function decide(terms: string[]) {
990+
const { service } = await bootWired();
991+
const out = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets({ terms }, ADMIN);
992+
expectNextStepInvariants(out, terms);
993+
return { decision: out.nextStep!.decision, terms: out.nextStep!.terms };
994+
}
995+
996+
it('N1: a dimension-matched word never outranks a measure-matched one', async () => {
997+
expect(await decide(['商机金额', '销售阶段'])).toEqual({ decision: 'one_measure', terms: ['商机金额'] });
998+
expect(await decide(['销售阶段', '商机金额'])).toEqual({ decision: 'one_measure', terms: ['商机金额'] });
999+
});
1000+
1001+
it('several_measures > one_measure > candidates_only > no_measure, naming every word in the reported case', async () => {
1002+
expect(await decide(['商机数', 'deal value'])).toEqual({ decision: 'several_measures', terms: ['deal value'] });
1003+
expect(await decide(['金额', 'deal value'])).toEqual({ decision: 'several_measures', terms: ['deal value'] });
1004+
expect(await decide(['金额', '商机数'])).toEqual({ decision: 'one_measure', terms: ['商机数'] });
1005+
expect(await decide(['库存周转', '金额'])).toEqual({ decision: 'candidates_only', terms: ['金额'] });
1006+
expect(await decide(['库存周转', '销售阶段'])).toEqual({ decision: 'no_measure', terms: ['库存周转', '销售阶段'] });
1007+
// Two words with one measure each are two metrics: both named, in the order sent.
1008+
expect(await decide(['商机金额', '商机数', '销售阶段'])).toEqual({ decision: 'one_measure', terms: ['商机金额', '商机数'] });
1009+
});
1010+
1011+
it('a word sent twice is one word, and the member it equals is counted once', async () => {
1012+
expect(await decide(['商机数', '商机数'])).toEqual({ decision: 'one_measure', terms: ['商机数'] });
1013+
});
1014+
});
1015+
1016+
describe('[#34919] list_datasets nextStep — an incomplete catalogue says so (N4)', () => {
1017+
it('a degraded read keeps nextStep over what it lists and ends the note by saying the catalogue was incomplete', async () => {
1018+
const { service } = await bootWired();
1019+
const whole = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets({ terms: ['商机数'] }, ADMIN);
1020+
const degraded = await service.datasetTools({
1021+
loadDatasets: async () => ({ items: [CRM_OPPORTUNITY_METRICS], partial: true as const, warning: 'one source unavailable' }),
1022+
}).listDatasets({ terms: ['商机数'] }, ADMIN);
1023+
expectNextStepInvariants(degraded, ['商机数']);
1024+
expect(degraded).toMatchObject({ partial: true, nextStep: { decision: 'one_measure', terms: ['商机数'] } });
1025+
// The whole read's sentence, plus one closing sentence naming the warning.
1026+
expect(degraded.nextStep!.note.startsWith(whole.nextStep!.note)).toBe(true);
1027+
const added = degraded.nextStep!.note.slice(whole.nextStep!.note.length);
1028+
expect(added).toContain('incomplete');
1029+
expect(added).toContain('warning');
1030+
expect(whole.nextStep!.note).not.toContain('incomplete');
1031+
});
1032+
1033+
it('a catalogue that could not be read at all answers no_measure for every word, and says the catalogue was incomplete', async () => {
1034+
const { service } = await bootWired();
1035+
const failed = await service.datasetTools({ loadDatasets: async () => { throw new Error('metadata loader down'); } })
1036+
.listDatasets({ terms: ['商机数', '销售阶段'] }, ADMIN);
1037+
expectNextStepInvariants(failed, ['商机数', '销售阶段']);
1038+
expect(failed).toMatchObject({ datasets: [], partial: true, nextStep: { decision: 'no_measure', terms: ['商机数', '销售阶段'] } });
1039+
expect(failed.nextStep!.note).toContain('incomplete');
1040+
});
1041+
1042+
it('an admission that could not be judged is a partial answer too, and its note says so', async () => {
1043+
const { service } = await bootWired();
1044+
vi.spyOn(service, 'admitDatasetCatalogEntry').mockImplementation(async () => ({ admitted: false, unresolved: true }) as never);
1045+
const out = await service.datasetTools({ loadDatasets: loadCrm }).listDatasets({ terms: ['商机数'] }, ADMIN);
1046+
expect(out).toMatchObject({ partial: true, nextStep: { decision: 'no_measure' } });
1047+
expect(out.nextStep!.note).toContain('incomplete');
1048+
});
1049+
});
1050+
1051+
describe('[#34919] the sentences are in the caller\'s language, by the user-text ladder', () => {
1052+
it('reads the request locale, then the workspace default, through the platform locale table; en below both', () => {
1053+
expect(datasetToolSentenceLocale(['zh-CN'])).toBe('zh-Hans');
1054+
expect(datasetToolSentenceLocale(['zh-TW'])).toBe('zh-Hant');
1055+
expect(datasetToolSentenceLocale(['zh-Hant-HK'])).toBe('zh-Hant');
1056+
expect(datasetToolSentenceLocale(['ja-JP'])).toBe('ja');
1057+
expect(datasetToolSentenceLocale(['en-GB'])).toBe('en');
1058+
// A language with no sentences takes the next rung: the workspace default, then en.
1059+
expect(datasetToolSentenceLocale(['fr-FR', 'ja-JP'])).toBe('ja');
1060+
expect(datasetToolSentenceLocale(['fr-FR'])).toBe('en');
1061+
expect(datasetToolSentenceLocale([])).toBe('en');
1062+
});
1063+
1064+
it('the executor writes the note for the context\'s locale, then its workspace default', async () => {
1065+
const { service } = await bootWired();
1066+
const tools = service.datasetTools({ loadDatasets: loadCrm });
1067+
const notes: Record<string, string> = {};
1068+
for (const [key, ctx] of Object.entries({
1069+
en: ADMIN,
1070+
zh: { ...ADMIN, locale: 'zh-CN' },
1071+
hant: { ...ADMIN, locale: 'zh-TW' },
1072+
ja: { ...ADMIN, locale: 'ja-JP' },
1073+
frThenJa: { ...ADMIN, locale: 'fr-FR', workspaceLocale: 'ja-JP' },
1074+
} as Record<string, ExecutionContext>)) {
1075+
const out = await tools.listDatasets({ terms: ['deal value'] }, ctx);
1076+
expect(out.nextStep!.decision).toBe('several_measures');
1077+
notes[key] = out.nextStep!.note;
1078+
}
1079+
expect(new Set([notes.en, notes.zh, notes.hant, notes.ja]).size).toBe(4);
1080+
expect(notes.frThenJa).toBe(notes.ja);
1081+
// Every language still names both members by label and dataset label.
1082+
for (const note of Object.values(notes)) {
1083+
for (const label of ['Total Amount', 'Opportunity Metrics', 'Line Amount', 'Line Item Metrics']) expect(note).toContain(label);
1084+
}
1085+
});
1086+
});
1087+
1088+
describe('[#34919] query_dataset sourceLine — the provenance as one finished line', () => {
1089+
it('is composed from the answer\'s provenance, in the caller\'s language, and parses', async () => {
1090+
const { service } = await bootWired([{ stage: 'won', revenue: 100 }]);
1091+
const tools = service.datasetTools({ loadDatasets: loadSaved });
1092+
const out = await tools.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'], dimensions: ['stage'] } }, ME);
1093+
expect(out.sourceLine).toBe(composeDatasetSourceLine(out.provenance, ['zh-CN']));
1094+
for (const label of ['营收', '销售分析', 'Stage']) expect(out.sourceLine).toContain(label);
1095+
const admin = await tools.queryDataset({ datasetName: 'pipeline', selection: { measures: ['revenue'] } }, ADMIN);
1096+
expect(admin.sourceLine).toBe(composeDatasetSourceLine(admin.provenance, []));
1097+
for (const label of ['Revenue', 'Pipeline']) expect(admin.sourceLine).toContain(label);
1098+
for (const answer of [out, admin]) expect(QueryDatasetOutputSchema.safeParse(answer).success).toBe(true);
1099+
});
1100+
1101+
it('names no member the caller was not admitted to (N5): a withheld measure is refused before any line exists', async () => {
1102+
const { service } = await bootWired([{ stage: 'won', opp_count: 3 }]);
1103+
const tools = service.datasetTools({ loadDatasets: loadCrm });
1104+
const out = await tools.queryDataset({ datasetName: 'crm_opportunity_metrics', selection: { measures: ['opp_count'], dimensions: ['stage'] } }, REP);
1105+
for (const label of ['Opportunities', 'Opportunity Metrics', 'Stage']) expect(out.sourceLine).toContain(label);
1106+
for (const word of WITHHELD_WORDS) expect(out.sourceLine).not.toContain(word);
1107+
await expect(tools.queryDataset({ datasetName: 'crm_opportunity_metrics', selection: { measures: ['total_amount'] } }, REP))
1108+
.rejects.toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
1109+
});
1110+
});

0 commit comments

Comments
 (0)