feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

@@ -1,9 +1,10 @@
"""
jobs/handlers/shipping_auto_progress.py
用途:消费 P0-3 Task 级 AutoProgress Job。
用途:终态化历史 APX AutoProgress Job。
依赖:JobContext、auto_progress_controller。
逻辑:Job 已由通用队列领取为 running;本 Handler 只委托正式控制器执行一个 Gate,不再调用旧全链路 facade。
逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX
Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。
"""
from __future__ import annotations
@@ -16,7 +17,7 @@ from app.services.shipping_notice.auto_progress_controller import run_auto_progr
@register_handler(JobType.SHIPPING_AUTO_PROGRESS)
def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None:
"""执行一个正式 Gate;payload 必须含队列注入的 job_id。"""
"""终态化历史 APX Job;payload 必须含队列注入的 job_id。"""
raw_job_id = payload.get('job_id')
if not raw_job_id:
raise RuntimeError('missing_job_id_for_shipping_auto_progress')
@@ -5,7 +5,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、
process_gate_error_sanitizer。
逻辑:由 shipping worker 领取;技术失败按该 Attempt 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队;
次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal);
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
waiting_external 先结束当前 Job 再延迟入队新 Job;
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
@@ -14,8 +14,6 @@ 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
from app.jobs.queue import fail_job, finish_job
@@ -30,80 +28,32 @@ from app.services.shipping_notice.process_gate_job_service import (
)
from app.services.shipping_notice.process_gate_service import complete_gate_attempt
# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。
_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120)
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 _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(
def _finalize_attempt_after_failure(
*,
attempt: ShippingProcessGateAttempt,
exc: BaseException,
) -> None:
"""
技术重试耗尽:将 Attempt/Gate 收口为 failed_terminal。
单次门禁执行失败:结束当前 Attempt,并将 Gate 收口为可人工恢复阻断。
核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。
"""
safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_retry_exhausted'
safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_failure'
if attempt.status == 'queued':
attempt.status = 'running'
db.session.flush()
complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='failed_terminal',
outcome='blocked_retryable',
# 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure
blocking_reason_code='technical_retry_exhausted',
blocking_reason_code='technical_failure_present',
blocking_reason_json={
'reason_code': 'technical_retry_exhausted',
'reason_code': 'technical_failure_present',
'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',
effective_result_json={'findings': [], 'error': 'technical_failure'},
output_snapshot={'error': safe},
error_code='TECHNICAL_FAILURE',
error_summary=safe,
)
@@ -141,6 +91,9 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
try:
result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id)
except Exception as exc:
# claim/execute 可能已经让 SQLAlchemy 事务进入 aborted 状态(例如死锁)。
# 任何失败收口前必须先回滚,避免把 Job 标记失败后留下 queued Attempt/Gate。
db.session.rollback()
attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
gate = None
gate_status = None
@@ -163,45 +116,15 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
db.session.commit()
return
# [STEP] 技术失败:按 Attempt 下 failed Job 累计判定,禁止因 force_new 无限重试。
max_attempts = max(
int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3),
1,
)
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'
# 本次 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,
error=safe_error,
retryable=False,
owned_attempt=owned_attempt,
)
_strip_legacy_retry_count_from_input_snapshot(attempt)
attempt.status = 'queued'
attempt.job_id = None
attempt.worker_id = None
attempt.lease_token = None
attempt.lease_expires_at = None
if gate is not None and gate.status == 'running':
gate.status = 'queued'
db.session.flush()
enqueue_gate_attempt_job(
attempt_id=attempt_id,
delay_seconds=delay,
force_new=True,
)
db.session.commit()
return
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
# 先把 Attempt/Gate/Execution 收口,再独立结束 Job;即使 Runner 随后兜底标记
# Job failed,也不会再留下 failed Job + queued 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()
fresh_attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
if fresh_attempt is not None and fresh_attempt.status in {'queued', 'running'}:
_finalize_attempt_after_failure(attempt=fresh_attempt, exc=exc)
db.session.commit()
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
return
finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)