feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相

纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断,
Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-01 13:08:32 +08:00
1 parent b352c281d5
commit 323928626b
92 files changed
+11930 -458

No files matched your search

@@ -0,0 +1,72 @@
"""
migrations/versions/b8c9d0e1f2a4_add_external_reservation_id_alias.py
用途:为发货订单 Schema 的行级预约号补充真实邮件表头 External reservation ID。
依赖:shipping_order_schemas、shipping_order_schema_versions,以及当前统一 Alembic head。
逻辑:遍历 STANDARD_SHIPPING_NOTICE 的历史与当前版本,幂等追加显式别名并重算
definition checksum;不修改历史 Run 已冻结快照,重识别时由新 Run 使用更新后的 Schema。
"""
from __future__ import annotations
import hashlib
import json
from typing import Any
from alembic import op
import sqlalchemy as sa
revision = 'b8c9d0e1f2a4'
down_revision = 'a7b8c9d0e1f3'
branch_labels = None
depends_on = None
_ALIAS = 'External reservation ID'
def _definition_checksum(definition: dict[str, Any]) -> str:
"""使用 Schema 发布服务相同的规范 JSON 算法重算配置校验和。"""
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
return hashlib.sha256(encoded).hexdigest()
def upgrade() -> None:
"""为所有标准 Schema 版本的行级 reservation_id 幂等追加邮件表头别名。"""
bind = op.get_bind()
rows = bind.execute(sa.text("""
SELECT version.id, version.definition_json
FROM shipping_order_schema_versions AS version
JOIN shipping_order_schemas AS schema ON schema.id = version.schema_id
WHERE schema.schema_code = 'STANDARD_SHIPPING_NOTICE'
""")).mappings().all()
for row in rows:
raw_definition = row['definition_json']
definition = json.loads(raw_definition) if isinstance(raw_definition, str) else dict(raw_definition or {})
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
changed = False
for field in fields:
if not isinstance(field, dict):
continue
if str(field.get('field_code') or '') != 'reservation_id' or str(field.get('scope') or '') != 'line':
continue
aliases = [str(value).strip() for value in field.get('aliases') or [] if str(value).strip()]
if _ALIAS not in aliases:
field['aliases'] = [*aliases, _ALIAS]
changed = True
if changed:
bind.execute(sa.text("""
UPDATE shipping_order_schema_versions
SET definition_json = CAST(:definition_json AS jsonb), checksum = :checksum
WHERE id = :version_id
"""), {
'version_id': int(row['id']),
'definition_json': json.dumps(definition, ensure_ascii=False),
'checksum': _definition_checksum(definition),
})
def downgrade() -> None:
"""配置别名迁移不可逆,避免回滚后已冻结识别规则失去解释能力。"""
pass
@@ -0,0 +1,253 @@
"""
migrations/versions/d0e1f2a3b4c6_add_shipping_process_gate_recovery.py
用途:新增门禁恢复三表 ShippingProcessExecution / Gate / Attempt 及唯一约束与索引;
并扩展 shipping_audit_events.actor_type 允许 worker。
依赖:shipping_notice_workflow_items/versions、shipping_order_review_cases、shipping_tasks、jobs、
shipping_audit_events;Alembic revision b8c9d0e1f2a4。
逻辑:建表与约束,不迁移历史运行实例;同步放宽审计 actor CHECK;downgrade 删除三表并回退 CHECK。
说明:原误用 revision c9d0e1f2a3b5(与 seed_file_asset_cleanup_schedule 冲突),已改为 d0e1f2a3b4c6。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'd0e1f2a3b4c6'
down_revision = 'b8c9d0e1f2a4'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""创建 Execution / Gate / Attempt 三表、外键、唯一约束与查询索引。"""
op.create_table(
'shipping_process_executions',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('execution_no', sa.String(length=64), nullable=False),
sa.Column('workflow_item_id', sa.Integer(), nullable=False),
sa.Column('workflow_item_version_id', sa.Integer(), nullable=False),
sa.Column('review_case_id', sa.Integer(), nullable=True),
sa.Column('task_id', sa.Integer(), nullable=True),
sa.Column('status', sa.String(length=32), nullable=False, server_default='active'),
sa.Column('current_gate_code', sa.String(length=64), nullable=True),
sa.Column('last_passed_gate_code', sa.String(length=64), nullable=True),
sa.Column('primary_next_action_code', sa.String(length=64), nullable=True),
sa.Column('responsible_party', sa.String(length=32), nullable=True),
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint(
"status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')",
name='ck_shipping_process_executions_status',
),
sa.CheckConstraint('lock_version >= 1', name='ck_shipping_process_executions_lock_version'),
sa.ForeignKeyConstraint(['workflow_item_id'], ['shipping_notice_workflow_items.id']),
sa.ForeignKeyConstraint(['workflow_item_version_id'], ['shipping_notice_workflow_item_versions.id']),
sa.ForeignKeyConstraint(['review_case_id'], ['shipping_order_review_cases.id']),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']),
sa.UniqueConstraint('execution_no', name='uq_shipping_process_executions_no'),
sa.UniqueConstraint(
'workflow_item_version_id',
name='uq_shipping_process_executions_workflow_item_version',
),
)
op.create_index(
'ix_shipping_process_executions_status_updated',
'shipping_process_executions',
['status', 'updated_at'],
)
op.create_index(
'ix_shipping_process_executions_workflow_item',
'shipping_process_executions',
['workflow_item_id', 'updated_at'],
)
op.create_index(
'ix_shipping_process_executions_current_gate',
'shipping_process_executions',
['current_gate_code', 'status', 'updated_at'],
)
op.create_index(
'ix_shipping_process_executions_review_case',
'shipping_process_executions',
['review_case_id'],
)
op.create_index(
'ix_shipping_process_executions_task',
'shipping_process_executions',
['task_id'],
)
op.create_table(
'shipping_process_gates',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('execution_id', sa.Integer(), nullable=False),
sa.Column('gate_code', sa.String(length=64), nullable=False),
sa.Column('sequence_no', sa.Integer(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'),
sa.Column('evaluation_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('input_fingerprint', sa.String(length=64), nullable=True),
sa.Column('blocking_reason_code', sa.String(length=64), nullable=True),
sa.Column('blocking_reason_json', sa.JSON(), nullable=True),
sa.Column('recommendation_json', sa.JSON(), nullable=True),
sa.Column('effective_result_json', sa.JSON(), nullable=True),
sa.Column('next_action_code', sa.String(length=64), nullable=True),
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
sa.Column('latest_attempt_id', sa.Integer(), nullable=True),
sa.Column('passed_at', sa.DateTime(), nullable=True),
sa.Column('invalidated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint(
"status IN ("
"'pending', 'queued', 'running', 'passed', 'blocked_retryable', "
"'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped'"
")",
name='ck_shipping_process_gates_status',
),
sa.CheckConstraint('sequence_no >= 1', name='ck_shipping_process_gates_sequence'),
sa.CheckConstraint('evaluation_version >= 1', name='ck_shipping_process_gates_eval_version'),
sa.CheckConstraint('lock_version >= 1', name='ck_shipping_process_gates_lock_version'),
sa.ForeignKeyConstraint(
['execution_id'],
['shipping_process_executions.id'],
ondelete='CASCADE',
),
sa.UniqueConstraint(
'execution_id',
'gate_code',
name='uq_shipping_process_gates_execution_code',
),
sa.UniqueConstraint(
'execution_id',
'sequence_no',
name='uq_shipping_process_gates_execution_sequence',
),
)
op.create_index(
'ix_shipping_process_gates_execution_status',
'shipping_process_gates',
['execution_id', 'status', 'updated_at'],
)
op.create_index(
'ix_shipping_process_gates_code_status',
'shipping_process_gates',
['gate_code', 'status', 'updated_at'],
)
op.create_table(
'shipping_process_gate_attempts',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('gate_id', sa.Integer(), nullable=False),
sa.Column('attempt_no', sa.Integer(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
sa.Column('trigger_type', sa.String(length=32), nullable=False, server_default='auto'),
sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'),
sa.Column('actor_id', sa.String(length=64), nullable=True),
sa.Column('idempotency_key', sa.String(length=128), nullable=False),
sa.Column('input_snapshot_json', sa.JSON(), nullable=True),
sa.Column('input_snapshot_hash', sa.String(length=64), nullable=True),
sa.Column('rule_snapshot_json', sa.JSON(), nullable=True),
sa.Column('rule_snapshot_hash', sa.String(length=64), nullable=True),
sa.Column('output_snapshot_json', sa.JSON(), nullable=True),
sa.Column('output_snapshot_hash', sa.String(length=64), nullable=True),
sa.Column('job_id', sa.Integer(), nullable=True),
sa.Column('worker_id', sa.String(length=64), nullable=True),
sa.Column('lease_token', sa.String(length=64), nullable=True),
sa.Column('lease_expires_at', sa.DateTime(), nullable=True),
sa.Column('heartbeat_at', sa.DateTime(), nullable=True),
sa.Column('started_at', sa.DateTime(), nullable=True),
sa.Column('finished_at', sa.DateTime(), nullable=True),
sa.Column('error_code', sa.String(length=64), nullable=True),
sa.Column('error_summary', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint(
"status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled', 'superseded')",
name='ck_shipping_process_gate_attempts_status',
),
sa.CheckConstraint('attempt_no >= 1', name='ck_shipping_process_gate_attempts_no'),
sa.CheckConstraint(
"trigger_type IN ("
"'auto', 'user_retry', 'user_manual', 'worker_takeover', "
"'upstream_invalidation', 'system_requeue'"
")",
name='ck_shipping_process_gate_attempts_trigger',
),
sa.CheckConstraint(
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')",
name='ck_shipping_process_gate_attempts_actor_type',
),
sa.ForeignKeyConstraint(
['gate_id'],
['shipping_process_gates.id'],
ondelete='CASCADE',
),
sa.ForeignKeyConstraint(['job_id'], ['jobs.id']),
sa.UniqueConstraint(
'gate_id',
'attempt_no',
name='uq_shipping_process_gate_attempts_gate_no',
),
sa.UniqueConstraint(
'idempotency_key',
name='uq_shipping_process_gate_attempts_idempotency',
),
)
op.create_index(
'uq_shipping_process_gate_attempts_one_active',
'shipping_process_gate_attempts',
['gate_id'],
unique=True,
postgresql_where=sa.text("status IN ('queued', 'running')"),
sqlite_where=sa.text("status IN ('queued', 'running')"),
)
op.create_index(
'ix_shipping_process_gate_attempts_lease',
'shipping_process_gate_attempts',
['lease_token', 'lease_expires_at'],
)
op.create_index(
'ix_shipping_process_gate_attempts_job',
'shipping_process_gate_attempts',
['job_id'],
)
op.create_index(
'ix_shipping_process_gate_attempts_gate_status',
'shipping_process_gate_attempts',
['gate_id', 'status', 'created_at'],
)
# [STEP] 门禁 Worker 审计需要 actor_type=worker。
with op.batch_alter_table('shipping_audit_events') as batch_op:
batch_op.drop_constraint('ck_shipping_audit_events_actor_type', type_='check')
batch_op.create_check_constraint(
'ck_shipping_audit_events_actor_type',
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin', 'worker')",
)
def downgrade() -> None:
"""删除门禁恢复三表(先 Attempt → Gate → Execution)并回退审计 actor CHECK。"""
with op.batch_alter_table('shipping_audit_events') as batch_op:
batch_op.drop_constraint('ck_shipping_audit_events_actor_type', type_='check')
batch_op.create_check_constraint(
'ck_shipping_audit_events_actor_type',
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')",
)
op.drop_index('ix_shipping_process_gate_attempts_gate_status', table_name='shipping_process_gate_attempts')
op.drop_index('ix_shipping_process_gate_attempts_job', table_name='shipping_process_gate_attempts')
op.drop_index('ix_shipping_process_gate_attempts_lease', table_name='shipping_process_gate_attempts')
op.drop_index('uq_shipping_process_gate_attempts_one_active', table_name='shipping_process_gate_attempts')
op.drop_table('shipping_process_gate_attempts')
op.drop_index('ix_shipping_process_gates_code_status', table_name='shipping_process_gates')
op.drop_index('ix_shipping_process_gates_execution_status', table_name='shipping_process_gates')
op.drop_table('shipping_process_gates')
op.drop_index('ix_shipping_process_executions_task', table_name='shipping_process_executions')
op.drop_index('ix_shipping_process_executions_review_case', table_name='shipping_process_executions')
op.drop_index('ix_shipping_process_executions_current_gate', table_name='shipping_process_executions')
op.drop_index('ix_shipping_process_executions_workflow_item', table_name='shipping_process_executions')
op.drop_index('ix_shipping_process_executions_status_updated', table_name='shipping_process_executions')
op.drop_table('shipping_process_executions')