""" 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(blocked_retryable),保留人工恢复入口; 不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致; waiting_external 先结束当前 Job 再延迟入队新 Job; external-wait 轮询异常时回滚并按 Gate 现状重排/安静结束,保证轮询链不因瞬时冲突断裂; healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。 """ from __future__ import annotations from flask import current_app 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, schedule_waiting_external_poll, ) from app.services.shipping_notice.process_gate_service import complete_gate_attempt def _finalize_attempt_after_failure( *, attempt: ShippingProcessGateAttempt, exc: BaseException, ) -> None: """ 单次门禁执行失败:结束当前 Attempt,并将 Gate 收口为可人工恢复阻断。 核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。 """ 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='blocked_retryable', # 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure blocking_reason_code='technical_failure_present', blocking_reason_json={ 'reason_code': 'technical_failure_present', 'message': safe, }, effective_result_json={'findings': [], 'error': 'technical_failure'}, output_snapshot={'error': safe}, error_code='TECHNICAL_FAILURE', 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 external_wait_poll_gate_id = int(payload.get('external_wait_poll_gate_id') or 0) if external_wait_poll_gate_id and job is not None: from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll try: result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id) except Exception as exc: # [STEP] 轮询与库存回调可能以相反顺序争抢 Gate 行与候选行(2026-09-23 test job 8818, # 事务被毒化后以 InFailedSqlTransaction 收口,轮询链断裂导致 Gate 永久等待)。 # 回滚后按 Gate 现状分流:仍在等待外部 → 结束本 Job 并延迟重排,保持轮询链不断; # Gate 已被回调等其他路径收口 → 安静结束。错误文本留在 result_json 供排查。 db.session.rollback() gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id) gate_status = str(getattr(gate, 'status', '') or '') if gate is not None else None 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', 'poll_error': sanitize_gate_error_text(exc, max_len=300), }, owned_attempt=int(job.attempts or 0), ) if gate is not None and gate.latest_attempt_id: schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id)) db.session.commit() return finish_job( job.id, result={'status': 'poll_superseded', 'gate_status': gate_status}, owned_attempt=int(job.attempts or 0), ) db.session.commit() return finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0)) if str(result.get('gate_status') or '') == 'waiting_external': gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id) if gate is not None and gate.latest_attempt_id: schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id)) db.session.commit() return 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: # claim/execute 可能已经让 SQLAlchemy 事务进入 aborted 状态(例如死锁)。 # 任何失败收口前必须先回滚,避免把 Job 标记失败后留下 queued Attempt/Gate。 db.session.rollback() 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 safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure' # 先把 Attempt/Gate/Execution 收口,再独立结束 Job;即使 Runner 随后兜底标记 # Job failed,也不会再留下 failed Job + queued Attempt 的非法组合。 if attempt is not None: 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 # [STEP] 外部等待不是终态:Attempt 已正常执行完且 Gate 明确等待外部系统时, # 必须在当前 Job 成功收口后创建新的延迟 poll Attempt。此前只结束 Job,造成 # Gate 永久停在 waiting_external,批次中心持续显示“处理中”。 result_payload = result if isinstance(result, dict) else {'status': 'ok'} finish_job(job.id, result=result_payload, owned_attempt=owned_attempt) if str(result_payload.get('gate_status') or '').strip().lower() == 'waiting_external': schedule_waiting_external_poll(attempt_id=attempt_id) db.session.commit()