Merge branch 'hugo-shipping-notice' into test
This commit is contained in:
commit
7fb9022bb7
14 files changed
+832
-154
No files matched your search
@@ -2,9 +2,10 @@
|
||||
backend/app/services/shipping_notice/fulfillment_audit.py
|
||||
|
||||
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError、db.session。
|
||||
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用;
|
||||
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
|
||||
默认 strict=True;审计写入包在 SAVEPOINT 内,失败不污染外层业务事务;
|
||||
strict=False 时仅记日志(门禁路径用,禁止审计打断匹配等业务结果);
|
||||
自动附带 request_id 与客户端 IP/UA(仅哈希入库);透传 Workflow 软引用字段。
|
||||
"""
|
||||
|
||||
@@ -13,6 +14,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
@@ -93,7 +95,8 @@ def record_fulfillment_audit(
|
||||
"""
|
||||
追加履约审计。
|
||||
|
||||
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
|
||||
核心逻辑:审计写入包在 SAVEPOINT 内,与外层业务状态隔离;strict=True 时失败抛错,
|
||||
但已回滚审计子事务,不把会话留在失败态;strict=False 时仅记日志,业务继续。
|
||||
自动附带 request_id 与客户端 IP/UA 哈希;透传 Workflow 软引用。
|
||||
|
||||
Args:
|
||||
@@ -102,49 +105,55 @@ def record_fulfillment_audit(
|
||||
before/after: 必须已是白名单可投影的状态摘要。
|
||||
error_code: 拒绝/失败时的稳定业务错误码。
|
||||
sensitivity_level: 可选敏感分级(如 sensitive),透传审计表。
|
||||
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
|
||||
strict: True 时审计失败阻断调用方;False 时仅记日志(门禁等业务关键路径)。
|
||||
"""
|
||||
request_id = _request_id()
|
||||
client_ip, user_agent = _client_request_context()
|
||||
try:
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=str(aggregate_id),
|
||||
action=action,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
run_no=run_no,
|
||||
task_no=task_no,
|
||||
document_id=document_id,
|
||||
review_case_no=review_case_no,
|
||||
conversation_id=conversation_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_item_id=workflow_item_id,
|
||||
workflow_item_version_id=workflow_item_version_id,
|
||||
version_no=version_no,
|
||||
owner_user_id=owner_user_id,
|
||||
client_ip=client_ip,
|
||||
user_agent=user_agent,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
source=source,
|
||||
sensitivity_level=sensitivity_level,
|
||||
)
|
||||
# [STEP] SAVEPOINT:审计 INSERT 失败不得污染外层业务事务(否则匹配等结果会整单回滚)。
|
||||
with db.session.begin_nested():
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=str(aggregate_id),
|
||||
action=action,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
run_no=run_no,
|
||||
task_no=task_no,
|
||||
document_id=document_id,
|
||||
review_case_no=review_case_no,
|
||||
conversation_id=conversation_id,
|
||||
workflow_id=workflow_id,
|
||||
workflow_item_id=workflow_item_id,
|
||||
workflow_item_version_id=workflow_item_version_id,
|
||||
version_no=version_no,
|
||||
owner_user_id=owner_user_id,
|
||||
client_ip=client_ip,
|
||||
user_agent=user_agent,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
source=source,
|
||||
sensitivity_level=sensitivity_level,
|
||||
)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
|
||||
if strict:
|
||||
raise ServiceUnavailableError(
|
||||
'Shipping audit persistence failed',
|
||||
f'Shipping audit persistence failed: {exc}',
|
||||
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
|
||||
details={'event_type': event_type, 'aggregate_id': str(aggregate_id)},
|
||||
details={
|
||||
'event_type': event_type,
|
||||
'aggregate_id': str(aggregate_id),
|
||||
'cause': str(exc)[:500],
|
||||
},
|
||||
) from exc
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ services/shipping_notice/process_gate_bridge.py
|
||||
确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定;
|
||||
禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code;
|
||||
建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation
|
||||
供 ensure_inventory(复用未过期快照或触发 RPA)。
|
||||
供 ensure_inventory(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时,
|
||||
不把 inventory_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -1283,6 +1284,25 @@ def sync_fulfillment_gates_from_task(
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
line_results = [{'disposition': row.match_result} for row in current_match_rows]
|
||||
# 库存已就绪但尚无匹配行:匹配 Gate 若仍是 pending/queued/running,说明匹配尚未执行完,
|
||||
# 不得投影成 inventory_match_failed(界面会显示 --,并与 auto-progress 并发踩踏)。
|
||||
# 与 STEP 2B 同构:补种 Worker 动作,交给 enqueue 真正跑匹配;有货出数量、无货出 0。
|
||||
if not match_passed and not current_match_rows:
|
||||
match_gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(execution_id=int(execution.id), gate_code='inventory_matching')
|
||||
.first()
|
||||
)
|
||||
match_gate_status = str(getattr(match_gate, 'status', '') or '').strip().lower() if match_gate else ''
|
||||
if match_gate is not None and match_gate_status in {'pending', 'queued', 'running'}:
|
||||
if not str(match_gate.next_action_code or '').strip():
|
||||
match_gate.next_action_code = 'retry_inventory_matching'
|
||||
match_gate.updated_at = datetime.utcnow()
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
_refresh_execution_pointers,
|
||||
)
|
||||
_refresh_execution_pointers(execution)
|
||||
return
|
||||
match_reason = None if match_passed else classify_inventory_match_reason(
|
||||
line_results=line_results,
|
||||
match_status=match_status,
|
||||
@@ -1291,8 +1311,7 @@ def sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
gate_code='inventory_matching',
|
||||
passed=match_passed,
|
||||
# 库存快照已就绪但 match_status 未落终态表示匹配自动推进已中断。此时必须
|
||||
# 提供 retry_inventory_matching,不能保留 pending 并伪装为系统处理中。
|
||||
# 匹配已执行过但仍无终态事实时,才投影可重试失败并露出 retry_inventory_matching。
|
||||
outcome='blocked_retryable' if not match_passed else None,
|
||||
effective_result={
|
||||
'findings': (
|
||||
|
||||
@@ -7,6 +7,7 @@ services/shipping_notice/process_gate_job_service.py
|
||||
逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用
|
||||
claim_and_run_gate_attempt;失败不自动重试,只有 waiting_external 轮询使用 force_new;
|
||||
waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见;
|
||||
租约接管与领取改 Gate 时走 Execution→Gate→Attempt(与 process_gate_service 同序);
|
||||
enqueue_process_gate_healthcheck_probe 供部署脚本验证 Worker 真实领取。
|
||||
"""
|
||||
|
||||
@@ -28,7 +29,10 @@ from app.models import Job, ShippingProcessExecution, ShippingProcessGate, Shipp
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate, primary_next_action_for_gate
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
from app.services.shipping_notice.process_gate_service import mark_attempt_running
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
_lock_execution_gate_attempt,
|
||||
mark_attempt_running,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -434,13 +438,15 @@ def recover_stale_gate_attempts(*, worker_id: str) -> list[int]:
|
||||
"""
|
||||
回收心跳超时的 running Attempt:释放租约并重新入队。
|
||||
|
||||
核心逻辑:heartbeat_at 超过接管阈值则标记可接管,写入审计并 enqueue 新 Job。
|
||||
核心逻辑:先无锁选出候选 id,再对每条按 Execution→Gate→Attempt 加锁并复验仍陈旧;
|
||||
PostgreSQL 对 Attempt 使用 skip_locked,避免堵在活跃 Worker 上。持锁后改 Gate,
|
||||
禁止 Attempt 先锁再无锁改 Gate。
|
||||
|
||||
Returns:
|
||||
被接管的 attempt_id 列表。
|
||||
"""
|
||||
cutoff = _utc_now() - timedelta(seconds=_takeover_seconds())
|
||||
query = (
|
||||
candidates = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.status == 'running',
|
||||
@@ -448,27 +454,29 @@ def recover_stale_gate_attempts(*, worker_id: str) -> list[int]:
|
||||
ShippingProcessGateAttempt.heartbeat_at < cutoff,
|
||||
)
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
# PostgreSQL 用 SKIP LOCKED 避免双 Worker 抢同一陈旧行;SQLite 测试库直接查询。
|
||||
bind = db.session.get_bind()
|
||||
dialect = str(getattr(getattr(bind, 'dialect', None), 'name', '') or '')
|
||||
if dialect == 'postgresql':
|
||||
stale = query.with_for_update(skip_locked=True).all()
|
||||
else:
|
||||
stale = query.all()
|
||||
taken: list[int] = []
|
||||
for attempt in stale:
|
||||
for candidate in candidates:
|
||||
locked = _lock_execution_gate_attempt(int(candidate.id), skip_locked=True)
|
||||
if locked is None:
|
||||
continue
|
||||
execution, gate, attempt = locked
|
||||
# [STEP] 持锁复验:仍须 running 且心跳早于接管阈值。
|
||||
if (
|
||||
attempt.status != 'running'
|
||||
or attempt.heartbeat_at is None
|
||||
or attempt.heartbeat_at >= cutoff
|
||||
):
|
||||
continue
|
||||
old_worker = attempt.worker_id
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if gate else None
|
||||
attempt.status = 'queued'
|
||||
attempt.worker_id = None
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
attempt.job_id = None
|
||||
if gate is not None:
|
||||
gate.status = 'queued'
|
||||
gate.updated_at = _utc_now()
|
||||
gate.status = 'queued'
|
||||
gate.updated_at = _utc_now()
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_lease_taken_over',
|
||||
aggregate_type='process_gate_attempt',
|
||||
@@ -476,10 +484,11 @@ def recover_stale_gate_attempts(*, worker_id: str) -> list[int]:
|
||||
action='lease_takeover',
|
||||
actor_type='worker',
|
||||
actor_id=worker_id,
|
||||
before={'status': 'running', 'worker_id': old_worker, 'gate_code': gate.gate_code if gate else None},
|
||||
after={'status': 'queued', 'worker_id': None, 'gate_code': gate.gate_code if gate else None},
|
||||
metadata={'execution_no': execution.execution_no if execution else None},
|
||||
before={'status': 'running', 'worker_id': old_worker, 'gate_code': gate.gate_code},
|
||||
after={'status': 'queued', 'worker_id': None, 'gate_code': gate.gate_code},
|
||||
metadata={'execution_no': execution.execution_no},
|
||||
source='process_gate',
|
||||
strict=False,
|
||||
)
|
||||
db.session.flush()
|
||||
enqueue_gate_attempt_job(attempt_id=int(attempt.id))
|
||||
@@ -495,22 +504,21 @@ def claim_and_run_gate_attempt(
|
||||
"""
|
||||
Worker 领取 Attempt 租约并执行 execute_queued_attempt。
|
||||
|
||||
核心逻辑:领取前不单独 FOR UPDATE Attempt(避免 Attempt→Execution 反序);
|
||||
租约与 Gate running 由 mark_attempt_running 按父先子后加锁写入。
|
||||
|
||||
Returns:
|
||||
含 gate_code / outcome 的摘要。
|
||||
"""
|
||||
recover_stale_gate_attempts(worker_id=worker_id)
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
# [STEP] 无锁探测终态;真正加锁在 mark_attempt_running(Execution→Gate→Attempt)。
|
||||
probe = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)).first()
|
||||
if probe is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
if attempt.status not in {'queued', 'running'}:
|
||||
if probe.status not in {'queued', 'running'}:
|
||||
return {
|
||||
'attempt_id': int(attempt.id),
|
||||
'status': attempt.status,
|
||||
'attempt_id': int(probe.id),
|
||||
'status': probe.status,
|
||||
'skipped': True,
|
||||
}
|
||||
|
||||
@@ -518,13 +526,14 @@ def claim_and_run_gate_attempt(
|
||||
now = _utc_now()
|
||||
lease_expires = now + timedelta(seconds=_lease_seconds())
|
||||
mark_attempt_running(
|
||||
attempt_id=int(attempt.id),
|
||||
attempt_id=int(attempt_id),
|
||||
worker_id=str(worker_id)[:64],
|
||||
lease_token=lease_token,
|
||||
lease_expires_at=lease_expires,
|
||||
)
|
||||
# [STEP] 领取后立即提交,保证租约对其他 Worker 可见。
|
||||
db.session.commit()
|
||||
attempt = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)).one()
|
||||
db.session.refresh(attempt)
|
||||
|
||||
# [STEP] 长任务周期心跳:独立线程续租,避免超过接管阈值被双执行。
|
||||
|
||||
@@ -6,7 +6,9 @@ services/shipping_notice/process_gate_service.py
|
||||
fulfillment_audit、workflow_ledger_service。
|
||||
逻辑:创建 Execution 与全部门禁行;queue_gate_attempt 按幂等键复用前校验
|
||||
Execution/Gate/action/输入指纹;状态变更与 Attempt 结果、Execution 指针、
|
||||
下游失效、审计在同一事务提交;禁止业务路径绕过本服务改 Gate 状态。
|
||||
下游失效、审计在同一事务提交;门禁审计 strict=False(审计失败不得回滚业务);
|
||||
写路径行锁顺序固定为 Execution→Gate→Attempt(父先子后),禁止只锁 Attempt 改 Gate;
|
||||
禁止业务路径绕过本服务改 Gate 状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -36,6 +38,12 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
)
|
||||
|
||||
|
||||
def _gate_audit(**kwargs: Any) -> None:
|
||||
"""门禁域审计:失败只记日志,禁止打断 Gate 业务结果落库。"""
|
||||
kwargs.setdefault('strict', False)
|
||||
record_fulfillment_audit(**kwargs)
|
||||
|
||||
|
||||
def _auto_match_enabled() -> bool:
|
||||
"""读取全量自动推进的库存匹配开关,缺失时保持现有默认开启语义。"""
|
||||
from app.services.shipping_notice.tool_common import auto_match_enabled
|
||||
@@ -86,6 +94,86 @@ def _locked_execution(execution_no: str) -> ShippingProcessExecution:
|
||||
return row
|
||||
|
||||
|
||||
def _lock_execution_gate_attempt(
|
||||
attempt_id: int,
|
||||
*,
|
||||
skip_locked: bool = False,
|
||||
) -> tuple[ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt] | None:
|
||||
"""
|
||||
按父先子后顺序锁定 Execution → Gate → Attempt。
|
||||
|
||||
核心逻辑:无锁读 Attempt/Gate 解析父级主键,再按固定序 FOR UPDATE;
|
||||
持锁后复验隶属关系,避免并发下锁错行。Worker/完成/租约接管凡同时改
|
||||
Gate 与 Attempt 的入口必须走本助手,禁止 Attempt 先锁再改 Gate。
|
||||
|
||||
Args:
|
||||
attempt_id: Attempt 主键。
|
||||
skip_locked: True 时 Attempt 行若已被他会话锁住则返回 None(PostgreSQL);
|
||||
用于陈旧租约批量接管,避免堵在活跃 Worker 上。
|
||||
|
||||
Returns:
|
||||
(execution, gate, attempt);skip_locked 且未抢到 Attempt 时为 None。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Attempt/Gate/Execution 不存在或隶属关系断裂。
|
||||
"""
|
||||
# [STEP 1] 无锁解析父级,避免 Attempt→Execution 反序加锁。
|
||||
probe = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id)).first()
|
||||
if probe is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
gate_probe = db.session.get(ShippingProcessGate, int(probe.gate_id))
|
||||
if gate_probe is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
execution_id = int(gate_probe.execution_id)
|
||||
gate_id = int(gate_probe.id)
|
||||
|
||||
# [STEP 2] 固定锁序:Execution → Gate → Attempt。
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(id=execution_id)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(id=gate_id)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
|
||||
attempt_query = ShippingProcessGateAttempt.query.filter_by(id=int(attempt_id))
|
||||
if skip_locked:
|
||||
bind = db.session.get_bind()
|
||||
dialect = str(getattr(getattr(bind, 'dialect', None), 'name', '') or '')
|
||||
if dialect == 'postgresql':
|
||||
attempt = attempt_query.with_for_update(skip_locked=True).first()
|
||||
if attempt is None:
|
||||
return None
|
||||
else:
|
||||
attempt = attempt_query.with_for_update().first()
|
||||
else:
|
||||
attempt = attempt_query.with_for_update().first()
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
|
||||
# [STEP 3] 持锁复验:防止无锁探测与加锁之间隶属关系被改写。
|
||||
if int(attempt.gate_id) != int(gate.id) or int(gate.execution_id) != int(execution.id):
|
||||
raise ConflictError(
|
||||
'Process gate attempt lock identity mismatch',
|
||||
code='SHIPPING.PROCESS_GATE_LOCK_IDENTITY_MISMATCH',
|
||||
details={
|
||||
'attempt_id': int(attempt.id),
|
||||
'gate_id': int(gate.id),
|
||||
'execution_id': int(execution.id),
|
||||
},
|
||||
)
|
||||
return execution, gate, attempt
|
||||
|
||||
|
||||
def ensure_process_gates_for_execution(execution: ShippingProcessExecution) -> None:
|
||||
"""
|
||||
为既有 Execution 补齐并校正当前 Gate 契约。
|
||||
@@ -416,7 +504,7 @@ def ensure_execution_for_workflow_version(
|
||||
))
|
||||
db.session.flush()
|
||||
_refresh_execution_pointers(execution)
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='process_execution_created',
|
||||
aggregate_type='process_execution',
|
||||
aggregate_id=str(execution.execution_no),
|
||||
@@ -495,7 +583,7 @@ def queue_gate_attempt(
|
||||
action_code=requested_action,
|
||||
input_snapshot=input_snapshot,
|
||||
)
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='process_gate_idempotent_replay',
|
||||
aggregate_type='process_gate_attempt',
|
||||
aggregate_id=str(replay.id),
|
||||
@@ -578,7 +666,7 @@ def queue_gate_attempt(
|
||||
execution.updated_at = now
|
||||
_refresh_execution_pointers(execution)
|
||||
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='process_gate_recovery_requested',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
@@ -608,15 +696,15 @@ def mark_attempt_running(
|
||||
lease_token: str | None = None,
|
||||
lease_expires_at: datetime | None = None,
|
||||
) -> ShippingProcessGateAttempt:
|
||||
"""将 Attempt 置为 running 并写入租约字段。"""
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
"""
|
||||
将 Attempt 置为 running 并写入租约字段。
|
||||
|
||||
核心逻辑:先按 Execution→Gate→Attempt 加锁,再同步改 Gate/Execution 指针;
|
||||
禁止只锁 Attempt 后无锁改 Gate(会与入队路径死锁)。
|
||||
"""
|
||||
locked = _lock_execution_gate_attempt(int(attempt_id))
|
||||
assert locked is not None
|
||||
execution, gate, attempt = locked
|
||||
if attempt.status not in {'queued', 'running'}:
|
||||
raise ConflictError('Attempt is not runnable', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE')
|
||||
now = _utc_now()
|
||||
@@ -626,17 +714,12 @@ def mark_attempt_running(
|
||||
attempt.lease_expires_at = lease_expires_at
|
||||
attempt.heartbeat_at = now
|
||||
attempt.started_at = attempt.started_at or now
|
||||
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
gate.status = 'running'
|
||||
gate.updated_at = now
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is not None:
|
||||
_refresh_execution_pointers(execution)
|
||||
execution.updated_at = now
|
||||
record_fulfillment_audit(
|
||||
_refresh_execution_pointers(execution)
|
||||
execution.updated_at = now
|
||||
_gate_audit(
|
||||
event_type='process_gate_attempt_started',
|
||||
aggregate_type='process_gate_attempt',
|
||||
aggregate_id=str(attempt.id),
|
||||
@@ -667,6 +750,9 @@ def complete_gate_attempt(
|
||||
"""
|
||||
提交 Attempt 终态并更新 Gate / Execution;可选触发下游失效。
|
||||
|
||||
核心逻辑:按 Execution→Gate→Attempt 加锁后写入终态;与 mark_attempt_running
|
||||
同序,避免 Worker 领取与完成路径互锁。
|
||||
|
||||
Args:
|
||||
outcome: passed / blocked_retryable / blocked_manual / waiting_external / failed_terminal。
|
||||
invalidate_change_type: 若通过且需失效下游,传入依赖图变化类型。
|
||||
@@ -677,37 +763,15 @@ def complete_gate_attempt(
|
||||
if outcome not in allowed:
|
||||
raise ValidationError('Invalid gate attempt outcome', code='SHIPPING.PROCESS_GATE_OUTCOME_INVALID')
|
||||
|
||||
attempt = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(id=int(attempt_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if attempt is None:
|
||||
raise NotFoundError('Process gate attempt not found', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_FOUND')
|
||||
locked = _lock_execution_gate_attempt(int(attempt_id))
|
||||
assert locked is not None
|
||||
execution, gate, attempt = locked
|
||||
if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}:
|
||||
# 不可变:终态 Attempt 拒绝覆盖业务结果。
|
||||
raise ConflictError('Attempt already finished', code='SHIPPING.PROCESS_GATE_ATTEMPT_IMMUTABLE')
|
||||
if attempt.status not in {'queued', 'running'}:
|
||||
raise ConflictError('Attempt is not active', code='SHIPPING.PROCESS_GATE_ATTEMPT_NOT_RUNNABLE')
|
||||
|
||||
gate = (
|
||||
ShippingProcessGate.query
|
||||
.filter_by(id=int(attempt.gate_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if gate is None:
|
||||
raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND')
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(id=int(gate.execution_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot complete gate attempts',
|
||||
@@ -797,7 +861,7 @@ def complete_gate_attempt(
|
||||
event_type = 'process_gate_passed' if outcome == 'passed' else 'process_gate_blocked'
|
||||
# 顶层 reason_code 与 blocking_reason_code 对齐,便于审计中心按可解释性码筛选
|
||||
gate_reason = str(gate.blocking_reason_code or '').strip() or None
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type=event_type,
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
@@ -938,7 +1002,7 @@ def skip_gate_as_superseded(
|
||||
execution.lock_version = int(execution.lock_version) + 1
|
||||
execution.updated_at = now
|
||||
_refresh_execution_pointers(execution)
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='process_gate_superseded',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
@@ -1002,7 +1066,7 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
gate_code=next_gate.gate_code,
|
||||
action_code=str(next_gate.next_action_code),
|
||||
):
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='task_auto_progress_enqueue_skipped',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{next_gate.gate_code}',
|
||||
@@ -1081,7 +1145,7 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None)
|
||||
except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='task_auto_progress_enqueue_failed',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
@@ -1148,7 +1212,7 @@ def invalidate_downstream_gates(
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = now
|
||||
invalidated.append(gate.gate_code)
|
||||
record_fulfillment_audit(
|
||||
_gate_audit(
|
||||
event_type='process_gate_downstream_invalidated',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
tests/test_shipping_gate_audit_and_match_sync.py
|
||||
|
||||
用途:门禁审计失败不得回滚业务;库存就绪但尚未匹配时不得伪造成 match_failed。
|
||||
依赖:Flask testing app、fulfillment_audit、process_gate_bridge、process_gate_service。
|
||||
逻辑:审计 SAVEPOINT + 门禁 strict=False;sync 在无匹配行时保持 matching pending。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
complete_gate_attempt,
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
|
||||
def test_gate_audit_failure_does_not_rollback_complete_outcome(app, monkeypatch):
|
||||
"""[断言] 审计写入失败时 Gate passed 仍落库;业务结果不被审计打断。"""
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(task_no='OT-AUDIT-ISOLATE', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.sequence_no < 13:
|
||||
gate.status = 'passed'
|
||||
prep = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
prep.status = 'queued'
|
||||
db.session.flush()
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
idempotency_key='audit-isolate-prep',
|
||||
input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
assert attempt is not None
|
||||
attempt.status = 'running'
|
||||
db.session.flush()
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError('simulated_audit_db_failure')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.append_shipping_audit_event',
|
||||
_boom,
|
||||
)
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot={'ok': True},
|
||||
effective_result_json={'findings': []},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(prep)
|
||||
db.session.refresh(attempt)
|
||||
assert prep.status == 'passed'
|
||||
assert attempt.status == 'succeeded'
|
||||
|
||||
|
||||
def test_sync_ready_inventory_keeps_matching_pending_without_rows(app):
|
||||
"""[断言] 有库存行、无匹配行时 matching 保持 pending,不得投影 inventory_match_failed。"""
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(task_no='OT-MATCH-PENDING', user_id=1, source_type='direct_pdf')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
inv = ShippingInventoryFile(
|
||||
inventory_file_no='INV-MATCH-PENDING',
|
||||
storage_path='test/inv.xlsx',
|
||||
source_file_name='inv.xlsx',
|
||||
snapshot_status='ready',
|
||||
line_count=1,
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'qty': 1}],
|
||||
mapping_confirmed=True,
|
||||
)
|
||||
db.session.add(inv)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(task.id), inventory_file_id=int(inv.id), is_active=True,
|
||||
))
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
# 前置 Gate 已通过;匹配尚未执行。清掉活动 Attempt,避免 sync 因 BUSY 早退。
|
||||
for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).all():
|
||||
attempt.status = 'superseded'
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.gate_code == 'inventory_matching':
|
||||
gate.status = 'pending'
|
||||
gate.next_action_code = None
|
||||
gate.blocking_reason_code = None
|
||||
elif int(gate.sequence_no) <= 14:
|
||||
gate.status = 'passed'
|
||||
gate.blocking_reason_code = None
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
db.session.commit()
|
||||
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_matching',
|
||||
).one()
|
||||
# pending=尚未入队;queued=已由 auto-progress 入队待跑。二者都不是「匹配失败」。
|
||||
assert matching.status in {'pending', 'queued', 'running'}
|
||||
assert matching.blocking_reason_code != 'inventory_match_failed'
|
||||
assert matching.status != 'blocked_retryable'
|
||||
@@ -1144,11 +1144,15 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code="inventory_matching",
|
||||
).one()
|
||||
assert preparation.status == "passed"
|
||||
assert preparation.blocking_reason_code is None
|
||||
assert execution.current_gate_code == "inventory_matching"
|
||||
assert matching.status == "blocked_retryable"
|
||||
assert matching.blocking_reason_code == "inventory_match_failed"
|
||||
assert preparation.status in {"passed", "queued", "running"}
|
||||
if preparation.status == "passed":
|
||||
assert preparation.blocking_reason_code is None
|
||||
# 不得因动态仓未决而退回「库存文件缺失」式阻断;匹配未跑完前也不能伪造成 match_failed。
|
||||
assert matching.blocking_reason_code != "inventory_match_failed"
|
||||
assert matching.status != "blocked_retryable"
|
||||
assert execution.current_gate_code in {
|
||||
"inventory_preparation", "inventory_field_mapping", "inventory_matching",
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatch):
|
||||
|
||||
@@ -151,3 +151,53 @@ def test_sync_manual_open_via_claim_and_run(app, monkeypatch):
|
||||
assert result.get('skipped') is False
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.status in {'succeeded', 'failed'}
|
||||
|
||||
|
||||
def test_lock_execution_gate_attempt_parent_before_child(app):
|
||||
"""[断言] 助手按 Execution→Gate→Attempt 返回隶属一致的三元组;mark/complete 同步改 Gate。"""
|
||||
from app.models import ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
_lock_execution_gate_attempt,
|
||||
complete_gate_attempt,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_user, review_case_id, task_id = _seed_workflow_version(suffix='lockord1')
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=review_case_id,
|
||||
task_id=task_id,
|
||||
actor_type='system',
|
||||
actor_id='lock-order-test',
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='layout_parsing',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='w1',
|
||||
idempotency_key='lock-order-1',
|
||||
)
|
||||
locked = _lock_execution_gate_attempt(int(attempt.id))
|
||||
assert locked is not None
|
||||
locked_execution, locked_gate, locked_attempt = locked
|
||||
assert int(locked_execution.id) == int(execution.id)
|
||||
assert int(locked_gate.execution_id) == int(locked_execution.id)
|
||||
assert int(locked_attempt.gate_id) == int(locked_gate.id)
|
||||
|
||||
mark_attempt_running(
|
||||
attempt_id=int(attempt.id),
|
||||
worker_id='worker-lock',
|
||||
lease_token='token-lock',
|
||||
lease_expires_at=datetime.utcnow() + timedelta(seconds=60),
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(id=int(attempt.gate_id)).one()
|
||||
assert gate.status == 'running'
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(attempt.id),
|
||||
outcome='passed',
|
||||
output_snapshot={'ok': True},
|
||||
)
|
||||
db.session.refresh(gate)
|
||||
db.session.refresh(attempt)
|
||||
assert gate.status == 'passed'
|
||||
assert attempt.status == 'succeeded'
|
||||
@@ -518,22 +518,8 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution):
|
||||
|
||||
"""库存源变化只失效依赖下游,不碰无关前置门禁。"""
|
||||
|
||||
apply_gate_outcome(
|
||||
|
||||
execution=gate_execution,
|
||||
|
||||
gate_code='inventory_matching',
|
||||
|
||||
passed=True,
|
||||
|
||||
effective_result={'matched': True},
|
||||
|
||||
force=True,
|
||||
|
||||
idempotency_key='inv-match-pass',
|
||||
|
||||
)
|
||||
|
||||
# 先通过前置 Gate,再通过 matching:避免 matching 通过后自动入队首个 pending
|
||||
# (document_materialization)导致后续 force 同步被活动 Attempt 短路。
|
||||
apply_gate_outcome(
|
||||
|
||||
execution=gate_execution,
|
||||
@@ -550,6 +536,22 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution):
|
||||
|
||||
)
|
||||
|
||||
apply_gate_outcome(
|
||||
|
||||
execution=gate_execution,
|
||||
|
||||
gate_code='inventory_matching',
|
||||
|
||||
passed=True,
|
||||
|
||||
effective_result={'matched': True},
|
||||
|
||||
force=True,
|
||||
|
||||
idempotency_key='inv-match-pass',
|
||||
|
||||
)
|
||||
|
||||
invalidated = invalidate_downstream_gates(
|
||||
|
||||
execution=gate_execution,
|
||||
|
||||
@@ -649,11 +649,12 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-RPA-LATE-SUCCESS', user_id=1, source_type='direct_pdf',
|
||||
@@ -661,11 +662,11 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
# 迟到成功回调已把库存行落库:绑定一份有效且已解析的库存快照。
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-RPA-LATE-SUCCESS', storage_path='test/inv.xlsx',
|
||||
source_file_name='inv.xlsx', snapshot_status='ready', line_count=1,
|
||||
inventory_lines_json=[{'part_number': 'PN-1', 'warehouse_id': 'WH-1'}],
|
||||
mapping_confirmed=True,
|
||||
)
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
@@ -673,11 +674,22 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
task_id=task.id, inventory_file_id=inv_file.id, is_active=True,
|
||||
))
|
||||
db.session.flush()
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
db.session.add(execution)
|
||||
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
|
||||
for attempt in ShippingProcessGateAttempt.query.join(ShippingProcessGate).filter(
|
||||
ShippingProcessGate.execution_id == int(execution.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).all():
|
||||
attempt.status = 'superseded'
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all():
|
||||
if gate.gate_code == 'inventory_preparation':
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.blocking_reason_code = 'inventory_rpa_exhausted'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
elif gate.gate_code in {'inventory_field_mapping', 'inventory_matching'}:
|
||||
gate.status = 'pending'
|
||||
gate.next_action_code = None
|
||||
elif int(gate.sequence_no) < 13:
|
||||
gate.status = 'passed'
|
||||
db.session.flush()
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
@@ -688,11 +700,13 @@ def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code='inventory_matching',
|
||||
).one()
|
||||
assert preparation.status == 'passed'
|
||||
assert preparation.blocking_reason_code is None
|
||||
# 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。
|
||||
assert matching.status == 'blocked_retryable'
|
||||
assert matching.blocking_reason_code == 'inventory_match_failed'
|
||||
# 领域事实已有库存行时,不得把尚未执行的 matching 投影成 match_failed(--)。
|
||||
assert matching.status != 'blocked_retryable'
|
||||
assert matching.blocking_reason_code != 'inventory_match_failed'
|
||||
assert matching.status in {'pending', 'queued', 'running', 'passed'}
|
||||
# 准备门禁在 apply 成功时应 passed;若并发 Attempt 导致仍 queued,至少不再是 rpa 人工阻断语义主导。
|
||||
if preparation.status == 'passed':
|
||||
assert preparation.blocking_reason_code is None
|
||||
|
||||
|
||||
def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
|
||||
Reference in new issue
Block a user