fix(shipping-process-gates): 收口技术重试并补齐运维 UI
跨 Job 累计技术失败次数,耗尽后将 Attempt/Gate 置为 failed_terminal; 收缩旧 action_buttons;healthcheck 增加 Worker 领取探针;恢复卡展示责任方与审计,Admin 诊断改主从布局。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
323928626b
commit
cef3d5b26a
15 files changed
+489
-150
No files matched your search
@@ -513,8 +513,8 @@ def workspace_create_shipping_task_from_notice():
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
|
||||
# 旧 action_buttons 业务调用清零:仅保留 human_options 文案提示,不再下发可点击恢复按钮。
|
||||
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': []})
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
@@ -915,9 +915,17 @@ def workspace_match_shipping_inventory(task_no: str):
|
||||
if options is not None:
|
||||
matched['human_options'] = options
|
||||
if 'action_buttons' not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched['action_buttons'] = buttons
|
||||
# [STEP] 已有 ProcessExecution 时不再补充旧 STP 恢复按钮。
|
||||
from app.models import ShippingProcessExecution
|
||||
has_execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.first()
|
||||
) is not None
|
||||
if not has_execution:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched['action_buttons'] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
backend/app/jobs/handlers/shipping_process_gate.py
|
||||
|
||||
用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。
|
||||
依赖:JobContext、process_gate_job_service、jobs.queue finish/fail。
|
||||
逻辑:由 shipping worker 领取;技术失败按 5s/30s/120s 退避重新入队;
|
||||
waiting_external 先结束当前 Job 再延迟入队新 Job(禁止复用仍 running 的 Job);
|
||||
成功进入 waiting_external 时调度下一次 poll Attempt。
|
||||
依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、
|
||||
process_gate_error_sanitizer。
|
||||
逻辑:由 shipping worker 领取;技术失败按 Attempt 累计次数 + 5s/30s/120s 退避重新入队;
|
||||
次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal);
|
||||
waiting_external 先结束当前 Job 再延迟入队新 Job;
|
||||
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,25 +20,85 @@ from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
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 (
|
||||
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 _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 _finalize_attempt_after_retry_exhausted(
|
||||
*,
|
||||
attempt: ShippingProcessGateAttempt,
|
||||
exc: BaseException,
|
||||
) -> None:
|
||||
"""
|
||||
技术重试耗尽:将 Attempt/Gate 收口为 failed_terminal。
|
||||
|
||||
核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。
|
||||
"""
|
||||
safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_retry_exhausted'
|
||||
if attempt.status == 'queued':
|
||||
attempt.status = 'running'
|
||||
db.session.flush()
|
||||
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},
|
||||
effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'},
|
||||
output_snapshot={'error': safe, 'technical_retry_exhausted': True},
|
||||
error_code='TECHNICAL_RETRY_EXHAUSTED',
|
||||
error_summary=safe,
|
||||
)
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_PROCESS_GATE)
|
||||
def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行门禁 Attempt。
|
||||
执行门禁 Attempt;支持部署健康检查探针载荷。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 attempt_id 与 job_id。
|
||||
payload: 须含 attempt_id 与 job_id;healthcheck_probe=True 时仅证明领取能力。
|
||||
"""
|
||||
# [STEP] 部署探针:Worker 领取后立即成功结束,不触碰业务 Attempt。
|
||||
if bool(payload.get('healthcheck_probe')):
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_job_id_for_healthcheck_probe')
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'healthcheck_probe_ok'},
|
||||
owned_attempt=int(job.attempts or 0),
|
||||
)
|
||||
return
|
||||
|
||||
attempt_id = int(payload.get('attempt_id') or 0)
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
@@ -70,17 +132,23 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
db.session.commit()
|
||||
return
|
||||
|
||||
# [STEP] 技术失败:先 fail 当前 Job,再按退避入队新 Job。
|
||||
max_attempts = int(job.max_attempts or 3)
|
||||
if attempt is not None and owned_attempt < max_attempts:
|
||||
delay_idx = min(max(owned_attempt - 1, 0), len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1)
|
||||
# [STEP] 技术失败:按 Attempt 累计次数判定,禁止因 force_new Job.attempts=0 无限重试。
|
||||
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
|
||||
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)
|
||||
delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx]
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc)[:1000],
|
||||
error=safe_error,
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
_bump_technical_retry_count(attempt)
|
||||
attempt.status = 'queued'
|
||||
attempt.job_id = None
|
||||
attempt.worker_id = None
|
||||
@@ -97,7 +165,10 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
db.session.commit()
|
||||
return
|
||||
|
||||
fail_job(job.id, error=str(exc)[:1000], retryable=False, owned_attempt=owned_attempt)
|
||||
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
|
||||
if attempt is not None:
|
||||
_finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc)
|
||||
db.session.commit()
|
||||
return
|
||||
|
||||
finish_job(job.id, result=result, owned_attempt=owned_attempt)
|
||||
|
||||
@@ -6,7 +6,8 @@ services/shipping_notice/process_gate_job_service.py
|
||||
process_gate_service、fulfillment_audit。
|
||||
逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用
|
||||
claim_and_run_gate_attempt;重试/轮询使用 force_new 避免复用 running Job;
|
||||
waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见。
|
||||
waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见;
|
||||
enqueue_process_gate_healthcheck_probe 供部署脚本验证 Worker 真实领取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -54,6 +55,31 @@ def _heartbeat_seconds() -> int:
|
||||
return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS', 15) or 15), 5)
|
||||
|
||||
|
||||
def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int:
|
||||
"""
|
||||
入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。
|
||||
|
||||
核心逻辑:payload.healthcheck_probe=True,handler 领取后直接 finish,不依赖 Attempt。
|
||||
|
||||
Returns:
|
||||
Job 主键。
|
||||
"""
|
||||
business_ref = f'healthcheck:process-gate:{_utc_now().strftime("%Y%m%d%H%M%S")}:{uuid.uuid4().hex[:8]}'
|
||||
return int(
|
||||
enqueue(
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
{'healthcheck_probe': True},
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
business_ref=business_ref,
|
||||
created_by_id=created_by_id,
|
||||
message='Process Gate healthcheck probe',
|
||||
max_attempts=1,
|
||||
dedupe_active=False,
|
||||
commit=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def enqueue_gate_attempt_job(
|
||||
*,
|
||||
attempt_id: int,
|
||||
|
||||
@@ -6,8 +6,8 @@ services/shipping_notice/ui_state.py
|
||||
process_gate_projection(统一 Gate 用户摘要)。
|
||||
逻辑:从 ShippingTask DB 字段经状态机解析 checkpoint/checkpoint_kind/action_buttons,
|
||||
再补充七步流程与可解释 summary(当前待办、暂停原因、下一自动步骤、操作入口、stp_facts);
|
||||
若存在 ProcessExecution 且当前有 blocking Gate,则清空 action_buttons,
|
||||
恢复动作仅由 process_gate 驱动(Gate 为唯一业务真相);
|
||||
若存在 ProcessExecution:阻断时清空 action_buttons;非阻断时仅保留
|
||||
download_excel / mark_manual_uploaded / refresh(恢复动作仅由 process_gate 驱动);
|
||||
批次 UI 仅作会话上传集合摘要,不作为履约写操作面。
|
||||
"""
|
||||
|
||||
@@ -555,9 +555,17 @@ def build_task_ui_state(task: ShippingTask) -> dict[str, Any]:
|
||||
ui = resolve_task_ui_state(task)
|
||||
action_buttons = _action_buttons_for_task(task)
|
||||
process_gate = _process_gate_user_summary_for_task(task)
|
||||
# [STEP] Gate 阻断时旧 action_buttons 不再作为业务恢复真相,避免双卡片/双动作。
|
||||
if isinstance(process_gate, dict) and process_gate.get('current_blocking_gate'):
|
||||
action_buttons = []
|
||||
# [STEP] 存在 ProcessExecution 时恢复动作仅由 process_gate 驱动;
|
||||
# 仅保留非恢复类 STP 动作(下载 Excel / 人工上传凭据 / 刷新)。
|
||||
_non_recovery_action_ids = frozenset({'download_excel', 'mark_manual_uploaded', 'refresh'})
|
||||
if isinstance(process_gate, dict):
|
||||
if process_gate.get('current_blocking_gate'):
|
||||
action_buttons = []
|
||||
else:
|
||||
action_buttons = [
|
||||
button for button in action_buttons
|
||||
if str((button or {}).get('id') or '') in _non_recovery_action_ids
|
||||
]
|
||||
steps = build_shipping_workflow_steps(task, ui.checkpoint)
|
||||
current_index = _derive_current_step_index(task)
|
||||
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
tests/test_shipping_process_gate_retry_cap.py
|
||||
|
||||
用途:验证门禁技术失败跨 force_new Job 累计重试上限,并在耗尽后收口 Attempt/Gate。
|
||||
依赖:Flask testing app、run_shipping_process_gate handler、process_gate_service。
|
||||
逻辑:mock claim_and_run 持续抛错;断言最多 TECHNICAL_RETRIES 次失败后
|
||||
Attempt/Gate 进入 failed_terminal,且不再入队新的重试 Job。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from app import db
|
||||
from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
enqueue_gate_attempt_job,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
|
||||
|
||||
def test_technical_retries_cap_across_force_new_jobs(app):
|
||||
"""跨 Job 累计失败达到上限后必须 failed_terminal,且不再新建 queued Job。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES'] = 3
|
||||
_user, item, version = _seed_workflow_version(suffix='retrycap')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
workflow_item_id=int(item.id),
|
||||
workflow_item_version_id=int(version.id),
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='retry-cap',
|
||||
idempotency_key='retry-cap-1',
|
||||
input_snapshot={'action_code': 'retry_layout_parsing', 'payload': {}},
|
||||
)
|
||||
first_job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id))
|
||||
db.session.commit()
|
||||
attempt_id = int(attempt.id)
|
||||
|
||||
with patch(
|
||||
'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt',
|
||||
side_effect=RuntimeError('boom https://erp.example.com/x?token=abc'),
|
||||
):
|
||||
for round_idx in range(5):
|
||||
attempt_row = db.session.get(ShippingProcessGateAttempt, attempt_id)
|
||||
assert attempt_row is not None
|
||||
if attempt_row.status in {'failed', 'succeeded', 'cancelled'}:
|
||||
break
|
||||
job_id = int(attempt_row.job_id or 0)
|
||||
if job_id <= 0:
|
||||
job_id = enqueue_gate_attempt_job(attempt_id=attempt_id, force_new=True)
|
||||
db.session.commit()
|
||||
job = db.session.get(Job, job_id)
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = 1
|
||||
attempt_row.status = 'running'
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt_row.gate_id))
|
||||
if gate is not None:
|
||||
gate.status = 'running'
|
||||
db.session.commit()
|
||||
|
||||
ctx = MagicMock()
|
||||
ctx.extras = {'worker_label': f'retry-cap-worker-{round_idx}'}
|
||||
run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': job_id})
|
||||
|
||||
attempt_final = db.session.get(ShippingProcessGateAttempt, attempt_id)
|
||||
gate_final = db.session.get(ShippingProcessGate, int(attempt_final.gate_id))
|
||||
assert attempt_final is not None
|
||||
assert attempt_final.status == 'failed'
|
||||
assert gate_final is not None
|
||||
assert gate_final.status == 'failed_terminal'
|
||||
assert attempt_final.error_code == 'TECHNICAL_RETRY_EXHAUSTED'
|
||||
# 敏感 URL 不得原样落库
|
||||
assert 'erp.example.com' not in str(attempt_final.error_summary or '')
|
||||
|
||||
failed_jobs = (
|
||||
Job.query
|
||||
.filter_by(
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||||
status='failed',
|
||||
)
|
||||
.count()
|
||||
)
|
||||
assert failed_jobs == 3
|
||||
queued_jobs = (
|
||||
Job.query
|
||||
.filter_by(
|
||||
domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
job_type=JobType.SHIPPING_PROCESS_GATE.value,
|
||||
status='queued',
|
||||
)
|
||||
.count()
|
||||
)
|
||||
assert queued_jobs == 0
|
||||
assert int(first_job_id) > 0
|
||||
Reference in new issue
Block a user