videogen/docs/reelforge/ARCHITECTURE.md
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
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

607 lines
38 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# ReelForge — System Architecture
> **Evolving architecture narrative:** component descriptions remain useful,
> but embedded inventory and verification totals are historical. Use
> [`CURRENT_STATE.md`](./CURRENT_STATE.md) for authoritative current counts and
> gate status.
> **Scope:** ReelForge is a production UGC (user-generated-content) avatar-video generator
> forked from MoneyPrinterTurbo (MPT) at `/Users/arhansubasi/videogen`. This document
> describes the **current** runtime topology: the Celery render pipeline, the
> single-source-of-truth timing rule, how the fork layers on MPT, the graph-engineering
> build method, the creator-platform subsystems that surround the core pipeline
> (analytics/BI read models, template marketplace + remix trees, the hook-performance loop
> feeding Spark, per-API-key quotas + rate limits, OAuth account-connect + publishers seam,
> the public watermarked share surface, and the creator community graph), the opt-in
> **editing-polish pre-compose stage** (`app/services/editing/`), and the **enterprise
> governance + identity layer** (pycasbin RBAC + tenant isolation, append-only audit trail,
> platform-admin console, SAML SSO + SCIM 2.0 + security policy). The product now presents
> **three client surfaces** — web (Next.js), mobile (Expo), and desktop (Rust/GPUI) — on this
> one FastAPI backend.
>
> **Source of truth:** `docs/reelforge/INTEGRATION_CONTRACT.md` (the authoritative contract).
> Product/enterprise program: [`PRODUCT_BLUEPRINT.md`](./PRODUCT_BLUEPRINT.md) (the 10-epic
> enterprise roadmap — Epics 1–2 shipped, Epic 3 Billing in progress) and
> [`RESEARCH_ENTERPRISE_OSS.md`](./RESEARCH_ENTERPRISE_OSS.md). Plans:
> `ugc-video-tool-build-plan.md`, `ugc-tool-cto-plan.md`.
>
> **Forward target:** this document is *today*. For the next-gen topology (Redis-backed
> shared state, priority Celery queues, a GPU warm-pool worker tier, signed provider
> callbacks, and the BI/cost/margin pipeline) see [`ARCHITECTURE_NEXT.md`](./ARCHITECTURE_NEXT.md).
> Where the two differ, this doc is *current* and that one is *target*; this doc does not
> restate the target design.
>
> **Surface, today:** the FastAPI tier now serves **139 endpoints across 29 included routers**
> (`app/router.py`), backed by **27 Neon tables** and **24 Alembic migrations** on a single head
> `f1a2b3c4d5e6` (the enterprise identity/SSO migration). Backend adds **casbin** (Apache-2.0,
> RBAC decision engine), **python3-saml** (MIT, SAML — optional native `xmlsec`), and
> **scim2-filter-parser** (MIT, optional SCIM filter parsing); the web console adds
> **@refinedev/core** + **@refinedev/nextjs-router** (MIT). Quality gates run **locally**
> (`ruff --select F,E9` + `pytest` + `alembic upgrade head`/`check` + golden acceptance) plus
> an in-process ASGI smoke (`ops/smoke.py`, PASS); there is **no CI service** (intentionally
> omitted). The suite is **1986 passed, 4 skipped** (`python -m pytest tests/reelforge`).
---
## 1. Overview
ReelForge turns a subject prompt (or a manual script) into a finished, captioned
talking-head reel and optionally cross-posts it to social platforms. It is a **parallel
UGC avatar pipeline** layered on MPT's existing state machine, config loader, and service
plumbing (`INTEGRATION_CONTRACT.md §0`).
The canonical render is a fixed directed acyclic graph (DAG):
```
script → tts → { avatar ∥ captions } → compose → upload
```
`avatar` and `captions` depend only on `tts` and run **concurrently**; `compose` fans them
back in. `upload` is appended only when the job requests at least one publish platform.
---
## 2. Request / Worker / Storage Topology
ReelForge runs as four cooperating processes plus two managed data services. All four
processes are defined in `docker-compose.reelforge.yml`; a full local run harness that
brings the whole stack up alongside the databases lives in `docker-compose.full.yml` +
`Makefile.dev`, with an in-process ASGI smoke check at `ops/smoke.py`.
| Process | Command | Role |
|---------|---------|------|
| **api** | `uvicorn app.asgi:app --port 8080` | FastAPI request tier; serves all `/api/v1` surfaces (jobs + the platform subsystems of §7 + the enterprise governance/identity routers of §8), enqueues jobs |
| **worker** | `celery -A app.workers.celery_app worker -Q celery,render` | Executes stage tasks (light `celery` + heavy `render` queues) |
| **beat** | `celery -A app.workers.celery_app beat` | Periodic scheduler (fires the scheduled-publish due-runner every 60s) |
| **redis** | `redis:7-alpine` | Celery broker **and** result backend; also MPT's task-state store |
This one FastAPI backend fronts **three client surfaces** (all thin — no business logic
duplicated client-side): the **web** console (`apps/web/`, Next.js 15 + React 19, Clerk
auth, plus the refine-driven platform-admin console), the **mobile** app (`apps/mobile/`,
Expo / React Native), and the **desktop** app (`apps/desktop/`, Rust + GPUI) whose native
screen/file capture feeds the same `POST /api/v1/jobs` render path. The retained
`apps/desktop/electron-legacy/` tree is migration reference only.
Managed external data services (not in compose — cloud-hosted):
| Service | Purpose |
|---------|---------|
| **Neon Postgres** | Durable source of truth across **27 tables** (`app/models/db/models.py`): the render core (`jobs`, `job_events`, `job_performance`, `assets`, `users`, `credit_ledger`, `api_key_usage`, `user_api_keys`, presets/brands/voices, `scheduled_publish`, `notifications`, `saved_ideas`, `workspaces`/`workspace_members`), the §7 platform tables (`marketplace_templates`, `template_ratings`, `avatar_presets`, `social_accounts`, `share_links`, `creator_follows`), and the §8 enterprise tables — governance (`audit_log`) + identity (`sso_connections`, `scim_tokens`, `security_policies`, `external_identities`) |
| **Cloudflare R2** | Object storage for all media artifacts (audio, avatar, captions, final video, posters) via `app/platform/storage/r2.py` |
### 2.1 Request flow
1. A client `POST /api/v1/jobs` request lands in `app/domains/reels/router.py::create_job`.
The FastAPI app (`app/asgi.py::get_application`) mounts every v1 controller through
`app/router.py::root_api_router`.
2. The handler validates + normalizes the request into a frozen
`ReelForgeParams` DTO (`app/services/reelforge.py`), debits credits, persists a
`Job` row (`state=PROCESSING`, per-stage `stages` map), then calls
`app/workers/pipeline.py::start_pipeline`.
3. `start_pipeline` builds the Celery `chain` and `apply_async()`s it, returning the root
`AsyncResult.id`, which is persisted to `Job.celery_task_id`.
4. Redis receives the task; a **worker** picks up each stage in DAG order. Each stage task
writes its per-stage status and weighted progress back to the `Job` row.
5. The client polls `GET /api/v1/jobs/{job_id}` (`get_job`) for `state`, `progress`,
`stages`, and — on completion — a presigned R2 download URL for `Job.result_key`.
### 2.2 The DB row is the concurrency source of truth
Because `avatar ∥ captions` run as two independent worker tasks, the **persistent
`Job` row (not the in-memory MPT task doc) is authoritative** for parallel stages
(`INTEGRATION_CONTRACT.md §10`). Per-stage writes use
`JobRepository.update_stage` (atomic per-key write) instead of overwriting the whole
`stages` map, and progress is written with a guarded
`UPDATE jobs SET progress=:v WHERE progress < :v` so a slower sibling can never regress a
higher, already-committed value (`app/workers/tasks.py::_safe_set_progress`).
---
## 3. Component Diagram
```
┌────────────────────────────────────────────┐
HTTP /api/v1 │ CLIENTS (three surfaces) │
web (Next.js) ──────────▶│ web · mobile (Expo) · desktop (Rust/GPUI) │
mobile (Expo) ──────────▶│ POST /jobs · GET /jobs/{id} · retry · ... │
desktop (Rust/GPUI) ────▶│ + apps/web/app/admin platform console │
└───────────────────────┬────────────────────┘
│
┌──────────────────────────▼──────────────────────────┐
│ api — FastAPI (app.asgi:app, uvicorn :8080) │
│ app/router.py → controllers/v1/{jobs,studio,..., │
│ rbac,audit,admin,sso,scim,security_policy} │
│ ReelForgeParams DTO · credit debit · persist Job │
│ enterprise: RBAC gate + tenant isolation + audit │
└───────┬───────────────────────────────┬──────────────┘
│ start_pipeline() │ read/write
│ apply_async() │
┌───────▼──────────┐ ┌────────▼─────────┐
│ Redis (broker + │ │ Neon Postgres │
│ result backend) │ │ jobs·job_events │
│ queues: │ │ assets·users··· │
│ celery · render │ └────────▲─────────┘
└───────┬──────────┘ │
│ consume │ update_stage / progress
┌────────────────────────▼──────────────────────────┐ │ mark_failed / assets
│ worker — Celery (-Q celery,render, concurrency=2) │────┘
│ │
│ chain: script ─▶ tts ─▶ chord( avatar ∥ captions │
│ ) ─▶ compose ─▶ upload │
│ tasks wrap app/services/reelforge.py stage fns │
└───────────┬────────────────────────────┬───────────┘
│ get/put media │ external providers
┌───────▼─────────┐ ┌──────────▼───────────────────────────┐
│ Cloudflare R2 │ │ ElevenLabs (TTS+alignment) · HeyGen │
│ audio·avatar· │ │ (avatar) · Claude/litellm (script) · │
│ ass·final·poster│ │ upload_post (cross-post) · FFmpeg │
└─────────────────┘ └──────────────────────────────────────┘
┌───────────────────────────────────────────────────┐
│ beat — Celery beat (single process) │
│ every 60s → process_due_publishes_task │
│ (app/services/scheduler.process_due_publishes) │
└───────────────────────────────────────────────────┘
```
---
## 4. The Celery Pipeline DAG
Defined in `app/workers/pipeline.py`, `app/workers/tasks.py`, and
`app/workers/celery_app.py`.
### 4.1 Chain + chord assembly
`build_chain(job_id, params)` expresses the DAG as a linear Celery `chain` whose middle
element is a `chord` (fan-out/fan-in):
```python
parallel = chord(
group(stage_avatar_task.s(), stage_captions_task.s()), # fan-out (∥)
stage_compose_task.s(), # fan-in callback
)
steps = [
stage_script_task.s({"job_id": job_id, "params": params.__dict__}),
stage_tts_task.s(),
parallel,
]
if params.platforms:
steps.append(stage_upload_task.s())
return chain(*steps)
```
- `avatar` and `captions` both depend only on `tts`, so they run concurrently as a
`group`. Celery's `chord` guarantees `compose` (the callback) fires **only after both**
complete.
- `stage_compose_task` receives `results = [avatar_ctx, captions_ctx]` (order not
guaranteed) and unions them via `app/workers/context.py::merge_partials` before running
the compose stage.
- `upload` is omitted entirely when `params.platforms` is empty (compose becomes the
terminal stage).
The canonical DAG and its dependency closure live in
`app/models/const.py::REELFORGE_DAG`:
```python
REELFORGE_DAG = {
"script": (),
"tts": ("script",),
"avatar": ("tts",),
"captions": ("tts",),
"compose": ("avatar", "captions"),
"upload": ("compose",),
}
```
### 4.2 Stage tasks
Each task in `app/workers/tasks.py` is a thin, retry-aware wrapper (`_run_stage`) around a
**pure stage function** in `app/services/reelforge.py`. A task: reports `running`
(JobEvent + `Job.stages`), runs the stage function on the shared `JobContext` dict,
reports `complete` + advances weighted progress, and returns `{**ctx, **stage_result}` so
the next task receives the union.
| Task | Stage fn | Queue | Retry / timeout policy |
|------|----------|-------|------------------------|
| `stage_script_task` | `stage_script` | `celery` | retry `ConnectionError` ×3; soft 120s / hard 150s |
| `stage_tts_task` | `stage_tts` | `celery` | retry ×3; soft 180s / hard 210s |
| `stage_avatar_task` | `stage_avatar` | **`render`** | retry ×2; soft 1800s / hard 1860s |
| `stage_captions_task` | `stage_captions` | `celery` | no auto-retry; soft 120s / hard 150s |
| `stage_compose_task` | `stage_compose` | **`render`** | chord callback; soft 600s / hard 660s |
| `stage_upload_task` | `stage_upload` | `celery` | retry ×5; soft 120s / hard 150s |
The slow, GPU/render-heavy stages (`avatar`, `compose`) are routed to a dedicated
`render` queue via `celery_app.conf.task_routes` so a separate pool can service them
without starving the fast text/audio stages. A single worker consuming both queues is the
default (`-Q celery,render --concurrency=2`).
### 4.3 Shared JobContext
State flows between stages as a plain, **JSON-serializable** `JobContext` dict
(`app/workers/context.py`). It must never carry live objects (e.g. a `SubMaker`) —
ElevenLabs word timings are flattened to `list[[text, start_s, end_s]]` before entering
the context. Key fields include `audio_key`, `audio_url`, `audio_duration`, `words`,
`avatar_key`, `ass_key`, `final_key`, and `upload_results`.
### 4.4 Failure, progress, and resume semantics
- **First-failure guard:** on terminal failure (after retries), `StageTask.on_failure`
calls `JobRepository.mark_failed`, which records only the *earliest* failing stage under
a row lock. A later parallel sibling finds the job already failed and leaves the root
cause intact (`tasks.py::_safe_mark_failed`, `_report_failure`).
- **Monotonic progress:** progress is the weighted sum of the *union* of all completed
stages (`_completed_stages`), written with the guarded anti-regression `UPDATE`. Stage
weights (`app/models/const.py::REELFORGE_STAGE_WEIGHTS`, mirrored in
`app/telemetry/progress.py`):
| script | tts | avatar | captions | compose | upload |
|:------:|:---:|:------:|:--------:|:-------:|:------:|
| 10 | 20 | 30 | 15 | 20 | 5 |
When a job has no platforms, `upload` is excluded from both numerator and denominator so
a compose-only job still reaches 100%.
- **Resume from failed stage:** `retry_pipeline(job_id, params, failed_stage)` reconstructs
the last-good `JobContext` from the job's persisted `Asset` rows
(`_reconstruct_context`) and builds a sub-chain starting at `failed_stage`
(`build_retry_chain`). Resuming `avatar` or `captions` restarts the **whole chord** so
the fan-in stays intact. If artifacts can't be reconstructed (missing seeds, DB/R2
unavailable), it falls back to a full `start_pipeline` re-run. Exposed via
`POST /api/v1/jobs/{job_id}/retry`.
### 4.5 Scheduled publishing (beat)
`celery_app.conf.beat_schedule` fires `process_due_publishes_task` every 60s. The
due-runner (`app/services/scheduler.py::process_due_publishes`) claims every `pending`
`ScheduledPublish` row whose UTC time has arrived and publishes it. It is **idempotent**
(claimed rows aren't re-claimed) so a duplicate tick is safe; run **exactly one** beat
process.
### 4.6 Editing-polish pre-compose passes (opt-in)
The `compose` stage may run a short chain of **opt-in, default-off, degrade-safe**
pure-FFmpeg polish passes over the raw **screen recording / avatar clip** *before* the
`compose_avatar_over_screen` smart-handling. They live in `app/services/editing/` and are
toggled per-job through `ReelForgeParams` (persisted on `Job.params`), so they **do not
add a DAG node** — the six-stage graph is unchanged; they run *inside* `stage_compose`.
Fixed order **tighten → auto_zoom → motion → matte**:
| Pass | Module | What it does |
|------|--------|--------------|
| `tighten` | `editing/silence_cut.py` | Submagic-style dead-air remover — cuts stretches that are simultaneously silent (`silencedetect`) + static (`freezedetect`), re-synced A/V-safe |
| `auto_zoom` | `editing/auto_zoom.py` | Scene-driven "punch-in" zooms via `zoompan` (duration-preserving); PySceneDetect is an optional, import-guarded accelerator |
| `motion` | `editing/motion.py` | Synthetic "fake camera motion" (`ken_burns`/`push_in`/`pull_out`/`whip_pan`) baked in via `scale`+`crop`, clamped ≤1.15× |
| `matte` | `editing/matting.py` | Optional rembg-backed background matting for a cleaner avatar cut-out than raw chromakey (rembg is a strictly optional, lazily-imported dep) |
Every pass is **degrade-safe**: on any problem (no removable dead air, missing filter,
unreadable input, drifted duration, missing optional dep, or any exception) it returns the
**original clip unchanged** with `applied=False` and never fails the job. Because the passes
either preserve or shorten-then-re-derive duration, the §5 single-timing-authority
invariant is respected (with a defensive duration guard around `auto_zoom`).
---
## 5. The Single-Source-of-Truth Timing Rule (§8)
> **ElevenLabs `/with-timestamps` character alignment is the ONE authority for timing.**
> The word timings derived from it drive **both** the ASS karaoke captions **and** the
> avatar-duration validation. There is no second forced-alignment pass (no WhisperX /
> aeneas).
This rule is load-bearing because three stages (`tts`, `avatar`, `captions`) must agree on
timing. Deriving durations independently would desync captions from the avatar's lip
movement. Enforcement:
1. **`stage_tts` produces the authority.** It calls `voice.tts(...)` (which routes to the
ElevenLabs timestamps adapter) and computes
`audio_duration = voice.get_audio_duration(sub_maker)`
(`alignment.character_end_times_seconds[-1]`). It flattens `sub_maker.words` into the
context's `words` array. Both land in `JobContext["audio_duration"]` /
`JobContext["words"]` and in `Asset(kind="audio").duration_s`
(`app/services/reelforge.py::stage_tts`). `audio_duration` is documented in
`context.py` as *"the SINGLE TIMING AUTHORITY"*.
2. **`stage_captions` consumes it.** The ASS karaoke track is built **only** from
`JobContext["words"]` — no re-transcription — and the final caption end equals
`audio_duration`.
3. **`stage_avatar` validates against it.** It passes
`expected_duration_s=ctx["audio_duration"]` to `generate_avatar`. Because HeyGen
lip-syncs the *exact same* mp3 that produced the alignment, the returned render duration
must agree within a tolerance. On drift beyond `_AVATAR_DRIFT_TOLERANCE_S = 0.15s`,
`stage_avatar` records a warning `JobEvent` and **raises `ReelForgeStageError`** so the
render retries (`reelforge.py::stage_avatar`).
**Bring-Your-Own-Voiceover (BYOV) exception:** when `params.voiceover_key` is set, TTS is
skipped; the uploaded narration is transcribed once with faster-whisper
(`app/services/transcribe.py`) to produce the same `words`/`audio_duration` authority
shape (`_stage_tts_byov`). The single-authority invariant still holds — there is just one
source, not two.
---
## 6. How the Fork Layers on MPT
ReelForge deliberately **reuses** MPT's proven plumbing and **adds** an orchestration,
persistence, storage, and provider layer on top. It does not re-fork existing services.
### 6.1 Reused from MPT (unchanged plumbing)
| MPT module | Reused for |
|------------|------------|
| `app/services/state.py` | Task-state machine (`update_task` / `get_task` / `patch_task`) + `app/models/const.py` state ints (`PROCESSING=4`, `COMPLETE=1`, `FAILED=-1`) |
| `app/services/llm.py` | Script generation via `_generate_response` (single litellm → Claude choke point) |
| `app/services/voice.py` | TTS dispatcher `tts()` + `create_subtitle` / `get_audio_duration` on the legacy `SubMaker` `.subs`/`.offset` contract |
| `app/services/elevenlabs_music.py` | ElevenLabs music generation (AI BGM) |
| `app/services/video.py` | FFmpeg/codec helpers (`get_ffmpeg_binary`, `_get_effective_video_codec`, libx264 fallback) reused by the compose stage |
| `app/services/upload_post.py` | Cross-posting the final video (`cross_post_video`) |
| `app/services/material.py` | Stock material sourcing / caching (b-roll cutaways) |
| faster-whisper | BYOV transcription fallback for word timings (`app/services/transcribe.py`) |
### 6.2 Added by ReelForge (new layers)
| New area | Modules |
|----------|---------|
| **Avatar** | `app/services/avatar/base.py` (`TalkingHeadProvider` protocol + registry), `avatar/heygen.py` (HeyGen client) |
| **Captions** | `app/services/captions/words.py` (char → word/phrase grouping), `captions/ass_karaoke.py` (ASS karaoke generator + styles) |
| **Compose** | `app/services/compose/compose_ffmpeg.py` — pure single-pass FFmpeg filter-graph (no MoviePy in the prod render path), 3 layouts: `pip`, `hook_intro`, `split` |
| **Storage** | `app/platform/storage/r2.py` — Cloudflare R2 client (boto3 S3 API) + presign helpers |
| **Billing** | `app/services/billing/*` — Stripe + iyzico credit purchases; `CreditLedger` |
| **Workers** | `app/workers/{celery_app,context,tasks,pipeline}.py` — Celery orchestration |
| **DB** | `app/models/db/{base,models,repositories}.py` + Alembic (`migrations/`) — Neon Postgres persistence (repository pattern) |
| **TTS adapter** | `app/services/tts/elevenlabs_timestamps.py` — `/with-timestamps` alignment adapter, wired into `voice.tts()` (§9) |
| **Script** | `app/services/script/ugc.py` — `generate_ugc_script` wrapping `llm._generate_response` |
| **Telemetry** | `app/telemetry/{events,progress,cost,sentry}.py` — JobEvents, weighted progress, per-stage cost, Sentry wiring |
### 6.3 Reused infrastructure config (not forked)
The Celery broker/backend URL is composed from the **existing MPT `[app]` redis keys**
(`redis_host` / `redis_port` / `redis_db` / `redis_password`), with optional
`celery_broker_url` / `celery_result_backend` overrides — **no new `[redis]` section** is
introduced (`celery_app.py::_redis_url`, `INTEGRATION_CONTRACT.md §3.3`). The FastAPI
router prefix (`/api/v1`) and response envelope (`utils.get_response`) are MPT's.
---
## 7. Platform Subsystems (Added This Phase)
The render pipeline (§4) is now the core of a broader creator platform. Each subsystem
below is an **additive** router + service (+ tables) layered on the same auth guard, MPT
response envelope, and repository pattern as the job API — none of them change the DAG.
All seven read from data the pipeline already records (`Job` / `JobEvent` /
`JobPerformance` / `CreditLedger`) rather than introducing a parallel write path. They are
**shipped and live today**; the forward evolution of several of these seams (live OAuth
clients, live publishers, platform-metrics ingestion, a margin/BI aggregate, an event bus)
is the target described in [`ARCHITECTURE_NEXT.md`](./ARCHITECTURE_NEXT.md) and is **not**
restated here.
### 7.1 Creator Analytics — BI read models
`app/services/analytics.py` + `app/controllers/v1/analytics.py` expose a single
strictly-caller-scoped read model at `GET /me/analytics?days=` (clamped `1..365`). It
computes a funnel, cost-over-time, credit burn-rate + live balance, a render-time
distribution (`p50_ms`/`p90_ms` via `_percentile`), and usage breakdowns purely by
aggregating the caller's existing `Job`/`JobEvent`/`CreditLedger` rows — a read-only BI
projection, no new write path. The percentile/day-bucket/window helpers (`_percentile`,
`_bucket_by_day`, `_window_start`) are the reuse seam the target margin aggregate builds on.
### 7.2 Template Marketplace + remix trees
`app/services/marketplace.py` + `app/controllers/v1/marketplace.py` (7 endpoints:
browse/detail/list-mine, publish, clone, rate, delete) let creators publish a preset as a
public `marketplace_templates` listing, browse/clone it, and rate it (`template_ratings`).
Two ranking/lineage features distinguish it:
- **Win-score ranking** — listings can be re-ranked at query time by the **real-world
win-score of the reels cloned from them** (`listing_win_scores`), computed with the
*exact same* deterministic aggregation as the Hook Performance Loop (§7.3), guarded by a
k-anonymity floor before a numeric `win_score` is exposed to other users.
- **Remix trees** — cloning a listing records a parent link so descendants form a shallow
**remix tree**; the parent's `remix_count` is bumped once per remix, and a `lineage`
walk follows ancestors under a hard depth cap so a corrupted/cyclic chain can never
trigger an unbounded walk.
### 7.3 Hook Performance Loop → Spark
`app/services/hook_performance.py` + `app/controllers/v1/performance.py` (5 endpoints)
let a creator log self-reported per-reel outcomes (`JobPerformance`) and rank their
**hooks** and **templates** by a deterministic, divide-by-zero-safe **win score**
(`win_score = SCALE * (ENGAGEMENT_WEIGHT · min(engagement_rate,1) + RETENTION_WEIGHT ·
retention)`, aggregated per hook/template). These winning hooks feed the **Spark** idea
engine (`app/controllers/v1/ideas.py`) so idea generation is biased toward a creator's own
proven openers, and the same aggregation is re-exported to the marketplace win-score (§7.2).
### 7.4 Per-API-key quotas + rate limits (429)
Public programmatic access is minted/listed/revoked via `app/controllers/v1/api_keys.py`
(4 endpoints, `user_api_keys` table). Every key-authenticated request passes through the
power-user tier in `app/services/apikey_quota.py`, wired at the shared auth guard in
`app/controllers/v1/base.py`: `enforce_rate_limit` (per-minute) + `check_and_consume`
(atomic monthly-quota increment against `api_key_usage`, `monthly_quota` NULL = unlimited).
A typed `ApiKeyLimitError` is mapped to a single caller-facing **HTTP 429**. This is
distinct from the coarse Redis `enforce_rate_limit` (`app/services/ratelimit.py`,
**fail-open**) that guards write-heavy `/me` surfaces.
### 7.5 OAuth account-connect + publishers seam
`app/services/oauth_connect.py` + `app/controllers/v1/connections.py` (5 endpoints)
implement the direct-publish account-connect flow for TikTok / Instagram / YouTube. The
CSRF `state` is single-use (in-memory `SingleUseStateStore` today — the fail-closed Redis
replacement is a target seam), and provider tokens are **encrypted at rest with Fernet**
(`app/services/crypto_tokens.py`, AES-128-CBC + HMAC-SHA256) keyed by the required
**`SOCIAL_TOKEN_KEY`** env var (falling back to `config.app["social_token_key"]`), persisted
on `social_accounts`. The live token exchange and per-provider uploaders remain a stubbed
seam (`app/services/publishers/`); their live implementation is the target design.
### 7.6 Public watermarked share surface
`app/services/share.py` + `app/controllers/v1/share.py` (3 endpoints) let an owner mint or
revoke an unguessable share `token` (`share_links` table) and expose a **public**,
unauthenticated `GET /public/r/{token}` view. The public view only ever presigns a
**safe, watermarked/derived** preview artifact (never the clean master render) and counts a
view; a revoked/unknown token is a clean 404. Both the write (mint/revoke) and public-view
paths are rate-limited via config keys `reelforge_share_write_rate_{limit,window_s}` and
`reelforge_share_view_rate_{limit,window_s}`, with the page base URL from
`reelforge_share_base_url`.
### 7.7 Creator community graph
`app/services/creators.py` + `app/controllers/v1/creators.py` (6 endpoints) add public
creator **profiles** (addressable by `user_id` or handle), an idempotent directed
**follow graph** (`creator_follows`; no self-follow, double-follow is a no-op), and a
**leaderboard** ranking creators by a documented reputation blend (followers + clones
received + marketplace win-scores), with follower/following counts surfaced on the profile.
---
## 8. Enterprise Layer — Access & Governance (Epic 1) + Identity & SSO (Epic 2)
The enterprise program (see [`PRODUCT_BLUEPRINT.md`](./PRODUCT_BLUEPRINT.md)) layers a
governance and identity tier **around** the render core without changing the DAG. Epics 1
and 2 are **shipped**; Epic 3 (Billing) is **in progress** and not described here. Like §7,
every surface reuses the same auth guard, MPT response envelope, and repository pattern.
### 8.1 Access & Governance (Epic 1)
- **RBAC decision engine (`app/services/rbac.py` + `controllers/v1/rbac.py`, 3 endpoints).**
Authorization is split into two independently-testable concerns. **(1) Tenant isolation
(membership):** the caller's `WorkspaceMember` row is the gate — a caller with no
membership in the workspace is *not in the tenant* and is denied outright, so no endpoint
ever returns another tenant's data. **(2) Role → permission:** delegated to **pycasbin**
(Apache-2.0) — a module-level `casbin.Enforcer` built from an in-code RBAC model + policy
with a linear `owner > admin > editor > viewer` inheritance chain plus a standalone
`billing` role. It is **deny-by-default / fail-closed**: an unknown/legacy role carrying no
policy is denied every permission. `require_permission(session, user_id, workspace_id,
permission)` raises or passes and is called directly inside the enterprise controllers
(`admin`, `audit`, `rbac`, `scim`, `sso`, `security_policy`).
- **Append-only audit trail (`app/services/audit.py` + `controllers/v1/audit.py`,
`audit_log` table).** Exactly two operations: `record` (INSERT one immutable row — never
updates or deletes) and `query` (read a workspace's trail, but only after enforcing
`audit.read` via RBAC, strictly tenant-scoped). There is deliberately **no update/delete**
anywhere in the service or `AuditLogRepository`, so the trail is tamper-evident by
construction. Governance-sensitive writes across the enterprise layer append an audit row.
- **Platform-admin surface (`app/services/admin.py` + `controllers/v1/admin.py`,
4 endpoints).** The ReelForge *staff* surface: cross-tenant listing of users/workspaces/
jobs + short-lived, time-boxed **impersonation** (`IMPERSONATION_TTL_SECONDS = 15min`,
every impersonation writes an audit row). Hard-gated on **`User.is_staff`** and kept
deliberately **separate** from per-workspace RBAC — a workspace `owner` is not a platform
admin, and staff status grants nothing *inside* a workspace. Driven by the
**refine** admin console at `web/app/admin` (`@refinedev/core` + `@refinedev/nextjs-router`).
### 8.2 Identity & SSO (Epic 2)
Enterprise SSO/SCIM is an **additive, new auth path**, layered alongside — never replacing —
Clerk (email + Google) on the web/mobile/desktop clients.
- **SAML SSO (`app/services/sso.py` + `controllers/v1/sso.py`, 6 endpoints;
`sso_connections` + `external_identities` tables).** A workspace configures an IdP
connection (signing cert / secret Fernet-encrypted at rest via `crypto_tokens` /
`SOCIAL_TOKEN_KEY`); `build_login_redirect` issues the SP-initiated AuthnRequest and
`process_acs` validates → replay-protects → enforces email/domain → maps to an
`ExternalIdentity` keyed by `(workspace_id, idp_subject)`. **Signature/condition validation
is delegated entirely to python3-saml** (SAML-Toolkits/python3-saml, MIT — imports as
`onelogin.saml2`), never hand-rolled; the native `xmlsec` dependency is isolated behind an
import-guarded validator seam, so when it is absent the SSO endpoints degrade to a clean
`503` and tests inject a validated assertion through the seam.
- **SCIM 2.0 provisioning (`app/services/scim.py` + `controllers/v1/scim.py`, 12 endpoints;
`scim_tokens` table).** An IdP provisions/deprovisions users over SCIM 2.0. A `Bearer`
token is resolved by its SHA-256 digest to a `ScimToken` scoped to **one** workspace — a
token minted for workspace *B* can never touch workspace *A*. Provisioning state lives in
the shared `ExternalIdentity` (soft-disable on deactivate, never hard delete). The optional
`scim2-filter-parser` (MIT) is import-guarded, degrading to `userName`/`email` equality.
- **Workspace security policy (`app/services/security_policy.py` +
`controllers/v1/security_policy.py`, 2 endpoints; `security_policies` table).** A per-
workspace singleton (force-SSO, session lifetime, allowed email domains, MFA, IP
allowlist). Writes are **RBAC-gated at the service boundary** (`workspace.settings`) and
audited; `enforce_login_policy` raises `PolicyViolation` on the first failing rule.
---
## 9. Graph-Engineering Build Method
ReelForge was built by treating the render pipeline DAG as the primary engineering
artifact and letting the graph's dependency edges drive both the build order and the
runtime orchestration. Three concrete manifestations:
1. **The DAG is a declared constant, not implicit control flow.** `REELFORGE_DAG` (a
`stage → deps` adjacency map in `app/models/const.py`) is the single definition of
stage dependencies. `pipeline.py` compiles it into a Celery `chain`/`chord`;
`tasks.py::_done_stages` walks its transitive closure for progress; `pipeline.py`'s
retry logic reads it to decide resume points. Change the graph in one place and
orchestration, progress, and resume all follow.
2. **Dependency-ordered build order (`INTEGRATION_CONTRACT.md §10`).** The system was
assembled bottom-up along the graph's edges: config + deps → persistence → storage →
TTS adapter → script → avatar → captions → compose → stages/workers → API → tests. Each
layer only depends on layers already built, mirroring the render DAG's topological
order.
3. **The compose stage is itself a filter-graph.** The production render path is a
**single-pass FFmpeg filter-graph** (`compose/compose_ffmpeg.py`) that overlays avatar
over screen recording, burns in captions, and mixes ducked audio in one pass — avoiding
MPT's MoviePy multi-pass re-encode bottleneck (`ugc-tool-cto-plan.md`,
`ugc-video-tool-build-plan.md`). The three layouts (`pip`, `hook_intro`, `split`) are
config variants of the same graph builder.
**Non-negotiable graph invariants** (`INTEGRATION_CONTRACT.md §10`): the DB `Job` row is
the persistent source of truth for parallel stages (use atomic `update_stage`, never
whole-map overwrite); `JobContext` stays JSON-serializable (strip `SubMaker`); retry
honors the first-failure guard and never resurrects a deleted job.
---
## 10. Key File Map
| Concern | Path |
|---------|------|
| ASGI app / CORS / static mounts | `app/asgi.py` |
| Route registration (29 included routers) | `app/router.py` |
| Reel/job API (create/get/list/retry/rerun/avatars/voices/me) | `app/domains/reels/router.py` |
| Upload/media API (presign/register) | `app/domains/media/router.py` |
| Stage functions + `ReelForgeParams` DTO | `app/services/reelforge.py` |
| Celery app + queues + beat schedule | `app/workers/celery_app.py` |
| DAG assembly + enqueue + retry | `app/workers/pipeline.py` |
| Stage tasks (retry/progress/failure) | `app/workers/tasks.py` |
| Shared JobContext + chord fan-in | `app/workers/context.py` |
| DB models (jobs/assets/events/…) | `app/models/db/models.py` |
| R2 object storage client | `app/platform/storage/r2.py` |
| Weighted progress | `app/telemetry/progress.py` |
| Analytics BI read models (§7.1) | `app/services/analytics.py`, `app/controllers/v1/analytics.py` |
| Template marketplace + remix/win-score (§7.2) | `app/services/marketplace.py`, `app/controllers/v1/marketplace.py` |
| Hook-performance loop → Spark (§7.3) | `app/services/hook_performance.py`, `app/controllers/v1/performance.py`, `app/controllers/v1/ideas.py` |
| Per-key quota / rate-limit → 429 (§7.4) | `app/services/apikey_quota.py`, `app/controllers/v1/{api_keys,base}.py` |
| OAuth connect + token encryption (§7.5) | `app/services/{oauth_connect,crypto_tokens}.py`, `app/controllers/v1/connections.py` |
| Public watermarked share (§7.6) | `app/services/share.py`, `app/controllers/v1/share.py` |
| Creator profiles + follow graph (§7.7) | `app/services/creators.py`, `app/controllers/v1/creators.py` |
| Editing-polish pre-compose passes (§4.6) | `app/services/editing/{silence_cut,auto_zoom,motion,matting}.py` |
| Enterprise RBAC + tenant isolation (§8.1) | `app/services/rbac.py`, `app/controllers/v1/rbac.py` |
| Append-only audit trail (§8.1) | `app/services/audit.py`, `app/controllers/v1/audit.py` |
| Platform-admin (`is_staff`) surface (§8.1) | `app/services/admin.py`, `app/controllers/v1/admin.py`, `web/app/admin` |
| SAML SSO (§8.2) | `app/services/sso.py`, `app/controllers/v1/sso.py` |
| SCIM 2.0 provisioning (§8.2) | `app/services/scim.py`, `app/controllers/v1/scim.py` |
| Workspace security policy (§8.2) | `app/services/security_policy.py`, `app/controllers/v1/security_policy.py` |
| Client surfaces (web/mobile/desktop) | `web/`, `mobile/`, `desktop/` |
| Full local run harness + smoke | `docker-compose.full.yml`, `Makefile.dev`, `ops/smoke.py` |
| Forward/target topology | `docs/reelforge/ARCHITECTURE_NEXT.md` |
| Product + enterprise roadmap | `docs/reelforge/PRODUCT_BLUEPRINT.md` |
| Deployment stack | `docker-compose.reelforge.yml` |
| Authoritative contract | `docs/reelforge/INTEGRATION_CONTRACT.md` |