feat(shipping-notice): 增强订单抽取功能,添加进度事件和诊断运行管理,优化数据模型和访问控制
This commit is contained in:
1 parent
ce26d6d0c4
commit
c4095b08da
175 files changed
+13064
-1814
No files matched your search
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from copy import deepcopy
|
||||
from unittest.mock import patch
|
||||
from datetime import datetime, timedelta
|
||||
@@ -21,20 +23,28 @@ from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.shipping_order_extraction import run_shipping_order_extraction
|
||||
from app.jobs.handlers.shipping_order_extraction import (
|
||||
_execute_dify_unit_with_retry,
|
||||
run_shipping_order_extraction,
|
||||
)
|
||||
from app.jobs.queue import claim_next_job, recover_stale_jobs
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun, User,
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument,
|
||||
ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderSchemaVersion, User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding
|
||||
from app.services.admin.agent_service import update_agent_permissions
|
||||
from app.services.admin.agent_service import list_agents
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_order_extraction_workflow_inputs, execute_order_extraction_workflow,
|
||||
parse_order_extraction_workflow_result, validate_unit_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
sync_order_extraction_run_after_job_recovery,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
@@ -63,6 +73,59 @@ def test_binding_rejects_non_internal_or_non_workflow_provider(app):
|
||||
assert caught.value.code == 'AGENT.RUNTIME_PROVIDER_INVALID'
|
||||
|
||||
|
||||
def test_binding_catalog_exposes_internal_executor_role_constraint(app):
|
||||
"""订单抽取能力目录必须明确要求 internal_executor,避免仅靠界面约定。"""
|
||||
with app.app_context():
|
||||
owner = Agent(name='Owner', agent_code='shipping_notice', runtime_provider='hybrid')
|
||||
provider = Agent(
|
||||
name='Workflow Provider', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='workflow-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([owner, provider])
|
||||
db.session.commit()
|
||||
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=owner.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id,
|
||||
enabled=True,
|
||||
config={},
|
||||
)
|
||||
assert binding.provider_agent.exposure_mode == 'internal'
|
||||
|
||||
|
||||
def test_internal_executor_cannot_receive_user_permissions(app):
|
||||
"""内部执行器只能被运行时绑定,不能进入用户授权关系。"""
|
||||
with app.app_context():
|
||||
user = User(username='internal-permission-user', email='internal-permission@example.com', password_hash='x')
|
||||
provider = Agent(
|
||||
name='Internal Workflow', agent_code='generic', runtime_provider='dify',
|
||||
dify_app_type='workflow', exposure_mode='internal', dify_app_id='provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1', is_active=True,
|
||||
)
|
||||
db.session.add_all([user, provider])
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
update_agent_permissions(provider.id, [user.id])
|
||||
assert caught.value.code == 'AGENT.INTERNAL_EXECUTOR_PERMISSION_FORBIDDEN'
|
||||
|
||||
|
||||
def test_admin_agent_list_scopes_separate_applications_and_executors(app):
|
||||
"""管理页签后端列表必须按 workspace/internal 隔离。"""
|
||||
with app.app_context():
|
||||
application = Agent(name='Workspace App', exposure_mode='workspace', agent_code='generic')
|
||||
executor = Agent(
|
||||
name='Internal Executor', exposure_mode='internal',
|
||||
runtime_provider='dify', dify_app_type='workflow', dify_app_id='scope-provider',
|
||||
dify_api_key='key', api_base_url='http://dify.example/v1',
|
||||
)
|
||||
db.session.add_all([application, executor])
|
||||
db.session.commit()
|
||||
assert {item['exposure_mode'] for item in list_agents(scope='applications')} == {'workspace'}
|
||||
assert {item['exposure_mode'] for item in list_agents(scope='executors')} == {'internal'}
|
||||
|
||||
|
||||
def test_run_creation_requires_explicit_binding(app):
|
||||
"""删除显式绑定后创建 Run 必须阻断,且不得产生 Run 或 Job。"""
|
||||
with app.app_context():
|
||||
@@ -116,6 +179,18 @@ def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_
|
||||
)
|
||||
assert saved.status_code == 200
|
||||
assert saved.get_json()['data']['provider_agent_id'] == provider_id
|
||||
assert saved.get_json()['data']['config'] == {
|
||||
'timeout_seconds': 600,
|
||||
'max_attempts': 2,
|
||||
'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2,
|
||||
'unit_retry_backoff_ms': 500,
|
||||
'max_model_units': 20,
|
||||
'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5,
|
||||
'circuit_cooldown_seconds': 60,
|
||||
'auto_create_enabled': False,
|
||||
}
|
||||
assert 'dify_api_key' not in saved.get_json()['data']
|
||||
|
||||
listed = client.get('/api/agents', headers=auth)
|
||||
@@ -361,38 +436,463 @@ def test_workflow_request_errors_are_classified(app, upstream_error, expected_co
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
provider = db.session.get(Agent, run.provider_agent_id)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming',
|
||||
side_effect=upstream_error,
|
||||
), pytest.raises(Exception) as caught:
|
||||
execute_order_extraction_workflow(run=run, provider=provider, timeout_seconds=30)
|
||||
execute_order_extraction_workflow(run=run, unit=unit, provider=provider, timeout_seconds=30)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == expected_code
|
||||
assert getattr(caught.value, 'retryable', False) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'workflow_result',
|
||||
[
|
||||
None,
|
||||
{'status': 'failed', 'error': 'inventory_source_hint must not be a line number'},
|
||||
{'status': 'succeeded', 'outputs': {'orders': 'not-json'}},
|
||||
],
|
||||
)
|
||||
def test_workflow_terminal_or_output_contract_errors_are_not_retryable(workflow_result):
|
||||
"""Dify 已返回终态的画布/输出错误不得触发 Unit 重试或 Provider 熔断。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
parse_order_extraction_workflow_result(workflow_result)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
assert caught.value.retryable is False
|
||||
|
||||
|
||||
def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
"""Dify 已返回画布校验失败时,同一 Unit 不重复调用且不累计 Provider 熔断失败。"""
|
||||
error = ValidationError(
|
||||
'inventory_source_hint must not be a line number',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
run_snapshot = {
|
||||
'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1,
|
||||
'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {},
|
||||
}
|
||||
unit_snapshot = {
|
||||
'id': 1, 'intake_id': 1, 'document_id': 1,
|
||||
'document_type': 'attachment', 'unit_type': 'document_extraction',
|
||||
}
|
||||
provider_snapshot = {'id': 998877, 'api_base_url': 'http://dify.example/v1', 'dify_api_key': 'key'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=error,
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.record_provider_failure',
|
||||
) as record_failure, pytest.raises(ValidationError) as caught:
|
||||
_execute_dify_unit_with_retry(
|
||||
app=app, run_snapshot=run_snapshot, unit_snapshot=unit_snapshot,
|
||||
provider_snapshot=provider_snapshot, timeout_seconds=30,
|
||||
max_attempts=3, backoff_ms=1, job_id=1, job_attempt=1,
|
||||
provider_max_concurrency=1, circuit_failure_threshold=2,
|
||||
circuit_cooldown_seconds=60,
|
||||
)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
assert execute.call_count == 1
|
||||
record_failure.assert_not_called()
|
||||
|
||||
|
||||
def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
"""Workflow 分离冻结 LLM 契约与只读上下文,完整定义和 documents 均不得旁路泄露。"""
|
||||
"""Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
inputs = build_order_extraction_workflow_inputs(run)
|
||||
schema = json.loads(inputs['schema_contract'])
|
||||
documents = json.loads(inputs['documents'])
|
||||
readonly_context = json.loads(inputs['readonly_context'])
|
||||
unit = run.extraction_plan.units[0]
|
||||
inputs = build_order_extraction_workflow_inputs(run, unit=unit)
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
schema = manifest['extraction_contract']
|
||||
documents = manifest['documents']
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert schema == run.input_snapshot_json['schema']['extraction_contract']
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['unit']['document_id'] == unit.document_id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert 'definition' not in schema
|
||||
assert schema['fields'][0]['field_id'] == 'qty-id'
|
||||
assert 'deterministic_context' not in documents[0]
|
||||
assert 'sales-' not in inputs['documents'].lower()
|
||||
assert len(documents) == 1
|
||||
assert set(documents[0]) == {'intake_id', 'intake_no', 'document'}
|
||||
assert documents[0]['document']['document_id'] == unit.document_id
|
||||
assert 'sales-' not in repr(documents).lower()
|
||||
assert readonly_context == []
|
||||
assert set(inputs) == {
|
||||
'run_no', 'input_snapshot_hash', 'schema_contract', 'documents', 'readonly_context',
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
|
||||
|
||||
def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
"""Workflow 调用边界只能发送 execution_manifest,禁止回退到旧五变量契约。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
provider = db.session.get(Agent, run.provider_agent_id)
|
||||
unit = run.extraction_plan.units[0]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow.DifyService.run_workflow_streaming',
|
||||
return_value={'status': 'succeeded', 'outputs': {'orders': []}, 'workflow_run_id': 'wf-manifest'},
|
||||
) as mocked_run:
|
||||
orders, metadata = execute_order_extraction_workflow(
|
||||
run=run, unit=unit, provider=provider, timeout_seconds=30,
|
||||
)
|
||||
|
||||
inputs = mocked_run.call_args.kwargs['inputs']
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert manifest['run']['run_no'] == run.run_no
|
||||
assert manifest['unit']['unit_id'] == unit.id
|
||||
assert manifest['integrity']['input_snapshot_hash'] == run.input_snapshot_hash
|
||||
assert orders == []
|
||||
assert metadata['workflow_run_id'] == 'wf-manifest'
|
||||
|
||||
|
||||
def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
"""冻结 Schema 可完整解析的表格单元必须零模型调用,并缓存可恢复的局部订单。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'aliases': ['Part Number'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'aliases': ['Qty'], 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
]}
|
||||
document.extracted_text = 'Part Number\tQty\nPN-001\t3'
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='deterministic-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
) as submit:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
unit = finished.extraction_plan.units[0]
|
||||
assert execute.call_count == 0
|
||||
assert submit.call_args.kwargs['orders'][0]['lines'][0]['fields']
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'deterministic'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 1
|
||||
|
||||
|
||||
def test_unit_manifest_never_contains_sibling_document(app):
|
||||
"""单元级模型输入只能包含当前冻结 Document,禁止重新拼成整封邮件。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='COMPACT')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='second.pdf',
|
||||
filename='second.pdf',
|
||||
content_hash='d' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='SIBLING-SECRET-CONTENT',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = next(item for item in run.extraction_plan.units if item.document_id == first.id)
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(
|
||||
run, unit=unit,
|
||||
)['execution_manifest'])
|
||||
|
||||
assert len(manifest['documents']) == 1
|
||||
assert manifest['documents'][0]['document']['document_id'] == first.id
|
||||
assert 'SIBLING-SECRET-CONTENT' not in repr(manifest)
|
||||
|
||||
|
||||
def test_unit_result_cannot_reference_sibling_document(app):
|
||||
"""即使模型猜到兄弟 Document ID,单元边界也必须在局部结果落库前拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='UNIT-SCOPE')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='sibling.pdf',
|
||||
content_hash='e' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Sibling evidence',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = next(item for item in run.extraction_plan.units if item.document_id == first.id)
|
||||
orders = [{
|
||||
'source_intake_no': intake.intake_no,
|
||||
'primary_document_id': first.id,
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{
|
||||
'field_id': 'qty-id',
|
||||
'observations': [{'value': 1, 'document_id': second.id, 'quote': 'Sibling evidence'}],
|
||||
}]}],
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_unit_orders(run, unit=unit, orders=orders)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
|
||||
def test_worker_runs_dify_units_with_frozen_concurrency_limit(app):
|
||||
"""多个模型单元应实际并行,且同时在途数量不得超过 Run 冻结配置。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _first = _seed_run_input(suffix='PARALLEL')
|
||||
for index in range(2):
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment',
|
||||
attachment_key=f'parallel-{index}.pdf', content_hash=str(index + 1) * 64,
|
||||
classification='order_notice', parse_status='parsed',
|
||||
extracted_text=f'Unstructured document {index}',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='parallel-worker',
|
||||
)
|
||||
lock = threading.Lock()
|
||||
active = 0
|
||||
peak = 0
|
||||
|
||||
def execute(*, unit, **_kwargs):
|
||||
nonlocal active, peak
|
||||
with lock:
|
||||
active += 1
|
||||
peak = max(peak, active)
|
||||
time.sleep(0.08)
|
||||
with lock:
|
||||
active -= 1
|
||||
return [], {'workflow_run_id': f'wf-{unit.id}', 'provider_status': 'succeeded'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert peak == 2
|
||||
assert finished.provider_result_json['workflow']['unit_concurrency'] == 2
|
||||
assert finished.provider_result_json['workflow']['dify_unit_count'] == 3
|
||||
assert all(unit.status == 'succeeded' for unit in finished.extraction_plan.units)
|
||||
|
||||
|
||||
def test_worker_retries_only_failed_unit_locally(app):
|
||||
"""单元首次网络失败后只重试该单元,并保存 attempt/latency 指标。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOCAL-RETRY')
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 3, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='local-retry-worker',
|
||||
)
|
||||
calls = 0
|
||||
|
||||
def execute(**_kwargs):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
raise requests.exceptions.ReadTimeout('temporary slow unit')
|
||||
return [], {'workflow_run_id': 'wf-local-retry', 'provider_status': 'succeeded'}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
unit = db.session.get(ShippingOrderExtractionRun, run.id).extraction_plan.units[0]
|
||||
assert calls == 2
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.attempt_count == 2
|
||||
assert unit.result_json['workflow']['attempts'] == 2
|
||||
assert unit.result_json['workflow']['latency_ms'] >= 100
|
||||
|
||||
|
||||
def test_worker_persists_successful_units_when_one_unit_exhausts_retries(app):
|
||||
"""一个单元永久失败时,成功单元仍提交,Run 以 needs_review 收口。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='PARTIAL')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='partial-2.pdf',
|
||||
content_hash='f' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Second unstructured document',
|
||||
)
|
||||
db.session.add(second)
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='partial-worker',
|
||||
)
|
||||
submitted = {}
|
||||
|
||||
def execute(*, unit, **_kwargs):
|
||||
if unit.document_id == second.id:
|
||||
raise requests.exceptions.ReadTimeout('permanent unit timeout')
|
||||
return [], {'workflow_run_id': f'wf-{first.id}', 'provider_status': 'succeeded'}
|
||||
|
||||
def submit(*, orders, **_kwargs):
|
||||
submitted['orders'] = orders
|
||||
return {
|
||||
'batch_no': None, 'created_count': 0, 'opened_existing_count': 0,
|
||||
'pending_count': 0, 'non_shipping_count': 0,
|
||||
}
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
side_effect=execute,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
side_effect=submit,
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
finished = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
statuses = {unit.document_id: unit.status for unit in finished.extraction_plan.units}
|
||||
assert submitted['orders'] == []
|
||||
assert statuses[first.id] == 'succeeded'
|
||||
assert statuses[second.id] == 'failed'
|
||||
assert finished.status == 'needs_review'
|
||||
assert finished.result_json['failed_unit_count'] == 1
|
||||
|
||||
|
||||
def test_worker_blocks_model_calls_when_frozen_unit_budget_is_exceeded(app):
|
||||
"""需要模型的文档数超过 Run 冻结预算时必须在发请求前阻断。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='BUDGET')
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='budget-2.pdf',
|
||||
content_hash='9' * 64, classification='order_notice', parse_status='parsed',
|
||||
extracted_text='Another unstructured document',
|
||||
))
|
||||
binding = AgentRuntimeBinding.query.filter_by(owner_agent_id=agent.id).one()
|
||||
binding.config_json = {
|
||||
'timeout_seconds': 900, 'max_attempts': 1, 'unit_concurrency': 2,
|
||||
'unit_max_attempts': 1, 'unit_retry_backoff_ms': 100,
|
||||
'max_model_units': 1, 'provider_max_concurrency': 4,
|
||||
'circuit_failure_threshold': 5, 'circuit_cooldown_seconds': 60,
|
||||
}
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
worker_id='budget-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute:
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert execute.call_count == 0
|
||||
failed = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
assert failed.status == 'failed'
|
||||
assert failed.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_MODEL_BUDGET_EXCEEDED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'orders_output',
|
||||
[
|
||||
[{'classification': 'shipping_request'}],
|
||||
json.dumps([{'classification': 'shipping_request'}]),
|
||||
json.dumps(json.dumps([{'classification': 'shipping_request'}])),
|
||||
json.dumps({'orders': [{'classification': 'shipping_request'}]}),
|
||||
{'orders': json.dumps([{'classification': 'shipping_request'}])},
|
||||
],
|
||||
)
|
||||
def test_workflow_result_accepts_dify_orders_serialization_variants(orders_output):
|
||||
"""Dify End 的数组和最多两层 String 包装均须还原为订单数组。"""
|
||||
assert parse_order_extraction_workflow_result({
|
||||
'status': 'succeeded', 'outputs': {'orders': orders_output},
|
||||
}) == [{'classification': 'shipping_request'}]
|
||||
|
||||
|
||||
def test_workflow_readonly_context_uses_run_frozen_values(app):
|
||||
@@ -414,7 +914,10 @@ def test_workflow_readonly_context_uses_run_frozen_values(app):
|
||||
intake.structured_result_json = {'email': {'from': 'changed@later.example'}}
|
||||
db.session.commit()
|
||||
|
||||
readonly_context = json.loads(build_order_extraction_workflow_inputs(run)['readonly_context'])
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest'])
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert readonly_context[0]['fields'][0]['value'] == 'frozen@example.com'
|
||||
assert 'changed@later.example' not in repr(readonly_context)
|
||||
@@ -465,6 +968,48 @@ def test_worker_recovers_persisted_run_facts_without_duplicate_dify(app):
|
||||
assert db.session.get(Job, job.id).status == 'success'
|
||||
|
||||
|
||||
def test_manual_retry_reuses_cached_provider_result_without_duplicate_dify(app):
|
||||
"""失败卡片手工重试若已有 Provider 成功结果,只重跑 HXOPS 落库阶段。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='MANUAL-RETRY-CACHE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
original_job = db.session.get(Job, run.current_job_id)
|
||||
run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-manual-cache'}}
|
||||
transition_order_extraction_run(run, target_status='running', phase='persisting_result')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='database temporarily failed')
|
||||
original_job.status = 'failed'
|
||||
db.session.commit()
|
||||
|
||||
retried, reused = retry_order_extraction_run(user_id=user.id, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
assert reused is False
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION], worker_id='manual-retry-worker',
|
||||
)
|
||||
assert job.id == retried.current_job_id
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
'batch_no': None,
|
||||
'created_count': 0,
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': 0,
|
||||
'non_shipping_count': 0,
|
||||
},
|
||||
):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
db.session.expire_all()
|
||||
assert execute.call_count == 0
|
||||
assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'completed'
|
||||
assert db.session.get(Job, job.id).status == 'success'
|
||||
|
||||
|
||||
def test_worker_recovers_consumed_empty_result_without_duplicate_dify(app):
|
||||
"""空订单/非发货结果已消费 Intake 后,重试应补 submission 并完成 Run。"""
|
||||
with app.app_context():
|
||||
|
||||
Reference in new issue
Block a user