cmvr-visual/docs/api-contract.md

22 KiB
Raw Blame History

Shared API contract

All endpoints use /api. JSON errors: {detail:{code,message}}; normal FastAPI validation errors may additionally contain field locations. Session cookie cmvr_session is HttpOnly, same-origin. POST/PATCH/DELETE except login need X-CSRF-Token from auth response. Never expose inference keys or absolute server paths.

Private resources are owner-scoped for both regular users and admin: private assets, jobs, workflow drafts/runs and batches never become cross-user readable through the admin role. Explicit /shared-assets reads are authenticated cross-user reads of active publications. User administration does not grant access to another user's private content.

Authentication

  • POST /auth/login {username,password} → {user:{id,username,display_name,role},csrf_token} plus session cookie.
  • GET /auth/me → same shape; 401 when signed out.
  • POST /auth/logout → 204; close SSE on frontend.
  • Admin POST /auth/users {username,display_name,password} → user.

Capabilities and resources

  • GET /capabilities → {items:Capability[],scheduler:Scheduler}.
  • GET /system/status → {inference_online:boolean,scheduler:Scheduler,models:Capability[]}.
  • Capability: {task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}.
  • Scheduler: {available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}. No PID or user identity.
  • Types: image.generate, video.generate, defect.generate, audio.transcribe, math.solve, media.structure, video.compose, optional audio.speech (only available when a real provider is configured).

Assets

  • POST /assets multipart field file, optional name → Asset.
  • GET /assets?page=1&page_size=24&kind=&q=&tag=&origin=&favorite= → {items:Asset[],total,page,page_size}. Returns only the caller's active, ready, private assets. origin accepts upload, generated, or shared; omit favorite for no favorite filter.
  • GET /assets/{id} → Asset.
  • PATCH /assets/{id} {name?,tags?:string[],favorite?:boolean} → Asset.
  • DELETE /assets/{id} → 204 after soft deletion. Workflow references or active input use reject with 409 asset_in_use; resolve references/control the owning record first. Physical files are retained until explicit eligible GC.
  • GET /assets/{id}/content inline, Range supported; ?download=1 attachment.
  • GET /assets/{id}/thumbnail authenticated image preview (fallback image content when no separate thumbnail).
  • Asset: {id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated'|'shared',tags:string[],favorite:boolean,created_at:string}. A retained generated asset may keep source_job_id after its source job is archived; that identifier does not guarantee an accessible job.

Shared assets

Shared publications are independent file and metadata snapshots, separate from private Asset DTOs. All logged-in users may read active publications, including their content and thumbnails. Shared content is read-only; import it before using it as a private job/workflow input. Bearer-token reads require assets:read; publish/import/withdraw require assets:write, and ownership still applies.

  • POST /assets/{id}/publish → 201 SharedAsset, publishing only a caller-owned private asset. Optional body is absent or {}; extra fields are rejected. Repeating publication of a source with an active publication returns that existing snapshot. Editing/deleting the private source does not update/delete its publication.
  • GET /shared-assets?page=1&page_size=24&q=&kind=&tag=&mine=false → {items:SharedAsset[],total,page,page_size}. mine=true restricts to the caller's publications; page starts at1 and page_size is1–100.
  • GET /shared-assets/{id} → SharedAsset.
  • GET /shared-assets/{id}/content → authenticated inline content with Range support; ?download=1 downloads the snapshot.
  • GET /shared-assets/{id}/thumbnail → authenticated thumbnail, falling back to original content for an image without a separate thumbnail.
  • POST /shared-assets/{id}/import → 201 Asset. Optional body is absent or {}. Copies bytes into a new caller-owned private asset with a new asset ID, origin:'shared', source_job_id:null, and favorite:false. The publication ID is not a valid private input ID. Each new import without replay creates an independent copy.
  • DELETE /shared-assets/{id} → 204, publisher-only, idempotent withdrawal. A publication not owned by the caller returns404. Withdrawal makes shared metadata/content unavailable to further reads/imports; unavailable publications return 404 shared_asset_not_found. Existing private imports survive withdrawal and source deletion.
  • SharedAsset: {id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,tags:string[],created_at:string,publisher_id,publisher_name,is_owner:boolean,version:number,preview_url,thumbnail_url:null|string,download_url}. id is the publication ID; media URLs use /api/shared-assets/{id}/.... This DTO omits private source asset/job IDs, hidden snapshot asset IDs, favorite state and storage paths.

Publish and import accept optional Idempotency-Key headers under operations assets.publish and shared.import. Reuse the same key for the same operation and source ID after a lost response; a changed source ID with that key returns 409 idempotency_conflict. Replaying assets.publish after its publication is withdrawn, or shared.import after its imported private asset is deleted, returns 410 resource_purged. Publication copies charge the publisher's storage budget; private imports charge the importer. Soft-deleted retained files still consume quota until physically collected. Copy operations can fail with 429 quota_exceeded or 503 storage_insufficient.

Record deletion and retention

The following commands are caller-owned soft archival, each returning 200 with {deleted:{job_ids:string[],run_ids:string[],draft_ids:string[],batch_ids:string[]}}; arrays describe the complete archived tree, including empty arrays. They accept optional If-Match: <version>, not a request body. An already archived owned root returns the same tree without a new archival action. Missing/foreign records return404; a non-archived root with a mismatched version returns 409 version_conflict.

Command Cascade and retained resources
DELETE /jobs/{id} Archives an independent terminal job; all generated assets remain in its owner's private library
DELETE /workflows/{id} Archives the draft, its runs and their child jobs; generated assets remain
DELETE /workflow-runs/{id} Archives the run and its child jobs; preserves the draft and generated assets, clearing the draft's current-run pointer when applicable
DELETE /batches/{id} Archives the batch, member runs and jobs; preserves workflow drafts and generated assets

Archival removes resources from ordinary list/detail/control APIs while retaining audit rows. It releases obsolete job/input and snapshot references; it does not delete media or restore a cancelled run. The complete tree is validated before archival, so conflicts do not partially delete it.

  • 409 parent_control_required: a job belongs to a run/batch, a run belongs to a batch, or a draft still has runs belonging to a live batch. Delete through the required parent; delete the related batch before its draft.
  • 409 deletion_requires_terminal: a non-archived member is still active. Cancel first, then wait for terminal state. Allowed job terminal states are succeeded|failed|cancelled|timed_out; run terminal states are succeeded|failed|cancelled; batch terminal states are succeeded|cancelled|completed_with_errors.
  • 409 cleanup_pending: an execution has not reached exited or results_ready. Wait for confirmed execution exit/cleanup, even if the business record is already terminal.
  • 409 resource_in_use: another live run still selects a job in the proposed deletion tree for reuse. Delete the dependent run first. Private asset deletion uses the separate asset_in_use error above.
  • GET /submissions/{key}?operation=... and replay of an archived record's original command return 410 resource_purged. An old idempotency key cannot resurrect deleted records; intentionally creating new work requires a new submission.

Asset soft deletion and shared withdrawal do not promise immediate disk/quota recovery. GC defaults to dry-run (dry_run=True) with a14-day grace period; elapsed time alone does not trigger purge. Physical deletion requires explicit maintenance mode and an operator-invoked purge, rechecks job/snapshot/active-publication references, and skips protected files. Unknown/untracked files are never automatically removed. Archival audit rows are retained.

Jobs

MAX_INTERACTIVE_GPU_JOBS defaults to 0, which disables the per-owner unfinished interactive GPU queue cap. Direct submissions, standalone retries, workflow step retries and automatic workflow replenishment use the same rule. Positive values explicitly enable that optional cap; negative values are invalid. Creation-rate, total unfinished-job, storage and execution-resource limits still apply. This is not a lifetime video count or a GPU concurrency setting.

  • POST /jobs, optional Idempotency-Key, body {task_type,input:{prompt?,negative_prompt?,image_asset_id?,audio_asset_id?,asset_id?,asset_ids?:string[]},parameters:object,count?:1..4,scheduled_at?:ISO8601|null} → {jobs:Job[]}. Batch only for image/defect; each gets its own independent upstream job. Composition clip order and trims live in parameters.clips:[{asset_id,start_seconds?,end_seconds?}], optional audio_asset_id, subtitles:[{start,end,text}], width/height/fps. Server resolves owned assets only.
  • GET /jobs?page=1&page_size=24&task_type=&state= → {items:Job[],total,page,page_size,cursor:number}.
  • GET /jobs/{id} → Job.
  • POST /jobs/{id}/cancel → Job, cancellation may remain pending.
  • POST /jobs/{id}/retry → {jobs:Job[]} (user requested new generation, new business ID).
  • Job: {id,task_type,state,phase,version,prompt:string,parameters:object,input_asset_ids:string[],result_assets:Asset[],result:object|null,progress:number|null,queue_position:number|null,upstream_id:string|null,attempt_count:number,preemptions:number,last_preempted_reason:string|null,cancel_requested:boolean,error:null|{code,message,retriable},sync_warning:string|null,created_at:string,scheduled_at:string|null,started_at:string|null,finished_at:string|null}.
  • States: scheduled,submitting,queued,running,collecting,cancelling,succeeded,failed,cancelled,timed_out. Remote sync failures do not invent terminal failures; set sync_warning. Requeue is the same job ID and may go running→queued.
  • Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly num_inference_steps. Video accepts5–361 integer frames with num_frames % 4 == 1, fixed24fps. The web duration input supports1–15 whole seconds and submits 24 * seconds + 1 frames; default5 seconds remains121 frames. A15-second native source contains361 frames (15.041667 seconds), not interpolated or slowed-down footage. No fake generation percentage.
  • ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result subjects,scene,ocr,tags,frames?, timestamps reflect actual sampled frames. Math result {text}; ASR result {text,segments}; composition produces video asset.

Events

  • GET /events?after=0 authenticated EventSource. Last-Event-ID header overrides query on reconnect.
  • Durable event: id: <integer>\nevent: job.updated\ndata: {"job":Job}\n\n.
  • Other events: asset.created data {asset:Asset}, asset.updated same; asset.deleted {id}, reset asks client to refetch snapshots. Heartbeat comments do not change cursor. Stream owner-filtered; logout/expiry ends stream.
  • Record archival emits job.deleted, workflow.deleted (a run), draft.deleted, and batch.deleted, each with {id,version}. Cascades emit an event for each newly archived record. Treat these IDs as tombstones so delayed HTTP responses or older updates cannot reinsert deleted records; clear session state/tombstones on owner change. A surviving draft whose current run is deleted also receives draft.updated.
  • Fetch jobs snapshot and cursor before opening stream; after reconnection refresh HTTP state as well. Ignore Job versions older than or equal to the current version.

Backend provider interface

Implemented in app/providers.py and app/media.py, independent of database models.

Provider(settings) methods (async):

  • health() -> bool
  • scheduler_status() -> dict sanitized Scheduler above.
  • prepare_gpu_payload(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> dict validated original upstream payload {task_type,input,parameters,timeout_seconds}. Input paths must be within shared workspace. Preprocess video ASR as needed.
  • submit(payload:dict,idempotency_key:str) -> dict original upstream job response; retry only same immutable payload/key.
  • query(upstream_id:str) -> dict, cancel(upstream_id:str) -> dict.
  • download(upstream_id:str,index:int,destination:Path) -> None atomic streamed output, size bounded.
  • run_cpu(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> CpuResult.
  • aclose() -> None.
  • CpuResult dataclass: outputs:list[Path], result:dict, metadata:dict.
  • ProviderError(code,message,retriable=False) has those attributes; no secret/path leaks in public messages.
  • Settings attributes consumed: inference_base_url,inference_api_key,inference_api_key_file,workspace_root,asset_root,job_work_root,gpu_status_path,gpu_scheduler_path,qwen_base_url,qwen_model,qwen_api_key,ffmpeg_bin,ffprobe_bin,tts_base_url,tts_model,tts_api_key,request_timeout_seconds,max_output_bytes.
  • app/media.py: inspect_media(path:Path,settings)->dict (kind,mime_type,width,height,duration_seconds); make_thumbnail(path:Path,destination:Path,settings)->Path|None. These are async, subprocess is fixed argv, bounded time/resources; no shell. Image validation can use Pillow. JSON/text generated outputs supported.
  • capabilities(settings)->list[dict] returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible /audio/speech if selected later.

Production files live under /workspace/cmvr-visual. The website's business database is MySQL 192.168.28.10:3306/cmvr-visual; media originals/thumbnails live on the host at /data/llmusers/llmuser/workspace/cmvr-visual/assets, mounted as /workspace/cmvr-visual/assets. The inference service's SQLite is an independent GPU scheduling/recovery store, not the website business database. Database and media backups must be coordinated. These are operator deployment locations, not fields exposed in public resource DTOs.

Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt.

V2 additions

HTTP remains the command/query channel, SSE the owner-scoped notification channel. execution_policy is returned by capabilities/status: {timezone:'Asia/Shanghai',start:'21:00',end:'08:00',batch_open,next_batch_at,close_behavior:'finish_current'}. The server accepts and persists batch commands all day; only new compute phases are gated. Current work is never killed by the clock or a browser disconnect.

  • GET /live process liveness; GET /ready 200/503 with database, coordinator, upstream_protocol and accepting checks. GPU capacity does not affect readiness.
  • User DTO adds disabled,must_change_password; GET/PATCH /auth/users[/{id}] administer users, POST /auth/password {current_password,new_password} revokes sessions and requires relogin.
  • GET/POST /auth/tokens, DELETE /auth/tokens/{id}. POST {name,scopes,expires_at?} returns {token,record} once. Use Authorization: Bearer ... for machine calls; tokens never grant admin authority. Interactive use additionally requires interactive:write.
  • POST /jobs adds execution_mode:'interactive'|'batch'; new UI always persists and supplies an Idempotency-Key. GET list adds root_only=true to exclude workflow children. Job DTO adds run_id,step_key,batch_id,batch_item_index,execution_mode,explicit_attempt,desired_state,hold_reasons,current_execution_id. States additionally include paused,pausing,needs_attention.
  • POST /jobs/{id}/retry honors Idempotency-Key; legacy callers omitting it explicitly create a fresh attempt without replay guarantees. Parent-owned children require their parent retry/control APIs.
  • GET /submissions/{key}?operation=jobs.create|jobs.retry|workflow.run|workflow.retry|workflow.pause|workflow.resume|workflow.cancel|batch.create|batch.control|assets.publish|shared.import recovers owned resources. Replaying the original key and immutable JSON is safe after a lost response while its resources remain available; 404 alone does not prove an in-flight command was rejected. Archived resources return410 as specified above.
  • POST/GET /workflows; GET/PATCH /workflows/{id}. PATCH requires If-Match: <version>. Draft edits increment revision; new Runs freeze a snapshot.
  • POST /workflows/{id}/runs {draft_revision,expected_version,execution_mode?,reuse_run_id?} plus Idempotency-Key → {draft,run,steps,jobs,cursor}. GET /workflow-runs is paginated; GET /{id} returns the consistent snapshot.
  • POST /workflow-runs/{id}/pause|resume|cancel {expected_version?} plus Idempotency-Key. Pause closes future admission and drains current work. Cancel remains pending until cleanup/completion is known.
  • POST /workflow-runs/{id}/steps/{step_key}/retry {expected_run_version,target_job_id} plus Idempotency-Key retries only the selected failed step, preserving other successful shots and inherited mode/holds.
  • POST /batches {name?,items:[{kind:'workflow',draft_id,draft_revision,expected_version}|{kind:'job',task_type,input,parameters?,count?}]} plus Idempotency-Key. Maximum100 items, fixed batch mode, one active member per batch. GET list and /{id} snapshots; POST /{id}/control {desired_state:'run'|'pause'|'cancel',expected_version?} plus Idempotency-Key.
  • Asset list additionally accepts favorite and origin SQL filters. Workflow references protect frozen inputs/outputs from physical deletion.
  • SSE adds draft.updated:{draft}, workflow.updated:{run,steps,jobs}, batch.updated:{batch,items} with object versions. Ignore older/equal versions; reconnect/reset refreshes HTTP snapshots. Machine SSE requires events:read and Authorization, never tokens in URLs.

Legacy workflow spec schema1 remains exactly ordered shot_1,shot_2,shot_3, each {key,prompt,image_asset_id:null|string,parameters:{seed}}, with360 frames at24fps. Its serialization and generation hashes remain compatible.

Schema2 accepts1–1000 sequentially ordered shot_N entries with additional duration_frames (strict integer24–360, default120). New submissions are additionally bounded by the operator's configured shot limit. profile=landscape_1080_v1|portrait_1080_v1; render={fps:24,total_frames?:integer,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}. Omitted total_frames is derived from shots; a supplied unequal value fails validation. Each shot generates max(121, 4 * ceil(duration_frames / 4) + 1) source frames and composition trims to the requested frame count. A5/10/15-second workflow requests121/241/361-frame sources and produces720 final frames (30 seconds). Schema1 retains its original3×5-second contract. Audio must fit the entire dynamic timeline explicitly and subtitles use whole-film half-open frame intervals. Run total_steps is shot count+1, and steps/compose inputs follow snapshot order, including shot_10. New draft kind is multi_shot; three_shot remains accepted.

Capabilities and system/status include workflow_limits={max_shots,source_frames:121,default_source_frames:121,max_source_frames:361,default_clip_frames:120,max_clip_frames:360,fps:24} and execution_policy.batch_window_enabled, configuration_error, nullable next_batch_at. source_frames remains a legacy default; it is not the maximum. New snapshots freeze compiled.shot_generation_parameters keyed by shot; legacy snapshots without that map use their original frozen shared parameters. Long-source frame counts participate in reuse/retry semantic hashes, so a short source cannot satisfy a longer shot. Both API and GPU worker hot-read the operator-owned RUNTIME_POLICY_FILE (default /workspace/projects/llm-services/config/runtime-policy.json): {schema_version:1,batch_window_enabled:boolean,workflow_max_shots:integer1..1000}. Missing means production defaults; malformed policy blocks new batch compute. False bypasses only the clock/window, preserves durable clock evidence and all manual/maintenance/owner/GPU priority controls. Client payloads cannot override this switch. Already admitted work finishes when the switch is re-enabled.

Manual video.compose no longer has a24-clip or1800-second final-duration cap. New commands respect the same configured clip-count limit; source cuts stay within decoded media and a86400-second source bound. Output/intermediate size, storage, process and overall execution time budgets still apply.

Private inference protocol2 carries server-generated scheduling={execution_mode,principal_id,batch_id?,run_id?,step_key?,policy_version:'night-v1'}. Its /capabilities reports admission_pause/control_versions/final_output_indices. GPU result metadata identifies final enhanced output indices; workflows never choose the native intermediate by list order. Internal phase callbacks acquire separate new_gpu, cpu_media, qwen_http slots. No endpoint accepts arbitrary PIDs, Docker IDs, FFmpeg scripts or server filesystem paths from web users.