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.
39 KiB
ReelForge Data Model
Point-in-time model guide: table and migration counts below describe an earlier schema. Use
CURRENT_STATE.mdand the SQLAlchemy models/Alembic chain for the authoritative current state.
The persistence layer that backs ReelForge (a UGC avatar-reel generator forked
from MoneyPrinterTurbo). It is a SQLAlchemy 2.0 (Mapped[] typing) ORM over
Neon Postgres in production and SQLite in the test/verify engine, with
schema evolution managed by Alembic.
Source of truth:
| Concern | File |
|---|---|
| Declarative base, engine, session | app/models/db/base.py |
| ORM models (all tables) | app/models/db/models.py |
| Repository layer (atomic ops, ownership checks) | app/models/db/repositories.py |
| Migrations | migrations/versions/*.py |
| Alembic env | migrations/env.py |
1. Engine & Session
app/models/db/base.py defines the shared Base(DeclarativeBase) and a lazily
initialized, process-wide engine + sessionmaker.
- Connection URL resolves from
config.neon.database_url(bound inapp/config/config.py), falling back to theNEON_DATABASE_URLenv var._database_url()never raises — merely importing the module has no side effects, so the pipeline does not crash when the DB is unconfigured. - Engine (
get_engine()) is created on first use withpool_pre_ping=True(recycles stale connections after Neon's serverless auto-suspend),pool_size=5,max_overflow=10,future=True. Built under a double-checkedthreading.Lock(_init_lock) soengineandSessionLocalpublish atomically; raises a clearRuntimeError(never a bare driver error) when no URL is configured. - Session (
get_session()) is a context manager (commit on success, rollback on exception, always close) usable from both FastAPI dependencies and Celery workers. Thesessionmakerusesautoflush=False,expire_on_commit=False.
Design rules (per models.py module docstring)
- All non-sequence primary keys are 32-char uuid4 hex strings generated by
_uuid()(uuid.uuid4().hex). - All timestamps are
TIMESTAMP(timezone=True)with a server-sidenow()default (rendered asCURRENT_TIMESTAMPin migrations). job_eventsandcredit_ledgerare append-only audit trails — rows are never mutated after insert. A running balance is materialized inCreditLedger.balance_afterfor O(1) personal-balance reads.- Auto-increment PKs on the two append-only ledgers use
BigInteger().with_variant(Integer, "sqlite")—BIGINTon Postgres/Neon,INTEGERon SQLite (the only type SQLite auto-increments).
2. Tables
There are 22 tables. Every FK targets a 32-char string PK (except the two
append-only ledgers, whose auto-increment PKs are BigInteger/Integer(sqlite)).
2.1 users — User
A ReelForge account. credits is a denormalized cache of the personal ledger
balance.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid default |
email |
String(320) | NOT NULL, UNIQUE, indexed (ix_users_email) |
display_name |
String(200) | default "" |
handle |
String(64) | nullable, UNIQUE (multiple NULLs allowed); public creator vanity slug (/creators/<handle>) — Creator Profiles |
bio |
Text | nullable — short free-text public blurb (Creator Profiles) |
api_key_hash |
String(128) | default "" — sha256 hex of the raw API key (raw key never stored) |
credits |
Integer | default 0 — denormalized ledger cache |
referral_code |
String(16) | nullable, UNIQUE (multiple NULLs allowed); populated lazily on first share |
referred_by |
String(32) | nullable — referrer's user_id when a code is redeemed |
created_at |
DateTime(tz) | server now() |
Relationships: jobs → Job, presets → UserPreset.
referral_code / referred_by were added in Phase-7 (growth) as nullable
columns so the ADD COLUMN was safe on a populated table. handle / bio were
added for the Creator Profiles + Follow Graph feature — both nullable
(default NULL) so the ADD COLUMN stays safe on a populated table, and neither
is a private/financial field so both are safe to expose on a public profile /
leaderboard. handle is UNIQUE (multiple NULLs allowed on both SQLite and
Postgres, mirroring referral_code) so an unclaimed handle stays NULL while a
claimed one resolves to exactly one owner.
2.2 jobs — Job
A single avatar-reel render job and its per-stage status map.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_jobs_user_id) — ownership column |
batch_id |
String(32) | nullable, indexed (ix_jobs_batch_id) — links the N jobs of a variants:N request; NULL for single-variant |
kind |
String(40) | default "avatar_reel" |
state |
Integer | default 4, indexed (ix_jobs_state); reuses MPT TASK_STATE_* ints: PROCESSING=4, COMPLETE=1, FAILED=-1 (app/models/const.py) |
progress |
Integer | default 0 |
stages |
JSON | default {} — per-stage status map, e.g. {"script":"complete","tts":"running"} |
params |
JSON | default {} — ReelForgeParams dump |
failed_stage |
String(40) | default "" |
error |
Text | default "" |
celery_task_id |
String(64) | default "", indexed (ix_jobs_celery_task_id) |
result_key |
String(512) | default "" — final R2 key |
poster_key |
String(512) | NOT NULL, server_default '' — R2 key of poster/thumbnail frame (Phase-6 Creator Studio) |
preview_key |
String(512) | NOT NULL, server_default '' — R2 key of low-res preview clip |
webhook_url |
String(1024) | NOT NULL, server_default '' — optional completion callback |
script |
Text | nullable, server_default '' — finalized narration script (re-run / multi-language dubbing) |
cover_key |
String(512) | nullable, server_default '' — R2 key of latest cover/thumbnail image |
created_at |
DateTime(tz) | server now() |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
Relationships: user → User, events → JobEvent, assets → Asset.
Studio columns (poster_key, preview_key, webhook_url) declare a
server_default so their NOT NULL ADD COLUMN is safe on a populated table and
Alembic's compare_server_default=True reports no spurious drift.
2.3 job_events — JobEvent (append-only)
Append-only telemetry / audit trail row for a job stage transition.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
BigInteger / Integer(sqlite) | PK, autoincrement |
job_id |
String(32) | FK→jobs.id, NOT NULL, indexed (ix_job_events_job_id) |
stage |
String(40) | NOT NULL |
status |
String(20) | NOT NULL — REELFORGE_STAGE_* |
message |
Text | default "" |
payload |
JSON | default {} |
cost_usd |
Float | NOT NULL, default 0.0, server_default 0 — per-stage USD spend (unit economics, CTO plan §0) |
duration_ms |
Integer | NOT NULL, default 0, server_default 0 — stage wall-clock |
created_at |
DateTime(tz) | server now() |
Rows are never mutated after insert. cost_usd / duration_ms default to 0
so historical / non-cost events remain valid and the table stays append-only.
2.4 assets — Asset
A stored artifact in R2.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
job_id |
String(32) | FK→jobs.id, nullable, indexed (ix_assets_job_id) |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_assets_user_id) — ownership column |
kind |
String(40) | screen | audio | avatar | ass | final | upload |
r2_key |
String(512) | NOT NULL |
content_type |
String(120) | default "" |
size_bytes |
BigInteger | default 0 |
duration_s |
Float | default 0.0 |
meta |
JSON | default {} |
created_at |
DateTime(tz) | server now() |
Relationship: job → Job.
2.5 avatar_presets — AvatarPreset
A saved avatar/voice preset. user_id NULL means a global preset.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, nullable, indexed (ix_avatar_presets_user_id) — NULL ⇒ global |
provider |
String(40) | default "heygen" |
provider_avatar_id |
String(120) | NOT NULL |
display_name |
String(200) | default "" |
voice_name |
String(120) | default "" — e.g. "elevenlabs:<id>" |
thumbnail_url |
String(512) | default "" |
config |
JSON | default {} — background, style, dimension |
is_active |
Boolean | default True |
created_at |
DateTime(tz) | server now() |
2.6 credit_ledger — CreditLedger (append-only)
Append-only credit ledger. Personal balance == newest balance_after;
workspace-pool balance == SUM(delta).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
BigInteger / Integer(sqlite) | PK, autoincrement |
user_id |
String(32) | FK→users.id, nullable, indexed (ix_credit_ledger_user_id) — personal-pool owner; NULL allowed for a system workspace grant |
workspace_id |
String(32) | FK→workspaces.id, nullable, indexed (ix_credit_ledger_workspace_id) — set ⇒ workspace shared pool; NULL ⇒ personal pool |
job_id |
String(32) | FK→jobs.id, nullable, indexed (ix_credit_ledger_job_id) |
delta |
Integer | NOT NULL — +grant / -debit |
reason |
String(80) | NOT NULL — signup | purchase | job_debit | refund | workspace_grant | workspace_debit |
balance_after |
Integer | NOT NULL — materialized running balance (personal pool) |
created_at |
DateTime(tz) | server now() |
A row never counts toward both balances: personal reads filter
workspace_id IS NULL; pool reads filter workspace_id == X. user_id was
relaxed to nullable in migration 633c3ca06e6c so a workspace-pool row can exist
without a personal owner; every pre-existing row keeps its non-null user_id and
NULL workspace_id, so personal balances read identically. See §3 for the atomic
row-locked operations.
2.7 user_presets — UserPreset
A user-saved "brand kit" (Phase-7): a named bundle of render knobs (avatar, voice, layout, caption style, music, language).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_user_presets_user_id) — ownership column (always retained for attribution) |
workspace_id |
String(32) | FK→workspaces.id, nullable, indexed (ix_user_presets_workspace_id) — set ⇒ shared to a workspace; NULL ⇒ private |
name |
String(200) | NOT NULL |
config |
JSON | default {} — opaque brand-kit config; grows without migration |
created_at |
DateTime(tz) | server now() |
Relationship: user → User.
2.8 user_voices — UserVoice
A creator's cloned "brand voice" (Phase-11). Uploaded sample → ElevenLabs
Instant Voice Clone → selectable narrator via
voice_name = "elevenlabs:<provider_voice_id>".
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_user_voices_user_id) — ownership column |
provider |
String(40) | default "elevenlabs" |
provider_voice_id |
String(120) | default "", indexed (ix_user_voices_provider_voice_id) — resolves a job's narrator back to its row |
name |
String(200) | default "" |
sample_key |
String(512) | default "" — R2 key of uploaded sample |
consent |
Boolean | default False — mandatory ownership/authorization attestation |
status |
String(20) | default "ready" — ready | processing | failed |
created_at |
DateTime(tz) | server now() |
2.9 user_brands — UserBrand
Per-user "brand watermark" settings (singleton per user). One transparent-PNG logo overlaid by the FFmpeg compose stage.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, UNIQUE + indexed (ix_user_brands_user_id, unique) — enforces one row per user (repo upserts in place) |
logo_key |
String(512) | NOT NULL, server_default '' — R2 key of PNG logo; '' ⇒ no watermark |
position |
String(20) | NOT NULL, server_default 'bottom_right' — bottom_right | bottom_left | top_right | top_left |
opacity |
Float | NOT NULL, server_default 0.85 — [0.0, 1.0] |
enabled |
Boolean | NOT NULL, server_default 1 |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
A job can still override/disable the watermark via its ReelForgeParams.
2.10 saved_ideas — SavedIdea
A SPARK "AI Idea Engine" concept a creator saved for later (Phase-18).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_saved_ideas_user_id) — ownership column |
title |
String(300) | default "" — denormalized for cheap list rendering |
hook |
String(300) | default "" — denormalized |
payload |
JSON | default {} — full opaque idea dict (hook/angle/format/script_outline/…); grows without migration |
created_at |
DateTime(tz) | server now() |
2.11 notifications — Notification
In-app notification (bell / notification center); the counterpart to external
webhooks (app/services/webhooks.py).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_notifications_user_id) — ownership column |
kind |
String(40) | NOT NULL — job_complete | job_failed | low_credits | referral_earned |
title |
String(300) | NOT NULL, default "" |
body |
Text | NOT NULL, server_default '' |
data |
JSON | default {} — opaque per-event payload |
read |
Boolean | NOT NULL, server_default 0 |
created_at |
DateTime(tz) | server now(), indexed (ix_notifications_created_at) |
Indexes: ix_notifications_user_id, ix_notifications_created_at, and the
composite ix_notifications_user_id_read on (user_id, read) backing the hot
unread_count / unread_only queries.
2.12 scheduled_publish — ScheduledPublish
A finished reel queued to auto-publish to social platforms at a future UTC time.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_scheduled_publish_user_id) — ownership column |
job_id |
String(32) | FK→jobs.id, NOT NULL, indexed (ix_scheduled_publish_job_id) |
platforms |
JSON | default [] — e.g. ["tiktok","instagram","youtube_shorts"] |
youtube_privacy_status |
String(20) | NOT NULL, server_default 'private' |
scheduled_at |
DateTime(tz) | NOT NULL, indexed (ix_scheduled_publish_scheduled_at) — due-claim range scan |
status |
String(20) | NOT NULL, server_default 'pending', indexed (ix_scheduled_publish_status) — pending | publishing | published | failed | canceled |
attempts |
Integer | NOT NULL, server_default 0 |
result |
JSON | default {} — opaque publish result |
error |
Text | NOT NULL, server_default '' |
created_at |
DateTime(tz) | server now() |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
A Celery-beat due-runner claims pending rows where scheduled_at <= now via a
guarded UPDATE ... WHERE status='pending' (safe against two concurrent
runners), then flips them to published / failed.
2.13 workspaces — Workspace
A team workspace: a shared container a user owns and invites teammates into. A
purely additive membership layer — it does NOT touch the per-user
job/credit ownership model (every other table stays keyed on users.id).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
name |
String(200) | NOT NULL, default "" |
owner_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_workspaces_owner_id) — denormalized creator (also a role='owner' member row) |
created_at |
DateTime(tz) | server now() |
Relationship: members → WorkspaceMember.
2.14 workspace_members — WorkspaceMember
A user's membership of a workspace with a role.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
workspace_id |
String(32) | FK→workspaces.id, NOT NULL, indexed (ix_workspace_members_workspace_id) |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_workspace_members_user_id) |
role |
String(20) | NOT NULL, default "member" — owner | admin | member |
created_at |
DateTime(tz) | server now() |
Constraint: composite UniqueConstraint("workspace_id","user_id", name="uq_workspace_members_ws_user") — a user is a member of a given workspace
at most once (a duplicate invite can never create a second row).
Relationship: workspace → Workspace.
2.15 user_api_keys — UserApiKey
A power user's personal API key for programmatic /api/v1 access (Public API
Keys). Presented as the x-api-key header; the raw key is never persisted —
only its SHA-256 hex digest (key_hash). A revoke is a soft-delete (row retained
for audit / display).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_user_api_keys_user_id) — ownership column |
name |
String(200) | NOT NULL, server_default '' — human-friendly label (e.g. "CI", "n8n") |
key_hash |
String(64) | NOT NULL, UNIQUE + indexed (ix_user_api_keys_key_hash, unique) — sha256 hex; resolves a presented key to one owner |
prefix |
String(16) | NOT NULL, server_default '' — non-secret display prefix (e.g. rf_ab12…) |
last_used_at |
DateTime(tz) | nullable — best-effort last-use stamp; NULL until first use |
rate_limit_per_min |
Integer | nullable — max requests/minute; NULL ⇒ plan/config default, non-positive disables (per-key quota) |
monthly_quota |
Integer | nullable — max requests/calendar month (counted in api_key_usage); NULL ⇒ UNLIMITED |
revoked |
Boolean | NOT NULL, server_default 0, indexed (ix_user_api_keys_revoked) — soft-delete; a revoked key can never authenticate |
created_at |
DateTime(tz) | server now() |
rate_limit_per_min / monthly_quota were added later (per-API-key quotas +
rate limits) as nullable columns so the ADD COLUMN was safe on a populated
table and a pre-existing key inherits the plan default.
2.16 api_key_usage — ApiKeyUsage
Monthly request counter for one user_api_keys row (per-key quota enforcement,
app/services/apikey_quota.py). Every authenticated x-api-key request
atomically increments the counter for the key's current calendar month; the
enforcement layer rejects a request (HTTP 429) once the count exceeds the
key's monthly_quota.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
api_key_id |
String(32) | FK→user_api_keys.id, NOT NULL, indexed (ix_api_key_usage_api_key_id) |
period_ym |
String(7) | NOT NULL — zero-padded 'YYYY-MM' calendar month |
count |
Integer | NOT NULL, default 0, server_default 0 — authenticated requests made in period_ym |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
Constraint: composite UniqueConstraint("api_key_id","period_ym", name="uq_api_key_usage_key_period") — exactly one row per (key, month), so a
concurrent increment updates the single row in place; a new month inserts a fresh
row (prior months retained for audit / usage history).
2.17 marketplace_templates — MarketplaceTemplate
A creator-published, PUBLIC job template in the Template Marketplace. Publishing
copies an immutable snapshot of the source template's content, so a later
edit to the author's private template never mutates the public listing. Any
authenticated user can browse/search, clone (→ bumps clone_count), remix
(re-publish a clone → bumps parent's remix_count) and rate (1..5) a listing.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
author_user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_marketplace_templates_author_user_id) — ownership column (only the author may edit/unpublish) |
title |
String(300) | NOT NULL, server_default '' |
description |
Text | NOT NULL, server_default '' |
prompt |
Text | NOT NULL, server_default '' — immutable prompt/brief snapshot |
params |
JSON | default {} — opaque params snapshot (caption_style, target_duration_s, …) |
tags |
JSON | default [] — free-form discovery tags |
language |
String(20) | NOT NULL, server_default 'en' — tr | en | auto |
layout |
String(40) | NOT NULL, server_default '' — suggested compose layout id |
rating_avg |
Float | NOT NULL, default 0.0, server_default 0 — denormalized, recomputed atomically from template_ratings |
rating_count |
Integer | NOT NULL, default 0, server_default 0 — denormalized rating count |
clone_count |
Integer | NOT NULL, default 0, server_default 0 — bumped once per clone |
parent_template_id |
String(32) | self-FK→marketplace_templates.id, nullable, indexed (ix_marketplace_templates_parent_template_id) — REMIX TREE parent; NULL ⇒ original publish |
remix_count |
Integer | NOT NULL, default 0, server_default 0 — bumped once per remix ("most remixed" sort) |
published |
Boolean | NOT NULL, default True, server_default 1, indexed (ix_marketplace_templates_published) — visibility gate (soft unpublish) |
created_at |
DateTime(tz) | server now() |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
Relationship: ratings → TemplateRating.
parent_template_id / remix_count were added later (Marketplace Remix Trees)
via batch mode as a nullable self-FK + defaulted counter, so the ADD COLUMN is
safe on a populated table. No cycles are possible — a parent is always an
already-published, strictly-older row. The remix tree win-score ranking feeds the
browse "most cloned" / "most remixed" sorts.
2.18 template_ratings — TemplateRating
One user's 1..5 star rating of a marketplace_templates listing. A re-rate is an
UPSERT; after each upsert the parent listing's rating_avg / rating_count are
recomputed atomically (TemplateRatingRepository.upsert_rating).
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
template_id |
String(32) | FK→marketplace_templates.id, NOT NULL, indexed (ix_template_ratings_template_id) |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_template_ratings_user_id) |
stars |
Integer | NOT NULL — service layer validates into [1, 5] |
created_at |
DateTime(tz) | server now() |
Constraint: composite UniqueConstraint("template_id","user_id", name="uq_template_ratings_template_user") — one rating per (template, user); a
re-rate updates in place rather than duplicating.
Relationship: template → MarketplaceTemplate.
2.19 job_performance — JobPerformance
A creator's self-reported real-world outcome for one posted reel (Hook Performance Loop). Fully key-free: every metric is creator-entered (no external platform API). Outcomes are aggregated per HOOK and per TEMPLATE into a "win score" that biases the SPARK idea engine toward patterns that genuinely convert.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
job_id |
String(32) | FK→jobs.id, NOT NULL, UNIQUE + indexed (ix_job_performance_job_id, unique) — one row per job (re-log UPSERTs in place) |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_job_performance_user_id) — ownership column (always the job's owner, verified before insert) |
platform |
String(40) | NOT NULL, default "unknown", server_default 'unknown' — normalized lower-case tiktok | instagram | youtube | … |
views |
Integer | NOT NULL, default 0, server_default 0 — clamped non-negative |
likes |
Integer | NOT NULL, default 0, server_default 0 — clamped non-negative |
comments |
Integer | NOT NULL, default 0, server_default 0 — clamped non-negative |
shares |
Integer | NOT NULL, default 0, server_default 0 — clamped non-negative |
saves |
Integer | NOT NULL, default 0, server_default 0 — clamped non-negative |
retention_pct |
Float | NOT NULL, default 0.0, server_default 0 — watch-through %, clamped [0, 100] |
logged_at |
DateTime(tz) | server now() |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
The job_id UNIQUE index enforces the one-row-per-job singleton; the
denormalized user_id ensures every read/aggregate is owner-scoped so a creator
can never log against — or read the outcomes of — another creator's job.
2.20 social_accounts — SocialAccount
A user's OAuth-connected social platform account for Direct-Publish Account-Connect (TikTok / Instagram / YouTube seam). A finished reel can be posted straight to the creator's account on their behalf.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_social_accounts_user_id) — ownership column |
provider |
String(20) | NOT NULL — normalized lower-case tiktok | instagram | youtube |
external_account_id |
String(200) | NOT NULL, server_default '' — provider-side account/user id (e.g. TikTok open_id) |
access_token_enc |
Text | NOT NULL — encrypted OAuth access-token blob (never plaintext) |
refresh_token_enc |
Text | nullable — encrypted OAuth refresh-token blob; nullable (not every provider issues one) |
token_expires_at |
DateTime(tz) | nullable — drives proactive refresh before a publish |
scopes |
Text | NOT NULL, server_default '' — granted OAuth scope string |
connected_at |
DateTime(tz) | server now() |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
Constraint: composite UniqueConstraint("user_id","provider", name="uq_social_accounts_user_provider") — at most one connection per
(user, provider); re-connecting UPSERTs the row in place (fresh tokens replace
the old blobs).
Security: plaintext OAuth tokens are never persisted — only their
symmetrically-encrypted (Fernet) blobs are stored. Encryption/decryption happens
at the service boundary (app/services/crypto_tokens.py) with a key from the
required SOCIAL_TOKEN_KEY config/env, so a database leak never exposes a usable
token. Every read is owner-scoped.
2.21 share_links — ShareLink
A public, unguessable, revocable share link for one of a creator's completed
reels (Public Watermarked Share Pages). Anyone with the link (no auth) sees a
watermarked preview — never the clean result_key.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
job_id |
String(32) | FK→jobs.id, NOT NULL, indexed (ix_share_links_job_id) — one-active-link-per-job lookup |
user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_share_links_user_id) — ownership column (always the job's owner) |
token |
String(64) | NOT NULL, UNIQUE + indexed (ix_share_links_token, unique) — 128-bit secrets.token_urlsafe public handle (_share_token), can never be enumerated |
revoked |
Boolean | NOT NULL, default False, server_default 0 — soft kill-switch; a revoked link reads as non-existent |
view_count |
Integer | NOT NULL, default 0, server_default 0 — public view counter (social proof), bumped in place |
created_at |
DateTime(tz) | server now() |
updated_at |
DateTime(tz) | server now(), onupdate=now() |
The public view DTO exposes ONLY safe fields (title, a presigned GET of the
watermarked preview/poster/cover key, created_at, and the sharer's referral
code) — never result_key, user_id, or any private financials. Governed by the
reelforge_share_base_url + reelforge_share_{write,view}_rate_{limit,window_s}
config keys.
2.22 creator_follows — CreatorFollow
A directed FOLLOW edge in the creator social graph (Creator Profiles + Follow
Graph): follower_user_id follows followee_user_id. Powers public
follower/following counts and a "followers" leaderboard.
| Column | Type | Constraints / Notes |
|---|---|---|
id |
String(32) | PK, _uuid |
follower_user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_creator_follows_follower_user_id) — "who does X follow?" (following) |
followee_user_id |
String(32) | FK→users.id, NOT NULL, indexed (ix_creator_follows_followee_user_id) — "who follows X?" (followers) |
created_at |
DateTime(tz) | server now() |
Constraint: composite UniqueConstraint("follower_user_id","followee_user_id", name="uq_creator_follows_follower_followee") — a directed edge exists at most
once (idempotent follow). Self-follow is rejected at the service/repository
boundary (never persisted). An edge is physically removed on unfollow (no
soft-delete). Carries NO private data — a purely public social relationship.
3. Append-only ledgers & atomic row-locked credit ops
Two tables are append-only audit trails (job_events, credit_ledger). The
credit ledger backs all balance math via CreditRepository
(app/models/db/repositories.py).
Personal pool
balance(user_id)— reads the newestbalance_afterfiltered byuser_id AND workspace_id IS NULL(O(1)); returns 0 when no personal rows exist.debit(user_id, amount, job_id, reason)— locks theUserrow (select(User).where(...).with_for_update(),_locked_balance), recomputes the balance under the lock, and appends a negative-deltarow only whencurrent >= amount; otherwise raisesValueErrorso the API surfaces a402. The balance can never go negative.grant(user_id, amount, reason)— same lock, appends a positive-deltarow._append(...)inserts the immutable row and syncs the denormalizedUser.creditscache tobalance_after.
Workspace shared pool
workspace_balance(workspace_id)— computed asSUM(delta) WHERE workspace_id == X(aggregate, correct even if rows were inserted out of id order), not frombalance_after.workspace_debit(...)/workspace_grant(...)— lock theWorkspacerow (_locked_workspace_balance,with_for_update()), recompute the pool balance under the lock, and append a row tagged withworkspace_id._append_workspace(...)never touches anyUser.creditscache.actor_user_idis recorded for audit only and never affects a personal balance.
Row-locking semantics
with_for_update() (SELECT ... FOR UPDATE) serializes concurrent
debit/grant operations for the same user/workspace so balance_after stays
monotonic. Only SQLite's missing FOR UPDATE (raised as NotSupportedError) is
tolerated — the code degrades to an unlocked read only when
dialect.name == "sqlite"; any other backend error, including real
Postgres/Neon locking failures, propagates. JobRepository._locked_job()
applies the identical pattern to serialize concurrent job-state writes.
Ownership enforcement
Every user-owned table carries an indexed user_id FK (highlighted as an
ownership column above). Repositories enforce ownership in code — e.g.
UserPresetRepository.get(preset_id, user_id) returns None when the row
belongs to a different user, so a caller cannot read another user's row by
guessing its id, and delete(...) returns False rather than deleting a
foreign row. UserBrandRepository upserts the per-user singleton in place
(enforced by the user_id UNIQUE index).
4. Migration chain
Linear chain (no branches / merges), managed by Alembic (migrations/env.py).
Newest last:
| # | Revision | Down-revision | File | Summary |
|---|---|---|---|---|
| 1 | 1624fc8a02de |
(none / base) | 20260810_1542_..._reelforge_initial_schema.py |
Initial schema: users, avatar_presets, jobs, assets, credit_ledger, job_events |
| 2 | 8d33fcd0b532 |
1624fc8a02de |
20260811_0828_..._job_events_cost_columns.py |
Adds job_events.cost_usd, duration_ms (unit economics) |
| 3 | 677d1259a269 |
8d33fcd0b532 |
20260811_0858_..._job_studio_columns.py |
Adds jobs.poster_key, preview_key, webhook_url (Creator Studio) |
| 4 | e5ae1b861df3 |
677d1259a269 |
20260811_0926_..._growth_referrals_user_presets.py |
New user_presets; adds users.referral_code (UNIQUE) + referred_by via batch mode |
| 5 | 36c997a74166 |
e5ae1b861df3 |
20260811_1016_..._job_batch_id.py |
Adds jobs.batch_id + index (batch variant review) |
| 6 | 9393d1a8ecc0 |
36c997a74166 |
20260811_1058_..._user_voices_brand_voice_clones.py |
New user_voices table (brand voice cloning) |
| 7 | 704e1099f854 |
9393d1a8ecc0 |
20260811_1251_..._saved_ideas_spark.py |
New saved_ideas table (SPARK idea engine) |
| 8 | 011cc457e6fb |
704e1099f854 |
20260811_1317_..._notifications.py |
New notifications table + (user_id, read) composite index |
| 9 | 555b661b1cde |
011cc457e6fb |
20260811_1425_..._job_script_column.py |
Adds jobs.script (persist narration for re-run / dubbing) |
| 10 | a03a6d3bc673 |
555b661b1cde |
20260811_1505_..._scheduled_publish.py |
New scheduled_publish table (scheduled publishing) |
| 11 | 03a93b99b144 |
a03a6d3bc673 |
20260811_1537_..._job_cover_key.py |
Adds jobs.cover_key (cover/thumbnail generator) |
| 12 | c7fe3c8161bc |
03a93b99b144 |
20260811_2036_..._workspaces_members.py |
New workspaces + workspace_members (UNIQUE ws+user) |
| 13 | 633c3ca06e6c |
c7fe3c8161bc |
20260811_2112_..._workspace_credits_shared_presets.py |
Adds credit_ledger.workspace_id (+ relaxes user_id to nullable) and user_presets.workspace_id, both with FK→workspaces.id |
| 14 | 54e4dca8a24a |
633c3ca06e6c |
20260811_2309_..._user_brand_watermark.py |
New user_brands table (per-user watermark singleton, user_id UNIQUE) |
| 15 | 4e73c6aaa0a5 |
54e4dca8a24a |
20260812_1607_..._user_api_keys.py |
New user_api_keys table (Public API Keys; key_hash UNIQUE, revoked indexed) |
| 16 | 43d4be4d7d5e |
4e73c6aaa0a5 |
20260812_1700_..._marketplace_templates.py |
New marketplace_templates + template_ratings (rating/clone cols; (template_id,user_id) UNIQUE) |
| 17 | 9c1e7a4b2f60 |
43d4be4d7d5e |
20260812_2320_..._job_performance.py |
New job_performance table (Hook Performance Loop; job_id UNIQUE) |
| 18 | b7f3a1c92d84 |
9c1e7a4b2f60 |
20260813_1030_..._api_key_quotas_usage.py |
Adds user_api_keys.rate_limit_per_min + monthly_quota; new api_key_usage table ((api_key_id,period_ym) UNIQUE) |
| 19 | e2b9c4d7a1f5 |
b7f3a1c92d84 |
20260813_1130_..._social_accounts.py |
New social_accounts table (OAuth direct-publish; encrypted token cols; (user_id,provider) UNIQUE) |
| 20 | a1f4d8e6c3b9 |
e2b9c4d7a1f5 |
20260813_1200_..._share_links.py |
New share_links table (public watermarked share pages; token UNIQUE) |
| 21 | c3d9b7e2f4a8 |
a1f4d8e6c3b9 |
20260813_1230_..._marketplace_remix_trees.py |
Adds marketplace_templates.parent_template_id (self-FK) + remix_count via batch mode (Remix Trees) |
| 22 | d4e8c1b9f6a2 |
c3d9b7e2f4a8 |
20260813_1300_..._creator_profiles_follows.py |
Adds users.handle (UNIQUE) + bio; new creator_follows table ((follower,followee) UNIQUE). |
| 23 | e5f2a9c74b13 |
d4e8c1b9f6a2 |
20260813_1400_..._access_governance_rbac_audit.py |
Adds access-governance and append-only audit tables. |
| 24 | f1a2b3c4d5e6 |
e5f2a9c74b13 |
20260813_1500_..._identity_sso_scim.py |
Adds enterprise SSO, SCIM, security policies, and external identities. |
| 25 | a7c1e3f5b902 |
f1a2b3c4d5e6 |
20260813_1600_..._billing_platform.py |
Adds subscriptions, metered usage, invoices, and line items. |
| 26 | b3e9d1c47a52 |
a7c1e3f5b902 |
20260813_1700_..._api_platform.py |
Adds webhook subscriptions and deliveries. |
| 27 | c8a1f2e94d67 |
b3e9d1c47a52 |
20260813_1800_..._compliance_gdpr_retention.py |
Adds retention, consent, and erasure-request records. |
| 28 | d9b2c4e17f38 |
c8a1f2e94d67 |
20260813_1900_..._ai_broll_studio.py |
Adds curated B-roll presets and seed globals. |
| 29 | e6c4f9a12b73 |
d9b2c4e17f38 |
20260814_0300_..._job_request_idempotency.py |
Adds durable, user-scoped job-create idempotency records — current head. |
Migration conventions
ADD COLUMNsafety: every new NOT NULL column declares aserver_defaultso the add is safe on an already-populated table (existing rows backfill), and the ORMserver_defaultmirrors it so Alembic'scompare_server_default=Trueautogenerate reports no spurious drift.- SQLite compatibility: constraint/nullability changes that SQLite cannot do
in place (
referral_codeUNIQUE in rev 4;credit_ledger.workspace_idFK +user_idnullability in rev 13; themarketplace_templates.parent_template_idself-FK in rev 21) useop.batch_alter_table(...)with named constraints (copy-and-move on SQLite, plainALTERs on Postgres) so downgrades are deterministic. - Auto-increment ledger PKs use
BigInteger().with_variant(Integer, "sqlite").
The full 29-revision chain applies cleanly on a fresh DB and alembic check
reports "No new upgrade operations detected" — i.e. there is no model/migration
drift. Migrations, linting (ruff --select F,E9), the pytest suite
(2203 passed, 4 skipped) and a golden acceptance run are gated locally
(there is intentionally no CI pipeline).
5. Repository layer
app/models/db/repositories.py exposes one repository per aggregate, each taking
a Session:
JobRepository, AssetRepository, CreditRepository, UserRepository,
UserPresetRepository, UserVoiceRepository, UserBrandRepository,
SavedIdeaRepository, NotificationRepository, ScheduledPublishRepository,
WorkspaceRepository, UserApiKeyRepository, ApiKeyUsageRepository,
MarketplaceRepository, TemplateRatingRepository, JobPerformanceRepository,
SocialAccountRepository, ShareLinkRepository, CreatorFollowRepository.
These wrap all reads/writes, enforce ownership, and centralize the atomic
row-locked credit and job-state operations described in §3. The newer
repositories add their own in-place UPSERT / recompute patterns — e.g.
TemplateRatingRepository.upsert_rating recomputes a listing's rating_avg /
rating_count atomically, ApiKeyUsageRepository increments the single
(key, month) counter row, and SocialAccountRepository /
JobPerformanceRepository / ShareLinkRepository upsert their per-owner
singletons in place.