videogen/apps/api/app/workers/tasks_deferred_start.py
caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

157 lines
6.3 KiB
Python

"""Queue a reel while render disk is short instead of refusing it with a 503.
``pipeline.start_pipeline`` used to raise ``PreflightError`` when free space
at the render directory was below the floor, so the API refunded the debit
and the visitor saw "try again in a few minutes" -- the one real Menivor user
(2026-11-12) was refused 3 of 4 times this way. Now the job stays queued and
this task re-checks capacity every :data:`RECHECK_S` seconds:
* space back -> the real render chain is enqueued and ``Job.celery_task_id``
points at it (cancel still revokes the right task);
* still short -> the row is touched (so the stalled-reel reaper, which keys on
``Job.updated_at``, never retries it into a second chain) and the check is
re-scheduled;
* waited longer than :data:`MAX_WAIT_S` (``MENIVOR_DEFER_MAX_WAIT_S``, default
2 h) -> the same fail-and-refund path the reaper uses, plus the in-app
notification and one email.
Only the newest deferral for a job acts (``stages["_deferred"]["task"]``), so a
racing retry never starts two chains. Runs on the ``housekeeping`` queue.
"""
from __future__ import annotations
import os
import time
from typing import Any
from loguru import logger
from app.models import const
from app.workers.celery_app import celery_app
DEFER_MARKER = "_deferred"
RECHECK_S = 60
DEFAULT_MAX_WAIT_S = 2 * 3600
TASK_NAME = "app.workers.tasks_deferred_start.deferred_start_task"
celery_app.conf.task_routes[TASK_NAME] = {"queue": "housekeeping"}
def max_wait_s() -> int:
raw = (os.environ.get("MENIVOR_DEFER_MAX_WAIT_S") or "").strip()
try:
return max(RECHECK_S, int(raw)) if raw else DEFAULT_MAX_WAIT_S
except ValueError:
return DEFAULT_MAX_WAIT_S
def _stamp(job_id: str, task_id: str, since: float) -> bool:
"""Record this deferral as the job's current one (also bumps ``updated_at``)."""
from app.domains.reels.refunds import _locked_job
from app.models.db.base import get_session
with get_session() as session:
job = _locked_job(session, job_id)
if job is None or job.state != const.TASK_STATE_PROCESSING:
return False
job.stages = {**(job.stages or {}), DEFER_MARKER: {"task": task_id, "since": since}}
job.celery_task_id = task_id
return True
def _is_current(job_id: str, task_id: str) -> bool:
from app.models.db.base import get_session
from app.models.db.models import Job
with get_session() as session:
job = session.get(Job, job_id)
if job is None or job.state != const.TASK_STATE_PROCESSING:
return False
marker = (job.stages or {}).get(DEFER_MARKER) or {}
return marker.get("task") == task_id
def _clear_marker(job_id: str) -> None:
from app.domains.reels.refunds import _locked_job
from app.models.db.base import get_session
with get_session() as session:
job = _locked_job(session, job_id)
if job is not None:
stages = dict(job.stages or {})
stages.pop(DEFER_MARKER, None)
job.stages = stages
def defer(job_id: str, params_dict: dict, lane: str | None, *, since: float | None = None) -> str:
"""Schedule a capacity re-check for ``job_id``; returns the deferral task id."""
started = time.time() if since is None else since
result = deferred_start_task.apply_async(
args=(job_id, params_dict, lane, started), countdown=RECHECK_S
)
if not _stamp(job_id, result.id, started):
logger.info(f"deferred start: job {job_id} is no longer processing; not queued")
else:
logger.warning(f"deferred start: job {job_id} queued for render space (task {result.id})")
return result.id
def _give_up(job_id: str) -> None:
from app.domains.reels.refunds import STALLED_ERROR, fail_and_refund_stalled_reel
outcome = fail_and_refund_stalled_reel(job_id, "script")
if not outcome["failed"]:
return
logger.error(
f"deferred start: job {job_id} waited past {max_wait_s()}s for render space; "
f"stopped, refunded {outcome['refunded_credits']} credit(s)"
)
try:
from app.models.db.base import get_session
from app.models.db.models import Job
from app.services import notifications
with get_session() as session:
job = session.get(Job, job_id)
user_id = str(job.user_id) if job is not None else ""
if user_id:
notifications.notify_job_failed(user_id, job_id, STALLED_ERROR)
except Exception as exc: # noqa: BLE001 - notification is best-effort
logger.warning(f"deferred start: notification for job {job_id} failed: {exc}")
try:
from app.services.job_emails import send_reel_stopped_email
send_reel_stopped_email(job_id)
except Exception as exc: # noqa: BLE001
logger.warning(f"deferred start: email for job {job_id} failed: {exc}")
@celery_app.task(bind=True, name=TASK_NAME, soft_time_limit=60, time_limit=90)
def deferred_start_task(self, job_id: str, params_dict: dict, lane: str | None, since: float) -> dict[str, Any]:
"""One capacity re-check for a queued reel (see the module docstring)."""
from app.workers import pipeline, preflight
from app.workers.tasks import _build_params
try:
if not _is_current(job_id, self.request.id):
return {"job_id": job_id, "action": "superseded"}
if preflight.check().ok:
_clear_marker(job_id)
task_id = pipeline.enqueue_chain(job_id, _build_params(params_dict), lane)
from app.models.db.base import get_session
from app.models.db.repositories import JobRepository
with get_session() as session:
JobRepository(session).set_celery_task_id(job_id, task_id)
logger.info(f"deferred start: job {job_id} started after waiting for space (task {task_id})")
return {"job_id": job_id, "action": "started", "task": task_id}
if time.time() - since > max_wait_s():
_give_up(job_id)
return {"job_id": job_id, "action": "refunded"}
defer(job_id, params_dict, lane, since=since)
return {"job_id": job_id, "action": "requeued"}
except Exception as exc: # noqa: BLE001 - a broken check must not strand the credit
logger.error(f"deferred start: job {job_id} check failed: {type(exc).__name__}: {exc}")
_give_up(job_id)
return {"job_id": job_id, "action": "error"}