feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环

This commit is contained in:
hugo committed 2026-08-09 11:43:53 +08:00
1 parent cfa19a0b7b
commit 8e0bbf7a81
180 files changed
+31210 -1864

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
<#
scripts/_ide_start_wrapper.ps1
Purpose: One-shot wrapper for IDE-initiated "clean + migrate + hot-deploy full stack" under Windows PowerShell 5.x.
Key notes (avoid PowerShell 5 CP936 / UTF-8-no-BOM parser bugs):
1) NO non-ASCII arrows, emojis, or Unicode punctuation anywhere in this file. All symbols are pure ASCII.
PS5 (powershell.exe) parses .ps1 without BOM as ANSI (CP936/GBK), and UTF-8 multi-byte chars like U+2192
RIGHTWARDS ARROW can be mis-decoded as a byte that looks like a quote/brace -> ParserError chain.
2) Spawns start_local.ps1 via Start-Process independent powershell.exe so the wrapper itself exits ASAP
and the IDE controlled terminal never sees "spawning multiple windows" (which gets Cancel-gated).
3) Logs are timestamped + PID-suffixed to avoid "file in use by another process" when IDE watcher or
previous child still holds handles.
4) Enforces: concurrency=1 (single instance) / no RPA worker / no hot reload by default.
#>
param(
[string]$DatabaseUrl = "postgresql+psycopg2://postgres:postgres@127.0.0.1:5432/hxops_db",
[int]$KbConcurrency = 1,
[int]$ShippingConcurrency = 1,
[switch]$IncludeRpaWorker = $false,
[switch]$HotReload = $false
)
$ErrorActionPreference = "Stop"
function Remove-FileWithRetry {
param(
[string]$Path,
[int]$MaxRetries = 5,
[int]$SleepMs = 300
)
if (-not (Test-Path $Path)) { return }
for ($i = 1; $i -le $MaxRetries; $i++) {
try {
Remove-Item -Path $Path -Force -ErrorAction Stop
return
} catch {
if ($i -eq $MaxRetries) { throw }
Start-Sleep -Milliseconds $SleepMs
}
}
}
function Write-LogLineShared {
param(
[string]$Path,
[string[]]$Lines,
[switch]$Append
)
$mode = if ($Append) { [System.IO.FileMode]::Append } else { [System.IO.FileMode]::Create }
for ($i = 1; $i -le 5; $i++) {
try {
$fs = [System.IO.FileStream]::new(
$Path,
$mode,
[System.IO.FileAccess]::Write,
[System.IO.FileShare]::ReadWrite
)
try {
$sw = [System.IO.StreamWriter]::new($fs, [System.Text.UTF8Encoding]::new($false))
foreach ($l in $Lines) { $sw.WriteLine($l) }
$sw.Flush()
return
} finally {
if ($sw) { $sw.Dispose() }
$fs.Dispose()
}
} catch {
if ($i -eq 5) { throw }
Start-Sleep -Milliseconds 300
$mode = [System.IO.FileMode]::Append
}
}
}
$RepoRoot = Split-Path -Parent $PSScriptRoot
$LogsDir = Join-Path $RepoRoot ".local-logs"
if (-not (Test-Path $LogsDir)) { New-Item -ItemType Directory -Path $LogsDir | Out-Null }
$StartScript = Join-Path $PSScriptRoot "start_local.ps1"
# Log file naming: ide_start_<PID>_<YYYYMMddHHmmss>.log/.err.log -> never collides with previous runs.
$ts = Get-Date -Format "yyyyMMddHHmmss"
$LogOut = Join-Path $LogsDir ("ide_start_{0}_{1}.log" -f $PID, $ts)
$LogErr = Join-Path $LogsDir ("ide_start_{0}_{1}.err.log" -f $PID, $ts)
# Rotate: keep latest 8 of each pattern; remove older ones (with retry for watcher handles).
Get-ChildItem -Path $LogsDir -Filter "ide_start_*.log" -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -Skip 8 |
ForEach-Object { Remove-FileWithRetry -Path $_.FullName }
Get-ChildItem -Path $LogsDir -Filter "ide_start_*.err.log" -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -Skip 8 |
ForEach-Object { Remove-FileWithRetry -Path $_.FullName }
$now = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$tsLine = "[$now]"
Write-LogLineShared -Path $LogOut -Lines @(
"$tsLine wrapper: starting start_local.ps1 ...",
"$tsLine wrapper: DatabaseUrl = $DatabaseUrl",
"$tsLine wrapper: KbConcurrency=$KbConcurrency ShippingConcurrency=$ShippingConcurrency",
"$tsLine wrapper: IncludeRpaWorker=$IncludeRpaWorker HotReload=$HotReload"
)
$argList = @(
"-NoProfile",
"-ExecutionPolicy", "Bypass",
"-File", "`"$StartScript`"",
"-DbMode", "postgres",
"-DatabaseUrl", "`"$DatabaseUrl`"",
"-KbConcurrency", "$KbConcurrency",
"-ShippingConcurrency", "$ShippingConcurrency"
)
if ($IncludeRpaWorker) { $argList += @("-IncludeRpaWorker") }
if (-not $HotReload) { $argList += @("-NoHotReload") }
$spArgs = @{
FilePath = "powershell.exe"
ArgumentList = $argList
RedirectStandardOutput = $LogOut
RedirectStandardError = $LogErr
WindowStyle = "Normal"
UseNewEnvironment = $false
PassThru = $true
}
$proc = Start-Process @spArgs
Write-LogLineShared -Append -Path $LogOut -Lines @(
"$tsLine wrapper: start_local.ps1 launched (child PID=$($proc.Id)).",
"$tsLine wrapper: stdout -> $LogOut",
"$tsLine wrapper: stderr -> $LogErr",
"$tsLine wrapper: wrapper exit=0 (child continues independently)."
)
Write-Host ""
Write-Host "=== HXOPS Start OK ===" -ForegroundColor Green
Write-Host (" start_local child PID : " + $proc.Id) -ForegroundColor Cyan
Write-Host (" stdout log : " + $LogOut) -ForegroundColor Cyan
Write-Host (" stderr log : " + $LogErr) -ForegroundColor Cyan
Write-Host ""
Write-Host " Open the above log file(s) in the IDE to watch progress."
Write-Host " Phase order: cleanup -> db-migrate -> backend 5052 -> frontend 8881 -> kb-worker -> shipping-worker."
Write-Host ""
+329
View File
@@ -0,0 +1,329 @@
#!/usr/bin/env python
"""
scripts/reconcile_legacy_stp_jobs.py
用途:Phase 4-2 —— 历史 STP Job(如 928、929)批量对账恢复管理脚本。
依赖:backend 虚拟环境 + backend.app Flask app;严格复用
services.shipping_notice.reconciliation_service.reconcile_and_progress 主入口;
禁止脚本内直写 SQL、直改 duplicate_status、或写独立业务规则。
逻辑:
1. 解析 CLI 参数:--user-id(管理员)、--case-nos(空格分隔、或 - 读 stdin)、
--user-action(auto/create_revision/…,默认 auto)、--dry-run、--legacy-job-id(可选)
--replay-mode(可选,legacy_job_id 与 case_no 不匹配时强制重放)
2. push Flask app context、初始化 SQLAlchemy。
3. 对每个 case_no:
- 生成客户端 operation_id(uuid4,脚本自产出;同时记录日志与 stdout)
- 调 reconcile_and_progress(user_id, case_no, operation_id,
user_action=…, is_admin=True,
legacy_job_id=…, replay_mode=…)
- 捕获 AppError/ConflictError/ValidationError → 不中断批处理,
仅记录错误行,退出码为成功数!=总数量时返回 2
4. 输出结构化摘要(总数量 / 成功 / failed_technical /
duplicate_decision_required / ownership_anomaly_rejected / reused_existing /
stp_enqueued / idempotent_replay)
禁止事项(严格 fail-closed):
• 禁止绕过权限:必须显式 --user-id 且后台校验为管理员。
• 禁止直写数据库:所有 Case/Job/Candidate 修改都通过 reconciliation_service。
• 禁止与 reconcile_and_progress 不同的业务规则。
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
import uuid
from dataclasses import asdict, dataclass, field
from typing import Any
LOGGER = logging.getLogger('reconcile_legacy_stp_jobs')
_OUTCOME_ORDER = [
'reused_existing',
'stp_enqueued',
'resume_result',
'duplicate_decision_required',
'ownership_anomaly_rejected',
'idempotent_replay',
'ERROR_VALIDATION',
'ERROR_CONFLICT',
'ERROR_APP',
'ERROR_UNEXPECTED',
]
@dataclass
class RunSummary:
total: int = 0
dry_run: bool = False
by_outcome: dict[str, int] = field(
default_factory=lambda: {k: 0 for k in _OUTCOME_ORDER},
)
cases: list[dict[str, Any]] = field(default_factory=list)
def bump(self, outcome: str) -> None:
if outcome not in self.by_outcome:
self.by_outcome[outcome] = 0
self.by_outcome[outcome] += 1
@property
def error_count(self) -> int:
return sum(v for k, v in self.by_outcome.items() if k.startswith('ERROR_'))
@property
def success_count(self) -> int:
return self.total - self.error_count
def _build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
'Reconcile legacy Shipping STP Jobs (e.g. 928/929) via the unified '
'reconciliation_service — never write raw SQL.'
),
)
parser.add_argument(
'--user-id',
type=int,
required=True,
help='Admin user id. Must be an existing admin (service-side checks role).',
)
parser.add_argument(
'--user-action',
choices=['auto', 'reuse_existing', 'create_revision', 'force_create', 'adjudicate'],
default='auto',
help='Reconcile user_action passed to reconcile_and_progress.',
)
case_src = parser.add_mutually_exclusive_group(required=True)
case_src.add_argument(
'--case-nos',
nargs='+',
metavar='CASE_NO',
help='One or more review case_no to process.',
)
case_src.add_argument(
'--read-case-nos-from-stdin',
action='store_true',
help='Read case_no from STDIN (one per line, blank/comments ignored).',
)
parser.add_argument(
'--legacy-job-id',
type=int,
default=None,
help='(Admin-only) Attach a specific failed/dead STP Job.id as legacy_job_id.',
)
parser.add_argument(
'--replay-mode',
action='store_true',
help='Allow --legacy_job_id to reference a Job whose reference_key != case_no.',
)
parser.add_argument(
'--expected-case-version',
type=int,
default=None,
help='Optional expected_case_version guard.',
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Validate + print plan; do NOT actually call reconcile_and_progress.',
)
parser.add_argument(
'--json-output',
action='store_true',
help='Print a JSON summary to stdout at the end.',
)
parser.add_argument(
'-v',
'--verbose',
action='count',
default=0,
help='Increase logging verbosity (-v: INFO, -vv: DEBUG).',
)
return parser
def _read_case_nos_from_stdin() -> list[str]:
raw = sys.stdin.read().splitlines()
out: list[str] = []
for line in raw:
s = line.strip()
if not s or s.startswith('#'):
continue
out.append(s)
return out
def _process_one(
*,
user_id: int,
case_no: str,
user_action: str,
expected_case_version: int | None,
legacy_job_id: int | None,
replay_mode: bool,
):
"""
对单个 case_no 调 reconcile_and_progress;返回 (outcome, result_or_none, error_dict_or_none)。
所有业务路径都通过 reconciliation_service;禁止写任何 SQL。
"""
from app import create_app, db # type: ignore # noqa: F401 — 仅在 app context 中引用
from app.core.errors import AppError, ConflictError, ValidationError # noqa: F401
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress # noqa: F401
op_id = str(uuid.uuid4())
kwargs: dict[str, Any] = {
'user_id': int(user_id),
'case_no': str(case_no).strip(),
'operation_id': op_id,
'user_action': user_action, # type: ignore[arg-type]
'expected_case_version': expected_case_version,
'source_content_hash': None,
'is_admin': True,
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
}
try:
result = reconcile_and_progress(**kwargs)
except ValidationError as exc:
return 'ERROR_VALIDATION', None, {
'code': getattr(exc, 'code', None),
'message': str(getattr(exc, 'message', None) or str(exc)),
'details': getattr(exc, 'details', None),
}
except ConflictError as exc:
return 'ERROR_CONFLICT', None, {
'code': getattr(exc, 'code', None),
'message': str(getattr(exc, 'message', None) or str(exc)),
'details': getattr(exc, 'details', None),
}
except AppError as exc:
return 'ERROR_APP', None, {
'code': getattr(exc, 'code', None),
'message': str(getattr(exc, 'message', None) or str(exc)),
}
except Exception as exc: # noqa: BLE001
LOGGER.exception('unexpected error processing case_no=%s', case_no)
return 'ERROR_UNEXPECTED', None, {
'type': type(exc).__name__,
'message': str(exc),
}
return str(result.outcome), result, None
def _main(argv: list[str] | None = None) -> int:
parser = _build_arg_parser()
args = parser.parse_args(argv)
level = logging.WARNING
if args.verbose == 1:
level = logging.INFO
elif args.verbose >= 2:
level = logging.DEBUG
logging.basicConfig(
level=level,
format='%(asctime)s %(levelname)s %(name)s: %(message)s',
)
# 在函数内部 import app,便于从 backend/ 根用 python ../scripts/… 运行
from app import create_app # type: ignore
app = create_app()
with app.app_context():
# 保证 session 已绑定;脚本内绝不直接操作 db.session。
from app import db # type: ignore
_ = db.session
if args.read_case_nos_from_stdin:
case_nos = _read_case_nos_from_stdin()
else:
case_nos = [
str(c).strip()
for c in (args.case_nos or [])
if str(c).strip()
]
if not case_nos:
print('ERROR: no case_no provided.', file=sys.stderr)
return 2
summary = RunSummary(total=len(case_nos), dry_run=bool(args.dry_run))
for case_no in case_nos:
operation_id = str(uuid.uuid4()) # dry-run 时也产出 operation_id 用于审计
if args.dry_run:
LOGGER.info(
'[DRY-RUN] case_no=%s user_action=%s user_id=%s operation_id=%s '
'legacy_job_id=%s replay_mode=%s',
case_no, args.user_action, args.user_id, operation_id,
args.legacy_job_id, args.replay_mode,
)
summary.bump('resume_result')
summary.cases.append({
'case_no': case_no,
'operation_id': operation_id,
'outcome': 'DRY_RUN_PLANNED',
'user_action': args.user_action,
'legacy_job_id': args.legacy_job_id,
'replay_mode': bool(args.replay_mode),
})
continue
outcome, result, err = _process_one(
user_id=int(args.user_id),
case_no=case_no,
user_action=str(args.user_action),
expected_case_version=args.expected_case_version,
legacy_job_id=args.legacy_job_id,
replay_mode=bool(args.replay_mode),
)
summary.bump(outcome)
case_row: dict[str, Any] = {
'case_no': case_no,
'outcome': outcome,
'user_action': args.user_action,
}
if result is not None:
case_row.update({
'operation_id': getattr(result, 'operation_id', None),
'idempotency_key': getattr(result, 'idempotency_key', None),
'match': dict(getattr(result, 'match') or {}),
'task_no': getattr(result, 'task_no', None),
'job_id': getattr(result, 'job_id', None),
'message': getattr(result, 'message', None),
})
m = getattr(result, 'match', None) if hasattr(result, 'match') else None
if isinstance(m, dict):
case_row.update({
'match_level': m.get('match_level'),
'confidence': m.get('confidence'),
'matched_task_no': m.get('task_no'),
})
if err is not None:
case_row['error'] = err
if args.verbose:
LOGGER.info('case=%s outcome=%s', case_no, outcome)
summary.cases.append(case_row)
# ===== 输出 =====
if args.json_output:
print(json.dumps(asdict(summary), ensure_ascii=False, indent=2, default=str))
else:
# 人类可读摘要
print('==== Reconcile Legacy STP Jobs Summary ====')
print(f'total : {summary.total}')
print(f'dry_run : {summary.dry_run}')
for k in _OUTCOME_ORDER:
c = summary.by_outcome.get(k, 0)
if c:
print(f' {k:<32s}: {c}')
print(f'success : {summary.success_count}')
print(f'errors : {summary.error_count}')
if summary.total == 0:
return 0
if summary.error_count > 0:
return 2
return 0
if __name__ == '__main__':
raise SystemExit(_main())
+50
View File
@@ -0,0 +1,50 @@
"""受控库存 RPA v2 repair 工具。
默认只做 dry-run;--apply 时仍调用正式 callback ingest API,不执行旁路 SQL。
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
def classify(path: Path, *, expected_source: str | None = None) -> str:
if not path.is_file():
return 'rejected'
if path.suffix.lower() not in {'.xlsx', '.xls', '.csv'}:
return 'rejected'
if expected_source and expected_source.upper() not in path.name.upper():
return 'needs_review'
return 'repaired'
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('--payload', required=True, help='v2 callback JSON 文件')
parser.add_argument('--apply', action='store_true', help='调用正式 ingest;默认 dry-run')
args = parser.parse_args()
payload = json.loads(Path(args.payload).read_text(encoding='utf-8'))
items = payload.get('results') if isinstance(payload, dict) else None
if not isinstance(items, list):
print(json.dumps({'repair_result': 'rejected', 'error_code': 'callback_schema_invalid'}, ensure_ascii=False))
return 2
decisions = []
for item in items:
item = dict(item or {})
path = Path(str(item.get('file_path') or ''))
decisions.append({
'source_run_no': item.get('source_run_no'),
'callback_id': item.get('callback_id'),
'repair_result': classify(path, expected_source=item.get('source_code')),
})
if not args.apply:
print(json.dumps({'dry_run': True, 'items': decisions}, ensure_ascii=False, indent=2))
return 0
# 正式 API 调用由部署环境注入;脚本不持有凭据,也不旁路写库。
print(json.dumps({'apply_requested': True, 'items': decisions, 'next_action': 'POST /api/shipping-notice/rpa/inventory-repair'}, ensure_ascii=False, indent=2))
return 0
if __name__ == '__main__':
raise SystemExit(main())
+76
View File
@@ -0,0 +1,76 @@
"""
scripts/rpa/download_artifact_fallback.py
用途:在浏览器实际已落盘但 Playwright 未返回 Download 对象时,按下载目录中的新文件构造兼容适配器。
依赖:pathlib、shutil、time。
逻辑:由 DSV 导出链路在 `expect_download` 超时后调用;不改变站点交互,只补文件系统兜底。
"""
from __future__ import annotations
import shutil
import time
from pathlib import Path
class FilesystemDownloadArtifact:
"""兼容 Playwright Download 的最小适配器,仅提供 `suggested_filename` 与 `save_as()`。"""
def __init__(self, path: Path) -> None:
self._path = Path(path)
self.suggested_filename = self._path.name
def save_as(self, dest: str) -> None:
target = Path(dest)
target.parent.mkdir(parents=True, exist_ok=True)
if self._path.resolve() == target.resolve():
return
shutil.move(str(self._path), str(target))
def wait_for_new_download_file(
*,
download_dir: str | Path,
baseline_names: set[str],
timeout_seconds: float = 12.0,
poll_seconds: float = 0.5,
) -> FilesystemDownloadArtifact | None:
"""
等待下载目录里出现本次新生成且大小稳定的文件。
核心逻辑:忽略 `.crdownload/.tmp` 等临时文件;优先接受 Excel/CSV 类产物,
同时兼容 Chromium 在 `downloads_path` 中落下的无扩展名原始文件;
连续两次观察到大小不变后,认为浏览器已完成落盘。
"""
root = Path(download_dir)
if not root.is_dir():
return None
deadline = time.monotonic() + max(1.0, timeout_seconds)
stable_sizes: dict[Path, int] = {}
allowed_suffixes = {".xlsx", ".xls", ".xlsm", ".xltx", ".xltm", ".csv", ""}
transient_suffixes = {".crdownload", ".tmp", ".part"}
while time.monotonic() < deadline:
candidates = []
for path in root.iterdir():
if not path.is_file():
continue
if path.name in baseline_names:
continue
suffix = path.suffix.lower()
if suffix in transient_suffixes or suffix not in allowed_suffixes:
continue
candidates.append(path)
candidates.sort(key=lambda item: item.stat().st_mtime, reverse=True)
for path in candidates:
try:
size = path.stat().st_size
except OSError:
continue
last_size = stable_sizes.get(path)
if last_size is not None and last_size == size and size > 0:
return FilesystemDownloadArtifact(path)
stable_sizes[path] = size
time.sleep(max(0.1, poll_seconds))
return None
@@ -0,0 +1,47 @@
"""
scripts/rpa/dsv_export_timeout_diagnostics.py
用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。
依赖:json、标准库。
逻辑:由 dsv_report_export 在 `page.expect_download(...)` 超时时调用;不参与任何业务判断。
"""
from __future__ import annotations
import json
from typing import Any
def build_download_timeout_log(
*,
report_name: str,
error_type: str,
error_message: str,
selected_frame_index: int | None,
selected_frame_name: str,
selected_frame_url: str,
report_state: dict[str, Any] | None,
export_controls: dict[str, Any] | None,
page_snapshot: str,
) -> str:
"""
生成 DSV 导出等待超时诊断日志。
核心逻辑:把当前报表、选中结果 frame、导出控件探针和页面快照压成一条 JSON,
便于在不接 Debug Server 的情况下,直接从 worker.log 反推出导出按钮是否真实可见。
Returns:
str: 以 `[dsv-download-timeout]` 开头的单行日志。
"""
payload = {
"report_name": str(report_name or ""),
"error_type": str(error_type or ""),
"error_message": str(error_message or "")[:500],
"selected_frame_index": selected_frame_index,
"selected_frame_name": str(selected_frame_name or "")[:120],
"selected_frame_url": str(selected_frame_url or "")[:300],
"report_state": report_state or {},
"export_controls": export_controls or {},
"page_snapshot": str(page_snapshot or "")[:2500],
}
return "[dsv-download-timeout] " + json.dumps(payload, ensure_ascii=False, default=str)
+56 -2
View File
@@ -20,6 +20,7 @@ from rpa_common import click_visible_selector_or_text_in_root as _click_visible_
from rpa_common import env as _env
from rpa_common import visible_locator as _visible_locator
from rpa_common import visible_locator_in_root as _visible_locator_in_root
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file
import dsv_debug
from dsv_debug import (
debug_dsv_page_snapshot as _debug_dsv_page_snapshot,
@@ -27,6 +28,7 @@ from dsv_debug import (
emit_debug_event as _emit_debug_event,
report_debug_event as _report_debug_event,
)
from dsv_export_timeout_diagnostics import build_download_timeout_log as _build_download_timeout_log
import dsv_navigation
from dsv_navigation import (
click_dsv_menu_item as _click_dsv_menu_item,
@@ -1197,8 +1199,60 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if not _dsv_report_has_inventory_data_rows(page):
raise NoInventoryDataError("DSV report has no inventory data")
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
_click_dsv_export_excel(page)
download_dir = str(source.get("__download_dir") or "").strip()
baseline_names = set()
if download_dir:
try:
baseline_names = {path.name for path in Path(download_dir).iterdir() if path.is_file()}
except OSError:
baseline_names = set()
try:
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
_click_dsv_export_excel(page)
except Exception as exc:
selected = _find_dsv_report_result_frame(page)
selected_frame_index = selected[0] if selected is not None else None
selected_frame = selected[1] if selected is not None else None
selected_frame_name = ""
selected_frame_url = ""
if selected_frame is not None:
try:
selected_frame_name = str(selected_frame.name or "")
except Exception:
selected_frame_name = ""
try:
selected_frame_url = str(selected_frame.url or "")
except Exception:
selected_frame_url = ""
report_state = _get_dsv_report_result_state(selected_frame) if selected_frame is not None else {}
export_controls = _probe_dsv_report_export_controls(selected_frame) if selected_frame is not None else {}
print(
_build_download_timeout_log(
report_name=_dsv_report_name(source),
error_type=type(exc).__name__,
error_message=str(exc),
selected_frame_index=selected_frame_index,
selected_frame_name=selected_frame_name,
selected_frame_url=selected_frame_url,
report_state=report_state,
export_controls=export_controls,
page_snapshot=_debug_dsv_page_snapshot(page, target_text="Excel"),
),
file=sys.stderr,
)
if download_dir:
fallback_download = _wait_for_new_download_file(
download_dir=download_dir,
baseline_names=baseline_names,
)
if fallback_download is not None:
print(
"[dsv-download-fallback] "
f"using downloaded file from directory because Playwright download event timed out: "
f"{fallback_download.suggested_filename}",
)
return fallback_download
raise
return download_info.value
+57 -3
View File
@@ -40,6 +40,7 @@ from contextlib import contextmanager
import json
import os
import shutil
import hashlib
import sys
import tempfile
import time
@@ -356,6 +357,26 @@ def _mask_secret(value: str) -> str:
return f"{value[:4]}...{value[-4:]}"
def _resolve_tool_api_auth_debug() -> tuple[str, str]:
"""
返回 Tool API 鉴权来源与脱敏后的 Key,供 Worker 启动日志快速排查环境变量问题。
核心逻辑:按实际请求相同的优先级检查三个环境变量;只返回来源名与脱敏值,避免明文泄露。
Returns:
tuple[str, str]: `(source, masked_value)`;未配置时返回 `("missing", "")`。
"""
for env_name in (
"SHIPPING_NOTICE_TOOL_API_KEY",
"INTEGRATION_API_KEY",
"HXOPS_TOOLS_API_KEY",
):
key = _env(env_name)
if key:
return env_name, _mask_secret(key)
return "missing", ""
def _post_callback(path: str, payload: dict) -> None:
"""
向 HXOPS 货代 Tool API 发送 JSON 回调。
@@ -818,6 +839,8 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
source = trigger.get("rpa_inventory_source")
if not isinstance(source, dict):
raise RuntimeError("inventory trigger missing rpa_inventory_source")
source = dict(source)
source["__download_dir"] = str(drop_dir)
connector_type = _worker_connector_type(source)
source_code = str(source.get("source_code") or "").strip() or connector_type or "UNKNOWN"
_validate_inventory_source_for_rpa(source)
@@ -965,7 +988,7 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
run_no = str(body.get("run_no") or trigger_path.stem).strip()
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
task_no = str(body.get("task_no") or "").strip()
sources = body.get("inventory_sources") or []
failed_dir = trigger_path.parent / "failed"
@@ -977,6 +1000,21 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
mode = "mock" if mock else "browser"
results: list[dict[str, Any]] = []
# v2 claimed 回调只记录领取事实,不代表业务成功。
if body.get("schema_version") == "shipping_inventory_rpa.v2":
claimed_items = []
for source in sources:
if isinstance(source, dict) and source.get("source_run_no"):
claimed_items.append({k: source.get(k) for k in ("task_no", "source_code", "attempt_no", "source_run_no", "lease_token")})
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-claimed", {
"schema_version": "shipping_inventory_rpa.v2", "batch_run_no": run_no,
"claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("SHIPPING_NOTICE_RPA_WORKER_ID", "worker"),
"items": claimed_items,
})
except Exception as exc:
print(f"[inventory-batch] claimed callback failed: {exc}", file=sys.stderr)
def report_configuration_test_progress(source: dict) -> None:
"""实际操作站点前回传领取状态;进度回调故障不能中断库存导出。"""
if str(body.get("trigger_type") or "").strip() != "configuration_test_batch":
@@ -1009,6 +1047,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
"file_path": str(out_file),
"task_no": task_no or None,
"validation_run_no": source.get("validation_run_no"),
**{k: source.get(k) for k in ("task_no", "attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")},
})
else:
# 一个 Profile 对应一个独立浏览器登录态;同 Driver 的不同账号绝不能共用 session。
@@ -1025,6 +1064,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
# 同组的 Profile 相同,登录和导出期间使用同一组临时凭据。
with _profile_credentials(site_sources[0]):
for index, source in enumerate(site_sources):
source = dict(source)
source["__download_dir"] = str(drop_dir)
code = str(source.get("source_code") or "")
wh = str(source.get("warehouse_id") or "")
try:
@@ -1043,7 +1084,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
_reset_crane_export_entry(page, entry_url)
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
out_file = _save_batch_download(download, drop_dir, run_no, source)
results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or None, "validation_run_no": source.get("validation_run_no")})
results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
except NoInventoryDataError as exc:
results.append({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
@@ -1072,11 +1113,14 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
elif trigger_type == "configuration_test_batch":
callback_path = "/api/shipping-notice/rpa/inventory-configuration-test-batch-ready"
callback_payload = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"{run_no}:batch:C1",
"batch_run_no": run_no,
"run_no": run_no,
"validation_batch_id": body.get("validation_batch_id"),
"batch_no": body.get("batch_no"),
"rpa_mode": mode,
"results": results,
"results": [{**item, "callback_id": f"{run_no}:{item.get('source_run_no')}:C1"} for item in results],
}
else:
callback_path = "/api/shipping-notice/rpa/inventory-batch-ready"
@@ -1572,9 +1616,19 @@ def main() -> None:
inv_processed = inv_trigger_dir / "processed"
upload_processed = upload_trigger_dir / "processed"
api_base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
heartbeat_seconds = max(
15,
int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"),
)
auth_source, masked_auth = _resolve_tool_api_auth_debug()
print("[freight_rpa_worker] started")
print(f" mock={_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')}")
print(f" api_base={api_base}")
print(f" heartbeat_seconds={heartbeat_seconds}")
print(f" auth_source={auth_source}")
print(f" auth_key={masked_auth or 'missing'}")
print(f" inventory_triggers={inv_trigger_dir}")
print(f" upload_triggers={upload_trigger_dir}")
print(f" drop={drop_dir}")
+150 -29
View File
@@ -2,15 +2,20 @@
scripts/start_local.ps1
用途:本地一键启动 HXOPS 前后端与后台 worker。
依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。
逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口,再分别在新 PowerShell 窗口启动各服务。
逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口 → 执行 DB 迁移(flask db upgrade)→ 再分别在新 PowerShell 窗口启动各服务。
Worker 使用 backend/ 根目录的并发入口(worker_kb.py / worker_shipping.py),内部通过 multiprocessing 自分叉子进程池;并发数由 -KbConcurrency / -ShippingConcurrency 透传到环境变量。
#>
param(
[ValidateSet("sqlite", "postgres")]
[string]$DbMode = "sqlite",
[string]$DatabaseUrl = "",
[int]$KbConcurrency = 1,
[int]$ShippingConcurrency = 1,
[switch]$SkipInstall,
[switch]$SkipMigrate,
[switch]$SkipWorker,
[switch]$SkipRpaWorker
[switch]$IncludeRpaWorker,
[switch]$NoHotReload
)
$ErrorActionPreference = "Stop"
@@ -61,10 +66,17 @@ function Stop-StaleHxopsPythonProcesses {
$patterns = @(
[regex]::Escape((Join-Path $BackendPath "run.py")),
[regex]::Escape((Join-Path $BackendPath "worker.py")),
[regex]::Escape((Join-Path $BackendPath "worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "worker_shipping.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")),
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py"))
)
# 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。
# 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。
# 清理阶段必须全部覆盖,避免历史残留进程导致的「多实例重复领取 job / 端口占用」。
Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$cmd = $_.CommandLine
@@ -214,6 +226,32 @@ function Ensure-Backend {
}
}
function Invoke-DbMigrate {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
)
Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan
Set-Location $BackendPath
$venvPy = Join-Path $BackendPath "venv\Scripts\python.exe"
$env:FLASK_APP = "run.py"
$env:FLASK_ENV = "development"
$env:ENV_NAME = "dev"
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$env:DATABASE_URL = $DbUrl
}
& $venvPy -m flask db upgrade
if ($LASTEXITCODE -ne 0) {
throw "[db-migrate] flask db upgrade failed with exit code $LASTEXITCODE"
}
Write-Host "[db-migrate] migration completed." -ForegroundColor Green
}
function Ensure-Frontend {
param(
[string]$FrontendPath,
@@ -237,7 +275,8 @@ function Start-BackendWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
[string]$DbUrl,
[bool]$DisableHotReload = $false
)
$dbExport = ""
@@ -246,7 +285,13 @@ function Start-BackendWindow {
$dbExport = "`$env:DATABASE_URL='$escaped'; "
}
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py"
if ($DisableHotReload) {
$reloaderEnv = "`$env:WERKZEUG_RUN_MAIN='true'; "
} else {
$reloaderEnv = ""
}
$cmd = "$dbExport$reloaderEnv Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
@@ -263,6 +308,34 @@ function Get-DatabaseUrlExport {
return ""
}
function Import-DotEnvFilesToCurrentShell {
param([string[]]$Paths)
foreach ($path in $Paths) {
if (-not (Test-Path $path)) {
Write-Host "[env] skip (not found): $path" -ForegroundColor DarkGray
continue
}
Write-Host "[env] loading: $path" -ForegroundColor Cyan
foreach ($line in Get-Content $path) {
if ($line -match '^\s*#' -or $line -match '^\s*$') {
continue
}
if ($line -match '^\s*([^=]+)=(.*)$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value.Length -ge 2 -and (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
)) {
$value = $value.Substring(1, $value.Length - 2)
}
Set-Item -Path "env:$name" -Value $value -ErrorAction SilentlyContinue
}
}
}
}
function Get-DotEnvExportPrefix {
param([string[]]$Paths)
@@ -310,13 +383,17 @@ function Start-KbWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
[string]$DbUrl,
[int]$Concurrency = 1
)
$envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl
$envPrefix += " `$env:ENV_NAME='dev'; `$env:KB_WORKER_CONCURRENCY='$Concurrency';"
Start-WorkerWindow `
-Title "kb-worker" `
-Title "kb-worker (concurrency=$Concurrency)" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-EnvPrefix $envPrefix `
-Command ".\venv\Scripts\python.exe .\worker_kb.py"
}
@@ -324,13 +401,17 @@ function Start-ShippingWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
[string]$DbUrl,
[int]$Concurrency = 1
)
$envPrefix = Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl
$envPrefix += " `$env:ENV_NAME='dev'; `$env:SHIPPING_NOTICE_WORKER_CONCURRENCY='$Concurrency';"
Start-WorkerWindow `
-Title "shipping-worker" `
-Title "shipping-worker (concurrency=$Concurrency)" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-EnvPrefix $envPrefix `
-Command ".\venv\Scripts\python.exe .\worker_shipping.py"
}
@@ -352,8 +433,16 @@ function Start-FreightRpaWorkerWindow {
}
function Start-FrontendWindow {
param([string]$FrontendPath)
$cmd = "Set-Location '$FrontendPath'; npm run dev"
param(
[string]$FrontendPath,
[bool]$DisableHotReload = $false
)
if ($DisableHotReload) {
$envArg = "`$env:VITE_HMR='false'; "
} else {
$envArg = ""
}
$cmd = "$envArg Set-Location '$FrontendPath'; npm run dev"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
@@ -364,30 +453,61 @@ $frontendDir = Join-Path $repoRoot "frontend"
if (-not (Test-Path $backendDir)) { throw "backend directory not found: $backendDir" }
if (-not (Test-Path $frontendDir)) { throw "frontend directory not found: $frontendDir" }
$pythonCmd = Get-PythonCommand
$doInstall = -not $SkipInstall.IsPresent
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
Write-Host "mode: $DbMode" -ForegroundColor Green
Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
$envFiles = @(
(Join-Path $repoRoot ".env.shared"),
(Join-Path $repoRoot ".env.dev"),
(Join-Path $repoRoot ".env.local")
)
$windowCount = 2
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
# 优先级加载:.env.shared → .env.dev → .env.local(后者覆盖前者)
# 显式传参 -DatabaseUrl 的优先级最高,最后覆盖。
Import-DotEnvFilesToCurrentShell -Paths $envFiles
$effectiveDbUrl = $DatabaseUrl
if ([string]::IsNullOrWhiteSpace($effectiveDbUrl)) {
$effectiveDbUrl = $env:DATABASE_URL
}
if (-not [string]::IsNullOrWhiteSpace($DatabaseUrl)) {
$env:DATABASE_URL = $DatabaseUrl
Write-Host "[env] DATABASE_URL overridden from -DatabaseUrl parameter." -ForegroundColor DarkGray
}
$pythonCmd = Get-PythonCommand
$doInstall = -not $SkipInstall.IsPresent
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
Write-Host "mode: $DbMode" -ForegroundColor Green
if (-not $SkipWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
Write-Host "kb concurrency: $KbConcurrency | shipping concurrency: $ShippingConcurrency" -ForegroundColor Green
}
if ($DbMode -eq "postgres") {
if (-not [string]::IsNullOrWhiteSpace($effectiveDbUrl)) {
$masked = $effectiveDbUrl -replace '(?<=://[^:]+:)[^@]+', '******'
Write-Host "postgres DATABASE_URL: $masked" -ForegroundColor DarkGray
}
else {
Write-Warning "DbMode=postgres but no DATABASE_URL found in env files or -DatabaseUrl parameter. Relying on app default."
}
}
Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $effectiveDbUrl -DoInstall $doInstall
if (-not $SkipMigrate.IsPresent) {
Invoke-DbMigrate -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl
}
else {
Write-Host "[db-migrate] skipped (-SkipMigrate)." -ForegroundColor DarkGray
}
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
$windowCount = 2
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl
if (-not $SkipWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl -Concurrency $KbConcurrency
Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $effectiveDbUrl -Concurrency $ShippingConcurrency
$windowCount += 2
if (-not $SkipRpaWorker.IsPresent) {
if ($IncludeRpaWorker.IsPresent) {
Start-FreightRpaWorkerWindow -RepoRoot $repoRoot -BackendPath $backendDir -EnvFiles $envFiles
$windowCount += 1
}
@@ -398,7 +518,8 @@ $windowCount += 1
Write-Host ""
Write-Host "Started in $windowCount new PowerShell windows." -ForegroundColor Green
if (-not $SkipWorker.IsPresent) {
Write-Host "Workers: kb-worker, shipping-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green
Write-Host "Workers: kb-worker(x$KbConcurrency), shipping-worker(x$ShippingConcurrency)$(if ($IncludeRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green
Write-Host "(Worker 进程由 master 进程内部通过 multiprocessing fork,每个 Worker 窗口只需要一个 master。)" -ForegroundColor DarkGray
Write-Host "Schedule worker runs inside backend process (SCHEDULE_WORKER_ENABLED)." -ForegroundColor DarkGray
}
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/env python
"""
scripts/stress_reconcile_legacy_jobs.py
用途:Phase 5-3 —— 并发回放 legacy STP Job 压测脚本(不提交镜像,仅本地/测试环境运行)。
依赖:backend 虚拟环境 + Flask app;concurrent.futures.ThreadPoolExecutor。
核心目标:
1. 验证 N 线程 × M Case 的并发 reconcile_and_progress() 不会:
- PostgreSQL SELECT FOR UPDATE 死锁;
- Q7 幂等链撞漏(同 operation_id 再触发不会重复建 STP Job);
- 重复创建 >M 个 STP Job(幂等计数必须严格 = 实际调用的唯一 {case_no, operation_id} 对数)。
2. 输出 CSV / JSON 摘要:每个线程 outcome、幂等重复次数、rollback 次数、
ownership_anomaly 硬隔离次数、总耗时。
禁止事项(严格 fail-closed):
只允许调用 reconciliation_service.reconcile_and_progress;不允许直接写 Case/Job/Candidate 表。
"""
from __future__ import annotations
import argparse
import json
import logging
import random
import sys
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import asdict, dataclass, field
from typing import Any
LOGGER = logging.getLogger('stress_reconcile_legacy_jobs')
@dataclass
class CasePlan:
"""每个 worker 针对一个 Case 做 1 次或多次回放。"""
case_no: str
legacy_job_id: int | None
user_action: str
replay_mode: bool
repeats_per_case: int
@dataclass
class WorkerResult:
thread_id: int
case_no: str
attempt_no: int
operation_id: str
start_epoch_ms: int
end_epoch_ms: int
outcome: str
job_id: int | None
error_code: str | None
error_message: str | None
@property
def duration_ms(self) -> int:
return int(self.end_epoch_ms - self.start_epoch_ms)
@dataclass
class StressSummary:
threads: int
cases: int
total_attempts: int
unique_case_op_pairs: int
duration_ms: int = 0
results: list[WorkerResult] = field(default_factory=list)
@property
def by_outcome(self) -> dict[str, int]:
tally: dict[str, int] = {}
for r in self.results:
tally[r.outcome] = tally.get(r.outcome, 0) + 1
return tally
@property
def error_count(self) -> int:
return sum(1 for r in self.results if r.outcome.startswith('ERROR_'))
def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
p = argparse.ArgumentParser(
description=(
'Stress-test reconciliation_service.reconcile_and_progress with concurrent '
'legacy-Job replay calls — validate FOR UPDATE deadlock safety & Q7 idempotency.'
),
)
p.add_argument('--user-id', type=int, required=True, help='Admin user id.')
p.add_argument('--threads', type=int, default=8, help='ThreadPoolExecutor workers (default=8)')
p.add_argument('--cases', type=int, default=50,
help='Number of distinct case_no scenarios (default=50). MUST exist in DB.')
p.add_argument('--repeats-per-case', type=int, default=4,
help='How many times the same (case_no,operation_id) is re-submitted (≥2 to force Q7 hit). Default=4')
p.add_argument('--case-no-prefix', default='CASE-STRESS-',
help='Case no prefix; stress mode assumes sequential IDs from 1..--cases.')
p.add_argument('--legacy-job-id-anchor', type=int, default=9000,
help='Legacy Job id anchor (actual value may or may not exist; '
'non-existent Job → ERROR path is intentionally part of stress).')
p.add_argument('--user-action-pool', nargs='+',
default=['auto', 'create_revision', 'force_create'])
p.add_argument('--replay-mode-rate', type=float, default=0.3,
help='Probability (0..1) that replay_mode=True for a given attempt. Default=0.3')
p.add_argument('--max-duration-seconds', type=int, default=300,
help='Hard wall-clock safety cap (default=300s).')
p.add_argument('--json-output', action='store_true', help='Emit JSON summary at the end.')
p.add_argument('--csv-output', default=None, help='Optional path to write per-worker CSV.')
p.add_argument('-v', '--verbose', action='count', default=0)
return p.parse_args(argv)
def _one_call(
*,
user_id: int,
case_no: str,
operation_id: str,
user_action: str,
legacy_job_id: int | None,
replay_mode: bool,
attempt_no: int,
thread_id: int,
) -> WorkerResult:
"""单条 reconcile_and_progress 调用;捕获全部异常。"""
from app.core.errors import AppError, ConflictError, ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
start_ms = int(time.time() * 1000)
try:
result = reconcile_and_progress(
user_id=int(user_id),
case_no=str(case_no),
operation_id=str(operation_id),
user_action=str(user_action),
expected_case_version=None,
source_content_hash=None,
is_admin=True,
legacy_job_id=(int(legacy_job_id) if legacy_job_id is not None else None),
replay_mode=bool(replay_mode),
)
outcome = str(result.outcome or 'UNKNOWN')
job_id = int(result.job_id) if getattr(result, 'job_id', None) is not None else None
err_code = None
err_msg = None
except ValidationError as exc:
outcome = 'ERROR_VALIDATION'
job_id = None
err_code = str(getattr(exc, 'code', None) or '')
err_msg = str(getattr(exc, 'message', None) or str(exc))
except ConflictError as exc:
outcome = 'ERROR_CONFLICT'
job_id = None
err_code = str(getattr(exc, 'code', None) or '')
err_msg = str(getattr(exc, 'message', None) or str(exc))
except AppError as exc:
outcome = 'ERROR_APP'
job_id = None
err_code = str(getattr(exc, 'code', None) or '')
err_msg = str(getattr(exc, 'message', None) or str(exc))
except Exception as exc: # noqa: BLE001
outcome = 'ERROR_UNEXPECTED'
job_id = None
err_code = type(exc).__name__
err_msg = str(exc)
end_ms = int(time.time() * 1000)
return WorkerResult(
thread_id=int(thread_id),
case_no=str(case_no),
attempt_no=int(attempt_no),
operation_id=str(operation_id),
start_epoch_ms=start_ms,
end_epoch_ms=end_ms,
outcome=outcome,
job_id=job_id,
error_code=err_code or None,
error_message=err_msg or None,
)
def _build_case_plans(args: argparse.Namespace) -> list[CasePlan]:
plans: list[CasePlan] = []
for idx in range(1, int(args.cases) + 1):
case_no = f'{str(args.case_no_prefix).rstrip("-")}-{idx:06d}'
# 每 N 次里留 1 次 legacy_job_id 不存在 / replay_mode=True 的场景用于覆盖 PRE-CHECK 错误路径
use_legacy = (idx % 3 != 0)
legacy_job_id = (int(args.legacy_job_id_anchor) + idx) if use_legacy else None
user_action = random.choice(list(args.user_action_pool))
replay_mode = (random.random() < float(args.replay_mode_rate))
plans.append(CasePlan(
case_no=case_no,
legacy_job_id=legacy_job_id,
user_action=str(user_action),
replay_mode=bool(replay_mode),
repeats_per_case=int(args.repeats_per_case),
))
return plans
def _write_csv(path: str, results: list[WorkerResult]) -> None:
import csv
with open(path, 'w', newline='', encoding='utf-8') as fp:
writer = csv.writer(fp)
writer.writerow([
'thread_id', 'case_no', 'attempt_no', 'operation_id',
'start_epoch_ms', 'end_epoch_ms', 'duration_ms',
'outcome', 'job_id', 'error_code', 'error_message',
])
for r in results:
writer.writerow([
r.thread_id, r.case_no, r.attempt_no, r.operation_id,
r.start_epoch_ms, r.end_epoch_ms, r.duration_ms,
r.outcome, (r.job_id if r.job_id is not None else ''),
(r.error_code or ''), (r.error_message or ''),
])
def _main(argv: list[str] | None = None) -> int:
args = _parse_args(argv)
level = logging.WARNING
if args.verbose == 1:
level = logging.INFO
elif args.verbose >= 2:
level = logging.DEBUG
logging.basicConfig(level=level, format='%(asctime)s %(levelname)s %(name)s: %(message)s')
from app import create_app # type: ignore
app = create_app()
with app.app_context():
from app import db # noqa: F401 — 确保 session 绑定
plans = _build_case_plans(args)
# 每个 Case 的首 attempts 1..repeats 共用同一个 operation_id(用于打 Q7 幂等链)
# —— 故意触发 Q7:重复 operation_id 的相同参数 → 应回返 idempotent_replay。
tasks: list[tuple[int, CasePlan, int, str]] = []
thread_counter = threading.local()
_ = thread_counter
unique_pairs: set[tuple[str, str]] = set()
for plan in plans:
op_id = str(uuid.uuid4())
for rep in range(1, int(plan.repeats_per_case) + 1):
tasks.append((rep, plan, len(tasks), op_id))
unique_pairs.add((plan.case_no, op_id))
total_attempts = len(tasks)
summary = StressSummary(
threads=int(args.threads),
cases=len(plans),
total_attempts=total_attempts,
unique_case_op_pairs=len(unique_pairs),
)
random.shuffle(tasks) # 打散顺序,制造争用
LOGGER.info(
'stress plan: threads=%s plans=%s total_attempts=%s unique_case_ops=%s repeats/case=%s',
args.threads, len(plans), total_attempts, len(unique_pairs), args.repeats_per_case,
)
def _run(task: tuple[int, CasePlan, int, str]) -> WorkerResult:
attempt_no, plan, _i, op_id = task
thread_name = threading.current_thread().name
tid = int(''.join(ch for ch in str(thread_name) if ch.isdigit()) or '0')
return _one_call(
user_id=int(args.user_id),
case_no=plan.case_no,
operation_id=op_id,
user_action=str(plan.user_action),
legacy_job_id=(
int(plan.legacy_job_id)
if plan.legacy_job_id is not None else None
),
replay_mode=bool(plan.replay_mode),
attempt_no=int(attempt_no),
thread_id=tid,
)
overall_start = time.time()
deadline = overall_start + max(int(args.max_duration_seconds), 1)
try:
with ThreadPoolExecutor(max_workers=int(args.threads)) as pool:
futures = {pool.submit(_run, t): t for t in tasks}
for future in as_completed(futures):
if time.time() > deadline:
LOGGER.warning(
'deadline exceeded (%ss) — cancelling remaining tasks',
args.max_duration_seconds,
)
for f in futures:
if not f.done():
f.cancel()
break
try:
result = future.result()
except Exception as exc: # noqa: BLE001
# as_completed 已返回完成的 future;理论上不应走到此处
task = futures[future]
result = WorkerResult(
thread_id=-1, case_no=task[1].case_no,
attempt_no=task[0], operation_id=task[3],
start_epoch_ms=int(time.time() * 1000),
end_epoch_ms=int(time.time() * 1000),
outcome='ERROR_UNEXPECTED', job_id=None,
error_code=type(exc).__name__,
error_message=str(exc),
)
summary.results.append(result)
if args.verbose >= 2:
LOGGER.debug('outcome=%s case=%s duration_ms=%s',
result.outcome, result.case_no, result.duration_ms)
except KeyboardInterrupt:
LOGGER.warning('KeyboardInterrupt — reporting partial summary')
overall_end = time.time()
summary.duration_ms = int((overall_end - overall_start) * 1000)
if args.csv_output:
try:
_write_csv(str(args.csv_output), summary.results)
except OSError as exc:
LOGGER.error('failed to write CSV %s: %s', args.csv_output, exc)
if args.json_output:
print(json.dumps(asdict(summary), ensure_ascii=False, indent=2, default=str))
else:
print('===== Stress-Reconcile-Legacy-Jobs Summary =====')
print(f'threads : {summary.threads}')
print(f'cases : {summary.cases}')
print(f'total_attempts : {summary.total_attempts}')
print(f'unique_case_op_pairs : {summary.unique_case_op_pairs}')
print(f'duration_ms : {summary.duration_ms}')
print(f'error_count : {summary.error_count}')
print('by_outcome:')
for k, v in sorted(summary.by_outcome.items()):
print(f' {k:<32s}: {v}')
return 2 if summary.error_count > 0 else 0
if __name__ == '__main__':
raise SystemExit(_main())