fix(database): Recalculate batch run metrics from team results on cleanup

- Aggregate total_registered and total_added_to_s2a from batch_team_results table
- Calculate success_rate based on actual S2A additions vs total owners
- Compute duration_seconds from started_at and finished_at timestamps
- Improve stuck batch run recovery by restoring accurate metrics instead of zeroing them out
This commit is contained in:
2026-02-07 02:52:06 +08:00
parent 40a9da0809
commit 02ddb48f21

View File

@@ -612,13 +612,28 @@ func (d *DB) GetBatchRuns(limit int) ([]BatchRun, error) {
return runs, nil return runs, nil
} }
// CleanupStuckBatchRuns 清理卡住的 running 状态批次记录 // CleanupStuckBatchRuns 清理卡住的 running 状态批次记录,从子结果重新计算汇总
func (d *DB) CleanupStuckBatchRuns() (int64, error) { func (d *DB) CleanupStuckBatchRuns() (int64, error) {
// 先从 batch_team_results 重新汇总数据,再标记为 completed
result, err := d.db.Exec(` result, err := d.db.Exec(`
UPDATE batch_runs UPDATE batch_runs
SET status = 'completed', SET status = 'completed',
finished_at = COALESCE(finished_at, started_at), finished_at = COALESCE(finished_at, started_at),
duration_seconds = 0 total_registered = COALESCE((
SELECT SUM(registered) FROM batch_team_results WHERE batch_id = batch_runs.id
), 0),
total_added_to_s2a = COALESCE((
SELECT SUM(added_to_s2a) FROM batch_team_results WHERE batch_id = batch_runs.id
), 0),
success_rate = CASE
WHEN total_owners > 0 THEN
COALESCE((SELECT SUM(added_to_s2a) FROM batch_team_results WHERE batch_id = batch_runs.id), 0) * 100.0 / (total_owners * 4)
ELSE 0
END,
duration_seconds = CASE
WHEN finished_at IS NOT NULL THEN CAST((julianday(finished_at) - julianday(started_at)) * 86400 AS INTEGER)
ELSE 0
END
WHERE status = 'running' WHERE status = 'running'
`) `)
if err != nil { if err != nil {