"""Synthetic fault injection: no employee-specific instructions or production writes.""" from copy import deepcopy import json import pytest from app.modules.work_assistant import personnel_profile as profile from app.modules.work_assistant.personnel_recovery import apply_repair, row_fingerprint, reassess_findings from app.modules.work_assistant.model_gateway import ModelOutputInvalid, ModelUnavailable from app.modules.work_assistant.review_jobs import ReviewJobs, JobDeferred def scenario(person='9001'): entry=profile.ProfileRequest(person_id=person,name='回归样例',department_id='1',department='验证部门',posts='工程师', begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[ dict(id='duty',kind='duty',subject='报告交付',actor_id='',at='',relation='requirement',content='报告须完成评审并归档。'), dict(id='work',kind='feedback',subject='报告评审',actor_id=person,at='2026-11-16',relation='self',content='已提交报告,评审意见要求补充边界用例。')]) raw={section:[] for section in profile.DETAIL_SECTIONS} raw['findings']=[dict(key=key,status='review_required' if key=='assignment' else 'insufficient', headline='报告交付待核对',finding='本人反馈已提交报告,评审后的补充情况待核对。',action='',basis=[{'excerpt_id':'e2'}]) for key in profile.KEYS] raw['findings'][3]['headline']='建议侧重报告修订' raw['findings'][4]['headline']='建议承担报告修订' raw['findings'][4]['basis'].append({'excerpt_id':'e1'}) return entry,raw def normal_model(raw, calls): def invoke(instruction,payload,schema,**kwargs): if 'issues' in schema['properties']: calls.append('verify');return {'issues':[]} if 'repair_keys' in payload: calls.append(tuple(payload['repair_keys'])) return {'findings':[deepcopy(row) for row in raw['findings'] if row['key'] in payload['repair_keys']]} calls.append('generate');return deepcopy(raw) return invoke def test_old_checkpoint_gets_missing_portrait_without_regenerating_existing_work(): import hashlib entry, raw = scenario() raw.pop('portrait') checkpoint={'rule':profile.RULE_VERSION,'source_hash':hashlib.sha256(json.dumps(entry.model_dump(),ensure_ascii=False,sort_keys=True).encode()).hexdigest(), 'candidate':deepcopy(raw),'grounding_revision':profile.GROUNDING_REVISION,'repair_revision':profile.REPAIR_REVISION-1} calls=[] def invoke(instruction,payload,schema,**kwargs): if 'issues' in schema['properties']:return {'issues':[]} assert payload['generation_part']=='portrait' assert set(schema['properties'])=={'portrait'} calls.append('portrait') return {'portrait':[dict(topic='报告提交与修订推进',record='已提交报告,评审要求补充边界用例。', assessment='有报告提交动作,补充后的成果仍待核对。',action='',basis=[{'excerpt_id':'e2'}])]} result=profile.review_profile(entry,invoke=invoke,checkpoint=checkpoint) assert calls==['portrait'] assert len(result['portrait'])==1 assert result['findings'][0]['finding']==raw['findings'][0]['finding'] def test_each_column_has_its_own_budget_and_verified_rows_are_not_regenerated(monkeypatch): entry,raw=scenario();calls=[];saved=[];original_validate=profile.validate failures=iter(['recent','recent','attitude','attitude','development','development']) def fault(entry,candidate): result=original_validate(entry,candidate) key=next(failures,None) if key:raise ValueError(key+':需重新核对本行的具体工作。') return result monkeypatch.setattr(profile,'validate',fault) result=profile.review_profile(entry,invoke=normal_model(raw,calls),save_checkpoint=saved.append) assert calls.count('generate')==1 assert [c for c in calls if isinstance(c,tuple)]==[(k,) for k in ('recent','recent','attitude','attitude','development','development')] assert saved[-1]['repair_attempts']=={'recent':2,'attitude':2,'development':2} assert len(result['findings'])==5 assert saved[-1]['candidate']==raw def test_fit_repair_uses_task_quality_instructions_and_original_feedback(): entry,good=scenario();bad=deepcopy(good) bad['findings'][1].update(status='attention',basis=[{'excerpt_id':'e2'}]) repairs=[] def invoke(instruction,payload,schema,**kwargs): if 'issues' in schema['properties']:return {'issues':[]} if 'repair_keys' in payload: assert payload['repair_keys']==['fit'] assert '月度要求不能写成每日要求' in instruction assert '不能自行变成全部完成或验收合格' in instruction assert '岗位适配' in payload['validation_feedback'] repairs.append(True) return {'findings':[good['findings'][1]]} return deepcopy(bad) result=profile.review_profile(entry,invoke=invoke) assert repairs==[True] assert result['findings'][1]['status']=='insufficient' def test_repeated_joint_errors_are_repaired_one_column_at_a_time(monkeypatch): entry,good=scenario();bad=deepcopy(good);calls=[] for row in bad['findings'][:2]:row['headline']='错误摘要' original=profile.validate def validate(entry,candidate): result=original(entry,candidate) errors=[row['key']+':本行事实需修正。' for row in candidate['findings'] if row['headline']=='错误摘要'] if errors:raise ValueError('\n'.join(errors)) return result monkeypatch.setattr(profile,'validate',validate) def invoke(instruction,payload,schema,**kwargs): if 'issues' in schema['properties']:return {'issues':[]} if 'repair_keys' not in payload:return deepcopy(bad) keys=payload['repair_keys'];calls.append(tuple(keys)) source=bad if len(keys)>1 else good return {'findings':[deepcopy(row) for row in source['findings'] if row['key'] in keys]} assert profile.review_profile(entry,invoke=invoke)['findings'][0]['headline']!='错误摘要' assert calls==[('recent','fit'),('recent',),('fit',)] def test_focused_repair_keeps_only_the_corresponding_task_state(): entry,_=scenario();entry.evidence[1].task_id='T' for id,task_id in [('matched','T'),('unrelated','U')]: entry.evidence.append(profile.Evidence(id=id,kind='task',subject='报告提交',actor_id='',at='', relation='requirement',content='提交报告。',task_id=task_id,state='complete')) _,excerpts=profile.material(entry) selected={'findings':[{'basis':[{'evidence_id':'work','quote':entry.evidence[1].content}]}]} result=profile.include_task_context(selected,entry,excerpts) ids={ref['evidence_id'] for row in result['findings'] for ref in row['basis']} assert ids=={'work','matched'} def test_invalid_partial_patch_defers_without_erasing_good_rows_or_consuming_column_budget(): entry,good=scenario();broken=deepcopy(good);broken['findings'][0]['basis']=[{'excerpt_id':'missing'}] saved=[];repairs=0;generations=0 def invoke(instruction,payload,schema,**kwargs): nonlocal repairs,generations if 'issues' in schema['properties']:return {'issues':[]} if 'repair_keys' in payload: repairs+=1 return {'findings':[]} if repairs==1 else {'findings':[good['findings'][0]]} generations+=1;return deepcopy(broken) with pytest.raises(JobDeferred):profile.review_profile(entry,invoke=invoke,save_checkpoint=saved.append) assert saved[-1]['candidate']==broken assert saved[-1]['repair_attempts']=={} result=profile.review_profile(entry,invoke=invoke,checkpoint=saved[-1],save_checkpoint=saved.append) assert generations==1 and repairs==2 assert result['findings'][0]['basis'][0]['evidence_id']=='work' assert saved[-1]['candidate']['findings'][1:]==good['findings'][1:] @pytest.mark.parametrize('field,value',[('basis',None),('basis',[{'excerpt_id':['bad']}]),('headline',None),('finding',None),('status',[])]) def test_malformed_row_is_repaired_locally(field,value): entry,good=scenario();bad=deepcopy(good);bad['findings'][0][field]=value;calls=[] base=normal_model(good,calls) def invoke(instruction,payload,schema,**kwargs): if 'repair_keys' not in payload and 'issues' not in schema['properties']:calls.append('generate');return deepcopy(bad) return base(instruction,payload,schema,**kwargs) assert profile.review_profile(entry,invoke=invoke)['findings'][0]['headline']==good['findings'][0]['headline'] assert calls.count('generate')==1 and ('recent',) in calls def test_reordered_columns_and_a_bad_field_are_repaired_without_regenerating(): entry,good=scenario();bad=deepcopy(good);bad['findings'][0]['headline']=None bad['findings'].reverse();calls=[];base=normal_model(good,calls) def invoke(instruction,payload,schema,**kwargs): if 'repair_keys' not in payload and 'issues' not in schema['properties']:calls.append('generate');return deepcopy(bad) return base(instruction,payload,schema,**kwargs) result=profile.review_profile(entry,invoke=invoke) assert [row['key'] for row in result['findings']]==list(profile.KEYS) assert calls.count('generate')==1 and ('recent',) in calls def test_role_assessment_schema_requires_both_duty_and_actual_work(): schema=profile.generation_schema(profile.Decision.model_json_schema(),2,2,True) schema=profile.future_role_contract(schema,['duty-ref'],['work-ref']) fit=[row for row in schema['$defs']['Finding']['anyOf'] if row['properties']['key']['enum']==['fit'] and row['properties']['status']['enum']!=['insufficient']] assert fit for row in fit: basis=row['properties']['basis'] assert basis['minItems']==2 assert basis['prefixItems'][0]['properties']['excerpt_id']['enum']==['work-ref'] assert basis['prefixItems'][1]['properties']['excerpt_id']['enum']==['duty-ref'] @pytest.mark.parametrize('key',['development','assignment']) def test_specialized_repairs_keep_the_actual_validation_error(monkeypatch,key): entry,raw=scenario();original_validate=profile.validate problem=key+':原文没有说明独立完成,必须删除这项无依据推断。' def reject(entry,candidate): original_validate(entry,candidate);raise ValueError(problem) monkeypatch.setattr(profile,'validate',reject) class Reached(Exception):pass def invoke(instruction,payload,schema,**kwargs): if 'issues' in schema['properties']:return {'issues':[]} if 'repair_keys' in payload: assert problem in payload['validation_feedback'] raise Reached() return deepcopy(raw) with pytest.raises(Reached):profile.review_profile(entry,invoke=invoke) def test_capabilities_expose_the_personnel_policy_used_for_jobs(): from app.modules.work_assistant.routes import review_capabilities,PERSONNEL_RULE assert review_capabilities()['personnel_rule']==profile.REVIEW_POLICY assert PERSONNEL_RULE==profile.REVIEW_CACHE_RULE assert profile.REVIEW_POLICY.startswith(PERSONNEL_RULE+':context-') @pytest.mark.parametrize('confirmed',[False,True]) def test_repeated_semantic_objection_gets_an_evidence_checked_second_review(confirmed): entry,raw=scenario();raw['findings'][0]['action']='跟进报告归档' _,excerpts=profile.material(entry);candidate=profile.resolve(raw,excerpts) row=candidate['findings'][0];fingerprint=row_fingerprint('findings',row) cache={fingerprint:['把后续归档建议当成已完成事实']};adjudicated={};calls=[] def invoke(instruction,payload,schema,**kwargs): calls.append(payload) return kwargs['transform']({'issues':[dict(index=0,confirmed=confirmed,claim='跟进报告归档', source_quote=excerpts['e2']['quote'],reason='已核对动作范围与原文。')]}) reassess_findings(candidate,cache,adjudicated,{'recent':2},invoke,120,lambda rows:{'selected_rows':len(rows)}) assert bool(cache[fingerprint]) is confirmed reassess_findings(candidate,cache,adjudicated,{'recent':3},invoke,120,lambda rows:{'selected_rows':len(rows)}) assert len(calls)==1 and candidate['findings'][0]==row assert calls[0]['material']['selected_rows']==1 def test_fabricated_adjudication_quote_cannot_clear_an_objection(): entry,raw=scenario();_,excerpts=profile.material(entry);candidate=profile.resolve(raw,excerpts) fingerprint=row_fingerprint('findings',candidate['findings'][0]);cache={fingerprint:['事实不符']};adjudicated={} def invoke(instruction,payload,schema,**kwargs): return kwargs['transform']({'issues':[dict(index=0,confirmed=False,claim='本人反馈已提交报告', source_quote='原文不存在的证据',reason='假证据')]}) reassess_findings(candidate,cache,adjudicated,{'recent':2},invoke,120,lambda rows:{}) assert cache[fingerprint]==['事实不符'] assert adjudicated[fingerprint]['unusable_review'] is True def test_invalid_second_review_falls_back_to_repair_instead_of_aborting_the_profile(): entry,good=scenario();bad=deepcopy(good) bad['findings'][3]['finding']='本人已独立完成报告修订,建议继续负责报告修订。' saved=[];repairs=0 def invoke(instruction,payload,schema,**kwargs): nonlocal repairs if payload.get('adjudication'): return {'issues':[dict(index=0,confirmed=False,claim='独立完成',source_quote='不存在的原文',reason='无法采信的复核')]} if 'issues' in schema['properties']: rows=payload['candidate']['findings'] return {'issues':[dict(section='findings',index=i,reason='本人反馈未证明独立完成。') for i,row in enumerate(rows) if '独立完成' in row.get('finding','')]} if 'repair_keys' in payload: repairs+=1 return {'findings':[deepcopy((bad if repairs<3 else good)['findings'][3])]} return deepcopy(bad) for _ in range(6): try:result=profile.review_profile(entry,invoke=invoke,checkpoint=saved[-1] if saved else None,save_checkpoint=saved.append) except JobDeferred:continue break else:pytest.fail('invalid second opinion prevented ordinary repair') assert repairs==3 and '独立完成' not in result['findings'][3]['finding'] assert any(row.get('unusable_review') for row in saved[-1]['adjudicated'].values()) @pytest.mark.parametrize('confirmed',[False,True]) def test_full_pipeline_reassesses_once_and_still_blocks_confirmed_errors(confirmed): entry,raw=scenario();calls=[];saved=[] def invoke(instruction,payload,schema,**kwargs): if payload.get('adjudication'): calls.append('adjudicate') return {'issues':[dict(index=0,confirmed=confirmed,claim='评审后的补充情况待核对', source_quote=entry.evidence[1].content,reason='核对后保留原核验结论。' if confirmed else '候选已明确限定后续状态。')]} if 'issues' in schema['properties']: calls.append('verify') return {'issues':[dict(section='findings',index=0,reason='未说明后续补充的实际状态。')]} if 'repair_keys' in payload: calls.append('repair');return {'findings':[deepcopy(raw['findings'][0])]} calls.append('generate');return deepcopy(raw) if confirmed: with pytest.raises(ValueError,match='核对后保留'): profile.review_profile(entry,invoke=invoke,save_checkpoint=saved.append) assert calls.count('repair')==profile.MAX_CORRECTIONS else: result=profile.review_profile(entry,invoke=invoke,save_checkpoint=saved.append) assert result['findings'][0]['finding']==raw['findings'][0]['finding'] assert calls.count('repair')==2 assert calls.count('generate')==calls.count('adjudicate')==1 assert len(saved[-1]['adjudicated'])==1 def test_optional_bad_detail_does_not_use_up_the_main_conclusion_budget(monkeypatch): entry,raw=scenario();raw['development']=[dict(topic='报告修订',record='已提交报告',assessment='建议复核报告',action='',basis=[{'excerpt_id':'e2'}])] calls=[];saved=[];real_validate=profile.validate;rounds=[0] def validate(entry,candidate): result=real_validate(entry,candidate);rounds[0]+=1 if candidate['development']:raise ValueError('development[0]:该事例内容尚不准确。') if rounds[0]<=5:raise ValueError('recent:重新核对交付结果。') return result monkeypatch.setattr(profile,'validate',validate) base=normal_model(raw,calls) def invoke(instruction,payload,schema,**kwargs): if payload.get('repair_sections')==['development']: calls.append('detail');return {'development':deepcopy(raw['development'])} return base(instruction,payload,schema,**kwargs) result=profile.review_profile(entry,invoke=invoke,save_checkpoint=saved.append) assert result['development']==[] and len(result['findings'])==5 assert calls.count('detail')==2 assert saved[-1]['repair_attempts']['recent']==2 def test_permanent_factual_error_stops_at_its_own_limit(monkeypatch): entry,raw=scenario();calls=[];saved=[];original_validate=profile.validate def reject(entry,candidate): original_validate(entry,candidate) raise ValueError('recent:不能把原文的待提交写成已提交。') monkeypatch.setattr(profile,'validate',reject) with pytest.raises(ValueError,match='不能把原文'): profile.review_profile(entry,invoke=normal_model(raw,calls),save_checkpoint=saved.append) assert calls.count(('recent',))==profile.MAX_CORRECTIONS assert saved[-1]['repair_attempts']=={'recent':profile.MAX_CORRECTIONS} assert calls.count('generate')==1 def test_invalid_patch_cannot_mutate_candidate(): _,raw=scenario();before=deepcopy(raw) with pytest.raises(ModelOutputInvalid):apply_repair(raw,{'findings':[raw['findings'][1]]},['recent'],{}) assert raw==before def test_large_output_automatically_splits_and_resumes_only_missing_parts(): entry,good=scenario();saved=[];calls=[];interrupted=False def invoke(instruction,payload,schema,**kwargs): nonlocal interrupted if 'issues' in schema['properties']:return {'issues':[]} part=payload.get('generation_part') calls.append(part or 'full') if not part:raise ModelUnavailable('direct_output_truncated') if part=='attitude' and not interrupted: interrupted=True;raise ModelUnavailable('direct_timeout',retryable=True) if part=='details':return {section:[] for section in profile.DETAIL_SECTIONS} assert schema['properties']['findings']['maxItems']==1 return {'findings':[deepcopy(next(row for row in good['findings'] if row['key']==part))]} with pytest.raises(JobDeferred):profile.review_profile(entry,invoke=invoke,save_checkpoint=saved.append) assert saved[-1]['split_generation'] with pytest.raises(ModelUnavailable,match='direct_timeout'): profile.review_profile(entry,invoke=invoke,checkpoint=saved[-1],save_checkpoint=saved.append) assert set(saved[-1]['generation_parts'])=={'recent','fit'} result=profile.review_profile(entry,invoke=invoke,checkpoint=saved[-1],save_checkpoint=saved.append) assert len(result['findings'])==5 assert calls==['full','recent','fit','attitude','attitude','development','assignment','details'] def test_41_person_batch_recovers_in_the_same_jobs_without_version_bumps(tmp_path,monkeypatch): from app.modules.work_assistant import review_jobs as jobs_module clock=[2000000000.0];monkeypatch.setattr(jobs_module.time,'time',lambda:clock[0]) jobs=ReviewJobs(tmp_path/'reviews.sqlite3');completed=0;total_calls=0 for number in range(41): entry,good=scenario(str(8000+number));fault=number%4;calls=[];first=True base=normal_model(good,calls) def invoke(instruction,payload,schema,**kwargs): nonlocal first,total_calls total_calls+=1 if first: first=False if fault==0:raise json.JSONDecodeError('broken output','{',1) if fault==1: bad=deepcopy(good);bad['findings'][0]['basis']=[{'excerpt_id':'invalid'}];return bad if fault==2:raise ModelUnavailable('direct_timeout',retryable=True) return base(instruction,payload,schema,**kwargs) def action(checkpoint,save):return profile.review_profile(entry,invoke=invoke,checkpoint=checkpoint,save_checkpoint=save) for _ in range(6): try:result=jobs.run(entry.model_dump(),'unchanged-policy',action,lease_seconds=180,rapid_recovery=True) except ModelUnavailable: clock[0]+=1000;continue assert len(result['findings'])==5 completed+=1;break else:pytest.fail('normal durable recovery did not complete') before=total_calls assert jobs.run(entry.model_dump(),'unchanged-policy',action)==result assert total_calls==before assert completed==41 with jobs.connect() as db: assert db.execute("SELECT COUNT(*) FROM review_job WHERE status='ready'").fetchone()[0]==41 assert db.execute('SELECT COUNT(*) FROM review_job').fetchone()[0]==41