import copy import sys import unittest from pathlib import Path sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'scripts')] from dsh_model_input import compact_tool_result, planning_input, canonical_proposal, explicit_comparison_periods, recent_trend_period, DIRECT_PLANNING_PROMPT from nao_quality_tools import tool_definition from nao_weight_ranking import rank_response class DshModelInputTests(unittest.TestCase): def test_recent_monthly_trend_binds_published_months_instead_of_one_month(self): context = {'_businessCatalog': {'periods': [f'2026-{month:02d}' for month in range(1, 11)], 'latestDataPeriod': {'year': 2026, 'month': 10}}} value = {'kind': 'analysis', 'period': {'year': 2026, 'month': 10}, 'trendRequired': True, 'comparisonRequired': True} fixed = canonical_proposal(value, question='分析最近月份合格率的变化趋势', context=context) self.assertEqual(fixed['period'], {'year': 2026, 'monthStart': 5, 'monthEnd': 10}) self.assertTrue(fixed['trendRequired']) self.assertFalse(fixed['comparisonRequired']) three = recent_trend_period('最近3个月合格率走势', context) self.assertEqual(three['period'], {'year': 2026, 'monthStart': 8, 'monthEnd': 10}) self.assertEqual(recent_trend_period('最近三个月走势', context), three) self.assertEqual(recent_trend_period('最近3个已发布月份走势', context), three) self.assertFalse(recent_trend_period('最近1个月走势', context)['trendRequired']) self.assertIsNone(recent_trend_period('查看2026年8月至10月的近期走势', context)) self.assertIsNone(recent_trend_period('最近12个月走势', context)) self.assertIsNone(recent_trend_period('最近三年合格率趋势', context)) self.assertEqual(value['period'], {'year': 2026, 'month': 10}) def test_stage_comparison_and_monthly_trend_do_not_require_a_second_period(self): result = canonical_proposal({'kind': 'analysis', 'period': {'year': 2026, 'monthStart': 1, 'monthEnd': 10}, 'dimensions': ['month'], 'comparisonRequired': True, 'trendRequired': True, 'newTask': True}, question='生成2026年1—10月报告,给出黑片和亮片月度对照及趋势') self.assertFalse(result['comparisonRequired']) self.assertEqual(result['dimensions'], []) self.assertTrue(result['trendRequired']) prior = {'comparisonPeriod': {'year': 2026, 'month': 9}} followup = canonical_proposal({'kind': 'analysis', 'comparisonRequired': True}, question='只看黑片', context=prior) self.assertEqual(followup['comparisonPeriod'], prior['comparisonPeriod']) def test_explicit_two_month_comparison_cannot_be_misread_as_one_range(self): source = {'kind': 'analysis', 'fields': ['rate'], 'comparisonPeriod': {'year': 2026, 'monthStart': 9, 'monthEnd': 10}} binding = {'period': {'year': 2026, 'month': 10}, 'comparisonPeriod': {'year': 2026, 'month': 9}} result = canonical_proposal(source, question='比较2026年9月和10月公司总体合格率') self.assertEqual(result['period'], binding['period']) self.assertEqual(result['comparisonPeriod'], binding['comparisonPeriod']) self.assertEqual(explicit_comparison_periods('2026年10月比9月变化多少'), binding) self.assertIsNone(explicit_comparison_periods('生成2026年1—10月总体质量报告')) self.assertIsNone(explicit_comparison_periods('不要比较2026年9月和10月')) self.assertEqual(explicit_comparison_periods('比较2026年1—3月和2025年1—3月')['period'], {'year': 2026, 'monthStart': 1, 'monthEnd': 3}) def test_response_field_aliases_do_not_require_another_model_call(self): value = {'fields': ['compositeRate', 'blackRate', 'brightRate', 'rateDeltaPP']} self.assertEqual(canonical_proposal(value)['fields'], ['rate']) self.assertEqual(value['fields'], ['compositeRate', 'blackRate', 'brightRate', 'rateDeltaPP']) self.assertEqual(canonical_proposal({'fields': ['unknownMetric']})['fields'], ['unknownMetric']) def test_one_rank_query_preserves_auxiliary_metrics_for_the_same_selected_objects(self): source = {'summary': {'black': {'scrapWeight': 3, 'totalWeight': 100}}, 'rows': [{'key': 'A', 'label': '甲', 'black': {'scrapWeight': 2, 'totalWeight': 80}}, {'key': 'B', 'label': '乙', 'black': {'scrapWeight': 1, 'totalWeight': 20}}], 'coverage': {'sourceMonths': [{'year': 2026, 'month': 10, 'blackRows': 2}]}} before = copy.deepcopy(source) result = rank_response(source, {'id': 'fixture'}, {'year': 2026, 'month': 10}, {}, 'product', 'black', 'scrapWeight', 1, include_metrics=True) self.assertEqual(result['rows'][0]['key'], 'A') self.assertEqual(result['rows'][0]['metrics'], {'scrapWeight': 2.0, 'totalWeight': 80.0}) self.assertEqual(result['totalWeight'], 3.0) self.assertEqual(source, before) def test_native_tool_contract_exposes_only_executable_task_operations(self): task = {'period': {'year': 2026, 'month': 10}, 'stages': ['black'], 'dimensions': ['product','defect']} schema = tool_definition(native_protocol=True, task=task, release_id='release')['inputSchema'] self.assertEqual(set(schema['properties']['mode']['enum']), {'catalog', 'query', 'rank', 'defects'}) self.assertNotIn('top', tool_definition(native_protocol=True)['inputSchema']['properties']['mode']['enum']) self.assertEqual(schema['properties']['period']['const'], task['period']) self.assertEqual(schema['properties']['stage']['enum'], ['black']) self.assertEqual(schema['properties']['stage']['type'], 'string') self.assertNotIn('comparisonPeriod', schema['properties']) self.assertNotIn('action', schema['properties']) task.update(comparisonPeriod={'year': 2026, 'month': 9}, fullDetails=True) schema = tool_definition(native_protocol=True, task=task)['inputSchema'] self.assertTrue({'compare', 'changes', 'details', 'investigate'} <= set(schema['properties']['mode']['enum'])) self.assertEqual(schema['properties']['action']['enum'], ['rows']) overview = tool_definition(native_protocol=True, task={'kind':'analysis','dimensions':[], 'question':'生成总体报告,给出月度趋势和报废大类'})['inputSchema'] self.assertEqual(overview['properties']['mode']['enum'], ['catalog','query','rank']) def test_compaction_keeps_numbers_nulls_coverage_and_source_immutable(self): summary = {'compositeRate': 0, 'black': {'rate': None, 'scrapWeight': 12.3456, 'formalDisplay': {'scrapWeight': {'formatted': '12.35 kg'}}}} source = {'summary': summary, 'rows': [copy.deepcopy(summary)], 'rowCount': 1, 'coverage': {'missingStages': ['black']}, 'calculationRules': {'internal': 'rule'}, 'metricFormulaDescriptions': {'compositeRate': 'formal rule'}, 'trend': [{'periodLabel': '2026-09', 'compositeRate': 0.9512}, {'periodLabel': '2026-10', 'compositeRate': 0.9546}]} original = copy.deepcopy(source) view = compact_tool_result(source) self.assertEqual(source, original) self.assertEqual(view['summary']['black'], {'rate': None, 'scrapWeight': 12.3456}) self.assertEqual(view['coverage'], original['coverage']) self.assertEqual(view['metricFormulaDescriptions'], original['metricFormulaDescriptions']) self.assertNotIn('rows', view) self.assertEqual(view['trend'], source['trend']) self.assertEqual(view['trendSummary']['compositeRate']['minimum']['period'], '2026-09') self.assertEqual(view['trendSummary']['compositeRate']['firstToLastPP'], 0.34) source['rows'].append({'compositeRate': 0.9}) remaining = compact_tool_result(source)['rows'] self.assertEqual(len(remaining), 2) self.assertEqual(remaining[0]['black']['scrapWeight'], 12.3456) self.assertEqual(remaining[1], {'compositeRate': 0.9}) def test_planning_keeps_scope_and_questions_without_duplicate_answer_bodies(self): payload = {'question': '只看黑片', 'previousTask': {'filters': {'department': '甲'}}, 'protocol': {'availableRankings': [{'name': '真实产品'}]}, 'previousVerifiedTurns': [{'turnId': 'old', 'question': '前问', 'answer': '重复正文'*100}], 'previousUserQuestions': [{'question': '前问', 'status': 'COMPLETED'}], 'lastVisibleAnswer': '重复正文'*100} before = copy.deepcopy(payload) result = planning_input(payload) self.assertEqual(payload, before) self.assertEqual(result['previousTask'], payload['previousTask']) self.assertEqual(result['protocol'], payload['protocol']) self.assertEqual(result['previousVerifiedTurns'], [{'turnId': 'old', 'question': '前问'}]) self.assertNotIn('lastVisibleAnswer', result) self.assertNotIn('queryPlan=', DIRECT_PLANNING_PROMPT) def test_catalog_does_not_advertise_legacy_top_or_unavailable_raw_reads(self): source = {'kind': 'quality_catalog', 'topDimensions': ['category', 'product', 'group'], 'sourceFields': [{'key': 'source-field'}], 'fineDefects': {'fields': ['real-defect']}, 'investigation': {'actions': ['overview', 'fields', 'rows', 'source']}} view = compact_tool_result(source, task={}) self.assertEqual(view['rankingDimensions'], ['product', 'group']) self.assertNotIn('topDimensions', view) self.assertNotIn('sourceFields', view) self.assertNotIn('investigation', view) self.assertEqual(view['fineDefects'], source['fineDefects']) self.assertEqual(compact_tool_result(source, task={'fullDetails': True})['sourceFields'], source['sourceFields']) if __name__ == '__main__': unittest.main()