From f9f5053f0b7a20dd8dd28be4799037d39e1f2256 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 23 Sep 2026 20:51:50 +0800 Subject: [PATCH] =?UTF-8?q?fix(shipping-notice):=20=E5=BA=93=E5=AD=98?= =?UTF-8?q?=E5=9B=9E=E8=B0=83=E5=85=88=E9=94=81=20Gate=20=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E9=94=81=E5=BA=8F=E5=B9=B6=E4=BF=9D=E8=AF=81=E8=BD=AE?= =?UTF-8?q?=E8=AF=A2=E9=93=BE=E5=BC=82=E5=B8=B8=E4=B8=8D=E6=96=AD=E8=A3=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 库存 RPA 回调写候选数据前先锁活跃 Execution 的全部 Gate 行,与 external-wait 轮询统一加锁顺序,消除双方反序抢 Gate/候选行形成的死锁环 - external-wait 轮询异常时回滚并按 Gate 现状分流:仍在等待外部则以 waiting_external_requeued 延迟重排保持轮询链不断;已被回调收口则安静结束, 轮询 Job 不再终态失败 - 错误文本留在 result_json.poll_error 供排查 --- .../jobs/handlers/shipping_process_gate.py | 33 +++- .../shipping_notice/inventory_rpa_workflow.py | 22 +++ ...t_shipping_process_gate_poll_resilience.py | 145 ++++++++++++++++++ docs/features/shipping-notice/technical.md | 1 + 4 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 backend/tests/test_shipping_process_gate_poll_resilience.py diff --git a/backend/app/jobs/handlers/shipping_process_gate.py b/backend/app/jobs/handlers/shipping_process_gate.py index 4ddb205f..10bac725 100644 --- a/backend/app/jobs/handlers/shipping_process_gate.py +++ b/backend/app/jobs/handlers/shipping_process_gate.py @@ -8,6 +8,7 @@ backend/app/jobs/handlers/shipping_process_gate.py 次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口; 不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致; waiting_external 先结束当前 Job 再延迟入队新 Job; + external-wait 轮询异常时回滚并按 Gate 现状重排/安静结束,保证轮询链不因瞬时冲突断裂; healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。 """ @@ -88,7 +89,37 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None: 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 - result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id) + 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) diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index bbc889e9..ff54b90d 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -792,6 +792,24 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) return None +def _lock_process_gates_for_task(task: ShippingNotice) -> None: + """ + [锁序约定] 回调写库存候选数据前,先锁该任务活跃 Execution 的全部 Gate 行。 + + 外部等待轮询(run_inventory_external_wait_poll)的顺序是先锁 Gate 再读候选行; + 本侧若先写候选、后经 Gate 同步更新 Gate 行,会以相反顺序与轮询形成死锁环, + 事务被毒化后以 InFailedSqlTransaction 收口且轮询链断裂 + (2026-09-23 test job 8818:库存 RPA 回调 × external-wait 轮询竞跑)。 + 统一为两侧都先取 Gate 锁:后到方短暂阻塞后串行执行,不再产生错误。 + """ + from app.models import ShippingProcessGate + + execution_id = int(getattr(task, 'active_process_execution_id', 0) or 0) + if not execution_id: + return + ShippingProcessGate.query.filter_by(execution_id=execution_id).with_for_update().all() + + def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None: """ 复核 RPA 触发后可能漂移的订单与路由门禁(skipped/failed/success 共用)。 @@ -1813,6 +1831,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if gate_resp is not None: return gate_resp + # [锁序约定] 写入前先锁 Gate 行,与 external-wait 轮询串行(见 _lock_process_gates_for_task)。 + _lock_process_gates_for_task(task) runtime = _save_last_inventory_rpa_runtime(task, payload) callback_status = _normalize_rpa_inventory_result_status(payload) @@ -2486,6 +2506,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any "error": gate_resp.get("message") or "inventory_source_gate_blocked", }) continue + # [锁序约定] 写入前先锁 Gate 行,与 external-wait 轮询串行(见 _lock_process_gates_for_task)。 + _lock_process_gates_for_task(task) round_resp = _validate_rpa_callback_round(task, merged_item) if round_resp is not None: round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {} diff --git a/backend/tests/test_shipping_process_gate_poll_resilience.py b/backend/tests/test_shipping_process_gate_poll_resilience.py new file mode 100644 index 00000000..047dcb88 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_poll_resilience.py @@ -0,0 +1,145 @@ +""" +tests/test_shipping_process_gate_poll_resilience.py + +用途:锁定 external-wait 轮询 Job 的异常韧性契约与库存回调的 Gate 锁序约定。 +依赖:pytest、shipping_process_gate handler、inventory_rpa_workflow、monkeypatch。 +逻辑:不依赖 DB。轮询异常时回滚并按 Gate 现状分流(waiting_external 延迟重排保持轮询链不断 / + 已收口则安静结束),绝不终态失败;回调侧 `_lock_process_gates_for_task` 必须锁活跃 + Execution 的全部 Gate 行且无 Execution 时不查询。 +背景:2026-09-23 test job 8818——轮询与库存 RPA 回调以相反顺序争抢 Gate/候选行,事务被 + 毒化后以 InFailedSqlTransaction 终态失败,轮询链断裂(本次回调早到 400ms 自愈, + 若回调迟到则 run 将永久停在 external-wait)。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +@pytest.fixture() +def gate_job_env(monkeypatch): + """构造轮询 Job + Gate 的最小 handler 环境;返回各类捕获器。""" + import app.jobs.handlers.shipping_process_gate as handler + + job = SimpleNamespace(id=8818, attempts=1) + gate = SimpleNamespace(id=10313, status='waiting_external', latest_attempt_id=7) + finished: list[dict] = [] + failed: list[dict] = [] + scheduled: list[dict] = [] + + def _fake_get(model, _id): + if model is handler.Job: + return job + if model is handler.ShippingProcessGate: + return gate + return None + + monkeypatch.setattr(handler.db.session, 'get', _fake_get) + monkeypatch.setattr(handler.db.session, 'rollback', lambda: None) + monkeypatch.setattr(handler.db.session, 'commit', lambda: None) + monkeypatch.setattr( + handler, 'current_app', + SimpleNamespace(config={'SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS': 30}), + ) + + def _finish(job_id, *, result, owned_attempt): + finished.append({'job_id': job_id, 'result': result}) + + def _fail(job_id, *, error, result=None, retryable, owned_attempt): + failed.append({'job_id': job_id, 'error': error, 'retryable': retryable}) + + def _schedule(*, attempt_id): + scheduled.append({'attempt_id': attempt_id}) + + monkeypatch.setattr(handler, 'finish_job', _finish) + monkeypatch.setattr(handler, 'fail_job', _fail) + monkeypatch.setattr(handler, 'schedule_waiting_external_poll', _schedule) + return { + 'handler': handler, + 'job': job, + 'gate': gate, + 'finished': finished, + 'failed': failed, + 'scheduled': scheduled, + } + + +def _raise_poll(*_args, **_kwargs): + raise RuntimeError('poisoned transaction: InFailedSqlTransaction') + + +def test_poll_failure_while_waiting_external_requeues_chain(monkeypatch, gate_job_env): + """轮询异常且 Gate 仍在等待外部:回滚后延迟重排,轮询链不断,且不得终态失败。""" + handler = gate_job_env['handler'] + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.run_inventory_external_wait_poll', + _raise_poll, + ) + + handler.run_shipping_process_gate( + SimpleNamespace(), + {'external_wait_poll_gate_id': 10313, 'job_id': 8818}, + ) + + # 断言:以 waiting_external_requeued 成功收口并重排轮询链;绝不走 fail_job。 + assert len(gate_job_env['finished']) == 1 + result = gate_job_env['finished'][0]['result'] + assert result['status'] == 'waiting_external_requeued' + assert 'InFailedSqlTransaction' in (result.get('poll_error') or '') + assert gate_job_env['scheduled'] == [{'attempt_id': 7}] + assert gate_job_env['failed'] == [] + + +def test_poll_failure_after_gate_resolved_ends_quietly(monkeypatch, gate_job_env): + """Gate 已被回调等其他路径收口(status=passed):安静结束,不再重排。""" + handler = gate_job_env['handler'] + gate_job_env['gate'].status = 'passed' + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_job_service.run_inventory_external_wait_poll', + _raise_poll, + ) + + handler.run_shipping_process_gate( + SimpleNamespace(), + {'external_wait_poll_gate_id': 10313, 'job_id': 8818}, + ) + + # 断言:竞态输给回调时安静退出(poll_superseded),不重排、不失败。 + assert len(gate_job_env['finished']) == 1 + result = gate_job_env['finished'][0]['result'] + assert result['status'] == 'poll_superseded' + assert result['gate_status'] == 'passed' + assert gate_job_env['scheduled'] == [] + assert gate_job_env['failed'] == [] + + +def test_lock_process_gates_for_task_locks_active_execution_gates(monkeypatch): + """[锁序约定] 回调写候选前必须锁活跃 Execution 的全部 Gate 行;无 Execution 不查询。""" + from app.services.shipping_notice import inventory_rpa_workflow as wf + + calls: list[dict] = [] + + class _FakeQuery: + def filter_by(self, **kwargs): + calls.append(kwargs) + return self + + def with_for_update(self): + return self + + def all(self): + return [SimpleNamespace(id=1), SimpleNamespace(id=2)] + + monkeypatch.setattr('app.models.ShippingProcessGate', SimpleNamespace(query=_FakeQuery())) + + task = SimpleNamespace(active_process_execution_id=516) + wf._lock_process_gates_for_task(task) + # 断言:按活跃 Execution 过滤并加锁。 + assert calls == [{'execution_id': 516}] + + # 断言:无活跃 Execution(历史/已归档任务)直接跳过,不查询。 + calls.clear() + wf._lock_process_gates_for_task(SimpleNamespace(active_process_execution_id=None)) + assert calls == [] diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 1b0e271e..6fb5ac08 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -76,6 +76,7 @@ - “保存订单并校验”是唯一确认入口。后端先保存 Draft,再在同一业务链路重新计算必填、证据、冲突、重复、客户确认和自动建单策略门禁;只有 `auto_create_enabled=true` 且全部自动建单门禁通过时,才返回 `can_auto_create=true` 并进入建单,否则返回稳定阻断原因及可执行的 Review 动作。 - **显式校验幂等短路 + STP Job 串行化(2026-09-22)**:STP 自动建单持有草稿(等待入队/排队/执行)且内容相对最近一次校验未变(`validation_result_json.content_checksum` 比对)时,重复“保存并校验”幂等短路——不递增 `draft_version`、不写 `draft_validated` 事件、不重复入队。背景:连点保存曾产生版本/Job 风暴,同文档两个 STP Job 并发在建单 advisory 锁上死锁且 `max_attempts=1` 一次判死(case 永久停在 ready)。配套修复:`ensure_stp_auto_create_for_case` 入队前作废同文档旧版本 queued Job(running 由执行期“新版替代”检查收口);STP Job `max_attempts` 1→3,死锁类瞬时失败在 attempts 耗尽前自动重排,业务阻断仍 `retryable=false` 收口为“等待用户选择下一步动作”。自动化持有期间前端复核表单只读,与后端 `_locked_case` 的 `SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION` 同义。 - **抽取交接不变量:STP 只由最后一个抽取 Job 入队(2026-09-22 第二轮)**:多附件 EML 版面分批就绪时,交接 Job 与续抽 Job 同 commit 入队并被双 worker 并发执行,抽取链(持 run 锁→锁 intake)与 STP 确认链(持 intake→进度写锁 run)以相反顺序形成**结构性死锁**(`SNER-20260922-6466EB53` 整 run 卡死、附件滞留识别;同日 `879785D1` 的 STP 死锁同族)。修复:①`submit_order_extraction_unit_result` 增加 `defer_stp_enqueue`——Worker 开工快照仍有待排版附件(`pending_layout_ids` 非空、必交接)时跳过本 Unit 的 STP 入队,Candidate/Review Case 仍即时物化,STP 统一由最后一个抽取 Job 的 run 收口(`submit_order_extraction_run_result`)与 run 状态同事务入队,时序上消除抽取∥STP 并发;②收口前重放推送失败必须冒泡(原 try/except 吞错不回滚,会把真实死锁伪装成 `InFailedSqlTransaction` 并静默丢单),删除吞错让异常走外层收口;③外层收口对瞬时锁错(SQLSTATE 40P01 死锁 / 55P03 锁超时)标记 `retryable=true`,队列在 attempts 耗尽前自动重排(requeue 状态为 queued,`sync_order_extraction_run_after_job_failure` 的终态守卫保证不会误收口 run),attempts 耗尽仍终态失败等人工。残余概率性锁对(版面收尾×抽取、复核编辑×后台确认)由③兜底为秒级自愈。 +- **库存回调×external-wait 轮询锁序约定(2026-09-23,test job 8818)**:库存 RPA 回调与 external-wait 轮询曾以相反顺序争抢 Gate 行与库存候选行(回调=先写候选后更 Gate;轮询=先锁 Gate 后读候选),轮询事务被毒化后以 `InFailedSqlTransaction` 终态失败、轮询链断裂(本次回调早 400ms 自愈,否则 run 永久停在 external-wait)。根治:回调侧写候选前先锁活跃 Execution 的全部 Gate 行(`_lock_process_gates_for_task`,批量与单任务两个入口统一),两侧在 Gate 锁上串行、环消失;防御:`shipping_process_gate` 轮询分支增加异常韧性——异常回滚后按 Gate 现状分流(仍 `waiting_external` 则以 `waiting_external_requeued` 收口并延迟重排保持轮询链不断;已被收口则 `poll_superseded` 安静结束),错误文本留在 `result_json.poll_error` 供排查,轮询 Job 永不终态失败。 - Review Gate 或字段冲突发生变化时,即使生命周期 `stage/status` 不变,也必须递增 `progress_version` 并写入对应审计事件。Review 工作台、聊天投影和任务详情均按该版本刷新,禁止以前端旧 Projection 推导按钮。 - 上传成功(人工确认或 RPA 回调)必须统一清除历史上传阻断原因并收口正式 Execution 的履约 Gate;Notice 面成功词唯一为 `uploaded`(经 `project_notice_upload_status`;Attempt 库内仍写 `succeeded`)。业务完成用 `has_verified_upload_success`;`facts.upload_state` 成功词为 `succeeded`(`project_facts_upload_state`)。禁止调用方再读 Attempt 原词或扩同义词集合。 - `resolve_field_conflicts` 仅在当前 Case 仍存在开放字段冲突时展示;Case 已无开放冲突时,旧 Projection 中残留的该动作必须被前端隐藏,同时以后端 `ui_state.actions` 为最终动作契约。