videogen/docs/SCALE-PLAN.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

219 lines
12 KiB
Markdown

# Menivor scale plan (box 1, 2026-09-27)
Everything below was measured on 2026-09-26/27 (UTC) against production
(`https://api.menivor.com`, Cloudflare tunnel to box 1). No renders were
created, no provider money was spent, no database rows were written. Numbers
not measured are marked as recommendations.
## 1. What the box is
| Item | Measured |
|---|---|
| Host | 2 vCPU (`nproc` = 2), 11.9 GB RAM, 8 GB swap (1.4 GB in use) |
| Host load at test time | load average 12.7 to 13.5 on 2 CPUs; 11.5% steal. Other tenants: a niced `node` build (60+ CPU-minutes) and a style-sample render job in the Menivor worker |
| `menivor-api-1` | `uvicorn app.asgi:app`, one process, no `--workers`; CPU limit 2.0; memory limit 1.5 GiB |
| `menivor-worker-1` | `celery worker -Q celery,render,generation --concurrency=1 --max-tasks-per-child=25`; CPU limit 2.0; memory limit 2.5 GiB; `acks_late=True`, `prefetch_multiplier=1` |
| `menivor-redis-1` | `maxmemory 384mb`, `noeviction` |
| `menivor-db-1` | Postgres 16, `max_connections=60`, `shared_buffers=256MB`, limit 1 GiB / 1 CPU |
## 2. Load test (read paths only)
Script: `docs/loadtest/menivor-read-paths.js` (k6). Endpoints: `GET /healthz`,
`GET /api/v1/styles`, `GET /api/v1/billing/monthly-plans`. All public,
read-only, no auth, no moderation, no renders. Hard-capped at 20 VUs and 60 s,
with `abortOnFail` if error rate > 5% or p95 > 8 s. Run from the Mac
through Cloudflare, so latency includes the WAN round trip.
| Run | VUs (peak) | Pause/iter | Requests | Throughput | Errors | p50 | p95 | max |
|---|---|---|---|---|---|---|---|---|
| A | 10 | 1 s | 675 | 11.2 req/s | 0% | 124 ms | 400 ms | 1.22 s |
| B | 20 | 0.2 s | 1839 | 30.5 req/s | 0% | 213 ms | 732 ms | 2.23 s |
Per endpoint, run B, p95: healthz 877 ms, styles 731 ms, monthly-plans 678 ms.
Reading: tripling offered load (A to B) roughly doubled p95 with zero errors.
The API is not the bottleneck for page views at our current traffic; it is
already sharing 2 CPUs with a render and a build, so these numbers are a floor,
not a ceiling.
One single-request probe just before the test took 9.38 s on `/healthz` (the
next two requests took 1.75 s and 0.20 s). See section 3: the API was swapping.
## 3. Findings that limit scale (measured)
1. **API is at its memory limit and swapping.** cgroup `anon` = 1.566 GB of a
1.61 GB limit; `memory.swap.current` = 733 MB; `memory.events max` = 12230
(times the limit was hit since start 32 min earlier); `oom_kill` = 0.
Swapping is the likely cause of multi-second outliers like the 9.38 s
`/healthz`.
2. **One render at a time.** Worker concurrency is overridden to 1 (compose
default is 2). A single style-sample render's `ffmpeg` step used 1.53 GB RSS
and had been running 6 min at 45% CPU under host contention. With a 2.5 GiB
worker limit, two concurrent renders would exceed it; concurrency 1 is
correct for this box.
3. **One worker serves all queues.** `celery`, `render` and `generation` share
the single slot, so a 6+ minute render blocks beat housekeeping tasks
(`celery` queue depth was 3 while the render ran; `render` 0,
`generation` 0).
4. **No render duration history on the box DB.** The box-local `reelforge`
database had 0 rows in `jobs`, so there is no real p50/p90 render time yet.
Measure it after launch with the query in section 6.
## 4. Concrete limits (current and recommended)
| Limit | Current (code/config) | Recommended on this box |
|---|---|---|
| Worker concurrency | 1 (env `MENIVOR_WORKER_CONCURRENCY`) | Keep 1 |
| Worker memory | 2.5 GiB | Keep 2.5 GiB while concurrency is 1 |
| API memory | 1.5 GiB | Raise to 2.5 GiB (`mem_limit` in `infra-box/stacks/menivor/docker-compose.yml`) and find the 1.5 GB resident set; uvicorn stays 1 process |
| Queue split | DONE 2026-09-27: beat ticks on `housekeeping` (own worker, 0.5 CPU, 768m); render worker keeps `celery,render,generation` | See section 7 |
| Reel create rate | 30 requests/hour/user (`reelforge_jobs_rate_limit`, window 3600 s) | Keep; each request can fan out to 3 variants, so this is up to 90 renders/hour/user, far above what one slot can serve |
| B-roll create rate | 20/hour/user | Keep |
| Active captures | 3 per user | Keep |
| Ad Studio active renders | 40 per user | Lower to 6 on this box (one slot) |
| Global render queue cap | none | Add: reject new render jobs with a calm "busy, try in a few minutes" (HTTP 429 + Retry-After) when `llen render` + in-flight > 20 |
| Redis | 384 MB, noeviction | Keep; queue payloads are small |
| Postgres connections | 60 | Keep; API + worker + beat use well under this |
## 5. Capacity math (from the numbers above)
- One render slot. If a render takes T minutes, the box finishes 60/T reels per
hour. With the only measured sample (a style sample still running at 6 min),
that is at most 10 reels/hour, 240/day, before queueing grows.
- A one-flow create enqueues 3 variants, so about 3 creates/hour keep the slot
busy at T = 6 min.
- Read traffic is not the constraint: 30 req/s sustained with 0 errors while
the host was overloaded.
When sustained render queue wait exceeds 10 minutes, add a second render host
(another box or a GPU worker for `generation`) rather than raising concurrency
on this box.
## 6. How to re-measure
```bash
# Read paths (safe for prod): <= 20 VUs, <= 60 s
k6 run -e MAX_VUS=20 -e PAUSE_S=0.2 docs/loadtest/menivor-read-paths.js
# Box resources
ssh box 'docker stats --no-stream menivor-api-1 menivor-worker-1'
ssh box 'docker exec menivor-api-1 cat /sys/fs/cgroup/memory.events'
ssh box 'docker exec menivor-redis-1 sh -c "for q in celery render generation; do echo \$q \$(redis-cli llen \$q); done"'
```
Render duration (read-only SQL, run against the API's database):
```sql
SET default_transaction_read_only = on;
SELECT state, count(*),
percentile_cont(0.5) WITHIN GROUP (ORDER BY extract(epoch FROM updated_at - created_at)) AS p50_s,
percentile_cont(0.9) WITHIN GROUP (ORDER BY extract(epoch FROM updated_at - created_at)) AS p90_s
FROM jobs WHERE created_at > now() - interval '7 days' GROUP BY state;
```
Never load test `POST /jobs`, `/styles/hooks` or any generation endpoint
against prod: each call spends provider money or a render slot.
## 7. Render throughput pass (2026-09-27)
Trigger: the owner's 3 meme-hook reels (created 22:38:55 UTC on 09-26) sat on
"Waiting for a render slot". From `job_events` (read-only): the script stage
started 10 min 44 s after the click (behind the previous 3-reel run plus beat
sweeps on the same single slot), each compose took 462-479 s for 45-51 s of
narration, and the last reel finished at 23:14:39: 35 min 44 s from click.
### What changed
1. **Housekeeping queue.** Every beat entry (21 ticks incl. the engagement
ones) is routed to `housekeeping` with `expires` = its period (max 1 h), so
a tick nobody picked up is dropped instead of piling up. Box stack: new
`housekeeping` service (`-Q housekeeping --concurrency=2`, 0.5 CPU, 768m).
Dev workers consume `...,housekeeping` too.
2. **x264 preset.** Final reel encodes use `-preset veryfast -crf 21`
(FFmpeg default was `medium`, CRF 23). Override per host with
`MENIVOR_X264_PRESET` / `MENIVOR_X264_CRF`.
3. **Bounded `-shortest` buffer.** FFmpeg 6+ holds up to 10 s of raw decoded
frames for `-shortest`; `-shortest_buf_duration 1` (probed once per
binary) keeps the same output duration.
4. **No R2 round trip for style tracks.** The ~25 MB intermediate per variant
is composed from the local file.
5. **Render worker CPU weight.** `cpu_shares: 2048` on the render worker so a
creator's render outranks batch jobs (builds, imports, sample renders) when
box 1 is contended. No effect when idle.
6. **One page recording per reel, not per variant.** Styles now record the
pasted page in headless Chromium (added the same day, real time, up to
40 s + browser start per variant). The first variant's clip is cached
worker-locally for 20 min under `runtime/storage/cache/page-recordings`
with a per-page lock, and the scene stream-loops it to each variant's
length, so variants 2 and 3 skip Chromium entirely.
7. **Honest queue ETA.** `GET /jobs/{id}` adds `queue: {ahead, eta_s, slots}`
for unfinished jobs: `ahead` is a real count of unfinished jobs created
earlier (3 h window); `eta_s` comes only from the median summed stage
`duration_ms` of the last 12 completed jobs (7 days), times the rounds
through `MENIVOR_RENDER_SLOTS`; `null` with fewer than 3 samples. The
results page shows "2 reels ahead of yours. Ready in about 4 min." and,
while rendering, "Ready in about N min".
### Measurements
FFmpeg only, 25 s meme reel, idle box 2 (`railyard-box`, 2 OCPU A1, same
FFmpeg 7.1.5 build as the worker image), `apps/api/tools/ops/profile_render.py`
inputs:
| Step | Before | After |
|---|---|---|
| Scene track (ultrafast, unchanged) | 13.0 s, 290 MB | 13.0 s, 290 MB |
| Compose, default `medium` CRF 23 -> `veryfast` CRF 21 | 36.4 s | 18.2 s |
| Compose peak RSS (`-shortest` default -> 1 s buffer) | 1,419 MB | 417 MB |
| Output duration | 25.0 s | 25.0 s |
Real pipeline, 3 meme_hook variants for Rally (hooks met_me_at, nobody_me,
tell_me_without; 40-48 s narration each), in-process on box 1 with the worker
image and worker limits (`apps/api/tools/ops/time_style_variants.py`; no Job
rows; R2 test objects deleted). Old code (`origin/main` 7ae8e012) and new code
ran at the same time so both saw the same host load (load average 12-14):
| | Old | New |
|---|---|---|
| Wall clock, all 3 variants | 1,192.6 s (19.9 min) | 583.1 s (9.7 min) |
| Per variant (script to final upload) | 368 / 419 / 388 s | 170 / 198 / 197 s |
| First reel ready | 7.2 min | 3.9 min |
The old run finished its last variant after the new run had exited, so it had
less contention at the end; the real gap is slightly larger than shown.
Spend: 6 hook LLM calls (a few cents); narration used the free voice.
### Box 2 as a second render worker: not done, documented
Box 2 is idle (load 0.0, 10 GB free, same 2 OCPU A1) and renders the same
reel about 3x faster than contended box 1, so it is the next real lever.
It is not safe and simple today:
- **Broker/DB reach.** Redis and Postgres listen only on box 1's Docker
network. Box 2 can reach box 1 over the VCN (`10.0.0.71 -> 10.0.0.191`, SSH
tested), but publishing Redis would expose an unauthenticated broker
(`redis-server` runs without `requirepass`), and Docker-published ports
bypass ufw. Needs: `requirepass` on Redis + `redis_password` in config.toml
and `REDIS_PASSWORD` in menivor.env for every service, ports bound to
`10.0.0.191` only, an OCI security-list rule allowing 6379/5432 from
`10.0.0.71/32` only, and a DOCKER-USER iptables rule dropping other sources.
- **Code and secrets on box 2.** It needs its own `/srv/src/videogen`
checkout + gitignored `config.toml`, a copy of `menivor.env`, and a
worker-only compose file (install.sh `menivor` would start a second DB,
API and beat there, which must never happen).
- **Queue scope.** Reel stages are R2-backed (compose re-hydrates audio and
captions from R2 when the local path is missing), but other `render` tasks
(captures, Ad Studio, editor/film export) were written for one host. A box-2
worker must consume a reel-only queue (route `stage_compose_task` to e.g.
`render_reel`, consumed by BOTH boxes' render workers so box 1 still works
when box 2 is down).
- When done, set `MENIVOR_RENDER_SLOTS=2` in menivor.env so the ETA halves.
### Next levers (measured estimate, not done)
- Single-pass style render: draw captions and mux narration in the scene
FFmpeg call when the reel has no music, watermark or VFX (skips one full
1080x1920 encode + decode; about one third of compose time).
- Move batch tenants off box 1 (sample renders, builds, bulk imports); load
average was 12-20 on 2 vCPUs during every measurement above.