fix: 禁止 TikTok 同一成片被回收任务反复重发

回收卡住上传误用了录制 started_at,刚开始上传就会被打回 scheduled 再发一次。改为只看上传租约,超时直接失败,并关掉自动重试。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 11:52:06 -05:00
parent 43d1542234
commit dfdd2c539c
3 changed files with 55 additions and 17 deletions

View File

@ -420,7 +420,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"tiktok_upload_min_gap_sec": 720,
"tiktok_channel_min_gap_sec": 2400,
"tiktok_delete_clip_after_upload": True,
"tiktok_auto_retry_failed": True,
"tiktok_auto_retry_failed": False,
"tiktok_auto_retry_max_attempts": 3,
"tiktok_auto_retry_interval_sec": 300,
"tiktok_oauth_check_interval_sec": 3600,

View File

@ -411,7 +411,8 @@ def claim_due_tiktok_upload() -> dict[str, Any] | None:
SELECT * FROM tiktok_jobs
WHERE status = 'scheduled'
AND clip_path != ''
AND tiktok_video_id = ''
AND IFNULL(tiktok_video_id,'') = ''
AND IFNULL(tiktok_publish_id,'') = ''
AND upload_at > 0
AND upload_at <= ?
ORDER BY upload_at ASC, created_at ASC
@ -423,7 +424,13 @@ def claim_due_tiktok_upload() -> dict[str, Any] | None:
return None
jid = str(row["id"])
conn.execute(
"UPDATE tiktok_jobs SET status = 'uploading', updated_at = ? WHERE id = ? AND status = 'scheduled'",
"""
UPDATE tiktok_jobs
SET status = 'uploading', updated_at = ?, attempts = attempts + 1
WHERE id = ? AND status = 'scheduled'
AND IFNULL(tiktok_video_id,'') = ''
AND IFNULL(tiktok_publish_id,'') = ''
""",
(now, jid),
)
if conn.total_changes == 0:
@ -483,7 +490,9 @@ def touch_tiktok_upload_lease(job_id: str) -> bool:
cur = conn.execute(
"""
UPDATE tiktok_jobs SET updated_at = ?
WHERE id = ? AND status = 'uploading' AND tiktok_video_id = ''
WHERE id = ? AND status = 'uploading'
AND IFNULL(tiktok_video_id,'') = ''
AND IFNULL(tiktok_publish_id,'') = ''
""",
(now, job_id),
)
@ -500,6 +509,12 @@ def finalize_tiktok_upload(
tiktok_video_id: str = "",
) -> bool:
now = time.time()
pub = str(tiktok_publish_id or "").strip()
vid = str(tiktok_video_id or "").strip() or pub
if not pub:
pub = vid or f"cookie-{job_id[:12]}"
if not vid:
vid = pub
with _lock:
conn = _connect()
try:
@ -508,9 +523,10 @@ def finalize_tiktok_upload(
UPDATE tiktok_jobs
SET status = 'uploaded', tiktok_publish_id = ?, tiktok_video_id = ?,
error = '', finished_at = ?, updated_at = ?, clip_path = ''
WHERE id = ? AND status = 'uploading' AND tiktok_video_id = ''
WHERE id = ? AND IFNULL(tiktok_video_id,'') = ''
AND status IN ('uploading', 'scheduled', 'failed', 'recorded')
""",
(tiktok_publish_id, tiktok_video_id, now, now, job_id),
(pub, vid, now, now, job_id),
)
conn.commit()
return cur.rowcount > 0
@ -519,7 +535,8 @@ def finalize_tiktok_upload(
def reclaim_stale_tiktok_uploads(*, max_age_sec: float = 900) -> int:
cutoff = time.time() - max(60.0, float(max_age_sec))
"""Only use updated_at (upload lease), never recording started_at."""
cutoff = time.time() - max(600.0, float(max_age_sec))
now = time.time()
with _lock:
conn = _connect()
@ -527,12 +544,16 @@ def reclaim_stale_tiktok_uploads(*, max_age_sec: float = 900) -> int:
cur = conn.execute(
"""
UPDATE tiktok_jobs
SET status = 'scheduled', error = '', updated_at = ?
SET status = 'failed',
error = '上传超时已中止,未再次发送(防止重复发布)',
finished_at = ?,
updated_at = ?
WHERE status = 'uploading'
AND tiktok_video_id = ''
AND COALESCE(NULLIF(started_at, 0), updated_at) < ?
AND IFNULL(tiktok_video_id,'') = ''
AND IFNULL(tiktok_publish_id,'') = ''
AND updated_at < ?
""",
(now, cutoff),
(now, now, cutoff),
)
conn.commit()
return int(cur.rowcount)
@ -549,7 +570,8 @@ def list_auto_retry_tiktok_failed(*, limit: int = 20) -> list[dict[str, Any]]:
SELECT * FROM tiktok_jobs
WHERE status = 'failed'
AND clip_path != ''
AND tiktok_video_id = ''
AND IFNULL(tiktok_video_id,'') = ''
AND IFNULL(tiktok_publish_id,'') = ''
AND attempts < 5
ORDER BY updated_at ASC
LIMIT ?

View File

@ -181,6 +181,7 @@ class TikTokPipeline:
self._last_sample_at = 0.0
self._last_oauth_check_at = 0.0
self._last_auto_retry_at = 0.0
self._upload_inflight: set[str] = set()
def status(self) -> dict[str, Any]:
cfg = db.get_settings_map()
@ -291,7 +292,7 @@ class TikTokPipeline:
for ch in tiktok_db.list_tiktok_channels(enabled=True):
asyncio.create_task(asyncio.to_thread(tiktok_session.probe_channel_session, ch))
retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300))
if cfg.get("tiktok_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval:
if cfg.get("tiktok_auto_retry_failed") and (time.time() - self._last_auto_retry_at) >= retry_interval:
self._last_auto_retry_at = time.time()
for j in tiktok_db.list_auto_retry_tiktok_failed(limit=10):
tiktok_db.update_tiktok_job(
@ -301,7 +302,7 @@ class TikTokPipeline:
error="",
)
try:
tiktok_db.reclaim_stale_tiktok_uploads(max_age_sec=180)
tiktok_db.reclaim_stale_tiktok_uploads(max_age_sec=900)
except Exception:
pass
max_up = max(1, int(cfg.get("tiktok_max_concurrent") or 1))
@ -323,18 +324,24 @@ class TikTokPipeline:
await asyncio.sleep(3)
async def _run_upload(self, job: dict[str, Any]) -> None:
jid = str(job.get("id") or "")
if not jid or jid in self._upload_inflight:
self._active_uploads = max(0, self._active_uploads - 1)
return
self._upload_inflight.add(jid)
try:
await self._do_upload(job)
self.processed += 1
except Exception as exc:
self.last_error = str(exc)[:240]
tiktok_db.update_tiktok_job(
str(job.get("id") or ""),
jid,
status="failed",
error=str(exc)[:500],
finished_at=time.time(),
)
finally:
self._upload_inflight.discard(jid)
self._active_uploads = max(0, self._active_uploads - 1)
async def _run_record(self, job: dict[str, Any]) -> None:
@ -402,6 +409,13 @@ class TikTokPipeline:
cfg = db.get_settings_map()
jid = str(job.get("id") or "")
fresh = tiktok_db.get_tiktok_job(jid) or job
if str(fresh.get("tiktok_video_id") or "").strip() or str(fresh.get("tiktok_publish_id") or "").strip():
tiktok_db.finalize_tiktok_upload(
jid,
tiktok_publish_id=str(fresh.get("tiktok_publish_id") or ""),
tiktok_video_id=str(fresh.get("tiktok_video_id") or ""),
)
return
clip = str(fresh.get("clip_path") or "")
if not clip or not Path(clip).is_file():
raise ValueError("成片文件不存在")
@ -431,10 +445,12 @@ class TikTokPipeline:
privacy_level=str(channel.get("privacy_level") or "PUBLIC_TO_EVERYONE"),
channel_pk=str(channel["id"]),
)
pub = str(result.get("publish_id") or "").strip() or f"cookie-{jid[:12]}"
vid = str(result.get("video_id") or "").strip() or pub
if not tiktok_db.finalize_tiktok_upload(
jid,
tiktok_publish_id=str(result.get("publish_id") or ""),
tiktok_video_id=str(result.get("video_id") or ""),
tiktok_publish_id=pub,
tiktok_video_id=vid,
):
return
tiktok_db.update_tiktok_channel(