重识别 Run 收口时对本 Run 可复核 Case 原子激活文件 Stream (batch_reparse_succeeded,含 Run 谱系证明与可选来源声明), 使工作台队列不再因 Stream 断链而丢失单据。 - persist 收口对本 Run 候选批量调用 resolve_satisfied_supplement_conflicts: supplement_field_conflict 的字段级裁决已 accepted(PO 行收敛唯一写入 或正式值源)即标记 resolved,不再阻断提交订单; - 投影过滤 resolved 冲突不下发待裁决面板; - 同一 field_code 表头/行级双字段(如预约单号)任一位置 accepted 即满足; - 新增测试环境失败 Run 重排队运维脚本(仅测试库硬校验、dry-run 默认)。
252 lines
11 KiB
Python
252 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
scripts/reset_test_failed_run_state.py
|
||
|
||
用途:测试环境运维脚本——把「全部 Unit 失败的订单抽取 Run」留下的假完成文档/Intake
|
||
状态复位为诚实状态,使批次面板不再显示「已完成」,用户可手动重新解析。
|
||
依赖:psycopg2;仓库根目录 `.env.test` 的 DATABASE_URL(仅测试库,硬性校验库名)。
|
||
逻辑:
|
||
1. 按 --run-no 加载终态 Run(failed/cancelled 等)及其 Intake/Document 集合;
|
||
2. 文档级:`order_extraction_status` 为 completed/partially_completed、
|
||
`order_extraction_result_json.request_id` 等于本 Run、且本 Run 在该 Intake 下
|
||
零 Candidate(假完成特征)时,复位为 not_started 并清空来源/结果/错误;
|
||
3. Intake 级:同样条件下复位(ParseStatus='consumed' 属重新解析流程的正常输入,
|
||
不在此处理,重新解析服务端支持孤儿消费 Intake);
|
||
4. 不触碰 Run/Unit/Case/MinIO(历史事实保留审计)。
|
||
默认 dry-run 只打印计划;`--apply` 才写库。单事务、幂等,重复执行为 no-op。
|
||
复位后用户在批次面板对该批附件点「重新解析」,或调用
|
||
POST /shipping-notice/order-extraction-runs/<run_no>/reparse
|
||
(reason ∈ rule_updated / field_mapping_error / document_quality / other)。
|
||
|
||
用法(仓库根目录):
|
||
python scripts/reset_test_failed_run_state.py # dry-run
|
||
python scripts/reset_test_failed_run_state.py --apply # 写入测试库
|
||
python scripts/reset_test_failed_run_state.py --run-no SNER-20261014-8EBAB7A1 --apply
|
||
python scripts/reset_test_failed_run_state.py --apply --requeue
|
||
# 复位后立即走产品自身 reparse 创建排队中的新 Run:
|
||
# 批次进度中心需要「排队中的 Run」才会显示待处理——仅复位文档状态产生不了
|
||
# 待处理(终态 Run 仍是 failed)。--requeue 复用 reparse_order_extraction_run,
|
||
# 冻结当前发布规则(含最新修复),Worker 自动处理。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
from pathlib import Path
|
||
from urllib.parse import urlparse
|
||
|
||
import psycopg2
|
||
|
||
TEST_DB_NAME = 'hxops_testing'
|
||
DEFAULT_RUN_NO = 'SNER-20261014-8EBAB7A1'
|
||
FALSE_DONE_STATUSES = ('completed', 'partially_completed')
|
||
RESET_STATUS = 'not_started'
|
||
|
||
|
||
def _load_test_db_url(repo_root: Path) -> str:
|
||
"""从仓库根 `.env.test` 读取 DATABASE_URL,并强制校验指向测试库。"""
|
||
env_path = repo_root / '.env.test'
|
||
for line in env_path.read_text(encoding='utf-8').splitlines():
|
||
if line.strip().startswith('DATABASE_URL'):
|
||
url = line.split('=', 1)[1].strip().strip('"').strip("'")
|
||
dbname = urlparse(url).path.lstrip('/')
|
||
if dbname != TEST_DB_NAME:
|
||
raise SystemExit(
|
||
f'拒绝执行:目标库 {dbname!r} 不是测试库 {TEST_DB_NAME!r}。'
|
||
'本脚本仅允许操作测试环境数据。'
|
||
)
|
||
return url
|
||
raise SystemExit(f'未在 {env_path} 找到 DATABASE_URL')
|
||
|
||
|
||
def _connect(db_url: str):
|
||
u = urlparse(db_url)
|
||
return psycopg2.connect(
|
||
host=u.hostname, port=u.port, dbname=u.path[1:],
|
||
user=u.username, password=u.password, connect_timeout=10,
|
||
)
|
||
|
||
|
||
def _load_run(cur, run_no: str):
|
||
cur.execute(
|
||
"SELECT id, run_no, status FROM shipping_order_processing_runs WHERE run_no=%s",
|
||
(run_no,),
|
||
)
|
||
run = cur.fetchone()
|
||
if run is None:
|
||
raise SystemExit(f'Run 不存在:{run_no}')
|
||
if run[2] not in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
|
||
raise SystemExit(f'Run {run_no} 状态 {run[2]!r} 非终态,不适用本脚本')
|
||
return run
|
||
|
||
|
||
def _scope(cur, run_id: int) -> tuple[list[int], list[int]]:
|
||
"""解析 Run 冻结的 Intake 集合与全部 Document id(经 plan→unit 关联)。"""
|
||
cur.execute(
|
||
"SELECT input_snapshot_json->'intakes' FROM shipping_order_processing_runs WHERE id=%s",
|
||
(run_id,),
|
||
)
|
||
snapshot_intakes = cur.fetchone()[0] or []
|
||
intake_ids = sorted({
|
||
int(item['intake_id']) for item in snapshot_intakes
|
||
if isinstance(item, dict) and str(item.get('intake_id') or '').isdigit()
|
||
})
|
||
cur.execute(
|
||
"SELECT DISTINCT u.document_id FROM shipping_order_processing_units u "
|
||
"JOIN shipping_order_processing_plans p ON p.id = u.plan_id WHERE p.run_id=%s "
|
||
"ORDER BY 1",
|
||
(run_id,),
|
||
)
|
||
document_ids = [int(r[0]) for r in cur.fetchall()]
|
||
return intake_ids, document_ids
|
||
|
||
|
||
def _candidate_counts(cur, run_id: int, intake_ids: list[int]) -> dict[int, int]:
|
||
"""统计 Run 在各 Intake 下实际落地的 Candidate 数(假完成判定依据)。"""
|
||
if not intake_ids:
|
||
return {}
|
||
cur.execute(
|
||
"SELECT intake_id, count(*) FROM shipping_order_candidates "
|
||
"WHERE order_extraction_run_id=%s AND intake_id = ANY(%s) GROUP BY intake_id",
|
||
(run_id, intake_ids),
|
||
)
|
||
return {int(row[0]): int(row[1]) for row in cur.fetchall()}
|
||
|
||
|
||
def _plan_documents(cur, run_no: str, run_id: int, document_ids: list[int], candidate_counts: dict[int, int]):
|
||
"""筛选假完成的文档:状态为完成类、结果归属本 Run、且本 Run 零 Candidate。"""
|
||
plans = []
|
||
if not document_ids:
|
||
return plans
|
||
cur.execute(
|
||
"SELECT id, order_extraction_status, "
|
||
"coalesce(order_extraction_result_json->>'request_id',''), intake_id "
|
||
"FROM shipping_order_documents WHERE id = ANY(%s) ORDER BY id",
|
||
(document_ids,),
|
||
)
|
||
for doc_id, status, request_id, intake_id in cur.fetchall():
|
||
if status not in FALSE_DONE_STATUSES:
|
||
continue
|
||
if request_id != run_no:
|
||
continue
|
||
if candidate_counts.get(int(intake_id), 0) > 0:
|
||
continue
|
||
plans.append(('document', doc_id, status))
|
||
return plans
|
||
|
||
|
||
def _plan_intakes(cur, intake_ids: list[int], candidate_counts: dict[int, int]):
|
||
"""筛选假完成的 Intake:状态为完成类且本 Run 零 Candidate。"""
|
||
plans = []
|
||
if not intake_ids:
|
||
return plans
|
||
cur.execute(
|
||
"SELECT id, order_extraction_status FROM shipping_order_intakes "
|
||
"WHERE id = ANY(%s) ORDER BY id",
|
||
(intake_ids,),
|
||
)
|
||
for intake_id, status in cur.fetchall():
|
||
if status not in FALSE_DONE_STATUSES:
|
||
continue
|
||
if candidate_counts.get(int(intake_id), 0) > 0:
|
||
continue
|
||
plans.append(('intake', intake_id, status))
|
||
return plans
|
||
|
||
|
||
def _apply_resets(cur, plans) -> None:
|
||
"""单事务执行复位;文档清结果/来源/错误,Intake 清错误。"""
|
||
doc_ids = [key for kind, key, _ in plans if kind == 'document']
|
||
intake_ids = [key for kind, key, _ in plans if kind == 'intake']
|
||
if doc_ids:
|
||
cur.execute(
|
||
"UPDATE shipping_order_documents SET order_extraction_status=%s, "
|
||
"order_extraction_source=NULL, order_extraction_result_json=NULL, "
|
||
"order_extraction_error_code=NULL, order_extraction_error_message=NULL, "
|
||
"updated_at=NOW() WHERE id = ANY(%s)",
|
||
(RESET_STATUS, doc_ids),
|
||
)
|
||
if intake_ids:
|
||
cur.execute(
|
||
"UPDATE shipping_order_intakes SET order_extraction_status=%s, "
|
||
"order_extraction_error_code=NULL, order_extraction_error_message=NULL "
|
||
"WHERE id = ANY(%s)",
|
||
(RESET_STATUS, intake_ids),
|
||
)
|
||
|
||
|
||
def _requeue_run(db_url: str, run_no: str) -> None:
|
||
"""走产品自身 reparse 服务创建排队中的新 Run(批次中心随之显示待处理)。"""
|
||
import os
|
||
import sys
|
||
|
||
os.environ['DATABASE_URL'] = db_url
|
||
backend_dir = str(Path(__file__).resolve().parents[1] / 'backend')
|
||
if backend_dir not in sys.path:
|
||
sys.path.insert(0, backend_dir)
|
||
from app import create_app
|
||
from app.extensions import db
|
||
from app.models import ShippingOrderProcessingRun
|
||
from app.services.shipping_notice.order_extraction_run_service import (
|
||
reparse_order_extraction_run,
|
||
)
|
||
|
||
app = create_app('development')
|
||
with app.app_context():
|
||
run = ShippingOrderProcessingRun.query.filter_by(run_no=run_no).with_for_update().first()
|
||
if run is None:
|
||
raise SystemExit(f'Run 不存在:{run_no}')
|
||
new_run, reused = reparse_order_extraction_run(
|
||
user_id=int(run.user_id), run_no=run_no,
|
||
reason='document_quality', comment='运维脚本重排队:上一版本全部 Unit 技术失败',
|
||
)
|
||
db.session.commit()
|
||
state = '复用既有活跃后继' if reused else '已创建'
|
||
print(f'reparse {state}:新 Run {new_run.run_no} (status={new_run.status})')
|
||
|
||
|
||
def main() -> None:
|
||
parser = argparse.ArgumentParser(description='复位失败抽取 Run 留下的假完成状态(仅测试库)')
|
||
parser.add_argument('--run-no', default=DEFAULT_RUN_NO, help=f'订单抽取 Run 编号(默认 {DEFAULT_RUN_NO})')
|
||
parser.add_argument('--apply', action='store_true', help='实际写库;缺省为 dry-run')
|
||
parser.add_argument('--requeue', action='store_true',
|
||
help='复位后走产品 reparse 创建排队中的新 Run(批次中心显示待处理并自动处理)')
|
||
args = parser.parse_args()
|
||
|
||
repo_root = Path(__file__).resolve().parents[1]
|
||
db_url = _load_test_db_url(repo_root)
|
||
conn = _connect(db_url)
|
||
cur = conn.cursor()
|
||
run_id, run_no, run_status = _load_run(cur, args.run_no)
|
||
intake_ids, document_ids = _scope(cur, run_id)
|
||
candidate_counts = _candidate_counts(cur, run_id, intake_ids)
|
||
plans = _plan_documents(cur, run_no, run_id, document_ids, candidate_counts) + \
|
||
_plan_intakes(cur, intake_ids, candidate_counts)
|
||
|
||
print(f'Run {run_no} (id={run_id}, status={run_status})')
|
||
print(f'Intake 范围: {intake_ids} | Document 范围: {document_ids}')
|
||
print(f'Run 落地 Candidate 数(按 Intake): {candidate_counts or "{}"}')
|
||
if not plans:
|
||
print('无可复位对象:状态已是诚实状态(或假完成特征不成立)。')
|
||
else:
|
||
for kind, key, status in plans:
|
||
print(f' 计划复位 [{kind} {key}]: {status} -> {RESET_STATUS}')
|
||
if not args.apply:
|
||
print('dry-run 结束(未写库)。确认无误后加 --apply 执行。')
|
||
conn.close()
|
||
return
|
||
_apply_resets(cur, plans)
|
||
conn.commit()
|
||
print(f'已提交:复位 {len(plans)} 项。')
|
||
conn.close()
|
||
if args.requeue and args.apply:
|
||
_requeue_run(db_url, run_no)
|
||
print('批次进度中心稍后刷新即显示待处理(新 Run 排队中,Worker 将自动处理)。')
|
||
elif args.requeue:
|
||
print('--requeue 需与 --apply 同时使用(跳过)。')
|
||
conn.close()
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|