feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

@@ -0,0 +1,120 @@
"""
backend/tests/performance/test_shipping_conversation_processing_load.py
用途:会话多任务 processing 投影与统一提交的负载冒烟(阶段 5)。
依赖:project_conversation_processing、submit_order_extraction、ShippingOrderProcessingRun。
逻辑:同会话植入约 20 个 OT;断言投影耗时门槛与结果稳定;提交幂等重放不增 Run。
"""
from __future__ import annotations
import time
import uuid
from datetime import datetime
from app import db
from app.models import ShippingOrderProcessingRun
from app.services.shipping_notice.conversation_processing_projection import (
project_conversation_processing,
)
from app.services.shipping_notice.order_extraction_run_service import (
submit_order_extraction,
)
from app.services.shipping_notice.order_schema.runtime import published_version
from tests.test_shipping_order_extraction_runs import _seed_run_input
def _seed_parallel_runs(*, user, agent, session, count: int = 20) -> list[ShippingOrderProcessingRun]:
"""为同一会话轻量写入多个用户可见任务(跳过完整 Intake 解析链路)。"""
schema_version = published_version()
runs: list[ShippingOrderProcessingRun] = []
now = datetime.utcnow()
for index in range(count):
run_no = f'SNER-LOAD-{index:02d}-{uuid.uuid4().hex[:6].upper()}'
status = 'queued' if index % 3 == 0 else ('failed' if index % 3 == 1 else 'completed')
lifecycle = 'open' if status == 'queued' else ('frozen' if status == 'failed' else 'closed')
run = ShippingOrderProcessingRun(
run_no=run_no,
user_task_no=f'OT-{run_no}',
user_id=user.id,
owner_agent_id=agent.id,
parser_engine_version='load-test',
parser_policy_version='load-test',
auto_freeze_policy_json={'enabled': False},
conversation_id=session.session_id,
schema_version_id=schema_version.id,
request_snapshot_hash=f'hash-{index}-{uuid.uuid4().hex}',
request_snapshot_json={'intakes': []},
input_snapshot_hash=f'hash-{index}-{uuid.uuid4().hex}',
input_snapshot_json={'intakes': []},
idempotency_key=f'idem-load-{index}-{uuid.uuid4().hex}',
status=status,
phase=status,
input_lifecycle=lifecycle,
input_frozen_at=None if lifecycle == 'open' else now,
submission_ordinal=index + 1,
created_at=now,
updated_at=now,
last_activity_at=now,
)
db.session.add(run)
runs.append(run)
db.session.commit()
return runs
def test_processing_projection_for_twenty_tasks_meets_latency_budget(app):
"""约 20 个 OT 投影可重入;单次 P95 门槛放宽为 < 500ms(本地 SQLite 冒烟)。"""
with app.app_context():
user, agent, session, _intake, _ = _seed_run_input(suffix='PROC-LOAD')
_seed_parallel_runs(user=user, agent=agent, session=session, count=20)
latencies_ms: list[float] = []
summaries = []
for _ in range(10):
started = time.perf_counter()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
)
latencies_ms.append((time.perf_counter() - started) * 1000)
summaries.append(projection['summary']['total_tasks'])
assert summaries == [20] * 10
p95 = sorted(latencies_ms)[int(0.95 * (len(latencies_ms) - 1))]
assert p95 < 500, f'processing P95 {p95:.1f}ms exceeds 500ms budget; samples={latencies_ms}'
def test_submission_idempotent_replay_stays_under_latency_budget(app):
"""同 submission_id 连续重放不增 Run,且单次 < 800ms。"""
with app.app_context():
user, agent, session, intake, _ = _seed_run_input(suffix='SUB-LOAD')
first = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-LOAD-IDEM-1',
upload_batch_id=intake.upload_batch_id,
)
db.session.commit()
latencies_ms: list[float] = []
for _ in range(5):
started = time.perf_counter()
replay = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
submission_id='SUB-LOAD-IDEM-1',
upload_batch_id=intake.upload_batch_id,
)
latencies_ms.append((time.perf_counter() - started) * 1000)
db.session.commit()
assert replay['reused'] is True
assert replay['run_no'] == first['run_no']
assert ShippingOrderProcessingRun.query.count() == 1
p95 = sorted(latencies_ms)[int(0.95 * (len(latencies_ms) - 1))]
assert p95 < 800, f'submission replay P95 {p95:.1f}ms exceeds 800ms; samples={latencies_ms}'
@@ -0,0 +1,50 @@
"""
backend/tests/performance/test_shipping_xfa_extraction_load.py
用途:阶段 6 XFA 解析资源上限与超时冒烟(不声称生产 5 日 shadow 已完成)。
依赖:xfa_dataset 安全解析与默认资源上限。
逻辑:构造超限 XML / 正常小样本;断言超限 fail-closed 且正常样本在预算内完成。
"""
from __future__ import annotations
import time
import pytest
from app.services.shipping_notice.document_layout.xfa_dataset import (
XfaDatasetParseError,
parse_xfa_datasets,
)
def _minimal_datasets_xml(*, depth: int = 2, nodes: int = 8) -> bytes:
"""生成可控深度/节点数的最小 datasets XML。"""
body = '<HEADER><EBELN>4510039227</EBELN></HEADER>'
open_tags = ''.join(f'<L{i}>' for i in range(depth))
close_tags = ''.join(f'</L{i}>' for i in reversed(range(depth)))
extras = ''.join(f'<N{i}>v</N{i}>' for i in range(max(0, nodes - depth - 2)))
xml = (
'<?xml version="1.0"?>'
f'<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">'
f'<xfa:data><data>{open_tags}{body}{extras}{close_tags}</data></xfa:data>'
f'</xfa:datasets>'
)
return xml.encode('utf-8')
def test_xfa_parse_respects_node_limit_fail_closed():
"""节点超限在限制点终止,不拖垮 Worker。"""
xml = _minimal_datasets_xml(depth=3, nodes=80)
with pytest.raises(XfaDatasetParseError):
parse_xfa_datasets(xml, limits={'max_xml_nodes': 20, 'max_xml_depth': 64, 'max_line_rows': 2000})
def test_xfa_normal_sample_parses_within_latency_budget():
"""正常小样本解析应在本地冒烟预算内完成(<< 30s)。"""
xml = _minimal_datasets_xml(depth=2, nodes=10)
started = time.perf_counter()
result = parse_xfa_datasets(xml, limits={'max_xml_nodes': 100000, 'max_xml_depth': 64, 'max_line_rows': 2000})
elapsed = time.perf_counter() - started
assert result is not None
assert elapsed < 5.0