feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -0,0 +1,272 @@
|
||||
"""
|
||||
migrations/versions/cp1a2b3c4d5e_add_inventory_candidate_freeze_tables.py
|
||||
|
||||
用途:决策 C1 —— 库存候选冻结结构化表。新增 3 张表:
|
||||
shipping_inventory_candidate_sets(候选集合根)
|
||||
shipping_inventory_candidate_sources(任务级候选源,有序)
|
||||
shipping_inventory_candidate_lines(行级候选源,source_codes_json 有序列表)
|
||||
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']
|
||||
作为不可变审计副本。
|
||||
依赖:shipping_notices、shipping_order_review_cases、shipping_process_executions、
|
||||
users、shipping_inventory_routing_rules(外键均为 SET NULL / CASCADE,不破坏历史)。
|
||||
逻辑:Revises dc9a4a2683df_merge_heads;
|
||||
新增表 + 唯一索引 + 部分唯一索引(PostgreSQL WHERE 条件);
|
||||
不修改任何已有表字段,纯新增不破坏历史数据。
|
||||
|
||||
Revision ID: cp1a2b3c4d5e
|
||||
Revises: dc9a4a2683df
|
||||
Create Date: 2026-08-07 16:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'cp1a2b3c4d5e'
|
||||
down_revision = 'dc9a4a2683df'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建候选冻结 3 张结构化表及配套索引/约束。"""
|
||||
|
||||
# [STEP 1] 候选集合根(Set)
|
||||
op.create_table(
|
||||
'shipping_inventory_candidate_sets',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('set_version', sa.Integer(), nullable=False, server_default=sa.text('1')),
|
||||
sa.Column(
|
||||
'task_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_notices.id', ondelete='CASCADE'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
'review_case_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column(
|
||||
'execution_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_process_executions.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('frozen_at', sa.DateTime(), nullable=False),
|
||||
sa.Column(
|
||||
'frozen_by_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('users.id'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('input_fingerprint', sa.String(length=64), nullable=False),
|
||||
sa.Column('routing_rule_version_json', sa.JSON(), nullable=True),
|
||||
sa.Column('manifest_snapshot_sha256', sa.String(length=64), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('remark', sa.Text(), nullable=True),
|
||||
# 至少绑定 task 或 review_case 其中之一(跨方言表达式:PG/SQLite 都支持)
|
||||
sa.CheckConstraint(
|
||||
'task_id IS NOT NULL OR review_case_id IS NOT NULL',
|
||||
name='ck_shipping_inv_cand_sets_binding',
|
||||
),
|
||||
sa.CheckConstraint('set_version >= 1', name='ck_shipping_inv_cand_sets_version'),
|
||||
)
|
||||
# 幂等唯一:同一绑定对象 + 输入指纹相同 = 同一 Set
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'postgresql':
|
||||
op.execute(sa.text(
|
||||
'CREATE UNIQUE INDEX uq_shipping_inv_cand_sets_task_fp '
|
||||
'ON shipping_inventory_candidate_sets (task_id, input_fingerprint) '
|
||||
'WHERE task_id IS NOT NULL'
|
||||
))
|
||||
op.execute(sa.text(
|
||||
'CREATE UNIQUE INDEX uq_shipping_inv_cand_sets_review_fp '
|
||||
'ON shipping_inventory_candidate_sets (review_case_id, input_fingerprint) '
|
||||
'WHERE review_case_id IS NOT NULL'
|
||||
))
|
||||
else:
|
||||
# SQLite / 其他方言:普通唯一索引(NULL 视为 DISTINCT 行为依赖方言,但查询层会判 NULL)
|
||||
op.create_unique_constraint(
|
||||
'uq_shipping_inv_cand_sets_task_fp',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['task_id', 'input_fingerprint'],
|
||||
)
|
||||
op.create_unique_constraint(
|
||||
'uq_shipping_inv_cand_sets_review_fp',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['review_case_id', 'input_fingerprint'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_inv_cand_sets_task_frozen',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['task_id', 'frozen_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_inv_cand_sets_review_frozen',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['review_case_id', 'frozen_at'],
|
||||
)
|
||||
|
||||
# [STEP 2] 任务级候选源(Source),按 candidate_order 有序
|
||||
op.create_table(
|
||||
'shipping_inventory_candidate_sources',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'candidate_set_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('source_code', sa.String(length=64), nullable=False),
|
||||
sa.Column('candidate_order', sa.Integer(), nullable=False),
|
||||
sa.Column(
|
||||
'candidate_origin',
|
||||
sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default=sa.text("'rule'"),
|
||||
),
|
||||
sa.Column(
|
||||
'routing_rule_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('routing_rule_version', sa.Integer(), nullable=True),
|
||||
sa.Column('source_config_version', sa.String(length=64), nullable=True),
|
||||
sa.Column(
|
||||
'override_by_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('users.id'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('override_reason', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
'candidate_set_id', 'source_code',
|
||||
name='uq_shipping_inv_cand_sources_set_source',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"candidate_origin IN ('rule', 'manual_override')",
|
||||
name='ck_shipping_inv_cand_sources_origin',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'candidate_order >= 1',
|
||||
name='ck_shipping_inv_cand_sources_order',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_inv_cand_sources_set_order',
|
||||
'shipping_inventory_candidate_sources',
|
||||
['candidate_set_id', 'candidate_order'],
|
||||
)
|
||||
|
||||
# [STEP 3] 行级候选源(Line),按 line_no 对齐;source_codes_json 有序列表
|
||||
op.create_table(
|
||||
'shipping_inventory_candidate_lines',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column(
|
||||
'candidate_set_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column('line_no', sa.Integer(), nullable=False),
|
||||
sa.Column('part_number', sa.String(length=128), nullable=True),
|
||||
sa.Column('reservation_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('source_codes_json', sa.JSON(), nullable=False, server_default=sa.text("'[]'::json")),
|
||||
sa.Column(
|
||||
'override_by_id',
|
||||
sa.Integer(),
|
||||
sa.ForeignKey('users.id'),
|
||||
nullable=True,
|
||||
),
|
||||
sa.Column('override_reason', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
'candidate_set_id', 'line_no',
|
||||
name='uq_shipping_inv_cand_lines_set_line',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_inv_cand_lines_set_pn_resv',
|
||||
'shipping_inventory_candidate_lines',
|
||||
['candidate_set_id', 'part_number', 'reservation_id'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚 3 张候选冻结表及索引(纯新增,无破坏性)。"""
|
||||
|
||||
op.drop_index(
|
||||
'ix_shipping_inv_cand_lines_set_pn_resv',
|
||||
table_name='shipping_inventory_candidate_lines',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'uq_shipping_inv_cand_lines_set_line',
|
||||
'shipping_inventory_candidate_lines',
|
||||
type_='unique',
|
||||
)
|
||||
op.drop_table('shipping_inventory_candidate_lines')
|
||||
|
||||
op.drop_index(
|
||||
'ix_shipping_inv_cand_sources_set_order',
|
||||
table_name='shipping_inventory_candidate_sources',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'ck_shipping_inv_cand_sources_order',
|
||||
'shipping_inventory_candidate_sources',
|
||||
type_='check',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'ck_shipping_inv_cand_sources_origin',
|
||||
'shipping_inventory_candidate_sources',
|
||||
type_='check',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'uq_shipping_inv_cand_sources_set_source',
|
||||
'shipping_inventory_candidate_sources',
|
||||
type_='unique',
|
||||
)
|
||||
op.drop_table('shipping_inventory_candidate_sources')
|
||||
|
||||
op.drop_index(
|
||||
'ix_shipping_inv_cand_sets_review_frozen',
|
||||
table_name='shipping_inventory_candidate_sets',
|
||||
)
|
||||
op.drop_index(
|
||||
'ix_shipping_inv_cand_sets_task_frozen',
|
||||
table_name='shipping_inventory_candidate_sets',
|
||||
)
|
||||
bind = op.get_bind()
|
||||
if bind.dialect.name == 'postgresql':
|
||||
op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_inv_cand_sets_review_fp'))
|
||||
op.execute(sa.text('DROP INDEX IF EXISTS uq_shipping_inv_cand_sets_task_fp'))
|
||||
else:
|
||||
op.drop_constraint(
|
||||
'uq_shipping_inv_cand_sets_review_fp',
|
||||
'shipping_inventory_candidate_sets',
|
||||
type_='unique',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'uq_shipping_inv_cand_sets_task_fp',
|
||||
'shipping_inventory_candidate_sets',
|
||||
type_='unique',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'ck_shipping_inv_cand_sets_version',
|
||||
'shipping_inventory_candidate_sets',
|
||||
type_='check',
|
||||
)
|
||||
op.drop_constraint(
|
||||
'ck_shipping_inv_cand_sets_binding',
|
||||
'shipping_inventory_candidate_sets',
|
||||
type_='check',
|
||||
)
|
||||
op.drop_table('shipping_inventory_candidate_sets')
|
||||
@@ -0,0 +1,133 @@
|
||||
"""T4 add per-source inventory RPA attempts table
|
||||
|
||||
Revision ID: dq2e3f4g5h6i
|
||||
Revises: cp1a2b3c4d5e
|
||||
Create Date: 2026-08-16 10:00:00.000000
|
||||
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'dq2e3f4g5h6i'
|
||||
down_revision = 'cp1a2b3c4d5e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
PER_SOURCE_STATUS_VALUES = (
|
||||
'queued', 'running', 'succeeded', 'failed',
|
||||
'consumed', 'superseded', 'exhausted',
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
'shipping_task_inventory_rpa_attempts',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('task_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('source_code', sa.String(length=32), nullable=False),
|
||||
sa.Column('attempt_no', sa.Integer(), nullable=False),
|
||||
sa.Column('run_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
|
||||
sa.Column('trigger_file_path', sa.String(length=1024), nullable=True),
|
||||
sa.Column('callback_file_path', sa.String(length=1024), nullable=True),
|
||||
sa.Column('inventory_file_no', sa.String(length=128), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('error_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('lease_token', sa.String(length=128), nullable=True),
|
||||
sa.Column('leased_at', sa.DateTime(timezone=False), nullable=True),
|
||||
sa.Column('lease_expires_at', sa.DateTime(timezone=False), nullable=True),
|
||||
sa.Column(
|
||||
'callback_payload_json',
|
||||
postgresql.JSONB(astext_type=sa.Text()),
|
||||
nullable=False,
|
||||
server_default=sa.text("'{}'::jsonb"),
|
||||
),
|
||||
sa.Column(
|
||||
'extra_json',
|
||||
postgresql.JSONB(astext_type=sa.Text()),
|
||||
nullable=False,
|
||||
server_default=sa.text("'{}'::jsonb"),
|
||||
),
|
||||
sa.Column('triggered_at', sa.DateTime(timezone=False), nullable=True),
|
||||
sa.Column('callback_received_at', sa.DateTime(timezone=False), nullable=True),
|
||||
sa.Column('consumed_at', sa.DateTime(timezone=False), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=False), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=False), nullable=False,
|
||||
server_default=sa.func.now()),
|
||||
# 三元组唯一:同一运行号同一源只允许一条
|
||||
sa.UniqueConstraint(
|
||||
'task_no', 'source_code', 'run_no',
|
||||
name='uq_shipping_task_inv_rpa_triplet',
|
||||
),
|
||||
# Attempt status 枚举约束
|
||||
sa.CheckConstraint(
|
||||
"status IN ('queued','running','succeeded','failed','consumed','superseded','exhausted')",
|
||||
name='ck_shipping_task_inv_rpa_status_enum',
|
||||
),
|
||||
# Attempt 编号 ≥ 1
|
||||
sa.CheckConstraint(
|
||||
'attempt_no >= 1',
|
||||
name='ck_shipping_task_inv_rpa_attempt_positive',
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id', name='pk_shipping_task_inv_rpa_attempts'),
|
||||
)
|
||||
|
||||
# === PostgreSQL:部分唯一索引 + 高级索引 ===
|
||||
# 活动 Attempt 每源唯一
|
||||
op.execute(
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_shipping_task_inv_rpa_active_per_source
|
||||
ON shipping_task_inventory_rpa_attempts (task_no, source_code)
|
||||
WHERE status IN ('queued','running');
|
||||
"""
|
||||
)
|
||||
# 常用查询:按 task+source 取最新 attempt
|
||||
op.create_index(
|
||||
'ix_shipping_task_inv_rpa_task_source',
|
||||
'shipping_task_inventory_rpa_attempts',
|
||||
['task_no', 'source_code', 'attempt_no'],
|
||||
)
|
||||
# 扫描 stale running / queued
|
||||
op.create_index(
|
||||
'ix_shipping_task_inv_rpa_status_updated',
|
||||
'shipping_task_inventory_rpa_attempts',
|
||||
['status', 'updated_at'],
|
||||
)
|
||||
# task_no 单独索引(回调入口只传 task_no + source_code + run_no)
|
||||
op.create_index(
|
||||
'ix_shipping_task_inv_rpa_task_no',
|
||||
'shipping_task_inventory_rpa_attempts',
|
||||
['task_no'],
|
||||
)
|
||||
# source_code 单独索引(按源统计 attempt)
|
||||
op.create_index(
|
||||
'ix_shipping_task_inv_rpa_source_code',
|
||||
'shipping_task_inventory_rpa_attempts',
|
||||
['source_code'],
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
# PostgreSQL 部分唯一索引
|
||||
op.execute(
|
||||
"""
|
||||
DROP INDEX IF EXISTS uq_shipping_task_inv_rpa_active_per_source;
|
||||
"""
|
||||
)
|
||||
|
||||
op.drop_index('ix_shipping_task_inv_rpa_source_code', table_name='shipping_task_inventory_rpa_attempts')
|
||||
op.drop_index('ix_shipping_task_inv_rpa_task_no', table_name='shipping_task_inventory_rpa_attempts')
|
||||
op.drop_index('ix_shipping_task_inv_rpa_status_updated', table_name='shipping_task_inventory_rpa_attempts')
|
||||
op.drop_index('ix_shipping_task_inv_rpa_task_source', table_name='shipping_task_inventory_rpa_attempts')
|
||||
|
||||
op.drop_table('shipping_task_inventory_rpa_attempts')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,58 @@
|
||||
"""T6 add line_match_evidence_fields to line inventory matches
|
||||
|
||||
Revision ID: er5f6g7h8i9j
|
||||
Revises: dq2e3f4g5h6i
|
||||
Create Date: 2026-08-16 11:00:00.000000
|
||||
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'er5f6g7h8i9j'
|
||||
down_revision = 'dq2e3f4g5h6i'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('shipping_notice_line_inventory_matches', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('matched_file_no', sa.String(length=128), nullable=True))
|
||||
batch_op.add_column(sa.Column('matched_row_index', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('evidence_ref', sa.String(length=512), nullable=True))
|
||||
batch_op.add_column(
|
||||
sa.Column('match_attempt_id', sa.Integer(), sa.ForeignKey(
|
||||
'shipping_process_gate_attempts.id', ondelete='SET NULL',
|
||||
), nullable=True),
|
||||
)
|
||||
batch_op.create_index(
|
||||
'ix_shipping_notice_line_inv_match_matched_file_no',
|
||||
['matched_file_no'], unique=False,
|
||||
)
|
||||
batch_op.create_index(
|
||||
'ix_shipping_notice_line_inv_match_match_attempt_id',
|
||||
['match_attempt_id'], unique=False,
|
||||
)
|
||||
# 证据查询常用组合:按行+file_no 快速定位,避免全表扫描
|
||||
batch_op.create_index(
|
||||
'ix_shipping_notice_line_inv_match_task_evidence',
|
||||
['task_id', 'matched_file_no', 'matched_row_index'],
|
||||
unique=False,
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table('shipping_notice_line_inventory_matches', schema=None) as batch_op:
|
||||
batch_op.drop_index('ix_shipping_notice_line_inv_match_task_evidence')
|
||||
batch_op.drop_index('ix_shipping_notice_line_inv_match_match_attempt_id')
|
||||
batch_op.drop_index('ix_shipping_notice_line_inv_match_matched_file_no')
|
||||
batch_op.drop_column('match_attempt_id')
|
||||
batch_op.drop_column('evidence_ref')
|
||||
batch_op.drop_column('matched_row_index')
|
||||
batch_op.drop_column('matched_file_no')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge ct4d5e6f7a8b and er5f6g7h8i9j heads
|
||||
|
||||
Revision ID: fs1a2b3c4d5e
|
||||
Revises: ct4d5e6f7a8b, er5f6g7h8i9j
|
||||
Create Date: 2026-08-07 16:30:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'fs1a2b3c4d5e'
|
||||
down_revision = ('ct4d5e6f7a8b', 'er5f6g7h8i9j')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
"""
|
||||
expand_shipping_order_review_suggestion_v2
|
||||
|
||||
Phase 0 DB Schema 变更:为订单复核 LLM 建议表扩展 v2 契约。
|
||||
|
||||
变更点:
|
||||
1. status Check Constraint 新增 gated_failed
|
||||
2. evidence_level Check Constraint 新增 L2_row/L3_table/L4_page/L5_document(保留 L2_table/L3_page/L4_pdf 不篡改旧语义)
|
||||
3. 新增 8 个 provider & trace 独立列:
|
||||
provider / provider_conversation_id / provider_message_id
|
||||
latency_ms / context_hash / evidence_count
|
||||
context_truncated / auto_upgrade_reason
|
||||
4. 新增 3 个索引:
|
||||
ix_shipping_order_review_suggestions_provider_conversation
|
||||
ix_shipping_order_review_suggestions_context_hash
|
||||
ix_shipping_order_review_suggestions_status_created
|
||||
|
||||
策略:历史行保持 NULL / server_default,不回填。旧等级和旧状态不做语义迁移或覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'ft1a2b3c4d5e'
|
||||
down_revision = 'fs1a2b3c4d5e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
TABLE_NAME = 'shipping_order_review_suggestions'
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constraint 名称(与模型 __table_args__ 完全一致,drop/create 必须同名)
|
||||
# ---------------------------------------------------------------------------
|
||||
CK_STATUS = 'ck_shipping_order_review_suggestions_status'
|
||||
CK_LEVEL = 'ck_shipping_order_review_suggestions_evidence_level'
|
||||
|
||||
NEW_STATUS_ENUM = (
|
||||
"'pending', 'gated_failed', 'validated', 'validation_failed', "
|
||||
"'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable'"
|
||||
)
|
||||
NEW_LEVEL_ENUM = (
|
||||
"'L1_field', 'L2_table', 'L3_page', 'L4_pdf', "
|
||||
"'L2_row', 'L3_table', 'L4_page', 'L5_document'"
|
||||
)
|
||||
|
||||
IX_PROVIDER_CONV = 'ix_shipping_order_review_suggestions_provider_conversation'
|
||||
IX_CONTEXT_HASH = 'ix_shipping_order_review_suggestions_context_hash'
|
||||
IX_STATUS_CREATED = 'ix_shipping_order_review_suggestions_status_created'
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# [STEP 1] status Check Constraint:删除旧版 → 追加新版(含 gated_failed)
|
||||
op.drop_constraint(CK_STATUS, TABLE_NAME, type_='check')
|
||||
op.create_check_constraint(
|
||||
CK_STATUS,
|
||||
TABLE_NAME,
|
||||
f"status IN ({NEW_STATUS_ENUM})",
|
||||
)
|
||||
|
||||
# [STEP 2] evidence_level Check Constraint:删除旧版 → 追加新版
|
||||
op.drop_constraint(CK_LEVEL, TABLE_NAME, type_='check')
|
||||
op.create_check_constraint(
|
||||
CK_LEVEL,
|
||||
TABLE_NAME,
|
||||
f"evidence_level IN ({NEW_LEVEL_ENUM})",
|
||||
)
|
||||
|
||||
# [STEP 3] 新增 8 个独立列;历史保持 NULL / server_default,不回填
|
||||
with op.batch_alter_table(TABLE_NAME, schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column('provider', sa.String(length=32), nullable=True),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column('provider_conversation_id', sa.String(length=128), nullable=True),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column('provider_message_id', sa.String(length=128), nullable=True),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column('latency_ms', sa.Integer(), nullable=True),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column('context_hash', sa.String(length=64), nullable=True),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
'evidence_count',
|
||||
sa.Integer(),
|
||||
nullable=False,
|
||||
server_default=sa.text('0'),
|
||||
default=0,
|
||||
),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column(
|
||||
'context_truncated',
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default=sa.text('false'),
|
||||
default=False,
|
||||
),
|
||||
)
|
||||
batch_op.add_column(
|
||||
sa.Column('auto_upgrade_reason', sa.String(length=64), nullable=True),
|
||||
)
|
||||
|
||||
# [STEP 4] 新增 3 个索引
|
||||
op.create_index(IX_PROVIDER_CONV, TABLE_NAME, ['provider_conversation_id'], unique=False)
|
||||
op.create_index(IX_CONTEXT_HASH, TABLE_NAME, ['context_hash'], unique=False)
|
||||
op.create_index(IX_STATUS_CREATED, TABLE_NAME, ['status', 'created_at'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# [STEP 1] 移除 3 个新索引
|
||||
op.drop_index(IX_STATUS_CREATED, table_name=TABLE_NAME)
|
||||
op.drop_index(IX_CONTEXT_HASH, table_name=TABLE_NAME)
|
||||
op.drop_index(IX_PROVIDER_CONV, table_name=TABLE_NAME)
|
||||
|
||||
# [STEP 2] 移除 8 个新列
|
||||
with op.batch_alter_table(TABLE_NAME, schema=None) as batch_op:
|
||||
batch_op.drop_column('auto_upgrade_reason')
|
||||
batch_op.drop_column('context_truncated')
|
||||
batch_op.drop_column('evidence_count')
|
||||
batch_op.drop_column('context_hash')
|
||||
batch_op.drop_column('latency_ms')
|
||||
batch_op.drop_column('provider_message_id')
|
||||
batch_op.drop_column('provider_conversation_id')
|
||||
batch_op.drop_column('provider')
|
||||
|
||||
# [STEP 3] evidence_level Check Constraint:回退到 v1 四枚举
|
||||
op.drop_constraint(CK_LEVEL, TABLE_NAME, type_='check')
|
||||
op.create_check_constraint(
|
||||
CK_LEVEL,
|
||||
TABLE_NAME,
|
||||
"evidence_level IN ('L1_field', 'L2_table', 'L3_page', 'L4_pdf')",
|
||||
)
|
||||
|
||||
# [STEP 4] status Check Constraint:回退到 v1,移除 gated_failed
|
||||
op.drop_constraint(CK_STATUS, TABLE_NAME, type_='check')
|
||||
op.create_check_constraint(
|
||||
CK_STATUS,
|
||||
TABLE_NAME,
|
||||
(
|
||||
"status IN ('pending', 'validated', 'validation_failed', "
|
||||
"'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable')"
|
||||
),
|
||||
)
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
backend/migrations/versions/fu2b3c4d5e6f_add_review_revalidate_progress_active_unique.py
|
||||
|
||||
用途:为 Review Revalidate Progress Job(SHIPPING_REVIEW_REVALIDATE_PROGRESS)
|
||||
增加 active(queued/running) 状态下的 domain+job_type+business_ref 部分唯一索引,
|
||||
保证同 Case + 同 draft_version 只允许一条异步协调任务在队列中或执行中。
|
||||
依赖:Alembic revision ft1a2b3c4d5e;与 STP 的 cq1a2b3c4d5e 结构严格同构。
|
||||
逻辑:先合并同 domain/business_ref 的多条 queued/running Revalidate Job(保留最大 id),
|
||||
再加部分唯一索引;index_exists / column_exists 幂等,重复执行安全。
|
||||
|
||||
Revision ID: fu2b3c4d5e6f
|
||||
Revises: ft1a2b3c4d5e
|
||||
Create Date: 2026-08-08 01:30:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = 'fu2b3c4d5e6f'
|
||||
down_revision = 'ft1a2b3c4d5e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _index_names(table: str) -> set[str]:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
return {str(ix.get('name') or '') for ix in inspector.get_indexes(table)}
|
||||
|
||||
|
||||
def _dedupe_active_revalidate_jobs() -> None:
|
||||
"""同 domain/business_ref 的多条 queued/running Revalidate Job:保留最大 id,其余标 cancelled。"""
|
||||
bind = op.get_bind()
|
||||
groups = bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT domain, business_ref
|
||||
FROM jobs
|
||||
WHERE job_type = 'shipping_review_revalidate_progress'
|
||||
AND status IN ('queued', 'running')
|
||||
AND business_ref IS NOT NULL
|
||||
GROUP BY domain, business_ref
|
||||
HAVING COUNT(*) > 1
|
||||
"""
|
||||
)
|
||||
).fetchall()
|
||||
for row in groups:
|
||||
domain = str(row[0]) if len(row) > 0 else ''
|
||||
business_ref = str(row[1]) if len(row) > 1 else ''
|
||||
ids = [
|
||||
int(sub[0])
|
||||
for sub in bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT id
|
||||
FROM jobs
|
||||
WHERE domain = :domain
|
||||
AND job_type = 'shipping_review_revalidate_progress'
|
||||
AND business_ref = :business_ref
|
||||
AND status IN ('queued', 'running')
|
||||
ORDER BY id DESC
|
||||
"""
|
||||
),
|
||||
{'domain': domain, 'business_ref': business_ref},
|
||||
).fetchall()
|
||||
]
|
||||
if len(ids) < 2:
|
||||
continue
|
||||
keep_id = ids[0]
|
||||
for drop_id in ids[1:]:
|
||||
bind.execute(
|
||||
sa.text(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'cancelled',
|
||||
message = '并发去重:合并 active shipping_review_revalidate_progress',
|
||||
progress = 100,
|
||||
locked_by = NULL,
|
||||
locked_at = NULL,
|
||||
finished_at = CURRENT_TIMESTAMP,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = :drop_id
|
||||
AND id <> :keep_id
|
||||
AND status IN ('queued', 'running')
|
||||
"""
|
||||
),
|
||||
{'drop_id': drop_id, 'keep_id': keep_id},
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""加 Revalidate active 部分唯一索引;前置去重防唯一冲突。"""
|
||||
_dedupe_active_revalidate_jobs()
|
||||
if 'uq_jobs_shipping_review_revalidate_progress_active_ref' not in _index_names('jobs'):
|
||||
op.create_index(
|
||||
'uq_jobs_shipping_review_revalidate_progress_active_ref',
|
||||
'jobs',
|
||||
['domain', 'job_type', 'business_ref'],
|
||||
unique=True,
|
||||
postgresql_where=sa.text(
|
||||
"domain = 'shipping_notice' "
|
||||
"AND job_type = 'shipping_review_revalidate_progress' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
sqlite_where=sa.text(
|
||||
"domain = 'shipping_notice' "
|
||||
"AND job_type = 'shipping_review_revalidate_progress' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除 Revalidate active 唯一索引。"""
|
||||
if 'uq_jobs_shipping_review_revalidate_progress_active_ref' in _index_names('jobs'):
|
||||
op.drop_index(
|
||||
'uq_jobs_shipping_review_revalidate_progress_active_ref',
|
||||
table_name='jobs',
|
||||
)
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
"""
|
||||
为库存候选增加 active pointer、生命周期与版本化匹配证据字段
|
||||
|
||||
Revision ID: gv3c4d5e6f7g
|
||||
Revises: fu2b3c4d5e6f
|
||||
Create Date: 2026-08-08 22:20:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = 'gv3c4d5e6f7g'
|
||||
down_revision = 'fu2b3c4d5e6f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _column_names(table: str) -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
return {str(col.get('name') or '') for col in inspector.get_columns(table)}
|
||||
|
||||
|
||||
def _index_names(table: str) -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
return {str(ix.get('name') or '') for ix in inspector.get_indexes(table)}
|
||||
|
||||
|
||||
def _constraint_names(table: str) -> set[str]:
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
names: set[str] = set()
|
||||
for item in inspector.get_check_constraints(table):
|
||||
names.add(str(item.get('name') or ''))
|
||||
for item in inspector.get_unique_constraints(table):
|
||||
names.add(str(item.get('name') or ''))
|
||||
for item in inspector.get_foreign_keys(table):
|
||||
names.add(str(item.get('name') or ''))
|
||||
return names
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
dialect = bind.dialect.name
|
||||
|
||||
shipping_cols = _column_names('shipping_notices')
|
||||
if 'active_inventory_candidate_set_id' not in shipping_cols:
|
||||
with op.batch_alter_table('shipping_notices') as batch:
|
||||
batch.add_column(sa.Column('active_inventory_candidate_set_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_notices_active_inventory_candidate_set_id',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['active_inventory_candidate_set_id'],
|
||||
['id'],
|
||||
)
|
||||
batch.create_index(
|
||||
'ix_shipping_notices_active_inventory_candidate_set_id',
|
||||
['active_inventory_candidate_set_id'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
cand_cols = _column_names('shipping_inventory_candidate_sets')
|
||||
cand_constraints = _constraint_names('shipping_inventory_candidate_sets')
|
||||
with op.batch_alter_table('shipping_inventory_candidate_sets') as batch:
|
||||
if 'lifecycle_status' not in cand_cols:
|
||||
batch.add_column(sa.Column('lifecycle_status', sa.String(length=32), nullable=False, server_default='frozen'))
|
||||
if 'superseded_at' not in cand_cols:
|
||||
batch.add_column(sa.Column('superseded_at', sa.DateTime(), nullable=True))
|
||||
if 'superseded_by_set_id' not in cand_cols:
|
||||
batch.add_column(sa.Column('superseded_by_set_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_inv_cand_sets_superseded_by_set_id',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['superseded_by_set_id'],
|
||||
['id'],
|
||||
)
|
||||
if 'invalidated_at' not in cand_cols:
|
||||
batch.add_column(sa.Column('invalidated_at', sa.DateTime(), nullable=True))
|
||||
if 'invalidated_reason' not in cand_cols:
|
||||
batch.add_column(sa.Column('invalidated_reason', sa.Text(), nullable=True))
|
||||
if 'ck_shipping_inv_cand_sets_lifecycle' not in cand_constraints:
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_inv_cand_sets_lifecycle',
|
||||
"lifecycle_status IN ('draft', 'frozen', 'superseded', 'invalidated')",
|
||||
)
|
||||
if 'uq_shipping_inv_cand_sets_task_version' not in cand_constraints:
|
||||
batch.create_unique_constraint(
|
||||
'uq_shipping_inv_cand_sets_task_version',
|
||||
['task_id', 'set_version'],
|
||||
)
|
||||
|
||||
line_cols = _column_names('shipping_inventory_candidate_lines')
|
||||
if 'source_line_no' not in line_cols:
|
||||
with op.batch_alter_table('shipping_inventory_candidate_lines') as batch:
|
||||
batch.add_column(sa.Column('source_line_no', sa.String(length=64), nullable=True))
|
||||
|
||||
match_cols = _column_names('shipping_notice_line_inventory_matches')
|
||||
match_constraints = _constraint_names('shipping_notice_line_inventory_matches')
|
||||
with op.batch_alter_table('shipping_notice_line_inventory_matches') as batch:
|
||||
if 'candidate_set_id' not in match_cols:
|
||||
batch.add_column(sa.Column('candidate_set_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_notice_line_inv_match_candidate_set_id',
|
||||
'shipping_inventory_candidate_sets',
|
||||
['candidate_set_id'],
|
||||
['id'],
|
||||
)
|
||||
if 'candidate_set_version' not in match_cols:
|
||||
batch.add_column(sa.Column('candidate_set_version', sa.Integer(), nullable=True))
|
||||
if 'candidate_line_id' not in match_cols:
|
||||
batch.add_column(sa.Column('candidate_line_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_notice_line_inv_match_candidate_line_id',
|
||||
'shipping_inventory_candidate_lines',
|
||||
['candidate_line_id'],
|
||||
['id'],
|
||||
)
|
||||
if 'allowed_source_codes_snapshot' not in match_cols:
|
||||
batch.add_column(sa.Column('allowed_source_codes_snapshot', sa.JSON(), nullable=True))
|
||||
if 'matched_qty' not in match_cols:
|
||||
batch.add_column(sa.Column('matched_qty', sa.String(length=32), nullable=True))
|
||||
if 'evidence_checksum' not in match_cols:
|
||||
batch.add_column(sa.Column('evidence_checksum', sa.String(length=64), nullable=True))
|
||||
if 'ck_shipping_notice_line_inv_match_result' in match_constraints:
|
||||
batch.drop_constraint('ck_shipping_notice_line_inv_match_result', type_='check')
|
||||
if 'ck_shipping_notice_line_inv_match_status' in match_constraints:
|
||||
batch.drop_constraint('ck_shipping_notice_line_inv_match_status', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_line_inv_match_result',
|
||||
"match_result IN ('matched', 'not_found', 'result_missing', 'preparing', 'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable', 'invalid')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_line_inv_match_status',
|
||||
"inventory_status IN ('ready', 'preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key', 'invalid')",
|
||||
)
|
||||
|
||||
if dialect != 'sqlite':
|
||||
op.execute(sa.text(
|
||||
"UPDATE shipping_inventory_candidate_sets "
|
||||
"SET lifecycle_status = 'frozen' "
|
||||
"WHERE lifecycle_status IS NULL OR lifecycle_status = ''"
|
||||
))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('shipping_notice_line_inventory_matches') as batch:
|
||||
for name in (
|
||||
'ck_shipping_notice_line_inv_match_result',
|
||||
'ck_shipping_notice_line_inv_match_status',
|
||||
):
|
||||
try:
|
||||
batch.drop_constraint(name, type_='check')
|
||||
except Exception:
|
||||
pass
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_line_inv_match_result',
|
||||
"match_result IN ('matched', 'not_found', 'result_missing', 'preparing', 'source_conflict', 'invalid_key', 'mapping_failed', 'unavailable')",
|
||||
)
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_notice_line_inv_match_status',
|
||||
"inventory_status IN ('ready', 'preparing', 'mapping_failed', 'source_conflict', 'unavailable', 'invalid_key')",
|
||||
)
|
||||
for name in (
|
||||
'evidence_checksum',
|
||||
'matched_qty',
|
||||
'allowed_source_codes_snapshot',
|
||||
'candidate_set_version',
|
||||
'candidate_line_id',
|
||||
'candidate_set_id',
|
||||
):
|
||||
try:
|
||||
batch.drop_column(name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
with op.batch_alter_table('shipping_inventory_candidate_lines') as batch:
|
||||
try:
|
||||
batch.drop_column('source_line_no')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
with op.batch_alter_table('shipping_inventory_candidate_sets') as batch:
|
||||
for name in (
|
||||
'uq_shipping_inv_cand_sets_task_version',
|
||||
'ck_shipping_inv_cand_sets_lifecycle',
|
||||
):
|
||||
try:
|
||||
batch.drop_constraint(name, type_='unique' if name.startswith('uq_') else 'check')
|
||||
except Exception:
|
||||
pass
|
||||
for name in (
|
||||
'invalidated_reason',
|
||||
'invalidated_at',
|
||||
'superseded_by_set_id',
|
||||
'superseded_at',
|
||||
'lifecycle_status',
|
||||
):
|
||||
try:
|
||||
batch.drop_column(name)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
with op.batch_alter_table('shipping_notices') as batch:
|
||||
try:
|
||||
batch.drop_column('active_inventory_candidate_set_id')
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Freeze inventory RPA Attempt identity and callback v2 facts.
|
||||
|
||||
Revision ID: gw4d5e6f7g8h
|
||||
Revises: gv3c4d5e6f7g
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'gw4d5e6f7g8h'
|
||||
down_revision = 'gv3c4d5e6f7g'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.alter_column(
|
||||
'shipping_task_inventory_rpa_attempts', 'run_no',
|
||||
new_column_name='source_run_no',
|
||||
existing_type=sa.String(length=64),
|
||||
existing_nullable=False,
|
||||
)
|
||||
op.drop_constraint('uq_shipping_task_inv_rpa_triplet', 'shipping_task_inventory_rpa_attempts', type_='unique')
|
||||
op.create_unique_constraint(
|
||||
'uq_shipping_task_inv_rpa_triplet',
|
||||
'shipping_task_inventory_rpa_attempts',
|
||||
['task_no', 'source_code', 'source_run_no'],
|
||||
)
|
||||
op.add_column('shipping_task_inventory_rpa_attempts', sa.Column('callback_id', sa.String(256), nullable=True))
|
||||
op.create_unique_constraint('uq_shipping_task_inv_rpa_callback_id', 'shipping_task_inventory_rpa_attempts', ['callback_id'])
|
||||
for name, typ in (
|
||||
('claimed_at', sa.DateTime(timezone=False)),
|
||||
('worker_id', sa.String(128)),
|
||||
('execution_phase', sa.String(64)),
|
||||
('file_path', sa.String(1024)),
|
||||
('file_sha256', sa.String(64)),
|
||||
('file_size', sa.Integer()),
|
||||
('file_exists_at_callback', sa.Boolean()),
|
||||
('transaction_status', sa.String(32)),
|
||||
('transaction_error_code', sa.String(128)),
|
||||
('transaction_error_message', sa.Text()),
|
||||
):
|
||||
op.add_column('shipping_task_inventory_rpa_attempts', sa.Column(name, typ, nullable=True))
|
||||
op.add_column('shipping_task_inventory_rpa_attempts', sa.Column('file_generated', sa.Boolean(), nullable=False, server_default=sa.false()))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('shipping_task_inventory_rpa_attempts', 'file_generated')
|
||||
for name in ('transaction_error_message', 'transaction_error_code', 'transaction_status', 'file_exists_at_callback', 'file_size', 'file_sha256', 'file_path', 'execution_phase', 'worker_id', 'claimed_at'):
|
||||
op.drop_column('shipping_task_inventory_rpa_attempts', name)
|
||||
op.drop_constraint('uq_shipping_task_inv_rpa_callback_id', 'shipping_task_inventory_rpa_attempts', type_='unique')
|
||||
op.drop_column('shipping_task_inventory_rpa_attempts', 'callback_id')
|
||||
op.drop_constraint('uq_shipping_task_inv_rpa_triplet', 'shipping_task_inventory_rpa_attempts', type_='unique')
|
||||
op.alter_column('shipping_task_inventory_rpa_attempts', 'source_run_no', new_column_name='run_no', existing_type=sa.String(length=128), existing_nullable=False)
|
||||
op.create_unique_constraint('uq_shipping_task_inv_rpa_triplet', 'shipping_task_inventory_rpa_attempts', ['task_no', 'source_code', 'run_no'])
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Add P0-3 shipping AutoProgress execution scope and Task singleton outbox.
|
||||
|
||||
Revision ID: gx5h6i7j8k9l
|
||||
Revises: gw4d5e6f7g8h
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = 'gx5h6i7j8k9l'
|
||||
down_revision = 'gw4d5e6f7g8h'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _columns(table: str) -> set[str]:
|
||||
"""读取表字段名,使迁移可安全重跑于已有测试数据库。"""
|
||||
return {str(row['name']) for row in sa.inspect(op.get_bind()).get_columns(table)}
|
||||
|
||||
|
||||
def _indexes(table: str) -> set[str]:
|
||||
"""读取现有索引名,避免历史环境重复创建。"""
|
||||
return {str(row.get('name') or '') for row in sa.inspect(op.get_bind()).get_indexes(table)}
|
||||
|
||||
|
||||
def _foreign_keys(table: str) -> dict[tuple[str, ...], str]:
|
||||
"""读取本地字段到外表的外键映射,用于修正候选集 Task 聚合根。"""
|
||||
return {
|
||||
tuple(str(name) for name in item.get('constrained_columns') or []): str(item.get('referred_table') or '')
|
||||
for item in sa.inspect(op.get_bind()).get_foreign_keys(table)
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""增加正式编排作用域、Execution 版本绑定和活动 Job 数据库唯一约束。"""
|
||||
# 早期候选迁移误将实际 ShippingNotice.id 绑定到 shipping_order_tasks;SQLite 不强制
|
||||
# FK 会掩盖此问题,但 PostgreSQL 会阻断正式 P0-3 Candidate/Execution 围栏。
|
||||
candidate_fks = _foreign_keys('shipping_inventory_candidate_sets')
|
||||
if candidate_fks.get(('task_id',)) == 'shipping_order_tasks':
|
||||
with op.batch_alter_table('shipping_inventory_candidate_sets') as batch:
|
||||
batch.drop_constraint(
|
||||
next(
|
||||
str(item.get('name') or '')
|
||||
for item in sa.inspect(op.get_bind()).get_foreign_keys('shipping_inventory_candidate_sets')
|
||||
if tuple(item.get('constrained_columns') or []) == ('task_id',)
|
||||
),
|
||||
type_='foreignkey',
|
||||
)
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_inv_cand_sets_task_id', 'shipping_notices', ['task_id'], ['id'], ondelete='CASCADE',
|
||||
)
|
||||
|
||||
job_columns = _columns('jobs')
|
||||
with op.batch_alter_table('jobs') as batch:
|
||||
for name, target in (
|
||||
('task_id', 'shipping_notices.id'),
|
||||
('execution_id', 'shipping_process_executions.id'),
|
||||
('gate_id', 'shipping_process_gates.id'),
|
||||
('candidate_set_id', 'shipping_inventory_candidate_sets.id'),
|
||||
):
|
||||
if name not in job_columns:
|
||||
batch.add_column(sa.Column(name, sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(f'fk_jobs_{name}', target.split('.')[0], [name], ['id'])
|
||||
if 'fencing_token' not in job_columns:
|
||||
batch.add_column(sa.Column('fencing_token', sa.String(length=64), nullable=True))
|
||||
|
||||
execution_columns = _columns('shipping_process_executions')
|
||||
with op.batch_alter_table('shipping_process_executions') as batch:
|
||||
if 'candidate_set_id' not in execution_columns:
|
||||
batch.add_column(sa.Column('candidate_set_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_process_executions_candidate_set_id',
|
||||
'shipping_inventory_candidate_sets', ['candidate_set_id'], ['id'],
|
||||
)
|
||||
if 'execution_revision' not in execution_columns:
|
||||
batch.add_column(sa.Column(
|
||||
'execution_revision', sa.Integer(), nullable=False, server_default='1',
|
||||
))
|
||||
|
||||
notice_columns = _columns('shipping_notices')
|
||||
if 'active_process_execution_id' not in notice_columns:
|
||||
with op.batch_alter_table('shipping_notices') as batch:
|
||||
batch.add_column(sa.Column('active_process_execution_id', sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
'fk_shipping_notices_active_process_execution_id',
|
||||
'shipping_process_executions', ['active_process_execution_id'], ['id'],
|
||||
)
|
||||
batch.create_index('ix_shipping_notices_active_process_execution_id', ['active_process_execution_id'])
|
||||
|
||||
# 兼容旧链的历史 status,同时为 P0-3 supersede/cancel 增加合法值;不收紧旧状态集合。
|
||||
with op.batch_alter_table('shipping_process_executions') as batch:
|
||||
batch.drop_constraint('ck_shipping_process_executions_status', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_process_executions_status',
|
||||
"status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed', 'superseded')",
|
||||
)
|
||||
batch.create_index('ix_shipping_process_executions_candidate_set', ['candidate_set_id', 'status'])
|
||||
with op.batch_alter_table('shipping_process_gates') as batch:
|
||||
batch.drop_constraint('ck_shipping_process_gates_status', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_process_gates_status',
|
||||
"status IN ('pending', 'queued', 'running', 'passed', 'blocked_retryable', "
|
||||
"'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped', 'cancelled')",
|
||||
)
|
||||
|
||||
index_names = _indexes('jobs')
|
||||
if 'uq_jobs_shipping_auto_progress_one_active_task' not in index_names:
|
||||
op.create_index(
|
||||
'uq_jobs_shipping_auto_progress_one_active_task', 'jobs', ['task_id'], unique=True,
|
||||
postgresql_where=sa.text(
|
||||
"domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' "
|
||||
"AND status IN ('queued', 'running') AND task_id IS NOT NULL"
|
||||
),
|
||||
sqlite_where=sa.text(
|
||||
"domain = 'shipping_notice' AND job_type = 'shipping_auto_progress' "
|
||||
"AND status IN ('queued', 'running') AND task_id IS NOT NULL"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退 P0-3 新增字段和索引;历史状态约束恢复为原始集合。"""
|
||||
try:
|
||||
op.drop_index('uq_jobs_shipping_auto_progress_one_active_task', table_name='jobs')
|
||||
except Exception:
|
||||
pass
|
||||
with op.batch_alter_table('shipping_process_gates') as batch:
|
||||
batch.drop_constraint('ck_shipping_process_gates_status', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_process_gates_status',
|
||||
"status IN ('pending', 'queued', 'running', 'passed', 'blocked_retryable', "
|
||||
"'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'skipped')",
|
||||
)
|
||||
with op.batch_alter_table('shipping_process_executions') as batch:
|
||||
batch.drop_constraint('ck_shipping_process_executions_status', type_='check')
|
||||
batch.create_check_constraint(
|
||||
'ck_shipping_process_executions_status',
|
||||
"status IN ('active', 'blocked', 'waiting_external', 'completed', 'cancelled', 'failed')",
|
||||
)
|
||||
batch.drop_index('ix_shipping_process_executions_candidate_set')
|
||||
batch.drop_column('execution_revision')
|
||||
batch.drop_constraint('fk_shipping_process_executions_candidate_set_id', type_='foreignkey')
|
||||
batch.drop_column('candidate_set_id')
|
||||
with op.batch_alter_table('shipping_notices') as batch:
|
||||
batch.drop_index('ix_shipping_notices_active_process_execution_id')
|
||||
batch.drop_constraint('fk_shipping_notices_active_process_execution_id', type_='foreignkey')
|
||||
batch.drop_column('active_process_execution_id')
|
||||
with op.batch_alter_table('jobs') as batch:
|
||||
for name in ('candidate_set_id', 'gate_id', 'execution_id', 'task_id'):
|
||||
batch.drop_constraint(f'fk_jobs_{name}', type_='foreignkey')
|
||||
batch.drop_column(name)
|
||||
batch.drop_column('fencing_token')
|
||||
Reference in new issue
Block a user