Skip to Content
Slloy Docs
Generation, Settlement & Safeguards

Video Generation, Polling & Atomic Settlement

Two-phase async video pipeline, portrait bridge, browser polling vs. 5-minute Cron sweeper, atomic conditional settlement, and 24-hour signed URL expiry rules.

Video generation takes 30 seconds to several minutes upstream. Slloy processes video tasks via a two-phase asynchronous pipeline (server/src/http/routes/video.ts, server/src/videoSettle.ts, and server/src/videoSweeper.ts).

1. Phase 1: Task Creation (POST /api/video/generate)

  1. Rate Limit & Parameter Normalization:
    • Protected by a dedicated rate limiter (scope: "video", config.videoRateLimitMax = 6 requests per minute per user).
    • Validates prompt (<= 1500 chars), ratio (16:9, 9:16, 1:1), model (from videoModels.ts), resolution (defaults to 720p if supported, else model.resolutions[0]), and duration (clamped to config.videoDurations filtered by model.maxDuration; locked to 5s for fixedDuration: true models).
    • Validates optional firstFrame via checkRefImage() (imageSniff.ts). Models with requiresFirstFrame: true (wan-i2v-flash, wan-i2v, kling3-i2v) reject requests missing firstFrame with HTTP 400 FIRST_FRAME_REQUIRED before charging credits.
  2. Daily Spending Caps (videoDailyGuard):
  3. Pre-Charge & keepAlive Upstream Submission:
    • Inserts a generations row (kind = 'video', status = 'pending', est_tokens) and deducts credits via repo.chargeCredit.
    • Wraps the upstream provider.createVideoTask() call and DB taskId update in keepAlive(c, submit) (ctx.waitUntil) so a client disconnecting mid-submission does not leave an orphan charged row without a task_id.
    • For per-second priced providers (DashScope and Kling), costCny is locked and written to the DB immediately upon task creation (model.provider !== "ark"). For token-billed Ark Seedance, costCny remains null until settlement returns usageTokens.
  4. Portrait Bridge for Ark Real-Face Rejection (portraitBridge.ts):
    • Volcengine Ark Seedance 2.x rejects first-frame photos containing real human faces with InputImageSensitiveContentDetected.PrivacyInformation (failCode === "INPUT_PRIVACY").
    • When config.portraitBridge is enabled and an Ark Seedance 2.x task fails creation with INPUT_PRIVACY, /api/video/generate automatically invokes bridgePortrait() once: it redraws the first frame into an AI-stylized portrait via Seedream image-to-image (which Ark trusts) and retries createVideoTask with the bridged frame, returning bridged: true in the response.

2. Phase 2: Dual-Source Settlement (videoSettle.ts)

Once a video task is created, two independent drivers can settle it:

  1. Foreground Browser Polling (GET /api/video/status/:id): Polled every 2 seconds while the user has the page open (allowTrueUp: true).
  2. Background 5-Minute Cron Sweeper (server/src/videoSweeper.ts): Scans pending video tasks older than config.videoSweep.minAgeMin (default 5 minutes) every 5 minutes (allowTrueUp: false), rescuing videos where the user closed the browser tab before completion.

Both drivers call the exact same functions in server/src/videoSettle.ts (settleVideoGeneration, forceFailVideoGeneration, decideVideoAction) so financial accounting, R2 persistence, and refunds never diverge.

Atomic Conditional Settlement & Row Locking

  • Success Path:
    1. Downloads and persists the video to R2 (persistImage(t.videoUrl, { genId: gen.id })) before claiming the DB status—because R2 persistence is idempotent, whereas claiming success before persisting would make a persistence failure irreversible.
    2. Atomically transitions generations.status using repo.finishGeneration(gen.id, ..., { onlyIfStatus: "pending" }).
    3. Only the caller that receives claim.changed === true proceeds to apply any post-settlement surcharged true-up (repo.chargeCredit). If a concurrent driver already settled the row (claim.changed === false), settleVideoGeneration returns { handled: false, status: "success", reason: "already_settled" } and the HTTP route reads the fresh video_url from the DB.
  • Failure & Refund Path (claimAndRefund / forceFailVideoGeneration):
    • Calls repo.failGeneration(gen.id, ...), which acquires a PostgreSQL row lock on the pending generation row, sets status = 'failed' and fail_code, restores the charged credits to credit_buckets, and writes a refund ledger entry (GB...) in a single atomic transaction.

3. 24-Hour Signed URL Expiry & R2 Persistence Fallback Rules

Upstream video URLs (such as Volcengine Ark TOS URLs containing X-Tos-Expires=86400) are temporary signed links valid for 24 hours. Critically, querying the upstream task API after 24 hours returns the exact same expired signature (it does not re-sign the URL), causing downloads to fail with HTTP 403.

Therefore, settleVideoGeneration() and decideVideoAction() split R2 persistence failures into two distinct outcomes based on task age (waited = Date.now() - created_at) vs. linkTtlHours = 24:

Upstream StatusR2 Persistence (persisted)Task Age (waited)Settlement OutcomeReason
succeeded (with videoUrl)trueAnysuccess (videoUrl = /uploads/<yyyy>/<mm>/<id>_<rand>.mp4)Permanent self-hosted R2 object delivered.
succeeded (with videoUrl)false (download failed)< 24 hours (linkTtlHours)success (Silent Degradation) (videoUrl = t.videoUrl)Upstream signed link is still valid; user can watch and download immediately while [video] event=persist_failed is logged.
succeeded (with videoUrl)false ( or sweeper ageH >= 24h)>= 24 hours (linkTtlHours)failed + Full Credit Refund (reason = "artifact_expired", failCode = "ARTIFACT_EXPIRED")Upstream signed link has expired (403); delivering a dead link is unacceptable. Platform books the upstream costCny and refunds the user's credits.
succeeded (without videoUrl)N/A< 24 hours (urlWaitHours)wait (reason = "awaiting_url")Upstream marked task succeeded before populating artifact URL; wait rather than prematurely refunding a billed video.
succeeded (without videoUrl)N/A>= 24 hours (urlWaitHours)failed + Full Credit Refund (reason = "succeeded_without_url", failCode = "UPSTREAM_ERROR")Artifact never materialized within the 24h TTL window.
queued / runningN/A>= 6 hours (maxAgeHours)failed + Full Credit Refund (reason = "exceeded_max_age", failCode = "TIMEOUT")Zombie task stuck upstream beyond the 6-hour hard limit (forceFailVideoGeneration).
Missing task_idN/A>= 6 hours (maxAgeHours)failed + Full Credit Refund (reason = "no_task_id", failCode = "UPSTREAM_ERROR")Task creation crashed before recording task_id.

4. Upstream Cost & Resolution Drift Auditing

During video settlement, settleVideoGeneration performs three financial integrity checks:

  1. Failed Video Cost Accounting:
    • Alibaba DashScope (DASHSCOPE_VIDEO_PRICE): Explicitly does not bill failed tasks -> failed DashScope tasks record costCny = 0 (unless locked at creation, in which case forceFailVideoGeneration sets isDs ? 0 : ... so failed tasks do not artificially trip the daily CNY spending cap).
    • Volcengine Ark & Kling: Conservatively book costCny based on measured/estimated tokens or locked creation cost even on failure.
  2. Resolution Mismatch Detection (res_mismatch):
    • If the upstream response reports an actual output resolution (t.actualRes) different from gen.resolution (e.g., DashScope wan2.2-i2v-flash ignoring size and defaulting to 720p when 480p was requested), logs [video] event=res_mismatch level=error for billing reconciliation.
  3. Kling Credit Deduction Drift (credit_drift):
    • Kling returns final_balance_deduction (t.actualCredits). If |actualCredits - costCny| / costCny > 0.15 (15% drift, at 1 Kling credit ≈ ¥1), logs [video] event=credit_drift level=error to catch upstream price-table changes or ignored parameter defaults.

On this page