update
This commit is contained in:
@@ -67,6 +67,7 @@ def test_registration_cannot_become_acceptance_even_if_auditor_accepts():
|
||||
value=candidate();value['messages'][0]['judgment']='任务已完成验收并完成交付。'
|
||||
result=run(value,content='任务登记完成,实际验收尚待核对。')
|
||||
assert result['messages']==[] and result['summary'] is None
|
||||
assert result['outcome']=='unverified'
|
||||
assert result['empty_reason']
|
||||
|
||||
|
||||
@@ -79,7 +80,13 @@ def test_internal_fields_and_inline_lists_are_repaired_or_withheld(bad):
|
||||
def test_same_person_cannot_be_split_between_progress_and_actions():
|
||||
value=candidate();value['messages'].append(copy.deepcopy(value['messages'][0]))
|
||||
value['messages'][1]['title']='负责人核对会议纪要'
|
||||
assert run(value)['messages']==[]
|
||||
value['messages'][1]['judgment']='会议待办已登记。'
|
||||
value['messages'][1]['basis']=[dict(excerpt_id='e2')]
|
||||
items=run(value,content='张甲已提交会议纪要,待负责人核对。会议待办已登记。')['messages']
|
||||
assert len(items)==1
|
||||
assert '会议待办已登记' in items[0]['judgment']
|
||||
assert '纪要' in items[0]['judgment']
|
||||
assert len(items[0]['basis'])==2
|
||||
|
||||
|
||||
def test_normal_progress_needs_no_invented_action():
|
||||
@@ -106,6 +113,21 @@ def test_submission_is_not_supervisor_approval():
|
||||
assert run(value,content='已提交会议纪要,主管已经接收。')['messages']==[]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('claim',['需求确认未完成','需求调研未按时完成'])
|
||||
def test_missing_completion_registration_cannot_be_rephrased_as_actual_delay(claim):
|
||||
value=candidate();value['messages'][0]['title']=claim
|
||||
result=run(value,content='原计划11月20日确认需求,截至11月22日未登记完成,实际进展待核对。')
|
||||
assert result['outcome']=='unverified'
|
||||
assert result['messages']==[]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('title',['需求确认未登记完成', '需求确认登记未完成', '需求确认登记尚未完成'])
|
||||
def test_registration_qualification_is_kept_in_a_verified_title(title):
|
||||
value=candidate();value['messages'][0]['title']=title
|
||||
result=run(value,content='原计划11月20日确认需求,截至11月22日未登记完成,实际进展待核对。')
|
||||
assert result['messages'][0]['title']==title
|
||||
|
||||
|
||||
def test_missing_completion_field_does_not_create_a_rectification_requirement():
|
||||
value=candidate();value['messages'][0]['suggestion']='请补充任务登记时间。'
|
||||
assert run(value,content='任务登记完成时间为空,实际结果待核对。')['messages']==[]
|
||||
@@ -122,6 +144,60 @@ def test_missing_sources_never_calls_model_or_invents_conclusion():
|
||||
req=request();req.evidence=[]
|
||||
result=generate_preview(req,invoke=lambda *a,**kw:pytest.fail('No source needs no model'))
|
||||
assert result['messages']==[] and result['summary'] is None
|
||||
assert result['outcome']=='empty'
|
||||
|
||||
|
||||
def test_missing_timestamp_between_two_facts_preserves_literal_quotes():
|
||||
raw='初审已经完成,任务登记完成时间为null,复核安排待确认。'
|
||||
def invoke(prompt,material,schema,**kwargs):
|
||||
assert [x['text'] for x in material['excerpts']]==['初审已经完成,','复核安排待确认。']
|
||||
if 'decisions' in schema['properties']:
|
||||
return {'decisions':[dict(index=p['index'],supported=True,reason='引用为原文。') for p in material['points']]}
|
||||
value=candidate()
|
||||
value['summary'].update(text='初审完成,复核安排待确认。',basis=[dict(excerpt_id='e1'),dict(excerpt_id='e2')])
|
||||
value['messages'][0].update(title='初审完成',judgment='初审已完成,复核安排待确认。',suggestion='',basis=value['summary']['basis'])
|
||||
return value
|
||||
result=generate_preview(request(content=raw),invoke=invoke)
|
||||
assert result['outcome']=='ready'
|
||||
assert all(b['quote'] in raw for b in result['messages'][0]['basis'])
|
||||
|
||||
|
||||
def test_only_missing_timestamp_needs_no_model():
|
||||
result=generate_preview(request(content='任务登记完成时间为null。'),invoke=lambda *a,**kw:pytest.fail('No facts need no model'))
|
||||
assert result['outcome']=='empty'
|
||||
|
||||
|
||||
def test_empty_model_answer_does_not_publish_unverified_reason():
|
||||
result=generate_preview(request(),invoke=lambda *a,**kw:dict(summary=None,messages=[],empty_reason='所有任务均通过验收。'))
|
||||
assert result['outcome']=='empty'
|
||||
assert '验收' not in result['empty_reason']
|
||||
|
||||
|
||||
def test_repair_returning_empty_does_not_drop_verified_items():
|
||||
value=candidate()
|
||||
second=copy.deepcopy(value['messages'][0]);second.update(work='李乙',judgment='内容未归档 task-13247')
|
||||
value['messages'].append(second)
|
||||
def invoke(prompt,material,schema,**kwargs):
|
||||
if 'decisions' in schema['properties']:
|
||||
return {'decisions':[dict(index=p['index'],supported=True,reason='对照。') for p in material['points']]}
|
||||
return dict(summary=None,messages=[],empty_reason='') if 'audit' in material else value
|
||||
result=generate_preview(request(),invoke=invoke)
|
||||
assert result['outcome']=='ready'
|
||||
assert [item['work'] for item in result['messages']]==['张甲']
|
||||
|
||||
|
||||
def test_repair_keeps_verified_item_when_model_only_returns_corrected_item():
|
||||
original=candidate()
|
||||
second=copy.deepcopy(original['messages'][0]);second.update(work='李乙',judgment='内部编号 task-13247')
|
||||
original['messages'].append(second)
|
||||
revised=candidate();revised['messages'][0].update(work='李乙',title='复核安排待确认')
|
||||
def invoke(prompt,material,schema,**kwargs):
|
||||
if 'decisions' in schema['properties']:
|
||||
return {'decisions':[dict(index=p['index'],supported=True,reason='对照。') for p in material['points']]}
|
||||
return revised if 'audit' in material else original
|
||||
result=generate_preview(request(),invoke=invoke)
|
||||
assert [item['work'] for item in result['messages']]==['张甲','李乙']
|
||||
assert result['summary']['text']=='本期重点:纪要已提交,待核对;复核安排待确认'
|
||||
|
||||
|
||||
def test_citations_from_another_material_are_never_published():
|
||||
|
||||
@@ -195,7 +195,9 @@ def test_specialized_repairs_keep_the_actual_validation_error(monkeypatch,key):
|
||||
|
||||
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
|
||||
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])
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
from copy import deepcopy
|
||||
from collections import Counter
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.work_assistant import personnel_context as context, personnel_profile as profile
|
||||
from app.modules.work_assistant.model_gateway import ModelUnavailable, ModelOutputInvalid
|
||||
from app.modules.work_assistant.review_jobs import JobDeferred, ReviewJobs
|
||||
from test_personnel_autonomous_recovery import scenario
|
||||
|
||||
|
||||
def long_profile(person='9001', entries=115):
|
||||
entry, expected = scenario(person)
|
||||
for i in range(entries):
|
||||
passage = (f'合成编号{i:03}。本人完成了第{i+1}组的清单核对,复核记录仍待确认。'
|
||||
f'第{i+1}组的材料交接已登记,负责人要求补充可核对的结果。') * 3
|
||||
entry.evidence.append(profile.Evidence(id=f'work-{i}', kind='feedback', subject=f'资料核对 {i}', actor_id=person,
|
||||
at=f'2026-11-{i%18+1:02}', relation='self', content=passage))
|
||||
return entry, expected
|
||||
|
||||
|
||||
def test_every_original_excerpt_reaches_a_bounded_scan_page():
|
||||
entry, _ = long_profile()
|
||||
material, excerpts = profile.material(entry)
|
||||
pages = list(context.scan_pages(profile.pack_material(material)))
|
||||
assert len(pages) > 1
|
||||
read = [row for page in pages for row in page]
|
||||
assert {row[0]:row[-1] for row in read} == {key:part['quote'] for key,part in excerpts.items()}
|
||||
assert len(read) == len(excerpts)
|
||||
assert all(context.size(page) <= context.SCAN_BYTES + 1 for page in pages)
|
||||
with pytest.raises(ModelOutputInvalid):
|
||||
context.accept_scan({'refs':[pages[1][0][0]]}, pages[0])
|
||||
|
||||
|
||||
def test_long_workflow_resumes_after_scan_timeout_and_context_rejection(tmp_path, monkeypatch):
|
||||
from app.modules.work_assistant import review_jobs as module
|
||||
clock = [2e9]
|
||||
monkeypatch.setattr(module.time, 'time', lambda:clock[0])
|
||||
jobs = ReviewJobs(tmp_path/'reviews.sqlite3')
|
||||
entry, expected = long_profile()
|
||||
scan_calls = Counter()
|
||||
generation_calls = Counter()
|
||||
checked = []
|
||||
def fake(instruction, payload, schema, **options):
|
||||
assert context.prompt_bytes(instruction,payload,options['prompt_schema']) <= context.input_budget(options['max_tokens'])
|
||||
if 'evidence_batch' in payload:
|
||||
key = payload['evidence_batch']
|
||||
scan_calls[key] += 1
|
||||
if len(scan_calls)==2 and scan_calls[key]==1:
|
||||
raise ModelUnavailable('direct_timeout',retryable=True)
|
||||
return {'refs':[row[0] for row in payload['rows'][:8]]}
|
||||
if 'issues' in schema['properties']:
|
||||
checked.extend(row['key'] for row in payload['candidate']['findings'])
|
||||
return {'issues':[]}
|
||||
assert payload['selection_note'] == context.SCOPE_NOTE
|
||||
group = payload['generation_part']
|
||||
generation_calls[group] += 1
|
||||
if group=='requirements' and generation_calls[group]==1:
|
||||
raise ModelUnavailable('model_context_full')
|
||||
return {key:deepcopy(expected[key]) for key in schema['properties']}
|
||||
def run(checkpoint, save):
|
||||
return profile.review_profile(entry,invoke=fake,checkpoint=checkpoint,save_checkpoint=save,staged=True)
|
||||
for _ in range(40):
|
||||
try:
|
||||
result=jobs.run(entry.model_dump(),'local-test',run,progress_recovery=True,resume_context_failures=True)
|
||||
except (JobDeferred,ModelUnavailable):
|
||||
clock[0]+=1000
|
||||
continue
|
||||
break
|
||||
else:pytest.fail('long analysis never completed')
|
||||
assert sorted(scan_calls.values()).count(2)==1
|
||||
assert all(count<=2 for count in scan_calls.values())
|
||||
assert generation_calls=={'summary':1,'requirements':2,'work':1,'person':1}
|
||||
assert checked==list(profile.KEYS)
|
||||
assert result['findings'][0]['basis'][0]['quote']==entry.evidence[1].content
|
||||
|
||||
|
||||
def test_previous_context_suspension_reopens_the_same_checkpoint(tmp_path):
|
||||
jobs=ReviewJobs(tmp_path/'reviews.sqlite3')
|
||||
def old(cp, save):
|
||||
save({'generation_parts':{'summary':{'findings':[{'example':'saved'}]}}})
|
||||
raise ModelUnavailable('model_context_full')
|
||||
with pytest.raises(ModelUnavailable,match='model_context_full'):
|
||||
jobs.run({'request_id':'original'},'stable-policy-key',old)
|
||||
def fixed(cp, save):
|
||||
assert cp['generation_parts']['summary']['findings']==[{'example':'saved'}]
|
||||
return {'finished':True}
|
||||
assert jobs.run({'request_id':'original'},'stable-policy-key',fixed,resume_context_failures=True)=={'finished':True}
|
||||
|
||||
|
||||
def test_policy_recovery_does_not_reopen_factual_validation_failure(tmp_path):
|
||||
jobs=ReviewJobs(tmp_path/'reviews.sqlite3')
|
||||
def invalid(cp, save):
|
||||
raise ValueError('不支持的事实')
|
||||
with pytest.raises(ValueError):
|
||||
jobs.run({'request_id':'original'},'stable-policy-key',invalid)
|
||||
with pytest.raises(ModelUnavailable,match='review_suspended'):
|
||||
jobs.run({'request_id':'original'},'stable-policy-key',lambda *args:pytest.fail('validation bypass'),resume_context_failures=True)
|
||||
|
||||
|
||||
def test_repeated_transient_failure_survives_worker_restarts(tmp_path, monkeypatch):
|
||||
from app.modules.work_assistant import review_jobs as module
|
||||
clock = [2e9]
|
||||
monkeypatch.setattr(module.time, 'time', lambda: clock[0])
|
||||
ledger = tmp_path / 'reviews.sqlite3'
|
||||
checkpoint = {'context_scans': {'saved-batch': ['e1']}}
|
||||
report = {'request_id': 'outage'}
|
||||
|
||||
def timed_out(previous, save):
|
||||
if previous is None:
|
||||
save(checkpoint)
|
||||
else:
|
||||
assert previous == checkpoint
|
||||
raise ModelUnavailable('direct_timeout', retryable=True)
|
||||
|
||||
for attempt in range(5):
|
||||
jobs = ReviewJobs(ledger)
|
||||
with pytest.raises(ModelUnavailable, match='direct_timeout'):
|
||||
jobs.run(report, 'personnel', timed_out, rapid_recovery=True, progress_recovery=True)
|
||||
# Unrelated successful work can reset the shared circuit-breaker streak.
|
||||
jobs.run({'request_id': f'other-{attempt}'}, 'personnel', lambda *args: {'ok': True})
|
||||
clock[0] += 61
|
||||
|
||||
def recovered(previous, save):
|
||||
assert previous == checkpoint
|
||||
return {'ok': True}
|
||||
|
||||
assert ReviewJobs(ledger).run(report, 'personnel', recovered, rapid_recovery=True, progress_recovery=True) == {'ok': True}
|
||||
|
||||
|
||||
def test_personnel_route_resumes_legacy_validation_and_publishes_only_verified_work(tmp_path, monkeypatch):
|
||||
from app.modules.work_assistant import routes
|
||||
from app.modules.work_assistant.personnel_recovery import row_fingerprint
|
||||
|
||||
entry, raw = scenario()
|
||||
accepted = profile.resolve(raw, profile.material(entry)[1])['findings'][0]
|
||||
raw['findings'][1]['finding'] = '全部交付已通过最终验收。'
|
||||
checkpoint = {'candidate': raw, 'grounding_revision': profile.GROUNDING_REVISION,
|
||||
'grounding_cache': {row_fingerprint('findings', accepted): []}}
|
||||
jobs = ReviewJobs(tmp_path / 'reviews.sqlite3')
|
||||
monkeypatch.setattr(routes, 'review_jobs', jobs)
|
||||
rule = profile.REVIEW_CACHE_RULE + ':' + routes.routing_revision()
|
||||
|
||||
def old_workflow(previous, save):
|
||||
save(checkpoint)
|
||||
raise ValueError('unverified conclusion')
|
||||
|
||||
with pytest.raises(ValueError, match='unverified conclusion'):
|
||||
jobs.run(entry.model_dump(), rule, old_workflow)
|
||||
|
||||
def exhausted(payload, *, checkpoint, save_checkpoint, staged):
|
||||
assert checkpoint['candidate'] == raw
|
||||
raise ValueError('repair spent its full budget')
|
||||
|
||||
monkeypatch.setattr(routes, 'review_profile', exhausted)
|
||||
partial = routes.personnel_profile_review(entry)
|
||||
assert partial['assessment_status'] == 'partial'
|
||||
assert partial['findings'][0] == accepted
|
||||
assert partial['findings'][1]['status'] == 'insufficient'
|
||||
assert '通过最终验收' not in str(partial)
|
||||
assert partial['work_record_basis'][0]['quote'] in entry.evidence[1].content
|
||||
monkeypatch.setattr(routes, 'review_profile', lambda *args, **kwargs: pytest.fail('cached partial regenerated'))
|
||||
assert routes.personnel_profile_review(entry) == partial
|
||||
|
||||
|
||||
def test_worker_lease_expirations_do_not_consume_the_profile_retry_budget(tmp_path, monkeypatch):
|
||||
from app.modules.work_assistant import review_jobs as module
|
||||
now = 2e9
|
||||
monkeypatch.setattr(module.time, 'time', lambda: now)
|
||||
jobs = ReviewJobs(tmp_path / 'reviews.sqlite3')
|
||||
payload = {'request_id': 'interrupted-workers'}
|
||||
key = jobs.key(payload, 'personnel')
|
||||
with jobs.connect() as db:
|
||||
db.execute("INSERT INTO review_job(job_key,status,lease_until,attempts,checkpoint,updated_at) VALUES(?,'running',?,6,?,?)",
|
||||
(key, now - 1, '{"context_scans":{"done":["e1"]}}', now - 181))
|
||||
|
||||
def recover(checkpoint, save):
|
||||
assert checkpoint['context_scans'] == {'done': ['e1']}
|
||||
return {'finished': True}
|
||||
|
||||
assert jobs.run(payload, 'personnel', recover, progress_recovery=True) == {'finished': True}
|
||||
|
||||
|
||||
def test_only_repeated_nonadvancing_slices_finish_with_facts(tmp_path, monkeypatch):
|
||||
from fastapi import HTTPException
|
||||
from app.modules.work_assistant import review_jobs as module, routes
|
||||
from app.modules.work_assistant.personnel_workflow import MAX_UNCHANGED_SLICES
|
||||
|
||||
clock = [2e9]
|
||||
entry, _ = scenario()
|
||||
jobs = ReviewJobs(tmp_path / 'reviews.sqlite3')
|
||||
monkeypatch.setattr(routes, 'review_jobs', jobs)
|
||||
monkeypatch.setattr(module.time, 'time', lambda: clock[0])
|
||||
queue_unavailable = [True]
|
||||
|
||||
def execute(*args, **kwargs):
|
||||
if queue_unavailable[0]:
|
||||
raise ModelUnavailable('queue_timeout')
|
||||
raise JobDeferred()
|
||||
|
||||
monkeypatch.setattr(routes, 'review_profile', execute)
|
||||
for _ in range(MAX_UNCHANGED_SLICES + 2):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
routes.personnel_profile_review(entry)
|
||||
assert exc.value.headers['X-Review-State'] == 'queue_timeout'
|
||||
clock[0] += 61
|
||||
|
||||
queue_unavailable[0] = False
|
||||
for _ in range(MAX_UNCHANGED_SLICES - 1):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
routes.personnel_profile_review(entry)
|
||||
assert exc.value.headers['X-Review-State'] == 'review_continuation'
|
||||
clock[0] += 61
|
||||
|
||||
result = routes.personnel_profile_review(entry)
|
||||
assert result['assessment_status'] == 'partial'
|
||||
assert result['work_record_basis'][0]['evidence_id'] == 'work'
|
||||
|
||||
|
||||
def test_personnel_protocol_identifies_both_retry_and_success_responses(tmp_path, monkeypatch):
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from app.modules.work_assistant import routes
|
||||
|
||||
app = FastAPI()
|
||||
app.add_api_route('/capabilities', routes.review_capabilities)
|
||||
app.add_api_route('/profile', routes.personnel_profile_review, methods=['POST'])
|
||||
entry, _ = scenario()
|
||||
monkeypatch.setattr(routes, 'review_jobs', ReviewJobs(tmp_path / 'reviews.sqlite3'))
|
||||
|
||||
def unavailable(*args, **kwargs):
|
||||
raise ModelUnavailable('direct_timeout', retryable=True)
|
||||
|
||||
with TestClient(app) as client:
|
||||
protocol = str(client.get('/capabilities').json()['personnel_job_protocol'])
|
||||
monkeypatch.setattr(routes, 'review_profile', unavailable)
|
||||
waiting = client.post('/profile', json=entry.model_dump())
|
||||
assert waiting.status_code == 503 and waiting.headers['x-review-state'] == 'model_timeout'
|
||||
assert waiting.headers['x-personnel-job-protocol'] == protocol
|
||||
monkeypatch.setattr(routes, 'review_profile', lambda *args, **kwargs: {'finished': True})
|
||||
complete = client.post('/profile', json={**entry.model_dump(), 'request_id': 'new-request'})
|
||||
assert complete.status_code == 200 and complete.json() == {'finished': True}
|
||||
assert complete.headers['x-personnel-job-protocol'] == protocol
|
||||
Reference in New Issue
Block a user