""" 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 下 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。 """ 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 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 ( SHIPPING_PROCESS_GATE_JOB_DOMAIN, claim_and_run_gate_attempt, enqueue_gate_attempt_job, ) 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( *, 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', # 与 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', error_summary=safe, ) @register_handler(JobType.SHIPPING_PROCESS_GATE) def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None: """ 执行门禁 Attempt;支持部署健康检查探针载荷。 Args: ctx: Worker 上下文。 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 if attempt_id <= 0 or job is None: raise RuntimeError('missing_attempt_id_or_job_id') owned_attempt = int(job.attempts or 0) worker_id = str(ctx.extras.get('worker_label') or f'shipping-gate-{job.id}') try: result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id) except Exception as exc: attempt = db.session.get(ShippingProcessGateAttempt, attempt_id) gate = None gate_status = None if attempt is not None: gate = db.session.get(ShippingProcessGate, int(attempt.gate_id)) gate_status = gate.status if gate else None # [STEP] 外部等待:先结束当前 Job,再清空 job_id 并延迟入队,避免复用 running Job。 if gate_status == 'waiting_external': poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5) finish_job(job.id, result={'status': 'waiting_external_requeued'}, owned_attempt=owned_attempt) if attempt is not None: attempt.job_id = None db.session.flush() enqueue_gate_attempt_job( attempt_id=attempt_id, delay_seconds=poll, force_new=True, ) 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) 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 if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)