339 lines
13 KiB
Python
339 lines
13 KiB
Python
#!/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())
|