Run the API (operator)

The API is the back end of the free tier: accounts, marketing consent, studies, free runs, reports and shared results. It needs a Postgres database with the migrations applied and a way to check sign-in tokens. In production both come from the product's Supabase project.

What it does

Route Who What
GET /health anyone Checks the database connection
GET /me, PUT /me signed in Profile, what you sell, where it is today, consent status, whether the free survey is used
POST /me/consent signed in Grant (then confirm by email) or withdraw consent to marketing email
GET /consent/confirm?token= link from the email Confirms the consent
POST /studies, GET /studies, GET /studies/{id}, DELETE /studies/{id} signed in Create, list, read and delete your own studies
POST /studies/{id}/run signed in Put the free survey in the queue
POST /studies/{id}/cancel signed in Take a waiting study out of the queue; the free survey comes back
GET /admin/queue operators Queue length, oldest wait, workers alive, jobs finished and failed
POST /me/invite signed in Use an invite code to skip the waitlist
GET /admin/waitlist, POST /admin/waitlist, POST /admin/admit, POST /admin/invites operators The waitlist: figures, settings, admit by hand, invite codes. See The waitlist
GET /studies/{id}/result, /report.html, /report.pdf signed in The result and its reports
POST /studies/{id}/share signed in Share or unshare a finished result
GET /public/{slug} anyone with the link A shared result: scores and sample card, no individual answers
GET /admin/overview operators Accounts, opt-ins, studies by state, today's free-tier spend, interests

How access is limited: every signed-in request runs in the database as that user, so the database's own row-level security decides what can be read or written. A user can only ever see their own studies and results. A few steps run, inside the same request, as the API's own database role instead: counting a per-account limit, putting a study in the queue, redeeming an invite code and saving a new study (migration 0015). A signed-in user cannot call those through the database's REST interface, so nobody can reset a limit, choose their own budget or skip the checks.

Getting started (operator, in this order)

  1. Create the Supabase project for this product (PRD OQ-7). Do not reuse another product's.

  2. Apply the migrations in supabase/migrations/ in number order, in the Supabase SQL editor or with the Supabase CLI. Then run the two verification queries at the top of 0001_init.sql: every table must show row-level security on, and anon must hold no table privileges. After 0015_limits_server_only.sql, run the queries in its header too: every one must print the value given at its end.

  3. Set the environment variables on the server, by name. Values come from the Supabase project settings and are never written in this repository.

    Name Meaning
    DATABASE_URL Postgres connection string of the project: the privileged role (such as postgres), which may switch to authenticated and anon and back, and run the functions only the service may run
    SUPABASE_JWT_SECRET For projects that sign tokens with a shared secret
    SUPABASE_JWKS_URL For projects with asymmetric signing keys; use this instead of the secret
    MARKETSIM_PROVIDER fake (default, canned answers) or anthropic
    ANTHROPIC_API_KEY Needed when the provider is anthropic
    MARKETSIM_EMBEDDER hash (default, placeholder) or local
    FREE_PANEL_SIZE Respondents in a free survey (default 50)
    FREE_DAILY_BUDGET_USD Free-tier spend allowed per day (default 5)
    FREE_TIER_PAUSED 1 holds the queue: studies can still be queued, workers start none until it is unset
    PUBLIC_BASE_URL The web app's address, used in emails and share links
    STUDIES_PER_DAY Studies an account may save in 24 hours (default 20)
    RUNS_PER_DAY Run presses per account in 24 hours (default 10)
    API_DOCS 1 serves the interactive API docs at /docs. Leave unset in production
    SENDGRID_API_KEY, MAIL_FROM, MAIL_FROM_NAME, MAIL_REPLY_TO Real email. See Email setup. Without the first two, mail stays in memory
    MAIL_WEBHOOK_PUBLIC_KEY Bounces and spam complaints from the mail provider. See Email setup
    HELP_ASSISTANT, HELP_ASSISTANT_MODEL, HELP_DAILY_BUDGET_USD, HELP_QUESTIONS_PER_DAY, HELP_DIR The help assistant: on or off, its model, its daily budget (default 2 USD), questions per account in 24 hours (default 30), and where the articles are. See Help assistant setup
  4. Install and start:

    pip install -e ".[api,pdf]"
    
    uvicorn marketsim_api.main:app --host 127.0.0.1 --port 8000
    
  5. Make yourself an operator: in the SQL editor, set is_operator to true on your own row in profiles.

  6. Check it: GET /health answers {"ok": true}.

Settings and limits

  • One free survey per account, for good. A failed run does not count; a finished or running one does, and stays counted after the study is deleted (table free_runs, migration 0002). To give an account its free survey back, delete its row in free_runs in the SQL editor.
  • Free surveys test one version with FREE_PANEL_SIZE respondents and one interview each.
  • Daily budget. Each free run commits its estimated cost. When the day's total would pass FREE_DAILY_BUDGET_USD, free runs are refused until the next day.
  • The API never runs a survey. Run puts the study in a queue (migration 0003) and the workers do the work: see Run the workers. Without a worker, studies wait in the queue.
  • Limits are per account, kept in the database, so they work behind any proxy. The message says when the limit lifts. Only the API counts them, with the account id from the verified sign-in (migration 0015).
  • Email is not sent yet. Messages go to an in-memory outbox; the mail provider is not wired in. Until it is, consent can be granted but not confirmed outside tests.
  • Live Supabase project: schema applied, sign-in not yet tested. On 2026-11-21 the migration was applied to the product's Supabase project and the two verification queries passed (row-level security on every table, no privileges for anon); the API's /health answers against it. A signed-in request with a real Supabase token has not been tested yet. The automated tests run on a plain Postgres with a stand-in for Supabase's sign-in functions.
  • Use the session pooler address for DATABASE_URL unless the server has IPv6: the direct address (db.<project-ref>.supabase.co) is IPv6 only. The pooler string has the user postgres.<project-ref> and a host ending pooler.supabase.com, port 5432.
  • A migration applied by hand must be recorded for the Supabase CLI, or a later supabase db push tries to run it again: supabase migration repair --status applied 0001.

Troubleshooting

Message Cause Fix
"DATABASE_URL is not set" The API was started without it Set the variable and restart
"invalid connection option" at start The DATABASE_URL line holds the name twice (DATABASE_URL=DATABASE_URL=...) or is not a postgresql:// address Keep one name, then the address
"password authentication failed for user "postgres"" The password in DATABASE_URL is not the project's database password. Straight after a password reset the pooler can take a few minutes to accept the new one Check the password; after a reset, wait and try again. Characters such as @ : / # in a password must be URL-encoded
The connection times out The direct database address is IPv6 only and the server has no IPv6 route Use the session pooler address (see Settings and limits)
"Set SUPABASE_JWT_SECRET or SUPABASE_JWKS_URL so sign-in tokens can be checked" Neither is set Set the one that matches the project's signing method
"Sign in to continue." (401) No sign-in token on the request Sign in again in the web app
"Your sign-in has expired or is not valid. Sign in again." (401) Expired token, or the API's secret does not match the project Sign in again; if everyone sees it, check the secret or JWKS address
"Study rejected: ..." (400) The study breaks a rule; the message names the field Correct that field
"The free survey tests one version of your product." (400) More or fewer than one version was sent Send exactly one
"This study cannot be run: it is flagged or already finished." (409) The stimulus check flagged the text, or the study already has a result Read the flags on the study, edit the text and create it again
"You have already used your free survey." (409) The account has a row in free_runs: it ran a free survey to the end, or one is running. Deleting the study does not clear it Nothing to fix; this is the limit. An operator can delete the row to give the survey back
"This study is not waiting in the queue, so there is nothing to cancel." (409) Cancel was pressed for a study that is running, finished or never queued Nothing to do
"A study cannot be deleted while it is waiting or running. Cancel it first." (409) Delete was asked for a queued or running study Take it out of the queue first; a running study finishes by itself
"You have reached the limit of N saved studies in 24 hours. You can continue in about H h M min." (429; also "survey runs") The account reached STUDIES_PER_DAY or RUNS_PER_DAY Wait for the time shown, or raise the setting
"This study has no result yet." (409) The run has not finished or it failed Check the study's state and error
"Only a finished study can be shared." (409) Sharing was asked before the run finished Wait for reported
"This confirmation link has expired or is not valid. Ask for a new one on your account page." (400) Links last 30 days Choose Send the confirmation email again on the Account page
"This confirmation link no longer applies, because consent was withdrawn after it was sent." (400) Consent was withdrawn after the link was sent Grant again if wanted
"An invite code is 4 to 40 letters, digits or dashes, with 1 to 100000 uses." (400) An operator posted an invite code outside those limits Choose another code
"Admissions per day must be between 0 and 100000." (400) An operator posted a waitlist setting outside that range Correct the number
"Operators only." (403) The account is not an operator See step 5 above
Saving a study, running one, redeeming a code or asking the help assistant fails with 500, and the API log shows "permission denied for function" or "function account_allow_for does not exist" DATABASE_URL uses a role that cannot run the service-only functions, or migration 0015 is not applied while the API is newer Use the project's privileged role in DATABASE_URL (step 3), and apply 0015 before starting this API
"function account_allow(...) does not exist" in the API log Migration 0015 is applied but an older API is still running Deploy the API that matches the migrations, then restart it
A study stays in queued No worker is running, the free tier is paused, or the job is waiting for tomorrow's budget See Run the workers