fix: harden clip disk/CPU usage on small VPS
Cap long-form concurrency, delete masters after cascade/upload, restore post-upload deletes, shorten retention to 24h, and block recording when free disk is low. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
e0776c9142
commit
896d8a64b3
@ -1,19 +1,22 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Clip retention: materials must not stay on disk longer than 48h.
|
||||
"""Clip retention + disk pressure guards.
|
||||
|
||||
Policy:
|
||||
1) Prefer using clips to fill remaining platform quotas (accelerate upload_at)
|
||||
2) Then delete files older than max_age_hours and clear job clip_path when safe
|
||||
1) Prefer rushing uploads for aging clips
|
||||
2) Delete files older than max_age_hours when safe
|
||||
3) Under disk pressure, purge oldest non-inflight clips aggressively
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from .config import settings
|
||||
|
||||
_DEFAULT_MAX_AGE_H = 48.0
|
||||
_DEFAULT_MAX_AGE_H = 24.0
|
||||
_DEFAULT_MIN_FREE_GB = 12.0
|
||||
|
||||
|
||||
def _max_age_sec(cfg: dict[str, Any]) -> float:
|
||||
@ -24,6 +27,28 @@ def _max_age_sec(cfg: dict[str, Any]) -> float:
|
||||
return max(1.0, min(168.0, h)) * 3600.0
|
||||
|
||||
|
||||
def disk_free_gb(path: str | Path | None = None) -> float:
|
||||
try:
|
||||
usage = shutil.disk_usage(str(path or settings.clips_dir))
|
||||
return float(usage.free) / (1024.0 ** 3)
|
||||
except Exception:
|
||||
return 999.0
|
||||
|
||||
|
||||
def disk_ok_for_record(cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
|
||||
"""Block new long recordings when free space is too low."""
|
||||
from . import db
|
||||
|
||||
settings_map = cfg if cfg is not None else db.get_settings_map()
|
||||
try:
|
||||
min_free = float(settings_map.get("clips_min_free_gb") or _DEFAULT_MIN_FREE_GB)
|
||||
except Exception:
|
||||
min_free = _DEFAULT_MIN_FREE_GB
|
||||
min_free = max(4.0, min(40.0, min_free))
|
||||
free = disk_free_gb()
|
||||
return free >= min_free, free
|
||||
|
||||
|
||||
def _iter_clip_files() -> list[Path]:
|
||||
root = Path(settings.clips_dir)
|
||||
out: list[Path] = []
|
||||
@ -62,7 +87,8 @@ def _accelerate_jobs_for_path(path: str, now: float) -> int:
|
||||
(
|
||||
"yt_long_jobs",
|
||||
"UPDATE yt_long_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' "
|
||||
"WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = ''",
|
||||
"WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = '' "
|
||||
"AND IFNULL(error,'') != 'cascade_only'",
|
||||
),
|
||||
)
|
||||
try:
|
||||
@ -131,38 +157,80 @@ def _job_still_needs_file(path: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def unlink_clip(path: str, *, clear_refs: bool = True) -> bool:
|
||||
p = Path(str(path or "").strip())
|
||||
if not str(p):
|
||||
return False
|
||||
try:
|
||||
if p.is_file():
|
||||
p.unlink()
|
||||
if clear_refs:
|
||||
_clear_path_refs(str(p), time.time())
|
||||
try:
|
||||
_clear_path_refs(str(p.resolve()), time.time())
|
||||
except OSError:
|
||||
pass
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""Rush pending uploads for old clips, then delete files older than retention window."""
|
||||
"""Rush pending uploads for old clips, then delete by age / disk pressure."""
|
||||
from . import db
|
||||
|
||||
settings_map = cfg if cfg is not None else db.get_settings_map()
|
||||
max_age = _max_age_sec(settings_map)
|
||||
try:
|
||||
min_free = float(settings_map.get("clips_min_free_gb") or _DEFAULT_MIN_FREE_GB)
|
||||
except Exception:
|
||||
min_free = _DEFAULT_MIN_FREE_GB
|
||||
min_free = max(4.0, min(40.0, min_free))
|
||||
|
||||
now = time.time()
|
||||
rushed = 0
|
||||
deleted = 0
|
||||
skipped_inflight = 0
|
||||
examined = 0
|
||||
for path in _iter_clip_files():
|
||||
free_before = disk_free_gb()
|
||||
|
||||
files = _iter_clip_files()
|
||||
# Oldest first helps pressure purge reclaim space quickly
|
||||
files.sort(key=lambda p: p.stat().st_mtime if p.exists() else now)
|
||||
|
||||
for path in files:
|
||||
examined += 1
|
||||
try:
|
||||
mtime = path.stat().st_mtime
|
||||
size = path.stat().st_size
|
||||
except OSError:
|
||||
continue
|
||||
age = now - mtime
|
||||
if age < max_age * 0.85:
|
||||
continue
|
||||
variants = {str(path)}
|
||||
try:
|
||||
variants.add(str(path.resolve()))
|
||||
except OSError:
|
||||
pass
|
||||
if age < max_age:
|
||||
for sp in variants:
|
||||
rushed += _accelerate_jobs_for_path(sp, now)
|
||||
continue
|
||||
|
||||
free_now = disk_free_gb()
|
||||
under_pressure = free_now < min_free
|
||||
# Under pressure: purge anything older than 2h that is not inflight
|
||||
# Normal: rush near expiry, delete past max_age
|
||||
if under_pressure:
|
||||
if age < 2 * 3600:
|
||||
continue
|
||||
else:
|
||||
if age < max_age * 0.85:
|
||||
continue
|
||||
if age < max_age:
|
||||
for sp in variants:
|
||||
rushed += _accelerate_jobs_for_path(sp, now)
|
||||
continue
|
||||
|
||||
if any(_job_still_needs_file(sp) for sp in variants):
|
||||
skipped_inflight += 1
|
||||
continue
|
||||
# cascade_only masters can be dropped immediately under pressure / age
|
||||
for sp in variants:
|
||||
_accelerate_jobs_for_path(sp, now)
|
||||
try:
|
||||
@ -170,8 +238,12 @@ def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
deleted += 1
|
||||
for sp in variants:
|
||||
_clear_path_refs(sp, now)
|
||||
_ = size
|
||||
except OSError:
|
||||
continue
|
||||
if under_pressure and disk_free_gb() >= min_free:
|
||||
break
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"examined": examined,
|
||||
@ -179,4 +251,7 @@ def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"deleted": deleted,
|
||||
"skipped_inflight": skipped_inflight,
|
||||
"max_age_hours": max_age / 3600.0,
|
||||
"free_gb_before": round(free_before, 2),
|
||||
"free_gb_after": round(disk_free_gb(), 2),
|
||||
"min_free_gb": min_free,
|
||||
}
|
||||
|
||||
@ -427,7 +427,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"shorts_upload_spread": True,
|
||||
"shorts_upload_min_gap_sec": 720,
|
||||
"shorts_channel_min_gap_sec": 2400,
|
||||
"shorts_delete_clip_after_upload": False,
|
||||
"shorts_delete_clip_after_upload": True,
|
||||
"shorts_auto_retry_failed": True,
|
||||
"shorts_auto_retry_max_attempts": 3,
|
||||
"shorts_auto_retry_interval_sec": 300,
|
||||
@ -476,7 +476,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"tiktok_upload_spread": True,
|
||||
"tiktok_upload_min_gap_sec": 720,
|
||||
"tiktok_channel_min_gap_sec": 2400,
|
||||
"tiktok_delete_clip_after_upload": False,
|
||||
"tiktok_delete_clip_after_upload": True,
|
||||
# TikTok upload SOCKS profiles (pool); each account opts in via socks_enabled=0 by default
|
||||
"tiktok_upload_socks_profiles": [],
|
||||
# X2 (Twitter/X ops agent) ingest
|
||||
@ -497,7 +497,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"x_clips_sample_any_live": True,
|
||||
"x_clips_upload_spread": True,
|
||||
"x_clips_upload_min_gap_sec": 600,
|
||||
"x_clips_delete_clip_after_post": False,
|
||||
"x_clips_delete_clip_after_post": True,
|
||||
"x_clips_daily_max": 20,
|
||||
"x_clips_caption_template": "{anchor}",
|
||||
"x_clips_account_username": "",
|
||||
@ -507,23 +507,24 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
||||
"yt_long_auto_upload": True,
|
||||
"yt_long_live_sample": True,
|
||||
"yt_long_live_sample_interval_sec": 180,
|
||||
"yt_long_live_sample_batch": 3,
|
||||
"yt_long_live_sample_batch": 1,
|
||||
"yt_long_daily_max": 42,
|
||||
"yt_long_source_daily_max": 42,
|
||||
"yt_long_channel_daily_max": 3,
|
||||
"yt_long_min_sec": 180,
|
||||
"yt_long_max_sec": 480,
|
||||
"yt_long_dedupe_room_day": True,
|
||||
"yt_long_max_concurrent": 3,
|
||||
"yt_long_max_concurrent": 1,
|
||||
"yt_long_upload_min_gap_sec": 900,
|
||||
"yt_long_delete_clip_after_upload": False,
|
||||
"yt_long_delete_clip_after_upload": True,
|
||||
"yt_long_landscape_16x9": False,
|
||||
"yt_long_auto_match_source": True,
|
||||
"yt_long_source_cap": 200,
|
||||
"yt_long_title_template": "",
|
||||
"yt_long_description_template": "",
|
||||
"clip_cascade_enabled": True,
|
||||
"clips_max_age_hours": 48,
|
||||
"clips_max_age_hours": 24,
|
||||
"clips_min_free_gb": 12,
|
||||
"tiktok_auto_retry_failed": False,
|
||||
"tiktok_auto_retry_max_attempts": 3,
|
||||
"tiktok_auto_retry_interval_sec": 300,
|
||||
|
||||
@ -1226,6 +1226,11 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st
|
||||
patch["clips_max_age_hours"] = max(1, min(168, float(raw["clips_max_age_hours"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "clips_max_age_hours 无效") from None
|
||||
if "clips_min_free_gb" in raw:
|
||||
try:
|
||||
patch["clips_min_free_gb"] = max(4, min(40, float(raw["clips_min_free_gb"])))
|
||||
except Exception:
|
||||
raise HTTPException(400, "clips_min_free_gb 无效") from None
|
||||
if "yt_long_daily_max" in raw:
|
||||
try:
|
||||
patch["yt_long_daily_max"] = max(0, min(200, int(raw["yt_long_daily_max"])))
|
||||
|
||||
@ -565,7 +565,7 @@ class ShortsPipeline:
|
||||
"channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or 2400),
|
||||
"max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)),
|
||||
"upload_max_concurrent": self._upload_max(cfg),
|
||||
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", False)),
|
||||
"delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)),
|
||||
"stats": stats,
|
||||
"board": board,
|
||||
"history": history,
|
||||
@ -1299,7 +1299,7 @@ class ShortsPipeline:
|
||||
if not won:
|
||||
# Peer already finalized — do not treat as failure; avoid deleting their state
|
||||
return
|
||||
if cfg.get("shorts_delete_clip_after_upload", False):
|
||||
if cfg.get("shorts_delete_clip_after_upload", True):
|
||||
self._delete_clip(clip)
|
||||
self._emit_shorts_event(
|
||||
kind="shorts_ok",
|
||||
|
||||
@ -711,7 +711,7 @@ class TikTokPipeline:
|
||||
oauth_checked_at=time.time(),
|
||||
oauth_error="",
|
||||
)
|
||||
if cfg.get("tiktok_delete_clip_after_upload", False):
|
||||
if cfg.get("tiktok_delete_clip_after_upload", True):
|
||||
try:
|
||||
Path(clip).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
|
||||
@ -296,7 +296,7 @@ class XClipsPipeline:
|
||||
"x_clips_auto_post": bool(cfg.get("x_clips_auto_post", True)),
|
||||
"x_clips_upload_spread": bool(cfg.get("x_clips_upload_spread", True)),
|
||||
"x_clips_upload_min_gap_sec": int(cfg.get("x_clips_upload_min_gap_sec") or 600),
|
||||
"x_clips_delete_clip_after_post": bool(cfg.get("x_clips_delete_clip_after_post", False)),
|
||||
"x_clips_delete_clip_after_post": bool(cfg.get("x_clips_delete_clip_after_post", True)),
|
||||
},
|
||||
}
|
||||
|
||||
@ -649,7 +649,7 @@ class XClipsPipeline:
|
||||
error="",
|
||||
finished_at=time.time(),
|
||||
)
|
||||
if cfg.get("x_clips_delete_clip_after_post", False):
|
||||
if cfg.get("x_clips_delete_clip_after_post", True):
|
||||
self._delete_clip(str(job.get("clip_path") or ""))
|
||||
elif st in {"failed", "cancelled"}:
|
||||
err = str(row.get("error") or st)[:500]
|
||||
|
||||
@ -407,12 +407,13 @@ class YtLongPipeline:
|
||||
"yt_long_title_template": str(cfg.get("yt_long_title_template") or ""),
|
||||
"yt_long_description_template": str(cfg.get("yt_long_description_template") or ""),
|
||||
"yt_long_delete_clip_after_upload": bool(
|
||||
cfg.get("yt_long_delete_clip_after_upload", False)
|
||||
cfg.get("yt_long_delete_clip_after_upload", True)
|
||||
),
|
||||
"yt_long_upload_min_gap_sec": int(cfg.get("yt_long_upload_min_gap_sec") or 900),
|
||||
"yt_long_landscape_16x9": bool(cfg.get("yt_long_landscape_16x9", False)),
|
||||
"clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)),
|
||||
"clips_max_age_hours": float(cfg.get("clips_max_age_hours") or 48),
|
||||
"clips_max_age_hours": float(cfg.get("clips_max_age_hours") or 24),
|
||||
"clips_min_free_gb": float(cfg.get("clips_min_free_gb") or 12),
|
||||
},
|
||||
}
|
||||
|
||||
@ -595,7 +596,32 @@ class YtLongPipeline:
|
||||
finished_at=time.time(),
|
||||
)
|
||||
return
|
||||
try:
|
||||
from .clip_retention import disk_ok_for_record, purge_stale_clips
|
||||
|
||||
ok_disk, free_gb = disk_ok_for_record(cfg)
|
||||
if not ok_disk:
|
||||
purge_stale_clips(cfg)
|
||||
ok_disk, free_gb = disk_ok_for_record(cfg)
|
||||
if not ok_disk:
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid,
|
||||
status="pending",
|
||||
error=f"disk_low:{free_gb:.1f}GB",
|
||||
started_at=0,
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
sec = _rand_clip_sec(cfg)
|
||||
# Prefer shorter masters when disk is getting tight (<16GB free)
|
||||
try:
|
||||
from .clip_retention import disk_free_gb
|
||||
|
||||
if disk_free_gb() < 16.0:
|
||||
sec = min(sec, max(YT_LONG_MIN_SEC, int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC) + 60))
|
||||
except Exception:
|
||||
pass
|
||||
outcome = await record_long_clip(job_id=jid, stream_urls=candidates, seconds=sec, cfg=cfg)
|
||||
if not outcome.get("ok"):
|
||||
err = str(outcome.get("error") or "录制失败")[:500]
|
||||
@ -633,9 +659,22 @@ class YtLongPipeline:
|
||||
pass
|
||||
if not cfg.get("yt_long_auto_upload", True):
|
||||
return
|
||||
|
||||
def _drop_master_after_cascade() -> None:
|
||||
"""Cascade-only masters are not uploaded to YT — free disk ASAP."""
|
||||
try:
|
||||
from .clip_retention import unlink_clip
|
||||
|
||||
unlink_clip(clip_path, clear_refs=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Only schedule YouTube long upload when upload quota remains
|
||||
if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0:
|
||||
yt_long_db.update_yt_long_job(jid, status="recorded", error="cascade_only", upload_at=0)
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid, status="recorded", error="cascade_only", upload_at=0, clip_path=""
|
||||
)
|
||||
_drop_master_after_cascade()
|
||||
return
|
||||
channel = None
|
||||
if str(fresh.get("channel_pk") or "").strip():
|
||||
@ -643,7 +682,10 @@ class YtLongPipeline:
|
||||
if not channel:
|
||||
channel = pick_yt_long_channel(cfg, str(fresh.get("push_date") or ""))
|
||||
if not channel:
|
||||
yt_long_db.update_yt_long_job(jid, status="recorded", error="cascade_only", upload_at=0)
|
||||
yt_long_db.update_yt_long_job(
|
||||
jid, status="recorded", error="cascade_only", upload_at=0, clip_path=""
|
||||
)
|
||||
_drop_master_after_cascade()
|
||||
return
|
||||
gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900))
|
||||
upload_at = time.time() + random.uniform(30, gap)
|
||||
@ -747,7 +789,7 @@ class YtLongPipeline:
|
||||
description=description,
|
||||
error="",
|
||||
finished_at=time.time(),
|
||||
clip_path="" if cfg.get("yt_long_delete_clip_after_upload", False) else clip,
|
||||
clip_path="" if cfg.get("yt_long_delete_clip_after_upload", True) else clip,
|
||||
)
|
||||
_emit(
|
||||
"yt_long_ok",
|
||||
@ -756,11 +798,16 @@ class YtLongPipeline:
|
||||
fresh,
|
||||
{"youtube_url": url, "video_id": vid},
|
||||
)
|
||||
if cfg.get("yt_long_delete_clip_after_upload", False):
|
||||
if cfg.get("yt_long_delete_clip_after_upload", True):
|
||||
try:
|
||||
Path(clip).unlink(missing_ok=True)
|
||||
from .clip_retention import unlink_clip
|
||||
|
||||
unlink_clip(clip, clear_refs=False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
Path(clip).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
yt_long_pipeline = YtLongPipeline()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user