import copy import json import sys import tempfile import threading import unittest from pathlib import Path from unittest.mock import patch sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'scripts'), str(Path(__file__).resolve().parent)] from nao_agent_task import normalize_task from nao_protocol_execution import execute from test_nao_agent_task import task_value from test_nao_protocol_execution import RELEASE, TURN, identity from test_nao_query_plan_defects import defect_catalog, defect_node from test_nao_quality_tools import FakeApi SOURCE_FIELD = '责废尺寸重量' def java_category_reconciliation(fields, source_rows): expected_counts = {'责废': 7, '料废': 5} component_codes = {'责废': 'black_responsibility_scrap', '料废': 'black_material_scrap'} by_category = {} for field in fields: by_category.setdefault(field['category'], []).append(field) result = [] for category, selected in by_category.items(): components = [{'key': field['key'], 'label': field['label'], 'weight': 4.0, 'sourceRows': source_rows, 'presentRows': source_rows, 'missingRows': 0, 'invalidRows': 0, 'negativeRows': 0} for field in selected] expected = expected_counts[category] result.append({'category': category, 'sourceRows': source_rows, 'components': components, 'subitemWeightSum': 4.0 * len(selected), 'validSubitemCount': len(selected), 'subitemFieldCount': expected, 'coverage': {'valid': len(selected), 'total': expected}, 'formalComponent': component_codes[category], 'formalComponentSum': 9.0, 'formalComponentCoverage': {'sourceRows': source_rows, 'presentRows': source_rows, 'missingRows': 0, 'invalidRows': 0, 'negativeRows': 0}, 'diff': 4.0 * len(selected) - 9.0, 'isReconciled': False, 'reconciliationStatus': 'INCOMPLETE', 'reconciliationReasons': ['部分原始分项字段受授权限制,不能完整回加']}) return result class DefectProtocolApi(FakeApi): def __init__(self, *, bad_proof=False, unavailable=False): super().__init__() self.root = None self.node = None self.bad_proof = bad_proof self.unavailable = unavailable self.envelopes = [] self.reads = [] def call(self, path, payload=None, method=None, *, node_id=None, scope_id=None): self.envelopes.append({'path': path, 'nodeId': node_id, 'scopeId': scope_id}) if path == '/api/analysis/protocol/queries': child = copy.deepcopy(self.root) child.pop('queryPlan', None) child['defectQuery'] = {'dimension': self.node['dimension'], 'limit': self.node['limit']} scope = {'nodeId': self.node['nodeId'], 'scopeId': 'black-defects-scope', 'label': '黑片具体缺陷', 'purpose': 'defects', 'task': child} return {'version': 1, 'scopes': [scope], 'pending': [], 'gaps': []} if path == '/api/analysis/defects': self.reads.append(copy.deepcopy(payload)) year = payload['year'] rows = [ {'key': SOURCE_FIELD, 'label': SOURCE_FIELD, 'category': '责废', 'weight': 8.0 if year == 2026 else 5.0, 'sourceRows': 3, 'presentRows': 3, 'missingRows': 0, 'invalidRows': 0, 'negativeRows': 0}, {'key': '料废尺寸重量', 'label': '料废尺寸重量', 'category': '料废', 'weight': 4.0 if year == 2026 else 3.0, 'sourceRows': 3, 'presentRows': 3, 'missingRows': 0, 'invalidRows': 0, 'negativeRows': 0}, ] fields = [{'key': row['key'], 'label': row['label'], 'sourceField': row['key'], 'category': row['category']} for row in rows] context = {key: payload.get(key) for key in ( 'year', 'month', 'quarter', 'monthStart', 'monthEnd', 'department', 'group', 'product', 'projectGroup', 'includeUnassigned', 'stage', 'dimension', 'defect', 'category')} context['extraFilters'] = payload.get('extraFilters', {}) context['exclusions'] = payload.get('exclusions', {}) context['filters'] = {'columnFilters': payload.get('columnFilters', [])} available = not self.unavailable proof = {**identity(), 'queryId': f'defect-{year}', 'responseHash': f'{year:064x}', 'nodeId': 'forged' if self.bad_proof else node_id, 'scopeId': scope_id} return {'kind': 'fine_defect_top', 'releaseId': payload['releaseId'], 'release': {'id': payload['releaseId'], 'status': 'PUBLISHED'}, 'context': {**context, 'mode': 'top'}, 'grain': 'source_defect_weight', 'rows': rows if available else [], 'totalGroups': len(rows) if available else 0, 'rowsTruncated': False, 'sourceRows': 3, 'coverage': {'available': available, 'sourceRows': 3, 'hasValidWeights': available}, 'categoryReconciliation': java_category_reconciliation(fields, 3) if available else [], 'sourceFields': fields if available else [], 'notice': '来源细项重量。', 'protocolEvidence': proof} return super().call(path, payload, method) class QueryPlanDefectExecutionTests(unittest.TestCase): def task(self): node = defect_node(comparison=True, node_id='faults') value = task_value(kind='analysis', queryPlan=[node], dimensions=['defect'], dimensionStages={'defect': ['black']}, stages=['black'], fields=['scrapWeight'], trendRequired=False, comparisonRequired=True, period={'year': 2026, 'month': 9}, comparisonPeriod={'year': 2025, 'month': 9}, visualPreference='auto', visualType='bar') task = normalize_task(value, '比较2026年9月和2025年9月黑片来源具体缺陷重量', {'_protocol': {'version': 1}, '_businessCatalog': defect_catalog()}) if task['filters'].get('columnFilters') == []: task['filters'].pop('columnFilters') return task def run_query(self, api): task = self.task() api.root, api.node = task, task['queryPlan'][0] request = {'releaseId': RELEASE, 'turnId': TURN, 'question': task['question']} with tempfile.TemporaryDirectory() as folder: root = Path(folder) (root / 'evidence').mkdir() (root / 'private').mkdir() with patch('nao_evidence_finalizer.synthesize', return_value={ 'answer': '已核对两个期间的来源缺陷重量。', 'evidenceSufficient': True, 'missingEvidence': [], 'usage': {}}): result = execute(request=request, task=task, authority={**identity(), 'task': task}, actor_root=root, delegated=api, connection=('offline', 'synthetic', 'model'), cancel_event=threading.Event(), emit=lambda _: None) documents = [json.loads(path.read_text()) for path in (root / 'evidence').glob('nao-quality-*.json')] return result, documents def test_comparison_defect_node_uses_two_bound_requests_and_completes(self): api = DefectProtocolApi() result, documents = self.run_query(api) self.assertEqual(result['status'], 'COMPLETED', result['evidenceCompletion']['missingEvidence']) self.assertEqual(result['stopReason'], 'evidence_finalized') self.assertEqual(result['completionMethod'], 'bounded_scoped_query_plan') self.assertEqual([item['year'] for item in api.reads], [2026, 2025]) self.assertTrue(all(item['limit'] == 100 for item in api.reads)) self.assertEqual(len(documents), 1) self.assertEqual(len(documents[0]['result']['protocolEvidence']), 2) self.assertEqual({proof['nodeId'] for proof in result['protocolEvidence']}, {'faults'}) self.assertEqual({proof['scopeId'] for proof in result['protocolEvidence']}, {'black-defects-scope'}) self.assertEqual([item['nodeId'] for item in api.envelopes if item['path'] == '/api/analysis/defects'], ['faults', 'faults']) self.assertEqual([item['scopeId'] for item in api.envelopes if item['path'] == '/api/analysis/defects'], ['black-defects-scope', 'black-defects-scope']) def test_unavailable_detail_or_forged_scope_receipt_stays_partial(self): for api in (DefectProtocolApi(unavailable=True), DefectProtocolApi(bad_proof=True)): with self.subTest(api=api): result, _ = self.run_query(api) self.assertEqual(result['status'], 'PARTIAL') self.assertFalse(result['evidenceCompletion']['serverCoverageSufficient']) self.assertTrue(result['evidenceCompletion']['missingEvidence']) if __name__ == '__main__': unittest.main()