Pre-release. Parity is not publicly available yet: the CLI, the GitHub Action and the hosted workspace open at launch. The demo runs on example data.

Skip to content

Hosted API

Endpoints, authentication, adapters and their environment variables, limits, errors, migrations, scheduled work and webhooks of the Parity hosted backend.

The hosted backend lives in apps/web (Next.js route handlers under src/app/api, server modules under src/server). It stores reports uploaded from CI, serves them to the workspace UI, and records review decisions. It never calls a customer's API: environments are metadata only.

All responses are JSON with Cache-Control: no-store. Errors always have the shape

json
{ "error": { "code": "not_found", "message": "Not found" } }

with extra fields on some codes (required_plan, capability, retry_after, issues, reason).

#Platform

ConcernServiceLocal substitute
Identity and organisationsClerk (Clerk Organizations), shared by all x1991 productssigned dev identities
DataSupabase PostgreSQLPGlite, in process
ArtifactsCloudflare R2 (S3 API)table parity.blobs
HostingCloudflare Workers via @opennextjs/cloudflarenext dev / next start
EmailResend through @x1991/emaillocal outbox
BillingStripelocal provider
AnalyticsPostHogconsole / none

Identity, the organisation model and billing infrastructure are shared across products; product data, permissions and entitlements are Parity's own.

A Parity workspace is a Clerk organisation. Parity stores no passwords and has no invitation flow: people are invited, removed and given their Clerk role in Clerk.

#Authentication

#Users (browser)

In clerk mode the session is Clerk's. Every /api/orgs/:org/... route requires that :org — a Clerk organisation id or its slug — is the caller's active organisation:

SituationResult
Not signed in401 unauthorized
Signed in, no active organisation409 organization_required
:org is not the active organisation (whether or not it exists)404 not_found
Resource id belongs to another organisation404 not_found
Parity role too low403 forbidden
Plan lacks the capability402 plan_required with required_plan

Non-GET requests authenticated by a cookie must carry a same-origin Origin header (or Sec-Fetch-Site: same-origin); otherwise 403 csrf_failed. PARITY_APP_URL pins the accepted origin.

#Parity roles

Roles are product-specific: admin, member, viewer.

  • Default mapping from the Clerk role: org:admin → admin, anything else → member.
  • An organisation admin can override one person's Parity role (for example to viewer) without touching Clerk or any other product. Overrides live in parity.member_roles, need the Team plan to edit, and cannot be applied to yourself.
viewermemberadmin
Read projects, runs, scenarios, reviews, membersyesyesyes
Subscribe yourself to notifications (Team)yesyesyes
Classify differencesnoTeam planPro and Team
Projects, tokens, run deletion, settings, billing, audit log, role overridesnonoyes

#Local identity mode (development and tests only)

PARITY_AUTH=local (the default when CLERK_SECRET_KEY is not set) replaces Clerk with fake identities. It is refused when NODE_ENV=production. POST /api/dev/session sets a signed, HttpOnly cookie naming a fake user, organisation and Clerk-style role; there are no passwords. In clerk mode the /api/dev/* endpoints return 404.

bash
curl -c jar -H 'Origin: http://localhost:3000' -H 'Content-Type: application/json' \
  -d '{"user":"admin"}' http://localhost:3000/api/dev/session

Seeded identities: admin, member, viewer (organisation org_dev_acme) and outsider (org_dev_globex). Any other fake id works too: {"user":"user_x","org":"org_y","role":"org:admin"}.

#CI (ingestion)

POST /api/v1/ingest authenticates only by a project token: Authorization: Bearer pty_…. Cookies are ignored. A token is shown once at creation, stored as a SHA-256 hash plus a display prefix, has the scope ingest, and is valid only for its own project.

#Machines

Webhooks authenticate by the provider's signature over the raw body. The internal endpoints (/api/internal/cron, /api/internal/queue) accept Authorization: Bearer $CRON_SECRET, or — on Cloudflare Workers — a random token that the Worker entry creates per isolate and that never leaves it, so the Worker's own cron ticks and queue batches need no configured secret. With neither, they answer 503.

#Endpoints

:org = active organisation id or slug. :project = project id or slug within the organisation.

#Session

MethodPathAuthPurpose
GET/api/auth/meoptional sessionUser (or null), auth mode, active organisation with Parity role, plan and entitlements, feature flags (billing provider, public analytics key)
POST/api/dev/sessionlocal modeSign in as a fake identity { user, org?, role?, email?, name?, org_slug?, org_name? }
DELETE/api/dev/sessionlocal modeSign out
GET/api/dev/identitieslocal modeSeeded identities
GET/api/healthnoneLiveness and database reachability

#Organisation

MethodPathRolePurpose
GET/api/orgs/:orgviewerOrganisation, role, plan, entitlements, default policy
PATCH/api/orgs/:orgadmin{ default_policy } for new projects (Team; null clears)
GET/api/orgs/:org/membersviewerKnown members with provider role, default and effective Parity role
PUT/api/orgs/:org/members/:user/roleadmin, TeamOverride a person's Parity role { role }
DELETE/api/orgs/:org/members/:user/roleadmin, TeamRemove the override
GET/api/orgs/:org/auditadmin, TeamAudit log, ?cursor=&limit=
GET/api/orgs/:org/usageviewerCurrent usage against the plan's quotas (see Quotas)

"Known members" are people who have signed in with the organisation active or arrived through a Clerk webhook. There is no endpoint to add, invite or remove a member.

#Projects, tokens, notifications

MethodPathRolePurpose
GET/api/orgs/:org/projectsviewerProjects with run count, latest run summary and unreviewed-change count
POST/api/orgs/:org/projectsadminCreate { name, slug?, repository_url?, description?, environments?, policy?, retention_days? }
GET/api/orgs/:org/projects/:projectviewerOne project
PATCH/api/orgs/:org/projects/:projectadminUpdate
DELETE/api/orgs/:org/projects/:projectadminDelete with tokens, runs, reviews and artifacts
GET/api/orgs/:org/projects/:project/tokensadminList tokens (no secrets)
POST/api/orgs/:org/projects/:project/tokensadminCreate { name } → { token, secret }, secret shown once
DELETE/api/orgs/:org/projects/:project/tokens/:tokenadminRevoke
GET/api/orgs/:org/projects/:project/runsviewerRuns, newest first, ?cursor=&limit=&verdict=pass|fail&pr=<n>
GET/api/orgs/:org/projects/:project/auditadmin, TeamAudit log of the project
GET/api/orgs/:org/projects/:project/notificationsviewerYour own run_failed subscription
PUT/api/orgs/:org/projects/:project/notificationsviewer, TeamSubscribe yourself
DELETE/api/orgs/:org/projects/:project/notificationsviewerUnsubscribe yourself

#Runs, scenarios, review

MethodPathRolePurpose
GET/api/orgs/:org/runs/:runviewerRun, policy, comparison settings and every light scenario row with its review rollup (one query, no payloads)
DELETE/api/orgs/:org/runs/:runadminDelete the run and its artifacts
GET/api/orgs/:org/runs/:run/scenarios/:scenarioviewerFull scenario result (one artifact chunk is decrypted), per-difference review state and prior hints
GET/api/orgs/:org/runs/:run/reviewsviewerClassifications that apply to this run, and the rollup
PUT/api/orgs/:org/runs/:run/reviewsplan-dependentClassify one difference { scenario_id, difference_id, classification, note? }
PUT/api/orgs/:org/runs/:run/reviews/bulkplan-dependent{ items: [...] }, up to 1,000, all or nothing

:scenario is the hosted row id (scn_…) from the run detail; scenario_id in review bodies is the scenario id from the report.

#Billing

MethodPathRolePurpose
GET/api/orgs/:org/billingadminProvider, plan, seats, period, plans with entitlements
POST/api/orgs/:org/billing/checkoutadmin{ plan: "pro"|"team", seats?, return_path? } → { url }
POST/api/orgs/:org/billing/portaladmin{ return_path? } → { url }
POST/api/orgs/:org/billing/dev-planadmin, local provider{ plan, seats? }, instant

#Machine endpoints

MethodPathAuthPurpose
POST/api/v1/ingestproject tokenUpload a parity.report/v1 document
POST/api/stripe/webhookStripe-SignatureSubscription state
POST/api/clerk/webhookSvix signature (CLERK_WEBHOOK_SIGNING_SECRET)Mirror of users, organisations, memberships
POST/api/resend/webhookSvix signature (RESEND_WEBHOOK_SECRET)Email delivery status
POST/api/internal/cronisolate token or Bearer $CRON_SECRETSend due email, purge expired data
POST/api/internal/queueisolate token or Bearer $CRON_SECRETQueue batches forwarded by the Worker's queue handler: { queue, messages: [{ id, attempts, body }] } → { decisions: [{ id, action: "ack" | "retry", delaySeconds? }] }
GET, POST/api/notifications/unsubscribe?s=&t=signed linkGET shows a confirmation form, POST unsubscribes (RFC 8058 one-click)

The typed client for all user endpoints is apps/web/src/lib/api-client.ts; request and response types are in apps/web/src/lib/api-types.ts.

#Ingestion

bash
curl -X POST "$PARITY_URL/api/v1/ingest" \
  -H "Authorization: Bearer $PARITY_TOKEN" -H 'Content-Type: application/json' \
  --data-binary @parity-report.json

Response: 201 { "run": { "id", "url" }, "duplicate": false }.

  • Idempotent on (project, run.id), decided by a unique constraint. The same report again → 200 with duplicate: true (key order and whitespace do not matter). A different body under the same run id → 409 run_conflict. Concurrent uploads of one report create one run.
  • Every string in a report is treated as untrusted. Sensitive headers (authorization, proxy-authorization, cookie, set-cookie, x-api-key, x-auth-token) are redacted again on the server, and credentials in URLs are stripped.
  • If artifact storage is unavailable the upload fails with 503 storage_unavailable and nothing is stored; retry.
  • On the Free plan only the organisation's first project ingests (402 plan_required).
  • Quotas are checked twice: before the body is read (an exhausted quota costs almost nothing to refuse — this also applies to a re-upload of a report that is already stored) and again, authoritatively, inside the transaction that stores the run.

The order of work is: kill switch → token → rate limit → quota pre-check → read and parse the body → validate the report head and hash the report → duplicate check → validate, sanitise, serialise, compress and encrypt the scenarios one at a time → write the chunks to the blob store → one database transaction (run, scenario rows, differences, audit entry, outbox rows, quota counters). Each scenario is serialised exactly once and there is never a second full copy of the report in memory.

#Limits

LimitDefaultVariableOver the limit
Request body8 MiB, enforced while streaming; configurable up to 20 MiBPARITY_INGEST_MAX_BODY_BYTES413 payload_too_large
Scenarios per report10,000PARITY_INGEST_MAX_SCENARIOS413
One scenario1 MiB (at most 8 MiB)PARITY_INGEST_MAX_SCENARIO_BYTESbodies stripped, scenario marked truncated
Uploads per token60 per minutePARITY_INGEST_RATE_PER_MIN, or the INGEST_RATE_LIMITER binding429 rate_limited with Retry-After
Failed token attempts per address30 per minutethe AUTH_RATE_LIMITER binding429 rate_limited
Other JSON bodies256 KBPARITY_JSON_MAX_BODY_BYTES413
Page size50, at most 200—400

The body limit is the one large runs meet first. A report with small JSON responses is about 1 KB per scenario, so 8 MiB holds roughly 7,000 scenarios, fewer with large bodies; the 10,000-scenario cap only applies to reports that are still under the size limit. An oversized upload is refused with 413 and the CLI says so; the local report is unaffected. Uploading a large run in parts is not supported yet.

The default body limit was 20 MiB and is now 8 MiB: an 8 MiB report costs about 120 ms of CPU and about 57 MB of transient memory to ingest, a 20 MiB report about 335 ms and about 90 MB, against an isolate limit of 128 MB on Cloudflare Workers. Raise it (up to 20 MiB, the hard ceiling) only on a host with more memory, or accept that the largest reports run close to the limit.

Rate limiting has two implementations behind one function (src/server/adapters/ratelimit). On Cloudflare Workers with the rate-limit bindings declared in wrangler.jsonc, the Workers Rate Limiting API decides; its budget and window are set in that file (simple.limit, simple.period), it is shared by all isolates in a Cloudflare location, and it is approximate by design. Everywhere else an in-memory token bucket decides, per process. PARITY_INGEST_RATE_PER_MIN=0 disables the per-token limit in both. Neither is a quota.

#Quotas and spending safeguards

Hard limits are counted in PostgreSQL (parity.usage_counters, parity.org_usage — primary-key lookups only, no count(*) over runs or scenarios) and enforced on the server.

Per organisation, by plan (src/server/entitlements.ts, PLAN_QUOTAS). Every value can be overridden per deployment with PARITY_QUOTA_<PLAN>_<NAME>, for example PARITY_QUOTA_FREE_RUNS_PER_DAY=100 or PARITY_QUOTA_TEAM_STORAGE_BYTES=unlimited.

Quota (<NAME>)FreeProTeamWindow
RUNS_PER_DAY — reports accepted253001,000UTC day
RUNS_PER_MONTH — reports accepted3005,00020,000UTC month
STORAGE_BYTES — encrypted artifact bytes stored250 MB5 GB25 GB—
SCENARIOS_STORED — scenario rows stored50,0002,000,00010,000,000—
TOKENS_PER_PROJECT — active tokens21025—
EMAILS_PER_DAY — notification emails sent1050200UTC day

Projects per organisation (Free: 1) and retention (Free: 7 days; Pro and Team: 90 by default, at most 365) are plan limits too; see Plans.

Whole deployment, last resort.

SafeguardDefaultVariableEffect
Kill switchoffPARITY_INGEST_DISABLED=1every upload → 503 ingest_disabled, before any token or body is looked at
Daily ingest cap5,000 runs per UTC dayPARITY_GLOBAL_INGEST_PER_DAY (unlimited to remove)503 quota_exceeded, scope: "deployment"
Daily email cap90 emails per UTC dayPARITY_GLOBAL_EMAILS_PER_DAYa circuit breaker: remaining rows stay queued, a log line and an audit entry are written, sending resumes when the window turns or the cap is raised
Analytics events per request5PARITY_ANALYTICS_MAX_EVENTS_PER_REQUESTfurther events in that request are dropped (analytics is best effort)

A refusal is always this shape. Organisation quotas are HTTP 402 (a higher plan raises them); deployment-wide caps are 503. Retry-After is set when the quota resets with time.

json
{ "error": { "code": "quota_exceeded", "message": "This organisation has reached the daily limit of 25 runs. It resets at 2026-11-29T00:00:00.000Z.",
             "quota": "runs_per_day", "limit": 25, "used": 25, "resets_at": "2026-11-29T00:00:00.000Z",
             "scope": "organization", "current_plan": "free" } }

quota is one of runs_per_day, runs_per_month, storage_bytes, scenarios_stored, tokens_per_project, emails_per_day, global_ingest_per_day, global_emails_per_day. resets_at is null for quotas that do not reset with time.

  • Duplicates do not count: only a run that is actually stored takes a unit. The counters are reserved in the same transaction as the run, so concurrent uploads cannot overshoot.
  • Stored bytes and stored scenarios are kept exact by triggers on parity.runs, so deleting a run or a project, the retention purge and the purge of a deleted organisation all give the space back. Scenarios are counted by the server, not taken from the report's summary.
  • Email quotas are applied when an email is about to be handed to the provider. A held row keeps status queued, spends no attempt, and records why in last_error; it is never dropped.
  • The first refusal of each quota per organisation per UTC day is written to the audit log (quota.exceeded; safeguard.triggered for deployment-wide caps) and logged. Further refusals that day only increase a counter, so a retrying client cannot fill the audit log.

GET /api/orgs/:org/usage (any member) returns the current numbers for the UI:

json
{ "plan": "team", "ingest_enabled": true,
  "runs_per_day":     { "used": 12, "limit": 1000, "resets_at": "2026-11-29T00:00:00.000Z" },
  "runs_per_month":   { "used": 340, "limit": 20000, "resets_at": "2026-12-01T00:00:00.000Z" },
  "storage_bytes":    { "used": 48211934, "limit": 26843545600, "resets_at": null },
  "scenarios_stored": { "used": 30260, "limit": 10000000, "resets_at": null },
  "emails_per_day":   { "used": 3, "limit": 200, "resets_at": "2026-11-29T00:00:00.000Z" },
  "projects":         { "used": 2, "limit": null, "resets_at": null },
  "runs_stored": 340,
  "limits": { "tokens_per_project": 25, "scenarios_per_run": 10000, "report_bytes": 8388608, "scenario_bytes": 1048576, "ingest_per_minute_per_token": 60 } }

A limit of null means unlimited. The plan's quotas are also in entitlements.quotas of GET /api/orgs/:org and GET /api/auth/me.

#Artifacts and encryption at rest

Full scenario payloads are never stored in table rows. The scenarios of a run are packed into chunks of about 512 KB of JSON, gzipped, encrypted with AES-256-GCM (random IV per chunk; the object key is authenticated as additional data) and written to the blob store under

parity/<org id>/<project id>/<run id>/<chunk index>

Scenario rows keep light columns plus (chunk_index, chunk_offset). Reading one scenario fetches and decrypts one chunk. Deleting a run or a project, the retention purge and the purge of a deleted organisation delete the objects too; deletions are queued in the same transaction (parity.blob_purge_queue) so a temporary storage failure is retried by the cron.

Where the chunks go is chosen by the blob adapter: the Worker's R2 bucket binding (PARITY_ARTIFACTS) when it exists, otherwise the S3-compatible API with R2_* credentials, otherwise the table parity.blobs. BLOB_STORE=r2 requires one of the first two; BLOB_STORE=postgres selects the table explicitly. In production the table is never chosen silently: without R2 configured and without an explicit BLOB_STORE=postgres, the server refuses to store artifacts. There is no fallback between stores at run time — if R2 fails the upload fails (503), and nothing is written to PostgreSQL instead.

PARITY_DATA_KEY (32 bytes, base64) is required in production. The id of the key (PARITY_DATA_KEY_ID, default k1) is stored in every chunk and on the run. To rotate, set a new key and id and list the old keys in PARITY_DATA_KEYS_PREVIOUS (<id>:<base64>,…); old data stays readable, new data uses the new key.

#Review

A classification (regression, intentional, nondeterministic; unreviewed clears it) is keyed by its full scope:

(project, scenario id, difference id, baseline revision, candidate revision, config fingerprint)

It applies to a difference in a run only when every part matches exactly; a missing revision is the empty string. It never carries over to another difference, scenario, revision pair or comparison configuration. Classifications made under another scope are returned only as prior hints on the scenario detail, with the parts that differ. Every change is written to the audit log with before and after.

#Plans

src/server/entitlements.ts is the only place that maps a Parity plan to capabilities.

FreePro ($9.99/month)Team ($19.99/seat/month, proposed)
Projects1unlimitedunlimited
Retention7 days90 days default, up to 365same as Pro
Workspaceread-onlyfullfull
Reviewnoadminsadmins and members
Role overrides, org default policy, audit log, failed-run emailnonoyes

Billing infrastructure is shared: one provider customer per organisation (x1991.billing_customers) and one subscription row per (organisation, product) (x1991.subscriptions, Parity's is product = 'parity').

  • BILLING_PROVIDER=stripe: Checkout Sessions in subscription mode (STRIPE_PRICE_PARITY_PRO, STRIPE_PRICE_PARITY_TEAM, quantity = seats for Team, metadata org_id and product), Customer Portal, and the webhook. The plan changes only when the webhook says so. Keys that do not start with sk_test_ or rk_test_ are refused unless PARITY_ALLOW_LIVE_BILLING=1.
  • BILLING_PROVIDER=local (development default): checkout applies the plan immediately and returns to return_path?checkout=success; billing/dev-plan switches plans directly. Never active in production.
  • BILLING_PROVIDER=none: GET billing reports configured: false; checkout and portal return 503 billing_not_configured.

#Adapters and environment variables

Every external dependency is an interface in apps/web/src/server/adapters/<name>/ with a factory that picks the implementation from the environment. Moving a service to another account, or replacing it, is a change of environment variables only. apps/web/.env.example lists every variable.

PortSelectorProductionVariables
identityPARITY_AUTH=clerk|localClerkCLERK_SECRET_KEY, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, CLERK_WEBHOOK_SIGNING_SECRET; local: PARITY_DEV_SESSION_SECRET
databaseHYPERDRIVE binding on Workers, else presence of DATABASE_URLpg → Hyperdrive → SupabaseDATABASE_URL, PARITY_DB_SSL, DATABASE_CA_CERT, PARITY_DB_POOL_MAX; local: PARITY_PGLITE_DIR
blobBLOB_STORE=r2|postgresR2 by bucket binding (PARITY_ARTIFACTS); off Workers, R2 via aws4fetchR2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET, R2_ENDPOINT, R2_REGION (S3 API only; the binding needs none)
billingBILLING_PROVIDER=stripe|local|noneStripe RESTSTRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_PARITY_PRO, STRIPE_PRICE_PARITY_TEAM, STRIPE_API_VERSION, STRIPE_API_BASE, PARITY_ALLOW_LIVE_BILLING
analyticsANALYTICS_PROVIDER=posthog|console|nonePostHog capture APIPOSTHOG_KEY, POSTHOG_HOST
emailEMAIL_PROVIDER=resend|localResend via @x1991/emailRESEND_API_KEY, RESEND_WEBHOOK_SECRET, PARITY_EMAIL_FROM, EMAIL_ALLOWED_FROM_DOMAINS, EMAIL_LOCAL_DIR
rate limitrate-limit bindings on WorkersWorkers Rate Limiting API (INGEST_RATE_LIMITER, AUTH_RATE_LIMITER); elsewhere an in-memory token bucketPARITY_INGEST_RATE_PER_MIN
jobsPARITY_JOBS queue binding on WorkersCloudflare Queues; elsewhere a background task in the same process—

Cloudflare bindings are read in one place, src/server/adapters/cloudflare, through OpenNext's getCloudflareContext(); off Workers it returns nothing and every adapter uses its portable implementation.

Other variables: PARITY_APP_URL, PARITY_TRUSTED_PROXY_HOPS, PARITY_DATA_KEY, PARITY_DATA_KEY_ID, PARITY_DATA_KEYS_PREVIOUS, PARITY_ARTIFACT_CHUNK_BYTES, CRON_SECRET, PARITY_ORG_PURGE_GRACE_DAYS, PARITY_AUDIT_RETENTION_DAYS, PARITY_MIGRATIONS_DIR, the limits above, the quota and safeguard variables (PARITY_QUOTA_<PLAN>_<NAME>, PARITY_GLOBAL_INGEST_PER_DAY, PARITY_GLOBAL_EMAILS_PER_DAY, PARITY_INGEST_DISABLED, PARITY_ANALYTICS_MAX_EVENTS_PER_REQUEST), PARITY_INGEST_TIMING (measurements only: adds a Server-Timing header with phase durations to ingest responses) and PARITY_LOCAL_PREVIEW (the local Workers preview only).

With R2_ENDPOINT set, any S3-compatible store works in place of R2.

Analytics events (run_ingested, review_classified, project_created, checkout_started, plan_changed) carry ids and counts only — never report content, email addresses or tokens. A failing analytics provider never affects a request.

#Database

Two schemas; nothing is created in public.

  • x1991 — shared by all products: organizations (id = Clerk organisation id, soft-deleted), users and memberships (a display mirror of Clerk for audit trails, member lists and seat counts), billing_customers, subscriptions, webhook_events, email_outbox.
  • parity — product tables: projects, project_tokens, runs, scenarios, run_differences, blobs, blob_purge_queue, reviews, audit_log, member_roles, org_settings, org_purges, notification_subscriptions, and for quotas org_usage (stored bytes, runs and scenarios per organisation, maintained by triggers on runs) and usage_counters (windowed counters per organisation and for the deployment).

Timestamps are bigint milliseconds since the Unix epoch. Row level security is enabled on every table with no policies, and schema usage is revoked from anon and authenticated: the Supabase Data API can reach nothing. The application connects with a privileged server role and enforces tenancy in code on every query path; RLS is a backstop.

The pg driver is used in a way that works through a transaction-mode pooler: no session state, unnamed statements only, explicit transactions on one client.

On Cloudflare Workers the connection goes through Hyperdrive when the HYPERDRIVE binding exists (env.HYPERDRIVE.connectionString, no TLS from the Worker: Hyperdrive encrypts the hop to the origin itself), and straight to DATABASE_URL otherwise. There is no module-global pool or client on Workers: every request, background task, queue batch and cron tick gets its own clients, opened lazily (a typical request uses one) and closed when it ends. The Hyperdrive configuration must have query caching disabled — the application reads its own writes (idempotency, quota counters, review state) and Hyperdrive's cache is not invalidated by writes.

#Migrations

Plain SQL in supabase/migrations/, in this order:

  1. 20261128170000_x1991_platform.sql
  2. 20261128170100_parity_product.sql
  3. 20261128180000_parity_usage_quotas.sql

Each file is idempotent and records itself (x1991.schema_migrations or parity.schema_migrations), so it can be applied and re-applied with the Supabase CLI, psql or the bundled runner:

bash
npm run db:migrate -w @x1991/parity-web   # applies what is pending
npm run db:status  -w @x1991/parity-web   # applied / PENDING per file

The embedded development database migrates itself when it opens.

#Scheduled work

POST /api/internal/cron:

  1. sends due rows of the email outbox — the sweep for anything a queue message did not finish,
  2. deletes runs past their retention, bounded by the plan, with their artifacts,
  3. purges the product data of organisations deleted in Clerk once the grace period (PARITY_ORG_PURGE_GRACE_DAYS, default 7) has passed,
  4. drains the artifact deletion queue, trims old webhook ids, finished outbox rows and usage counters of past windows.

On Cloudflare Workers the Cron Trigger in wrangler.jsonc (every five minutes) calls the Worker's scheduled handler (apps/web/cloudflare/worker.ts), which calls this endpoint inside the isolate with the isolate token. Off Workers, call it from any scheduler with Authorization: Bearer $CRON_SECRET. npm run purge -w @x1991/parity-web runs steps 2–4 from a shell. Retention also runs opportunistically for a project after each upload.

#Email

When an uploaded run's verdict is fail, one email per run_failed subscriber of the project is queued in x1991.email_outbox in the same transaction as the run. The idempotency key parity:run_failed:<run id>:<user id> is unique in the table and is passed to the provider, so neither a re-upload nor a retry can send twice. The upload response never waits for email.

After the transaction commits, delivery is handed off:

  • On Workers with the PARITY_JOBS queue bound: one small message per 25 rows, { "type": "outbox", "ids": ["eml_…"] } — ids only, never addresses or report content. The Worker's queue handler forwards each batch to POST /api/internal/queue, and every message is acknowledged or retried on its own: sent, permanently failed or nothing left to do → acknowledged; a retryable provider error → retried when the row is due again (the outbox backoff, at most 12 hours); the batch could not be processed at all → retried with backoff. After five retries a message goes to the dead-letter queue (parity-jobs-dlq); the row itself is still in the outbox and the cron sweep keeps trying it.
  • Everywhere else (Node, tests, a Worker without the binding, or when the queue refuses the message): a background task in the same process, as before.

Queues deliver at least once. That is safe because the outbox decides who sends: a row is claimed with FOR UPDATE SKIP LOCKED, only while it is due, and its idempotency key goes to the provider. A duplicate delivery finds nothing to claim.

The sender renders the template from light table columns, sends, and records the provider message id. Network errors, 5xx and 429 are retried with exponential backoff and jitter, honouring Retry-After, up to six attempts; other 4xx responses mark the row failed. Daily email quotas are applied just before sending; see Quotas.

Statuses: queued → sending → sent → delivered, or bounced, complained, failed. A bounce or complaint also removes the subscription.

Organisation invitations and every authentication email are sent by Clerk, not by Parity.

#Webhooks

All three verify the signature over the raw body and are idempotent through x1991.webhook_events (provider, event_id).

EndpointEventsEffect
/api/stripe/webhookcheckout.session.completed, customer.subscription.created, .updated, .deletedSets the Parity plan, seats and period. 5-minute timestamp tolerance, constant-time comparison. Out-of-order events and subscriptions of other products are ignored. Live-mode events are refused.
/api/clerk/webhookuser.created, .updated, .deleted; organization.created, .updated, .deleted; organizationMembership.created, .updated, .deletedKeeps the mirror current. Removing a membership removes the role override and that person's notification subscriptions. Deleting an organisation soft-deletes it, revokes its tokens and schedules its Parity data for purge.
/api/resend/webhookemail.sent, .delivered, .bounced, .complained, .delivery_delayedUpdates the outbox row by provider message id; status never moves backwards.

#Cloudflare Workers

The bindings, the local preview and the deployment checklist are described in apps/web/CLOUDFLARE.md in the repository.

bash
npm run cf:db      -w @x1991/parity-web   # disposable Postgres in Docker for the preview, migrated
npm run cf:build   -w @x1991/parity-web   # OpenNext build → apps/web/.open-next, then strip and verify
npm run cf:preview -w @x1991/parity-web   # build and run the Worker in local workerd (http://localhost:8799)
npm run cf:smoke   -w @x1991/parity-web   # end-to-end check against the running preview
npm run cf:size    -w @x1991/parity-web   # Worker size and what contributes to it

apps/web/wrangler.jsonc holds no secrets, no account id and no real resource id. Secrets are Worker secrets with the names used in .env.example. In production PARITY_DATA_KEY and a database (the HYPERDRIVE binding, or DATABASE_URL) are required; the embedded database is never bundled into the Worker.

Always build with npm run cf:build, never with opennextjs-cloudflare build directly: OpenNext compiles every .env* file it finds, including .env.local, into the Worker bundle (.open-next/cloudflare/next-env.mjs). The script empties that file after the build and then scans the whole output for credential-shaped values and for assignments to secret names; a finding fails the build.

#Development

bash
npm run seed -w @x1991/parity-web                       # demo data, local identities
npm run seed -w @x1991/parity-web -- --org org_123      # attach the demo project to a Clerk organisation
npm test     -w @x1991/parity-web                       # vitest on an in-memory database
    Loading the index…