refactor(agent, shipping): 简化代理模型并完善订单抽取业务

- 移除 Agent 的 exposure_mode 与 internal_executor 相关逻辑,清理关联的过滤、序列化代码
- 删除废弃的 AgentRuntimeBinding 模型及其依赖
- 新增订单抽取上传批次、请求快照等数据库迁移与业务逻辑
- 修复附件完整性检测、订单抽取状态映射问题
- 更新多语言错误文案与前端单元测试配置
- 清理平台配置中不再使用的暴露模式配置
This commit is contained in:
hugo committed 2026-07-28 20:25:48 +08:00
1 parent 1f3ecb87b7
commit 61ac6403c4
159 files changed
+12883 -5099

No files matched your search

+289 -66
View File
@@ -8,6 +8,8 @@ backend/tests/test_shipping_notice_intakes.py
from __future__ import annotations
import threading
import time
from datetime import datetime
from unittest.mock import patch
@@ -932,6 +934,186 @@ def _seed_parsed_intake(user_id: int, *, intake_no: str = 'SNI-TEST-0001', hash_
return asset, intake
def test_run_intake_parse_for_pdf_uses_preview_and_creates_no_documents(app, shipping_user, monkeypatch):
"""普通文件上传只写快览,深度抽取与 Document 物化必须留给发送阶段。"""
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-PREVIEW')
asset.original_filename = 'order.pdf'
asset.mime_type = 'application/pdf'
intake.parse_status = 'parsing'
db.session.commit()
calls: list[dict] = []
def _preview_result(_asset, **kwargs):
calls.append(kwargs)
return NoticeIntakeResult(
filename='order.pdf', source_type='pdf', source_file_type='application/pdf',
text='', warnings=[], meta={'file_type': 'pdf', 'content_mode': 'preview'},
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
)
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
_preview_result,
)
result = run_intake_parse(intake, asset)
assert result['status'] == 'parsed'
assert calls == [{
'eml_attachment_mode': 'preview', 'retain_payloads': False, 'preview_only': True,
}]
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake.id).count() == 0
def test_materialize_single_file_reextracts_deeply_after_send(app, shipping_user, monkeypatch):
"""发送阶段物化普通文件时必须重新走深度抽取,而不是复用上传快览空文本。"""
from app.services.shipping_notice.order_extraction_materialization import (
ensure_order_extraction_input_documents,
)
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PDF-MATERIALIZE')
asset.original_filename = 'order.pdf'
asset.mime_type = 'application/pdf'
db.session.commit()
calls: list[dict] = []
def _deep_result(_asset, **kwargs):
calls.append(kwargs)
return NoticeIntakeResult(
filename='order.pdf', source_type='pdf', source_file_type='application/pdf',
text='PO Number: 4510039227\\nSKU-A qty 1', warnings=[], meta={'file_type': 'pdf'},
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_materialization.extract_notice_from_asset',
_deep_result,
)
persisted: list[NoticeIntakeResult] = []
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_materialization.persist_intake_documents',
lambda **kwargs: persisted.append(kwargs['result']) or {'document_count': 1},
)
ensure_order_extraction_input_documents(
intakes=[intake], attachment_selection={}, schema_definition={'fields': []},
)
assert calls == [{'eml_attachment_mode': 'deep'}]
assert len(persisted) == 1
assert persisted[0].text.startswith('PO Number:')
def test_selected_eml_attachments_use_bounded_parallel_deep_extraction(app, shipping_user, monkeypatch):
"""首轮附件深度抽取最多并发 2,ORM 持久化仍留在调用线程处理。"""
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
import app.services.shipping_notice.order_extraction_materialization as materialization
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-MATERIALIZE')
asset.original_filename = 'orders.eml'
asset.mime_type = 'message/rfc822'
db.session.commit()
active = 0
peak = 0
lock = threading.Lock()
def _preview_result(_asset, **kwargs):
assert kwargs == {'eml_attachment_mode': 'preview', 'retain_payloads': True}
return NoticeIntakeResult(
filename='orders.eml', source_type='email', source_file_type='message/rfc822',
text='mail preview', warnings=[],
meta={'attachments': [
{
'attachment_key': f'order-{index}.pdf', 'filename': f'order-{index}.pdf',
'mime_type': 'application/pdf', '_payload_bytes': f'pdf-{index}'.encode(),
}
for index in range(3)
]},
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
)
def _deep_extract(*, payload, filename, mime_type, flask_app):
nonlocal active, peak
assert flask_app is app
with lock:
active += 1
peak = max(peak, active)
time.sleep(0.03)
with lock:
active -= 1
return f'text:{filename}', {'warnings': []}
monkeypatch.setattr(materialization, 'extract_notice_from_asset', _preview_result)
monkeypatch.setattr(materialization, '_parse_attachment_payload', _deep_extract)
result = materialization._build_selected_eml_result(
intake=intake,
parent_asset=asset,
selected_attachment_keys={'order-0.pdf', 'order-1.pdf', 'order-2.pdf'},
max_concurrency=2,
)
assert peak == 2
assert [item['extracted_text'] for item in result.meta['attachments']] == [
'text:order-0.pdf', 'text:order-1.pdf', 'text:order-2.pdf',
]
def test_selected_normal_files_use_global_bounded_parallel_extraction(app, shipping_user, monkeypatch):
"""不同普通文件共享首轮并发预算,完成顺序不得改变主线程持久化顺序。"""
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
import app.services.shipping_notice.order_extraction_materialization as materialization
with app.app_context():
first_asset, first_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-1')
second_asset, second_intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-PARALLEL-PDF-2')
first_asset.original_filename = 'first.pdf'
second_asset.original_filename = 'second.pdf'
first_asset.mime_type = second_asset.mime_type = 'application/pdf'
db.session.commit()
active = 0
peak = 0
lock = threading.Lock()
persisted: list[str] = []
def _deep_result(*, parent_asset, flask_app):
nonlocal active, peak
assert flask_app is app
with lock:
active += 1
peak = max(peak, active)
time.sleep(0.03)
with lock:
active -= 1
return NoticeIntakeResult(
filename=parent_asset.original_filename, source_type='pdf', source_file_type='application/pdf',
text='PO 4510000001', warnings=[], meta={}, content_hash=str(parent_asset.content_hash),
file_size=12, status='accepted', saved_path=None,
)
monkeypatch.setattr(materialization, '_build_single_file_result_in_thread', _deep_result)
monkeypatch.setattr(
materialization,
'persist_intake_documents',
lambda **kwargs: persisted.append(kwargs['result'].filename) or {'document_count': 1},
)
materialization.ensure_order_extraction_input_documents(
intakes=[first_intake, second_intake],
attachment_selection={'max_initial_concurrency': 2},
schema_definition={'fields': []},
)
assert peak == 2
assert persisted == ['first.pdf', 'second.pdf']
def test_create_batch_from_intakes_marks_consumed_and_links_task(app, shipping_user, monkeypatch):
with app.app_context():
asset, intake = _seed_parsed_intake(shipping_user.id)
@@ -2461,6 +2643,51 @@ def test_recover_stale_parse_job_resets_stuck_parsing_intake(app, shipping_user)
assert finished.status == 'success'
def test_recover_stale_order_extraction_job_requeues_run(app, shipping_user):
"""订单抽取 Worker 退出后,超时回收须使 Job 和 Run 一起回到可重试状态。"""
with app.app_context():
from datetime import timedelta
from app.jobs.types import JobType
from app.models import Job, ShippingOrderExtractionRun
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
run = ShippingOrderExtractionRun(
run_no='SNER-STALE-RECOVERY',
user_id=shipping_user.id,
owner_agent_id=shipping_user.id,
conversation_id='stale-recovery-test',
schema_version_id=1,
input_snapshot_hash='stale-recovery-hash',
input_snapshot_json={'intakes': []},
idempotency_key='stale-recovery-idempotency-key',
status='processing',
phase='deterministic_parsing',
)
db.session.add(run)
db.session.flush()
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_ORDER_EXTRACTION.value,
status='running',
business_ref=run.run_no,
payload_json={'run_no': run.run_no},
attempts=1,
max_attempts=3,
started_at=datetime.utcnow() - timedelta(hours=1),
locked_at=datetime.utcnow() - timedelta(hours=1),
locked_by='dead-worker',
)
db.session.add(job)
db.session.commit()
count, _ = recover_stale_shipping_notice_jobs()
assert count >= 1
db.session.expire_all()
assert db.session.get(Job, job.id).status == 'queued'
assert db.session.get(ShippingOrderExtractionRun, run.id).status == 'queued'
def test_recover_exhausted_parse_job_marks_intake_parse_failed_and_clears_stage2(
app, shipping_user,
):
@@ -2775,7 +3002,7 @@ def test_stale_parse_lease_cannot_overwrite_after_recovery(app, shipping_user, m
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _asset: NoticeIntakeResult(
lambda _asset, **_kwargs: NoticeIntakeResult(
filename='notice.txt',
source_type='manual',
source_file_type='text/plain',
@@ -2952,7 +3179,7 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _asset: NoticeIntakeResult(
lambda _asset, **_kwargs: NoticeIntakeResult(
filename='notice.txt',
source_type='manual',
source_file_type='text/plain',
@@ -2976,9 +3203,10 @@ def test_parse_writeback_skips_cancel_during_extract(app, shipping_user, monkeyp
def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monkeypatch):
"""
FileAsset → run_intake_parse → DB:EML 附件独立文本应持久化进 structured_result_json。
FileAsset → run_intake_parse → DB:shipping_notice 用途的 EML 上传仅持久化附件目录。
核心逻辑:mock 读取资产字节为含文本附件的 EML,断言 attachment_count 与 extracted_text 落库。
核心逻辑:阶段 1 上传快览只保留邮件头/正文/附件目录,不得把附件全文、派生资产或 Document
混入 Intake 摘要;详情接口也只能回放目录事实。
"""
from email.message import EmailMessage
@@ -3049,14 +3277,18 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk
assert structured.get('email', {}).get('subject') == 'Intake EML Persist'
attachments = structured.get('attachments') or []
assert len(attachments) == 2
texts = {row['filename']: row.get('extracted_text') for row in attachments}
assert 'PO-PERSIST-LINE-001' in str(texts.get('order-a.txt') or '')
assert 'PO-PERSIST-LINE-002' in str(texts.get('order-b.txt') or '')
assert 'PO-PERSIST-LINE-001' in str(refreshed.extracted_text or '')
by_name = {str(row.get('filename') or ''): row for row in attachments}
assert by_name['order-a.txt'].get('parse_status') == 'ready_for_extraction'
assert by_name['order-b.txt'].get('parse_status') == 'ready_for_extraction'
assert by_name['order-a.txt'].get('ready_for_extraction') is True
assert by_name['order-b.txt'].get('ready_for_extraction') is True
assert all('extracted_text' not in row for row in attachments)
assert 'PO-PERSIST-LINE-001' not in str(refreshed.extracted_text or '')
expected_parser = str(app.config.get('SHIPPING_NOTICE_PARSER_VERSION') or 'v6')
assert refreshed.parser_version == expected_parser
assert all('_payload_bytes' not in row for row in attachments)
assert all(row.get('asset_no') for row in attachments)
assert all(row.get('asset_no') is None for row in attachments)
assert all(row.get('document_id') is None for row in attachments)
from app.services.shipping_notice.intake_service import serialize_intake
@@ -3067,17 +3299,17 @@ def test_run_intake_parse_persists_eml_attachment_texts(app, shipping_user, monk
full = serialize_intake(refreshed, asset=asset, include_parse_texts=True)
full_atts = (full.get('parse_summary') or {}).get('attachments') or []
assert 'PO-PERSIST-LINE-001' in str(full_atts[0].get('extracted_text') or '')
assert full_atts and 'extracted_text' not in full_atts[0]
def test_run_intake_parse_persists_attached_multipart_and_detail_api(
app, client, shipping_user, monkeypatch,
):
"""
FileAsset → run_intake_parse → DB → 详情接口:附件型 multipart 独立文本与超深深 skipped 须落库返回。
FileAsset → run_intake_parse → DB → 详情接口:上传快览只保留附件目录,不递归落 multipart 子内容。
核心逻辑:mixed 容器内 plain+html 均持久化;嵌套容器超限为 skipped 并带 depth warning;
status 瘦身、详情含全文。
核心逻辑:附件型 multipart 只作为单个目录项展示;嵌套内容和深度警告不应以附件全文形式写入
shipping_notice Intake 的摘要或详情接口。
"""
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
@@ -3151,18 +3383,12 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
for row in (structured.get('attachments') or [])
}
assert 'bundle-persist.mime' in by_name
assert 'inner-depth.mime' in by_name
bundle_text = str(by_name['bundle-persist.mime'].get('extracted_text') or '')
assert 'PLAIN-PO-101' in bundle_text
assert 'HTML-PO-202' in bundle_text
assert by_name['bundle-persist.mime'].get('parse_status') == 'parsed'
assert by_name['inner-depth.mime'].get('parse_status') == 'skipped'
warnings = list(structured.get('warnings') or []) + list(
by_name['inner-depth.mime'].get('warnings') or []
)
assert any(str(w).startswith('eml_nesting_depth_exceeded:') for w in warnings)
assert 'PLAIN-PO-101' in str(refreshed.extracted_text or '')
assert 'HTML-PO-202' in str(refreshed.extracted_text or '')
assert 'inner-depth.mime' not in by_name
assert by_name['bundle-persist.mime'].get('parse_status') == 'directory_only'
assert by_name['bundle-persist.mime'].get('ready_for_extraction') is False
assert by_name['bundle-persist.mime'].get('catalog_reason') == 'unknown_binary'
assert 'PLAIN-PO-101' not in str(refreshed.extracted_text or '')
assert 'HTML-PO-202' not in str(refreshed.extracted_text or '')
lean = serialize_intake(refreshed, asset=asset, include_parse_texts=False)
lean_bundle = next(
@@ -3178,8 +3404,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
for row in ((full.get('parse_summary') or {}).get('attachments') or [])
if row.get('filename') == 'bundle-persist.mime'
)
assert 'PLAIN-PO-101' in str(full_bundle.get('extracted_text') or '')
assert 'HTML-PO-202' in str(full_bundle.get('extracted_text') or '')
assert 'extracted_text' not in full_bundle
headers = {'Authorization': f'Bearer {issue_local_access_token(shipping_user)}'}
@@ -3193,8 +3418,7 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
status_atts = (status_item.get('parse_summary') or {}).get('attachments') or []
status_bundle = next(row for row in status_atts if row.get('filename') == 'bundle-persist.mime')
assert 'extracted_text' not in status_bundle
status_inner = next(row for row in status_atts if row.get('filename') == 'inner-depth.mime')
assert status_inner.get('parse_status') == 'skipped'
assert all(row.get('filename') != 'inner-depth.mime' for row in status_atts)
detail_res = client.get(
'/api/workspace/shipping-notice/intakes/SNI-EML-MP-PERSIST-001',
@@ -3203,10 +3427,8 @@ def test_run_intake_parse_persists_attached_multipart_and_detail_api(
assert detail_res.status_code == 200
detail_atts = (detail_res.get_json()['data'].get('parse_summary') or {}).get('attachments') or []
detail_bundle = next(row for row in detail_atts if row.get('filename') == 'bundle-persist.mime')
assert 'PLAIN-PO-101' in str(detail_bundle.get('extracted_text') or '')
assert 'HTML-PO-202' in str(detail_bundle.get('extracted_text') or '')
detail_inner = next(row for row in detail_atts if row.get('filename') == 'inner-depth.mime')
assert detail_inner.get('parse_status') == 'skipped'
assert 'extracted_text' not in detail_bundle
assert all(row.get('filename') != 'inner-depth.mime' for row in detail_atts)
def test_intake_status_api_strips_texts_detail_returns_full(app, client):
@@ -3413,8 +3635,10 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
app, shipping_user, monkeypatch,
):
"""
上传预处理验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document;
点击发送前不生成 Candidate;各 PDF 独立 FileAsset;重试不膨胀。
上传预处理验收:EML 快览阶段不创建附件 Document、派生资产或布局任务。
核心逻辑:即使附件是可解析 PDF,shipping_notice 上传阶段也只登记目录与可解析标记;
真正的 Document/资产/布局物化必须等到点击发送后的计划链路。
"""
from email.message import EmailMessage
@@ -3489,7 +3713,7 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
if str(w).startswith('document_candidate_persist_failed')
]
assert not persist_warns, persist_warns
assert first.get('document_count') == 4, first
assert first.get('document_count') == 0, first
docs = (
db.session.query(ShippingNoticeDocument)
.filter_by(intake_id=refreshed_intake.id)
@@ -3511,26 +3735,24 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
.all()
)
assert len(docs) == 4, (first, refreshed_intake.parse_warnings_json)
body_docs = [d for d in docs if d.document_type == 'email_body']
assert len(body_docs) == 1
assert body_docs[0].classification == 'email_context'
pdf_docs = [d for d in docs if d.document_type == 'attachment']
assert len(pdf_docs) == 3
assert all(d.classification == 'order_notice' for d in pdf_docs)
assert all(d.asset_id for d in pdf_docs)
assert len(docs) == 0, (first, refreshed_intake.parse_warnings_json)
assert len(cands) == 0
assert len(children) == 3
assert len({c.content_hash for c in children}) == 3
assert len(children) == 0
from app.models import Job, ShippingDocumentLayoutVersion
assert ShippingDocumentLayoutVersion.query.filter(
ShippingDocumentLayoutVersion.document_id.in_([item.id for item in pdf_docs]),
).count() == 3
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
assert ShippingDocumentLayoutVersion.query.count() == 0
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0
structured = refreshed_intake.structured_result_json or {}
assert structured.get('attachment_count') == 3
assert structured.get('ready_attachment_count') == 3
rows = structured.get('attachments') or []
assert {row.get('filename') for row in rows} == {f'{po}.pdf' for po in markers}
assert all(row.get('parse_status') == 'ready_for_extraction' for row in rows)
assert all('extracted_text' not in row for row in rows)
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
assert detail['document_count'] == 4
assert detail['document_count'] == 0
assert detail['candidate_count'] == 0
intake2 = (
@@ -3549,22 +3771,22 @@ def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candid
.one()
.id
)
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 0
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0
assert ShippingDocumentLayoutVersion.query.count() == 3
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 3
assert ShippingDocumentLayoutVersion.query.count() == 0
assert Job.query.filter_by(job_type='shipping_document_layout').count() == 0
assert (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
.count()
== 3
== 0
)
def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak(
app, shipping_user, monkeypatch,
):
"""HTML 正文表格应生成独立布局版本,临时 HTML 不得进入 Intake 摘要或 Dify 文档正文。"""
"""HTML 正文表格快览只保留脱敏摘要,不在上传阶段生成 Document 或布局版本。"""
from email.message import EmailMessage
from io import BytesIO
@@ -3607,18 +3829,19 @@ def test_run_intake_parse_persists_sanitized_email_html_layout_without_meta_leak
result = run_intake_parse(intake, parent)
db.session.expire_all()
body = ShippingNoticeDocument.query.filter_by(
intake_id=intake.id, document_type='email_body',
).one()
version = ShippingDocumentLayoutVersion.query.filter_by(document_id=body.id).one()
structured = db.session.get(ShippingNoticeIntake, intake.id).structured_result_json
assert result['status'] == 'parsed'
assert version.status == 'needs_review'
assert version.payload_json['layout_candidate']['parser']['name'] == 'eml-html-dom'
assert 'SECRET' not in repr(version.payload_json)
assert 'body_html_tables' not in repr(structured)
assert '<table' not in repr(structured)
assert ShippingNoticeDocument.query.filter_by(intake_id=intake.id).count() == 0
assert ShippingDocumentLayoutVersion.query.count() == 0
email_summary = (structured.get('email') or {})
html_tables = email_summary.get('body_html_tables') or []
assert len(html_tables) == 1
assert '<table' in str(html_tables[0] or '')
assert 'script' not in str(html_tables[0] or '').lower()
assert 'SECRET' not in repr(structured)
assert structured.get('document_count') == 0
assert structured.get('candidate_count') == 0
def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
@@ -4325,7 +4548,7 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.extract_notice_from_asset',
lambda _a: NoticeIntakeResult(
lambda _a, **_kwargs: NoticeIntakeResult(
filename='clear.eml',
source_type='email',
source_file_type='message/rfc822',