update
This commit is contained in:
@@ -0,0 +1,372 @@
|
||||
"""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']==PERSONNEL_RULE==profile.REVIEW_CACHE_RULE
|
||||
|
||||
|
||||
@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
|
||||
@@ -0,0 +1,163 @@
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.work_assistant.personnel_profile import (
|
||||
DETAIL_SECTIONS, normalize_scope, resolve,
|
||||
)
|
||||
|
||||
|
||||
def candidate():
|
||||
value={section:[] for section in DETAIL_SECTIONS}
|
||||
value['findings']=[dict(key='fit',status='attention',headline='尚未达到职责要求',finding='任务未完成。',action='',basis=[{'excerpt_id':'e1'}])]
|
||||
value['duties']=[dict(topic='归档',record='已提交',assessment='待复核',action='',basis=[{'excerpt_id':'e1'}])]
|
||||
return value
|
||||
|
||||
|
||||
def test_missing_duties_does_not_discard_work_or_invent_a_role_assessment():
|
||||
original=candidate()
|
||||
original['directions']=[{'topic':'完成报告修订','record':'本人反馈已修订','activity_id':'e2','basis':[{'excerpt_id':'e2'}]}]
|
||||
before=deepcopy(original)
|
||||
normalized=normalize_scope(original,False)
|
||||
assert normalized['duties']==original['duties']
|
||||
assert normalized['findings']==original['findings']
|
||||
assert normalized['directions']==original['directions']
|
||||
assert original==before
|
||||
assert normalize_scope(original,True)==original
|
||||
|
||||
|
||||
def test_numeric_business_task_id_is_resolved_to_the_same_original_task():
|
||||
value=candidate()
|
||||
value['progress']=[dict(task_id='13934',basis=[{'excerpt_id':'e2'}])]
|
||||
excerpts={'e1':{'evidence_id':'task-13934','quote':'原任务要求'},'e2':{'evidence_id':'feedback-7','quote':'已提交初稿'}}
|
||||
result=resolve(value,excerpts)
|
||||
assert result['progress'][0]['task_id']=='task-13934'
|
||||
assert {ref['evidence_id'] for ref in result['progress'][0]['basis']}=={'task-13934','feedback-7'}
|
||||
value['progress'][0]['task_id']='99999'
|
||||
with pytest.raises(ValueError,match=r'progress\[0\].*关联事项片段不存在'):
|
||||
resolve(value,excerpts)
|
||||
|
||||
|
||||
def test_copied_link_field_and_whitespace_typo_do_not_change_claims_or_citations():
|
||||
value=candidate()
|
||||
value['development']=[dict(topic='报告复核',record='已修订',assessment='建议复核同类报告',action='',activity_id='e2',**{'basi s':[{'excerpt_id':'e2'}]})]
|
||||
result=normalize_scope(value,True)
|
||||
assert result['development'][0]==dict(topic='报告复核',record='已修订',assessment='建议复核同类报告',action='',basis=[{'excerpt_id':'e2'}])
|
||||
|
||||
|
||||
def test_large_profile_reserves_context_for_output_without_removing_material(monkeypatch):
|
||||
from app.modules.work_assistant import model_gateway,model_capacity
|
||||
from app.modules.work_assistant.model_dispatch import reserved_turn
|
||||
monkeypatch.setattr(model_gateway,'get_settings',lambda:SimpleNamespace(direct_llm_api_key='test',work_assistant_model_control_url=''))
|
||||
monkeypatch.setattr(model_gateway,'_model_client',lambda:None)
|
||||
monkeypatch.setattr(model_capacity,'request_tokens',lambda messages,output,client:27919+128)
|
||||
seen={}
|
||||
def complete(instruction,content,schema,**kwargs):
|
||||
seen.update(kwargs);seen['content']=content
|
||||
return {'ok':True}
|
||||
monkeypatch.setattr(model_gateway,'_complete_json',complete)
|
||||
token=reserved_turn.set({})
|
||||
payload={'evidence':['完整原文']}
|
||||
try:
|
||||
assert model_gateway.complete_json('核对',payload,{},max_tokens=5500,fit_context=True)=={'ok':True}
|
||||
assert seen['max_tokens']==4593
|
||||
assert seen['content'] is payload
|
||||
model_gateway.complete_json('核对',payload,{},max_tokens=5500)
|
||||
assert seen['max_tokens']==5500
|
||||
finally:reserved_turn.reset(token)
|
||||
|
||||
|
||||
def test_invalid_link_reaches_targeted_repair_instead_of_crashing_again():
|
||||
from app.modules.work_assistant.personnel_profile import ProfileRequest,review_profile,KEYS,material
|
||||
entry=ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[
|
||||
dict(id='task-7',kind='task',subject='报告修订',actor_id='',at='',relation='requirement',content='修订报告。'),
|
||||
dict(id='feedback-8',kind='feedback',subject='报告修订',actor_id='1',at='',relation='self',content='已修订报告。')])
|
||||
value={section:[] for section in DETAIL_SECTIONS}
|
||||
value['findings']=[dict(key=key,status='review_required' if key=='assignment' else 'insufficient',headline='建议承担报告修订',finding='本期报告已修订。',action='',basis=[{'excerpt_id':'e2'}]) for key in KEYS]
|
||||
value['directions']=[dict(topic='报告修订',record='已修订报告',assessment='修订已反馈',action='',basis=[{'excerpt_id':'e2'}],activity_id='e99999')]
|
||||
class RepairReached(Exception):pass
|
||||
def invoke(instruction,payload,schema,**kwargs):
|
||||
if 'repair_sections' in payload:
|
||||
assert payload['repair_sections']==['directions']
|
||||
assert payload['repair_slots']=={'directions':[0]}
|
||||
raise RepairReached()
|
||||
return deepcopy(value)
|
||||
with pytest.raises(RepairReached):review_profile(entry,invoke=invoke)
|
||||
|
||||
|
||||
def test_headline_keeps_the_recorded_action_without_adding_initiative():
|
||||
value=candidate()
|
||||
value['findings']=[dict(key='attitude',headline='主动推进客户拜访',finding='本人反馈协调了客户拜访。',basis=[{'excerpt_id':'e1'}])]
|
||||
excerpts={'e1':{'evidence_id':'feedback-1','quote':'协调了客户拜访。'}}
|
||||
result=resolve(value,excerpts)
|
||||
assert result['findings'][0]['headline']=='推进客户拜访'
|
||||
assert result['findings'][0]['finding']==value['findings'][0]['finding']
|
||||
excerpts['e1']['quote']='主动协调了客户拜访。'
|
||||
assert resolve(value,excerpts)['findings'][0]['headline']=='主动推进客户拜访'
|
||||
value['findings'][0]['headline']='主动性强'
|
||||
excerpts['e1']['quote']='协调了客户拜访。'
|
||||
assert resolve(value,excerpts)['findings'][0]['headline']=='主动性强'
|
||||
|
||||
|
||||
def test_recent_repair_preserves_the_actual_stage_and_specific_error(monkeypatch):
|
||||
from app.modules.work_assistant import personnel_profile as profile
|
||||
entry=profile.ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[
|
||||
dict(id='feedback-8',kind='feedback',subject='报告修订',actor_id='1',at='',relation='self',content='已梳理问题并开始部分修改,待资料确认,预计明日完成初稿。')])
|
||||
value={section:[] for section in DETAIL_SECTIONS}
|
||||
value['findings']=[dict(key=key,status='review_required' if key=='assignment' else 'insufficient',headline='报告修订',finding='已完成整改。',action='',basis=[{'excerpt_id':'e1'}]) for key in profile.KEYS]
|
||||
problem='recent:原文仅开始部分修改,不能写已完成整改。'
|
||||
def reject(entry, resolved):raise ValueError(problem)
|
||||
monkeypatch.setattr(profile,'validate',reject)
|
||||
monkeypatch.setattr(profile,'grounding_errors',lambda *args:[])
|
||||
class RepairReached(Exception):pass
|
||||
def invoke(instruction,payload,schema,**kwargs):
|
||||
if 'repair_keys' in payload:
|
||||
assert payload['repair_keys']==['recent']
|
||||
assert payload['validation_feedback']==problem
|
||||
assert '待资料确认' in str(payload)
|
||||
assert '已完成整改' not in str(payload['previous_rows'])
|
||||
raise RepairReached()
|
||||
return deepcopy(value)
|
||||
with pytest.raises(RepairReached):profile.review_profile(entry,invoke=invoke)
|
||||
|
||||
|
||||
def test_fact_check_distinguishes_next_steps_and_keeps_past_claims_visible():
|
||||
from app.modules.work_assistant import personnel_profile as profile
|
||||
entry=profile.ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[
|
||||
dict(id='feedback-8',kind='feedback',subject='报告签字',actor_id='1',at='',relation='self',content='报告复审已完成,后续提交领导签字。')])
|
||||
data,excerpts=profile.material(entry)
|
||||
candidate={section:[] for section in DETAIL_SECTIONS}
|
||||
candidate['findings']=[dict(key='recent',status='supported',headline='报告复审',finding='本人反馈已完成复审,待提交签字。',action='跟进验收材料签字流程',basis=[excerpts['e1']])]
|
||||
calls=[]
|
||||
def invoke(instruction,payload,schema,**kwargs):
|
||||
calls.append(deepcopy(payload['candidate']['findings'][0]))
|
||||
return {'issues':[]}
|
||||
profile.grounding_errors(profile.pack_material(data),candidate,invoke,120,excerpts)
|
||||
assert calls[0]['action']==candidate['findings'][0]['action']
|
||||
assert '下一步' in calls[0]['action_type']
|
||||
candidate['findings'][0]['action']='已完成领导签字'
|
||||
profile.grounding_errors(profile.pack_material(data),candidate,invoke,120,excerpts)
|
||||
assert calls[1]['action']=='已完成领导签字'
|
||||
assert 'action_type' not in candidate['findings'][0]
|
||||
|
||||
|
||||
def test_malformed_model_json_retries_are_bounded_and_checkpointed():
|
||||
import json
|
||||
from app.modules.work_assistant import personnel_profile as profile
|
||||
entry=profile.ProfileRequest(person_id='1',name='测试',department_id='1',department='测试部',posts='工程师',begin='2026-11-01',end='2026-11-18',coverage=[],limits=[],evidence=[profile.Evidence(id='task',kind='task',subject='报告提交',actor_id='',at='2026-11-01',relation='requirement',content='提交测试报告。')])
|
||||
saved=[]
|
||||
def malformed(*args,**kwargs):raise json.JSONDecodeError('missing object','{',1)
|
||||
for expected in (1,2):
|
||||
with pytest.raises(profile.JobDeferred):
|
||||
profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1] if saved else None,save_checkpoint=saved.append)
|
||||
assert saved[-1]['format_failures']==expected
|
||||
assert saved[-1]['candidate'] is None
|
||||
with pytest.raises(profile.JobDeferred):
|
||||
profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1],save_checkpoint=saved.append)
|
||||
assert saved[-1]['split_generation']
|
||||
for _ in range(2):
|
||||
with pytest.raises(profile.JobDeferred):
|
||||
profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1],save_checkpoint=saved.append)
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
profile.review_profile(entry,invoke=malformed,checkpoint=saved[-1],save_checkpoint=saved.append)
|
||||
@@ -0,0 +1,354 @@
|
||||
import pytest
|
||||
|
||||
from app.modules.work_assistant.personnel_profile import (
|
||||
Decision, ProfileRequest, KEYS, DETAIL_SECTIONS, generation_schema, validate,
|
||||
)
|
||||
|
||||
|
||||
def fixture():
|
||||
evidence = [
|
||||
dict(id='duty', kind='duty', subject='测试交付', actor_id='', at='', relation='requirement', content='测试报告须完成评审并归档。'),
|
||||
dict(id='work', kind='feedback', subject='报告评审', actor_id='103', at='2026-11-16', relation='self', content='已提交测试报告,评审意见要求补充边界用例。'),
|
||||
]
|
||||
entry = ProfileRequest(person_id='103', name='测试人员', department_id='1', department='测试部', posts='测试经理',
|
||||
begin='2026-11-01', end='2026-11-18', evidence=evidence, coverage=[], limits=[])
|
||||
result = {section: [] for section in DETAIL_SECTIONS}
|
||||
result['findings'] = [dict(key=key, status='review_required' if key=='assignment' else 'insufficient',
|
||||
headline='测试交付待核对', finding='已提交报告,评审后的补充情况待核对。', action='',
|
||||
basis=[dict(evidence_id='work', quote=evidence[1]['content'])]) for key in KEYS]
|
||||
result['findings'][3]['headline']='适合侧重测试报告修订'
|
||||
result['findings'][4]['headline']='建议承担报告修订'
|
||||
result['findings'][4]['basis'].append(dict(evidence_id='duty',quote=evidence[0]['content']))
|
||||
return entry, result
|
||||
|
||||
|
||||
def test_role_judgment_requires_the_actual_role_requirement():
|
||||
entry, result = fixture()
|
||||
fit = result['findings'][1]
|
||||
fit['status'] = 'attention'
|
||||
with pytest.raises(ValueError, match='岗位适配'):
|
||||
validate(entry,result)
|
||||
fit['basis'].append(dict(evidence_id='duty',quote=entry.evidence[0].content))
|
||||
assert validate(entry,result)['heading_review_version']==3
|
||||
|
||||
|
||||
def test_person_portrait_retains_specific_work_and_requires_actual_evidence():
|
||||
entry, result = fixture()
|
||||
row = dict(topic='报告交付与修订推进', record=entry.evidence[1].content,
|
||||
assessment='已有报告提交记录,评审后的边界用例补充结果仍需核对。', action='',
|
||||
basis=[dict(evidence_id='work', quote=entry.evidence[1].content)])
|
||||
result['portrait'] = [row]
|
||||
validated = validate(entry, result)
|
||||
assert validated['detail_review_version'] == 1
|
||||
assert validated['portrait'][0]['assessment'] == row['assessment']
|
||||
entry.evidence = [e for e in entry.evidence if e.kind != 'duty']
|
||||
result['findings'][4]['basis'] = [row['basis'][0]]
|
||||
assert validate(entry, result)['portrait']
|
||||
row['basis'][0]['quote'] = '不存在的工作成果'
|
||||
with pytest.raises(ValueError):
|
||||
validate(entry, result)
|
||||
|
||||
|
||||
def test_portrait_is_backward_compatible_but_duties_alone_cannot_describe_person():
|
||||
entry, result = fixture()
|
||||
result.pop('portrait')
|
||||
assert validate(entry, result)['portrait'] == []
|
||||
result['portrait'] = [dict(topic='报告提交', record='岗位要求提交报告', assessment='需要核对实际提交情况',
|
||||
action='', basis=[dict(evidence_id='duty', quote=entry.evidence[0].content)])]
|
||||
with pytest.raises(ValueError):
|
||||
validate(entry, result)
|
||||
|
||||
|
||||
def test_portrait_has_detail_specific_space_without_expanding_roster_summaries():
|
||||
schema = generation_schema(Decision.model_json_schema(), 3, 3, True)
|
||||
assert schema['properties']['portrait']['maxItems'] == 3
|
||||
assert schema['$defs']['PortraitRow']['properties']['record']['maxLength'] == 240
|
||||
assert schema['$defs']['PortraitRow']['properties']['assessment']['maxLength'] == 240
|
||||
assert schema['$defs']['DetailRow']['properties']['record']['maxLength'] == 160
|
||||
|
||||
|
||||
@pytest.mark.parametrize('claim',['高频完成商务工作','完成了20余项商务任务','展现了良好的多任务处理能力'])
|
||||
def test_portrait_does_not_turn_activity_counts_into_ability_ratings(claim):
|
||||
entry,result=fixture()
|
||||
result['portrait']=[dict(topic='工作表现',record=claim,assessment='报告已提交,后续修订结果待核对。',action='',
|
||||
basis=[dict(evidence_id='work',quote=entry.evidence[1].content)])]
|
||||
with pytest.raises(ValueError,match='任务数量'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_assignment_cannot_be_replaced_by_a_description_of_current_problems():
|
||||
entry,result=fixture()
|
||||
result['findings'][4]['headline']='项目有推进但材料缺失'
|
||||
result['findings'][4]['finding']='已提交报告,后续材料尚未取得。'
|
||||
with pytest.raises(ValueError,match='具体分工建议'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_future_deliverable_is_not_mistaken_for_an_already_completed_result():
|
||||
from app.modules.work_assistant.personnel_profile import review_requires_repair
|
||||
row={'key':'assignment','status':'review_required','headline':'建议负责人员辅导',
|
||||
'finding':'负责未达标人员谈话,输出后续改进计划,由主管复核。',
|
||||
'basis':[{'source_role':'本人','quote':'未达标人员谈话记录已提交。'}]}
|
||||
assert not review_requires_repair(row,'原文未提及已制定改进计划,未来分工缺少依据。')
|
||||
assert review_requires_repair(row,'所建议分工与岗位职责不符,属于转岗。')
|
||||
row['finding']='已制定改进计划,建议负责人员辅导。'
|
||||
assert review_requires_repair(row,'原文未提及已制定改进计划。')
|
||||
|
||||
|
||||
def test_duty_details_require_a_traceable_requirement():
|
||||
entry, result = fixture()
|
||||
row = dict(topic='报告归档',record='提交报告',assessment='归档情况待核对',action='',
|
||||
basis=[dict(evidence_id='work',quote=entry.evidence[1].content)])
|
||||
result['duties']=[row]
|
||||
with pytest.raises(ValueError,match='岗位职责原文'):
|
||||
validate(entry,result)
|
||||
row['basis'].append(dict(evidence_id='duty',quote=entry.evidence[0].content))
|
||||
assert len(validate(entry,result)['duties'])==1
|
||||
|
||||
|
||||
def test_missing_work_is_allowed_as_an_explicit_unverified_duty():
|
||||
entry,result=fixture()
|
||||
result['duties']=[dict(topic='报告归档',record='未取得归档记录',assessment='归档结果待核对',action='',
|
||||
basis=[dict(evidence_id='duty',quote=entry.evidence[0].content)])]
|
||||
assert len(validate(entry,result)['duties'])==1
|
||||
|
||||
|
||||
def test_role_details_are_not_truncated_to_two_items():
|
||||
schema=Decision.model_json_schema()
|
||||
schema['properties']['duties']['maxItems']=9
|
||||
generated=generation_schema(schema,2,2,True)
|
||||
assert generated['properties']['duties']['maxItems']==9
|
||||
assert generated['properties']['development']['maxItems']==2
|
||||
|
||||
|
||||
def test_optional_sections_do_not_force_irrelevant_details():
|
||||
entry,result=fixture()
|
||||
entry.evidence.append(entry.evidence[1].model_copy(update={'id':'task','kind':'task','relation':'requirement','state':'unfinished'}))
|
||||
assert validate(entry,result)['progress']==[]
|
||||
|
||||
|
||||
def test_forged_duty_quote_is_rejected():
|
||||
entry,result=fixture()
|
||||
result['findings'][1]['basis']=[dict(evidence_id='duty',quote='所有职责均已完成')]
|
||||
with pytest.raises(ValueError,match='原始资料'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_task_quality_without_duties_survives_validation_and_normalization():
|
||||
from app.modules.work_assistant.personnel_profile import normalize_scope
|
||||
entry,result=fixture()
|
||||
entry.evidence=[e for e in entry.evidence if e.kind!='duty']
|
||||
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
|
||||
fit=result['findings'][1]
|
||||
fit.update(status='attention',headline='报告已提交,边界用例仍需补充',
|
||||
finding='本人反馈已提交测试报告,评审要求补充边界用例;交付动作已记录,当前报告仍有明确修改项。')
|
||||
result['duties']=[dict(topic='测试报告交付与评审',record='本人反馈已提交测试报告。',
|
||||
assessment='评审要求补充边界用例,当前交付尚有修改项。',action='补充用例后交审核人复核。',basis=fit['basis'])]
|
||||
validated=validate(entry,normalize_scope(result,False))
|
||||
assert validated['assessment_scope']=='tasks'
|
||||
assert validated['findings'][1]==fit
|
||||
assert validated['duties']==result['duties']
|
||||
|
||||
|
||||
def test_task_registration_alone_cannot_prove_quality():
|
||||
entry,result=fixture()
|
||||
entry.evidence=[entry.evidence[1].model_copy(update={'kind':'task','relation':'requirement','state':'complete'})]
|
||||
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
|
||||
result['findings'][1].update(status='supported',headline='交付合格',finding='任务已登记完成。')
|
||||
with pytest.raises(ValueError,match='缺少实际工作'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_one_actual_inspection_can_support_a_task_result_without_role_document():
|
||||
entry,result=fixture()
|
||||
entry.evidence=[entry.evidence[1].model_copy(update={'kind':'review','relation':'reviewer','content':'测试报告边界用例齐全,本次检查合格。'})]
|
||||
for row in result['findings']:
|
||||
row['basis']=[dict(evidence_id='work',quote=entry.evidence[0].content)]
|
||||
row['finding']='本次检查确认测试报告边界用例齐全。'
|
||||
result['findings'][1].update(status='supported',headline='测试报告本次检查合格')
|
||||
validated=validate(entry,result)
|
||||
assert validated['findings'][1]['status']=='supported'
|
||||
assert validated['assessment_scope']=='tasks'
|
||||
|
||||
|
||||
def test_expanded_generation_contract_keeps_explanations_and_citations():
|
||||
from app.modules.work_assistant.personnel_profile import prompt_contract
|
||||
schema=generation_schema(Decision.model_json_schema(),4,4,True)
|
||||
assert schema['properties']['directions']['maxItems']==4
|
||||
for variant in schema['$defs']['Finding']['anyOf']:
|
||||
assert variant['properties']['finding']['maxLength']==220
|
||||
assert variant['properties']['basis']['maxItems']==6
|
||||
prompt=prompt_contract(schema)
|
||||
for name in ('DetailRow','DirectionRow','ProgressRow','ResponseRow'):
|
||||
assert prompt['$defs'][name]['properties']['assessment']['maxLength']==160
|
||||
assert prompt['$defs'][name]['properties']['record']['maxLength']==160
|
||||
|
||||
|
||||
def test_hidden_attendance_section_does_not_require_an_impossible_row():
|
||||
from app.modules.work_assistant.personnel_profile import attendance_schema
|
||||
schema=Decision.model_json_schema()
|
||||
schema['properties']['followups']['maxItems']=0
|
||||
result=attendance_schema(schema,[0],['attendance'],[])
|
||||
assert result['properties']['followups'].get('minItems',0)==0
|
||||
|
||||
|
||||
def test_split_finding_generation_with_attendance_does_not_require_followups():
|
||||
from app.modules.work_assistant.personnel_profile import attendance_schema
|
||||
schema=Decision.model_json_schema()
|
||||
schema['properties']={'findings':schema['properties']['findings']}
|
||||
assert attendance_schema(schema,[0],['attendance'],[])==schema
|
||||
|
||||
|
||||
@pytest.mark.parametrize('text',[
|
||||
'完成了大连、沈阳等20余项任务的定稿。',
|
||||
'已完成报名,需核实是否因迟到影响报名。',
|
||||
'未见具体分析内容,履职深度不足。',
|
||||
'任务12735未完成。',
|
||||
])
|
||||
def test_expanded_analysis_does_not_invent_counts_or_unsupported_deficiencies(text):
|
||||
from app.modules.work_assistant.personnel_profile import unsupported_work_claim
|
||||
assert unsupported_work_claim(text,'本人反馈:大连项目标书定稿。')
|
||||
|
||||
|
||||
def test_missing_duties_fit_describes_task_results_not_ability():
|
||||
entry,result=fixture()
|
||||
entry.evidence=[e for e in entry.evidence if e.kind!='duty']
|
||||
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
|
||||
result['findings'][1].update(status='attention',headline='具备测试报告编制能力')
|
||||
with pytest.raises(ValueError,match='任务执行及交付质量'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_unread_attachments_do_not_replace_the_work_assessment():
|
||||
entry,result=fixture()
|
||||
entry.evidence=[e for e in entry.evidence if e.kind!='duty']
|
||||
result['findings'][4]['basis']=result['findings'][4]['basis'][:1]
|
||||
result['findings'][1].update(status='attention',headline='交付质量待核实',finding='附件无法读取,正文未提取,无法核实验收状态。')
|
||||
with pytest.raises(ValueError,match='不能用附件无法读取替代'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_empty_period_returns_honest_content_without_invented_model_citations():
|
||||
from app.modules.work_assistant.personnel_profile import review_profile
|
||||
entry,_=fixture();entry.evidence=[]
|
||||
def never(*args,**kwargs):raise AssertionError('Empty records must not call the model')
|
||||
result=review_profile(entry,invoke=never)
|
||||
assert result['assessment_scope']=='tasks'
|
||||
assert all(not row['basis'] for row in result['findings'])
|
||||
assert result['findings'][1]['status']=='insufficient'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phrase',['任务均登记完成。','任务完成登记。','系统登记状态为完成。'])
|
||||
def test_feedback_alone_cannot_be_presented_as_system_completion(phrase):
|
||||
entry,result=fixture()
|
||||
result['findings'][0]['finding']=phrase
|
||||
with pytest.raises(ValueError,match='登记完成须引用'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('state',['complete','unfinished'])
|
||||
def test_registered_completion_links_actual_task_record_without_inventing_its_state(state):
|
||||
from copy import deepcopy
|
||||
from app.modules.work_assistant.personnel_profile import attach_task_basis,material,Evidence
|
||||
entry,result=fixture();entry.evidence[1].task_id='T'
|
||||
entry.evidence.append(Evidence(id='task',kind='task',subject='报告',actor_id='',at='',relation='requirement',
|
||||
task_id='T',state=state,content='当前状态:'+('登记完成' if state=='complete' else '尚未登记完成')))
|
||||
entry.evidence.append(Evidence(id='unrelated',kind='task',subject='另一份报告',actor_id='',at='',relation='requirement',
|
||||
task_id='U',state='complete',content='当前状态:登记完成'))
|
||||
result['findings'][0]['finding']='报告任务登记完成。'
|
||||
original=deepcopy(result);_,excerpts=material(entry)
|
||||
linked=attach_task_basis(result,entry,excerpts)
|
||||
assert result==original
|
||||
assert {ref['evidence_id'] for ref in linked['findings'][0]['basis']}=={'work','task'}
|
||||
if state=='complete':assert validate(entry,linked)['findings'][0]['finding']=='报告任务登记完成。'
|
||||
else:
|
||||
with pytest.raises(ValueError,match='登记完成须引用'):
|
||||
validate(entry,linked)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('key,summary',[
|
||||
('recent','本周成果合格率100%,综合评估扣0.5%。'),
|
||||
('development','本周完成率100%,适合承担流程统筹。'),
|
||||
('fit','学习任务与周目标职责性质不同,不能混淆。'),
|
||||
])
|
||||
def test_business_summary_does_not_publish_statistics_or_repair_explanations(key,summary):
|
||||
entry,result=fixture()
|
||||
next(row for row in result['findings'] if row['key']==key)['finding']=summary
|
||||
with pytest.raises(ValueError,match=key+':'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_internal_reference_adjacent_to_chinese_is_rejected():
|
||||
entry,result=fixture()
|
||||
result['findings'][4]['finding']='建议负责报告修订,对应职责e17,由主管复核。'
|
||||
with pytest.raises(ValueError,match='内部规则或编号'):
|
||||
validate(entry,result)
|
||||
|
||||
|
||||
def test_parenthetical_internal_citation_is_removed_without_losing_business_content():
|
||||
from app.modules.work_assistant.personnel_profile import normalize_scope
|
||||
entry,result=fixture()
|
||||
result['findings'][4]['finding']='建议负责报告修订(对应职责e17),提交修订稿由主管复核。'
|
||||
normalized=normalize_scope(result,True)
|
||||
assert normalized['findings'][4]['finding']=='建议负责报告修订,提交修订稿由主管复核。'
|
||||
assert normalized['findings'][4]['basis']==result['findings'][4]['basis']
|
||||
validate(entry,normalized)
|
||||
|
||||
|
||||
def test_long_inspection_text_remains_generatable_in_a_concise_response_row():
|
||||
from app.modules.work_assistant.personnel_profile import linked_schema
|
||||
schema=generation_schema(Decision.model_json_schema(),2,2,True)
|
||||
review=dict(review='e1',record='检查发现材料缺失,需补充原始记录。'*8,responses=[],refs=['e1'])
|
||||
output=linked_schema(schema,[],[review])
|
||||
props=output['properties']['responses']['prefixItems'][0]['properties']
|
||||
assert props['record']['enum'][0]==review['record'][:160]
|
||||
assert len(props['record']['enum'][0])<=props['record']['maxLength']
|
||||
|
||||
|
||||
def test_focused_repair_preserves_quoted_text_without_unrelated_passages():
|
||||
from app.modules.work_assistant.personnel_profile import trim_shared_text
|
||||
data={'evidence':[['e1','@t1']], 'shared_text':{'@t1':'已提交谈话记录','@t2':'另一个任务台账未更新'}}
|
||||
assert trim_shared_text(data)['shared_text']=={'@t1':'已提交谈话记录'}
|
||||
|
||||
|
||||
def test_repair_can_find_actual_work_beyond_a_rejected_citation():
|
||||
from app.modules.work_assistant.personnel_profile import material,pack_material,cited_material
|
||||
entry,_=fixture()
|
||||
data,excerpts=material(entry)
|
||||
data=pack_material(data)
|
||||
candidate={section:[] for section in ('findings',)+DETAIL_SECTIONS}
|
||||
candidate['findings']=[{'basis':[{'evidence_id':'duty','quote':entry.evidence[0].content}]}]
|
||||
assert len(cited_material(data,candidate,excerpts)['evidence'])==1
|
||||
assert len(cited_material(data,candidate,excerpts,related=True)['evidence'])==2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('gateway', [False, True])
|
||||
def test_personnel_stop_boundary_preserves_json_validation(monkeypatch, gateway):
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
import httpx
|
||||
from app.modules.work_assistant import model_gateway as model
|
||||
|
||||
settings=SimpleNamespace(work_assistant_model_enabled=True,
|
||||
work_assistant_model_control_url='http://model.invalid' if gateway else '',
|
||||
work_assistant_model_control_api_key='', direct_llm_api_key='test',
|
||||
direct_llm_model='test', direct_llm_base_url='http://model.invalid/v1')
|
||||
monkeypatch.setattr(model,'get_settings',lambda:settings)
|
||||
answer={'content':'{"value": "complete"}'}
|
||||
finish={'reason':'stop'}
|
||||
def post(*args, **kwargs):
|
||||
assert kwargs['json']['stop']==['\n```']
|
||||
return httpx.Response(200,json={'choices':[{'finish_reason':finish['reason'],'message':dict(answer)}]})
|
||||
monkeypatch.setattr(model,'_model_client',lambda:SimpleNamespace(post=post))
|
||||
assert model._complete_json('one object',{},stop=['\n```'])=={'value':'complete'}
|
||||
answer['content']='{"value":'
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
model._complete_json('one object',{},stop=['\n```'])
|
||||
finish['reason']='length'
|
||||
answer['content']='{"value":"complete"}\n```json\n{"value":'
|
||||
assert model._complete_json('one object',{},stop=['\n```'],single_object=True)=={'value':'complete'}
|
||||
with pytest.raises(model.ModelUnavailable,match='output_truncated'):
|
||||
model._complete_json('one object',{},stop=['\n```'])
|
||||
answer['content']='{"value":'
|
||||
with pytest.raises(model.ModelUnavailable,match='output_truncated'):
|
||||
model._complete_json('one object',{},stop=['\n```'],single_object=True)
|
||||
Reference in New Issue
Block a user