feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理
This commit is contained in:
1 parent
c4095b08da
commit
c35223d49d
148 files changed
+15709
-1353
No files matched your search
@@ -31,10 +31,12 @@ 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, ShippingNoticeDocument,
|
||||
ShippingOrderExtraction, ShippingOrderExtractionRun, ShippingOrderSchemaVersion, User,
|
||||
ShippingOrderDocumentProfile, 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.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
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,
|
||||
@@ -95,6 +97,50 @@ def test_binding_catalog_exposes_internal_executor_role_constraint(app):
|
||||
assert binding.provider_agent.exposure_mode == 'internal'
|
||||
|
||||
|
||||
def test_binding_rejects_retired_workflow_contract_version(app):
|
||||
"""唯一协议不接受历史版本开关,防止运行时重新出现双格式分支。"""
|
||||
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()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id, enabled=True,
|
||||
config={'workflow_contract_version': 'latest'},
|
||||
)
|
||||
|
||||
assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_binding_rejects_retired_workflow_contract_version_with_auto_create(app):
|
||||
"""自动建单也不得通过历史版本配置绕过唯一协议约束。"""
|
||||
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()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
save_runtime_binding(
|
||||
owner_agent_id=owner.id, capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id, enabled=True,
|
||||
config={'workflow_contract_version': 'legacy', 'auto_create_enabled': True},
|
||||
)
|
||||
|
||||
assert caught.value.code == 'AGENT.RUNTIME_BINDING_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_internal_executor_cannot_receive_user_permissions(app):
|
||||
"""内部执行器只能被运行时绑定,不能进入用户授权关系。"""
|
||||
with app.app_context():
|
||||
@@ -182,14 +228,6 @@ def test_runtime_binding_admin_api_and_internal_agent_hidden(app, client, admin_
|
||||
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']
|
||||
|
||||
@@ -473,7 +511,9 @@ def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
)
|
||||
run_snapshot = {
|
||||
'id': 1, 'run_no': 'SNER-CONTRACT-ERROR', 'user_id': 1,
|
||||
'schema_version_id': 1,
|
||||
'input_snapshot_hash': 'a' * 64, 'input_snapshot_json': {},
|
||||
'provider_config_json': {},
|
||||
}
|
||||
unit_snapshot = {
|
||||
'id': 1, 'intake_id': 1, 'document_id': 1,
|
||||
@@ -500,8 +540,8 @@ def test_dify_terminal_contract_error_does_not_retry_or_open_circuit(app):
|
||||
record_failure.assert_not_called()
|
||||
|
||||
|
||||
def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
"""Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
def test_workflow_inputs_use_unique_extraction_contract_only(app):
|
||||
"""唯一 Workflow manifest 仅含冻结抽取契约与受控提示,完整定义不得旁路泄露。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input()
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -511,21 +551,19 @@ def test_workflow_inputs_use_frozen_extraction_contract_only(app):
|
||||
inputs = build_order_extraction_workflow_inputs(run, unit=unit)
|
||||
manifest = json.loads(inputs['execution_manifest'])
|
||||
schema = manifest['extraction_contract']
|
||||
documents = manifest['documents']
|
||||
document = manifest['document']
|
||||
readonly_context = manifest['readonly_hints']
|
||||
|
||||
assert schema == run.input_snapshot_json['schema']['extraction_contract']
|
||||
assert manifest['contract_version'] == 'shipping_order_extraction.unit.v2'
|
||||
assert 'contract_version' not in manifest
|
||||
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 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 document['document_id'] == unit.document_id
|
||||
assert 'sales-' not in repr(document).lower()
|
||||
assert readonly_context == []
|
||||
assert set(inputs) == {'execution_manifest'}
|
||||
|
||||
@@ -551,7 +589,7 @@ def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
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 'contract_version' not in manifest
|
||||
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
|
||||
@@ -559,8 +597,140 @@ def test_workflow_execution_sends_only_versioned_manifest(app):
|
||||
assert metadata['workflow_run_id'] == 'wf-manifest'
|
||||
|
||||
|
||||
def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
"""冻结 Schema 可完整解析的表格单元必须零模型调用,并缓存可恢复的局部订单。"""
|
||||
def test_unique_manifest_sends_compact_layout_candidates_only(app):
|
||||
"""唯一 Manifest 只发送紧凑字段候选,禁止泄漏 bbox、HTML、token、cell_id 或 field_code。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='UNIT-V3')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
frozen = run.input_snapshot_json['intakes'][0]['documents'][0]
|
||||
frozen['layout_snapshot'] = {'html': 'RAW-HTML', 'bbox': [1, 2, 3, 4]}
|
||||
frozen['layout_schema_candidates'] = [{
|
||||
'page_no': 2, 'table_id': 'table-1', 'mapping_status': 'candidate',
|
||||
'issues': ['layout_table_not_accepted'],
|
||||
'rows': [{
|
||||
'row_index': 3, 'role': 'data', 'issues': [],
|
||||
'fields': [{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'value': 30,
|
||||
'quote': 'Qty 30', 'column_index': 4, 'cell_id': 'secret-cell',
|
||||
'token_ids': ['secret-token'], 'evidence_ref': 'secret-ref',
|
||||
}],
|
||||
}],
|
||||
}]
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest'])
|
||||
|
||||
assert 'contract_version' not in manifest
|
||||
assert manifest['structured_table_candidates'][0]['field_policy'] == 'suggested'
|
||||
assert manifest['structured_table_candidates'][0]['rows'][0]['fields'] == [{
|
||||
'column_index': 4, 'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30',
|
||||
}]
|
||||
assert 'documents' not in manifest
|
||||
serialized = repr({
|
||||
'document': manifest['document'],
|
||||
'structured_table_candidates': manifest['structured_table_candidates'],
|
||||
})
|
||||
for forbidden in ('RAW-HTML', 'bbox', 'secret-cell', 'secret-token', 'secret-ref', 'field_code'):
|
||||
assert forbidden not in serialized
|
||||
|
||||
|
||||
def test_unique_manifest_prefers_mineru_pdf_text_and_table_grid(app):
|
||||
"""PDF 有 ready MinerU 快照时应向模型发送分页文本和 TSV 表格,替换旧拍平文本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='MINERU-TEXT')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
frozen = run.input_snapshot_json['intakes'][0]['documents'][0]
|
||||
frozen['filename'] = 'order.pdf'
|
||||
frozen['extracted_text'] = 'LEGACY-FLAT-TEXT'
|
||||
frozen['layout_snapshot'] = {
|
||||
'status': 'ready',
|
||||
'text_blocks': [{
|
||||
'page_no': 1, 'normalized_bbox': {'x0': 0.1, 'y0': 0.1},
|
||||
'text': 'PO Number: 4518838154',
|
||||
}],
|
||||
'tables': [{
|
||||
'table_id': 'table-1', 'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.3},
|
||||
'html': '<table><tr><th>Item</th><th>Reservation ID</th></tr>'
|
||||
'<tr><td>00020</td><td>12345</td></tr></table>',
|
||||
}],
|
||||
}
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest'])
|
||||
|
||||
document = manifest['document']
|
||||
assert document['text_source'] == 'mineru'
|
||||
assert 'LEGACY-FLAT-TEXT' not in document['extracted_text']
|
||||
assert 'PO Number: 4518838154' in document['extracted_text']
|
||||
assert 'Item\tReservation ID' in document['extracted_text']
|
||||
assert '00020\t12345' in document['extracted_text']
|
||||
assert 'html' not in repr(document)
|
||||
|
||||
|
||||
def test_unique_manifest_accepted_layout_fields_cannot_be_overridden(app):
|
||||
"""唯一 Manifest 模型可以补充候选,但 accepted 字段缺失或改值必须被后端拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOCKED-FIELD')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{
|
||||
'mapping_status': 'accepted', 'rows': [{
|
||||
'role': 'data', 'fields': [{'field_id': 'qty-id', 'value': 30}],
|
||||
}],
|
||||
}]
|
||||
invalid = [{
|
||||
'source_intake_no': intake.intake_no, 'primary_document_id': unit.document_id,
|
||||
'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': 'qty-id', 'observations': [{
|
||||
'value': 31, 'document_id': unit.document_id,
|
||||
}],
|
||||
}]}],
|
||||
}]
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
validate_unit_orders(run, unit=unit, orders=invalid)
|
||||
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
|
||||
|
||||
def test_accepted_complete_layout_builds_order_without_provider(app):
|
||||
"""唯一 accepted 表格覆盖全部必填字段时必须直接生成订单,保持零 Provider 调用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LAYOUT-ZERO-PROVIDER')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
run.input_snapshot_json['intakes'][0]['documents'][0]['layout_schema_candidates'] = [{
|
||||
'mapping_status': 'accepted', 'issues': [],
|
||||
'rows': [{
|
||||
'role': 'data', 'fields': [{
|
||||
'field_id': 'qty-id', 'value': 30, 'quote': 'Qty 30',
|
||||
}],
|
||||
}],
|
||||
}]
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
|
||||
|
||||
orders = build_deterministic_unit_orders(run, unit=unit)
|
||||
|
||||
assert orders is not None
|
||||
assert orders[0]['lines'][0]['fields'][0]['field_id'] == 'qty-id'
|
||||
assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30
|
||||
|
||||
|
||||
def test_plain_text_complete_table_still_uses_provider(app):
|
||||
"""纯文本表格即使字段齐全也不能零 Provider,防止 L7 恢复猜列运行路径。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DETERMINISTIC')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
@@ -590,6 +760,7 @@ def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
return_value=([], {'workflow_run_id': 'wf-plain-text', 'execution_mode': 'dify'}),
|
||||
) as execute, patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.submit_order_extraction_run_result',
|
||||
return_value={
|
||||
@@ -602,11 +773,149 @@ def test_deterministic_complete_table_skips_dify_and_persists_unit_result(app):
|
||||
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 execute.call_count == 1
|
||||
assert submit.call_args.kwargs['orders'] == []
|
||||
assert unit.status == 'succeeded'
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'deterministic'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 1
|
||||
assert unit.result_json['workflow']['execution_mode'] == 'dify'
|
||||
assert finished.provider_result_json['workflow']['deterministic_unit_count'] == 0
|
||||
|
||||
|
||||
def test_profile_template_candidate_uses_provider_after_l7_cleanup(app):
|
||||
"""Profile 仍提供紧凑语义候选,但未获 accepted cell 前不能跳过 Provider。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-MAP')
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
version.definition_json = {'fields': [
|
||||
{
|
||||
'field_id': 'customer-id', 'field_code': 'customer_part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': False,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
|
||||
'value_type': 'decimal', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
||||
},
|
||||
]}
|
||||
html = (
|
||||
'<table><tr><th>LN</th><th>Part Number</th><th>Vendor Item#</th><th>Qty</th></tr>'
|
||||
'<tr><td>1</td><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr>'
|
||||
'<tr><td>2</td><td>CUSTOMER-Z</td><td>INTERNAL-Z</td><td>0</td></tr></table>'
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint
|
||||
|
||||
fingerprint = order_profile_structure_fingerprint(parse_html_grid(html, table_id='fixture'), header_row_index=0)
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='PO_312207', display_name='PO template', version=1, status='published',
|
||||
schema_version_id=version.id, structure_fingerprint=fingerprint, checksum='e' * 64,
|
||||
definition_json={
|
||||
'contract_version': 'shipping_order_document_profile.v1',
|
||||
'structure_fingerprint': fingerprint, 'header_row_index': 0,
|
||||
'data_start_row_index': 1, 'row_structure': 'preserved', 'drop_zero_qty': True,
|
||||
'column_rules': [
|
||||
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number'],
|
||||
'target_fields': [{'field_id': 'customer-id', 'field_code': 'customer_part_number'}]},
|
||||
{'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['part_number'],
|
||||
'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}]},
|
||||
{'column_index': 3, 'extractor_key': 'direct', 'target_field_codes': ['qty'],
|
||||
'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}]},
|
||||
],
|
||||
}, published_at=datetime.utcnow(),
|
||||
)
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [],
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}],
|
||||
})
|
||||
db.session.add(profile)
|
||||
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='profile-worker',
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_order_extraction.execute_order_extraction_workflow',
|
||||
return_value=([], {'workflow_run_id': 'wf-profile', 'execution_mode': 'dify'}),
|
||||
) 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})
|
||||
|
||||
execute.assert_called_once()
|
||||
manifest = json.loads(execute.call_args.kwargs['run'].input_snapshot_json and build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest'])
|
||||
assert manifest['structured_table_candidates'] == []
|
||||
assert submit.call_args.kwargs['orders'] == []
|
||||
|
||||
|
||||
def test_profile_layout_html_is_not_sent_to_dify(app):
|
||||
"""Profile 不完整而回退 Dify 时,Manifest 只能携带紧凑候选,不能含坐标或原始 HTML。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-TOKEN')
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'issues': [],
|
||||
'tables': [{
|
||||
'table_id': 'table-secret', 'page_no': 1,
|
||||
'bbox': {'x0': 1, 'y0': 2, 'x1': 3, 'y1': 4},
|
||||
'html': '<table><tr><td>RAW-LAYOUT-SECRET</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
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 = run.extraction_plan.units[0]
|
||||
|
||||
manifest = json.loads(build_order_extraction_workflow_inputs(run, unit=unit)['execution_manifest'])
|
||||
|
||||
assert 'layout_snapshot' not in manifest['document']
|
||||
assert 'layout_schema_candidates' not in manifest['document']
|
||||
# 表格文字可作为 TSV 上下文提供给 LLM;布局 HTML 与坐标/证据内部标识不得泄漏。
|
||||
assert 'RAW-LAYOUT-SECRET' in manifest['document']['extracted_text']
|
||||
assert '<table' not in repr(manifest).lower()
|
||||
assert "'bbox'" not in repr(manifest)
|
||||
assert 'cell_id' not in repr(manifest)
|
||||
assert 'evidence_ref' not in repr(manifest)
|
||||
|
||||
|
||||
def test_multiple_profile_tables_fall_back_to_dify_instead_of_merging_orders(app):
|
||||
"""一个文档多张表命中 Profile 时不得自动合并成一张订单,必须交模型/复核拆单。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='PROFILE-MULTI')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
|
||||
return_value={
|
||||
'matched': True, 'blocking': False, 'issues': [],
|
||||
'tables': [{'rows': []}, {'rows': []}],
|
||||
},
|
||||
):
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
|
||||
|
||||
assert build_deterministic_unit_orders(run, unit=unit) is None
|
||||
|
||||
|
||||
def test_unit_manifest_never_contains_sibling_document(app):
|
||||
@@ -635,8 +944,7 @@ def test_unit_manifest_never_contains_sibling_document(app):
|
||||
run, unit=unit,
|
||||
)['execution_manifest'])
|
||||
|
||||
assert len(manifest['documents']) == 1
|
||||
assert manifest['documents'][0]['document']['document_id'] == first.id
|
||||
assert manifest['document']['document_id'] == first.id
|
||||
assert 'SIBLING-SECRET-CONTENT' not in repr(manifest)
|
||||
|
||||
|
||||
@@ -683,12 +991,6 @@ def test_worker_runs_dify_units_with_frozen_concurrency_limit(app):
|
||||
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],
|
||||
@@ -736,12 +1038,6 @@ 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],
|
||||
@@ -791,12 +1087,6 @@ def test_worker_persists_successful_units_when_one_unit_exhausts_retries(app):
|
||||
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],
|
||||
@@ -848,18 +1138,11 @@ def test_worker_blocks_model_calls_when_frozen_unit_budget_is_exceeded(app):
|
||||
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],
|
||||
)
|
||||
run.provider_config_json = {**dict(run.provider_config_json or {}), 'max_model_units': 1}
|
||||
db.session.commit()
|
||||
job = claim_next_job(
|
||||
domain='shipping_notice', job_types=[JobType.SHIPPING_ORDER_EXTRACTION],
|
||||
|
||||
Reference in new issue
Block a user