feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估

- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
This commit is contained in:
hugo committed 2026-08-02 19:26:35 +08:00
1 parent cef3d5b26a
commit 3a9fbac2fc
226 files changed
+25010 -2098

No files matched your search

@@ -160,6 +160,7 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
'issues': ['shipping_document_layout_input_unsupported'],
}
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
final_status = str(db.session.get(ShippingDocumentLayoutVersion, version.id).status or 'failed')
record_layout_document_progress(document_id=int(document.id), event_code='layout_parsing_completed')
_layout_job_audit(
event_type='document_layout_job_completed',
@@ -172,7 +173,10 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
'status': str(snapshot.get('status') or 'failed'),
'timings': {key: int(value) for key, value in timings.items()},
},
message='文档版面解析完成', owned_attempt=owned_attempt,
message=(
'文档版面解析完成' if final_status in {'ready', 'needs_review'}
else '文档版面解析失败'
), owned_attempt=owned_attempt,
)
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
@@ -4,8 +4,9 @@ backend/app/jobs/handlers/shipping_process_gate.py
用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。
依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、
process_gate_error_sanitizer。
逻辑:由 shipping worker 领取;技术失败按 Attempt 累计次数 + 5s/30s/120s 退避重新入队;
逻辑:由 shipping worker 领取;技术失败按该 Attempt 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队;
次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal);
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
waiting_external 先结束当前 Job 再延迟入队新 Job;
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
"""
@@ -13,6 +14,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
from __future__ import annotations
from flask import current_app
from sqlalchemy import or_
from app import db
from app.jobs.context import JobContext
@@ -22,33 +24,57 @@ from app.jobs.types import JobType
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text
from app.services.shipping_notice.process_gate_job_service import (
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
claim_and_run_gate_attempt,
enqueue_gate_attempt_job,
schedule_waiting_external_poll,
)
from app.services.shipping_notice.process_gate_service import complete_gate_attempt
# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。
_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120)
_TECH_RETRY_KEY = 'technical_retry_count'
def _technical_retry_count(attempt: ShippingProcessGateAttempt) -> int:
"""读取 Attempt 上累计的技术失败次数(跨 force_new Job 保留)。"""
snap = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
try:
return max(int(snap.get(_TECH_RETRY_KEY) or 0), 0)
except (TypeError, ValueError):
return 0
def _count_failed_technical_jobs(attempt_id: int) -> int:
"""
统计某 Attempt 已失败的技术 Job 数(含 force_new 的 business_ref 变体)。
核心逻辑:按 business_ref=`attempt:{id}` 或 `attempt:{id}:...` 过滤 failed Job,
作为跨 Job 累计重试次数,避免写入 input_snapshot 破坏 Hash。
Args:
attempt_id: ShippingProcessGateAttempt 主键。
Returns:
已处于 failed 状态的相关 Job 数量。
"""
prefix = f'attempt:{int(attempt_id)}'
return (
Job.query
.filter(
Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN,
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
Job.status == 'failed',
or_(
Job.business_ref == prefix,
Job.business_ref.like(f'{prefix}:%'),
),
)
.count()
)
def _bump_technical_retry_count(attempt: ShippingProcessGateAttempt) -> int:
"""递增并回写技术失败次数,返回递增后的值。"""
snap = dict(attempt.input_snapshot_json) if isinstance(attempt.input_snapshot_json, dict) else {}
next_count = _technical_retry_count(attempt) + 1
snap[_TECH_RETRY_KEY] = next_count
attempt.input_snapshot_json = snap
return next_count
def _strip_legacy_retry_count_from_input_snapshot(attempt: ShippingProcessGateAttempt) -> None:
"""
清理历史误写入 input_snapshot 的 technical_retry_count,避免污染业务输入快照。
核心逻辑:若键存在则删除;不重算 Hash(Hash 应对创建时的业务快照;遗留键本身已破坏一致性,
删除后正文与创建 Hash 仍可能不一致,但后续不再写入新的运行元数据)。
"""
snap = attempt.input_snapshot_json
if not isinstance(snap, dict) or 'technical_retry_count' not in snap:
return
cleaned = {k: v for k, v in snap.items() if k != 'technical_retry_count'}
attempt.input_snapshot_json = cleaned
def _finalize_attempt_after_retry_exhausted(
@@ -68,8 +94,13 @@ def _finalize_attempt_after_retry_exhausted(
complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='failed_terminal',
blocking_reason_code='technical_failure',
blocking_reason_json={'message': safe, 'technical_retry_exhausted': True},
# 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure
blocking_reason_code='technical_retry_exhausted',
blocking_reason_json={
'reason_code': 'technical_retry_exhausted',
'message': safe,
'technical_retry_exhausted': True,
},
effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'},
output_snapshot={'error': safe, 'technical_retry_exhausted': True},
error_code='TECHNICAL_RETRY_EXHAUSTED',
@@ -132,15 +163,16 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
db.session.commit()
return
# [STEP] 技术失败:按 Attempt 累计次数判定,禁止因 force_new Job.attempts=0 无限重试。
# [STEP] 技术失败:按 Attempt 下 failed Job 累计判定,禁止因 force_new 无限重试。
max_attempts = max(
int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3),
1,
)
retries_done = _technical_retry_count(attempt) if attempt is not None else max_attempts
failed_already = _count_failed_technical_jobs(attempt_id) if attempt is not None else max_attempts
safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure'
if attempt is not None and retries_done + 1 < max_attempts:
delay_idx = min(retries_done, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1)
# 本次 fail_job 后累计 = failed_already + 1;未达上限则退避重入队。
if attempt is not None and failed_already + 1 < max_attempts:
delay_idx = min(failed_already, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1)
delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx]
fail_job(
job.id,
@@ -148,7 +180,7 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
retryable=False,
owned_attempt=owned_attempt,
)
_bump_technical_retry_count(attempt)
_strip_legacy_retry_count_from_input_snapshot(attempt)
attempt.status = 'queued'
attempt.job_id = None
attempt.worker_id = None
@@ -167,16 +199,9 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
if attempt is not None:
_strip_legacy_retry_count_from_input_snapshot(attempt)
_finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc)
db.session.commit()
return
finish_job(job.id, result=result, owned_attempt=owned_attempt)
# [STEP] 成功落入 waiting_external:调度下一次 poll Attempt(含超时判定)。
if str((result or {}).get('gate_status') or '') == 'waiting_external':
schedule_waiting_external_poll(
attempt_id=int(attempt_id),
gate_code=str((result or {}).get('gate_code') or ''),
)
db.session.commit()
finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)