A modular app, one database, isolated ML jobs
API, worker, environment and trainer run as separate processes. Domain rules stay in one codebase.
| Option | Proves RL | Keeps review, access and pay history | High concurrency | Light to run before a buyer |
|---|---|---|---|---|
| Notebook and scripts | yes | no | no | yes |
| Modular app (chosen) | yes | yes | partly | yes |
| Kubernetes and workflow engine | yes | yes | yes | no |
Each part owns one thing
Control app
People, projects, permissions, transitions, approvals, delivery.
ML job
Sampled trajectories and optimization.
Environment
Episode state.
Verifier
Scoring.
None of these boundaries depends on a browser tab staying open. Next.js never writes to PostgreSQL, and training workers get no application database credentials.
New to these words? Plain-English meanings
| Word | What it means here |
|---|---|
| Rollout | One complete attempt by the model at one task. |
| Checkpoint | A saved copy of the model's weights at one moment. |
| Adapter | A small trainable add-on. The base model stays frozen underneath it. |
| Baseline | The saved score of the starting model, taken before any training. |
| Sealed test | Tasks that training can never read, kept for the final comparison. |
| Verifier | Protected code that scores an attempt. The model cannot see or reach it. |
| Unscorable | The infrastructure failed, so there is no score at all. This is different from scoring zero. |
| Tenant | One customer. Their data must never reach another customer. |
| Idempotent | Sending the same request twice has the same effect as sending it once. |
| Outbox | A to-do note saved with the data it describes, so a crash cannot lose it. |
| Lease | A time-limited right to act that must keep being renewed. |
| Fence | A number that rises with each attempt, so writes from an old worker get rejected. |
| Reconcile | Ask the cloud provider what really happened before acting on a guess. |
| Digest | A fingerprint of a file. If one byte changes, the digest changes. |
| Manifest | A signed-off list of the exact files and versions a step used. |
| Quarantine | Block something from new use while keeping its history intact. |
| RLS | Row-level security: the database itself filters rows by tenant. |
A short list of boring technology
Not needed for the first release
Add one only to solve an observed requirement. Pin CUDA, driver, PyTorch, TRL, Transformers, PEFT, OpenEnv and vLLM as one compatibility set, and never upgrade them separately during a paid experiment. If an integration needs main-branch behavior, pin a commit and test that image.
Exact tools and versions
| Layer | Choice | Note |
|---|---|---|
| Web | Node 24, supported Next.js release, TanStack Query | Pin after the web compatibility check |
| API | Python 3.12, FastAPI, Pydantic, Uvicorn | Generate OpenAPI from the real models |
| Database | RDS PostgreSQL 17, SQLAlchemy 2, Alembic, psycopg | Small Graviton instance to test first. RDS Proxy only if measured. |
| Ingress | Route 53, ACM certificate, HTTPS load balancer | /api/* to FastAPI, the rest to Next.js |
| Storage | S3 with SSE-KMS, versioning, lifecycle rules | Separate training and evaluation access |
| Images and secrets | ECR, Secrets Manager, KMS, workload IAM roles | Immutable images, controlled credentials |
| File checks | Isolated ClamAV, strict parsers, type validation | A clean scan does not mean safe to run |
| Generation | Transformers first, vLLM after a compatibility check | Use TRL's supported integration |
| Audit | CloudTrail, restricted audit bucket | Short-lived, attributable production access |
| Tests | pytest, real PostgreSQL, API contract tests, Playwright, small real GPU suite | Covers what unit tests cannot prove |
Repository layout
| Path | Owns |
|---|---|
apps/web | Screens, generated API client, browser tests |
services/api | Routes, auth, domain services, transactions |
services/worker | Outbox, queue, dispatch, reconciliation, exports, cleanup |
services/episodes | Broker and environment sessions |
services/verifier | Private scoring, versioned rules, adversarial tests |
training | Pinned recipe, bridge, preflight, checkpoint validation, GPU tests |
evaluation | Frozen protocols, statistics, audit inputs, reports |
packages/domain | Validated manifest types and task contracts |
infra | Terraform, with no secret values |
tests/integration | Database, permissions, queues, boundaries, end-to-end |
docs | Decisions, runbooks, threat model, release evidence |
This goes in a separate product repository. Every function gets a comment or docstring for its purpose, inputs, outputs and assumptions, as the founder asked.
API route groups
Routes under /api/v1 | Rule |
|---|---|
/api/auth | Browser login only, outside the versioned API |
/me, /organizations, /projects | Server checks current grants every time |
/projects/{project_id}/invitations | Intended identity, expiry, one-time acceptance |
/assignments, /claims | Atomic lease, one active owner |
/tasks, /tasks/{task_id}/revisions | Revision precondition, immutable once submitted |
/reviews, /adjudications | Author conflict and stale target fail first |
/assets/upload-intents, /assets/{asset_id}/complete | The browser never picks a key |
/environment-versions, /verifier-versions | Reviewed pipeline or authorized engineer only |
/dataset-releases | All members pin immutable versions |
/model-versions, /training-runs | Approval binds digest, budget and approver |
/checkpoints, /evaluations, /reports | No final test for training roles |
/deliveries, /deliveries/{delivery_id}/downloads | Rights rechecked before every link |
/payables, /settlements | No direct money movement in the MVP |
/audit-events | Bounded queries, no mutation route |
/internal/attempts, /internal/episodes | Workload audience and current attempt only |
/projects/{project_id}/sides | One side per person, per project |
/evaluations with a kind | Baseline first, then comparison against it |
/attempt-samples, /attempt-reviews | Training split only, scores never change |
/execution-lanes | Lab lanes need a passing rehearsal and an attestation |
Exact request behavior is in the LLD. Generate OpenAPI from the real Pydantic models.
Prove it cheaply, harden it, then go inside a lab
Internal proof
Build and demonstrate before paying for always-on.
External pilot
Must pass the release gates.
Lab account
After the first delivery, for a lab's checkpoint.
Spend first on real task quality and a correct RL experiment. Contributor payment records stay in approved operations systems until the app can protect them. Network and account detail is in the HLD, and the lab path is drawn there too.
Starting sizes and session settings
These are load-test starting points, not capacity guarantees. Every service gets readiness and liveness checks, a graceful stop and rolling deploys. Browsers get an opaque __Host-session cookie, and tokens never go in local storage. Require MFA for operators and reauthenticate for sensitive grants.
Never lose an event, and expect to see it twice
A file upload is never trusted
- 1AuthorizeCheck assignment, type, size and quota. Server picks a random key.
- 2SignShort-lived POST policy, 5 minutes to start.
- 3QuarantineVerify bytes, type, size, checksum and content.
- 4BindPin the verified version, so a replay cannot replace it.
- 5Clean upRemove unbound and expired objects.
Manifest rules
Every dataset, run, checkpoint, evaluation and delivery has a versioned manifest with code commit, input digests, exact artifact references, checksums and permitted-use references. Producers write shards to a unique staging prefix and request finalization with their current lease and fence. A presigned URL can be reused until it expires, so it is neither a one-time token nor proof of content. Never log its query string.
One episode and one update, on one GPU
The nine-step run
- ClaimGet the start lease, verify the manifest, approval, assets and rights.
- LoadCheck special tokens, template, tool encoding, adapter targets, precision and gradient flow.
- OpenTraining tasks only. Approved number of sessions, current policy pinned.
- SampleEach task's attempt group, with real tokens, log probabilities, limits and score validity.
- ValidateComplete groups, masks, likelihoods and reward parts. Apply the unscorable-group rule.
- OptimizeThe pinned trainer's GRPO objective. Record loss, gradients, reward spread, eligible tokens.
- SyncUpdate the generation policy before the next batch. No stale server or mixed adapter state.
- SaveVerified checkpoints on schedule, with development evaluation for selection.
- StopOn budget, steps, cancel, quality alarm or numerical failure. Finalize only complete evidence.
The manifest freezes digests, adapter config, trainable names, template, releases, versions, seeds, image, dependency lock, optimizer, schedule, precision, reward aggregation, stop rules and budget. Changing any substantive setting makes a new run.
What has to fit on one GPU
Begin small, with short contexts, small batches and gradient accumulation. Context length and concurrent generation can outweigh what a small adapter saves. Measure peak memory, step time, usable rollouts per hour and checkpoint time, then leave headroom. Start with Transformers generation, and add vLLM only after synchronization, masking and checkpoint tests pass.
Treat a model file as untrusted input
Proof the weights changed
Counts as proof
Does not
A separate job, a separate role, a sealed test
| Role | Train release | Dev release | Sealed test | Hidden answers | Candidate |
|---|---|---|---|---|---|
| Trainer | yes | writes | |||
| Training experts | tasks | failures | |||
| ML development evaluator | yes | yes | |||
| Final evaluator | yes | yes | |||
| Benchmark experts | audit | ||||
| Verifier | yes | ||||
| Environment |
Benchmark, train, benchmark again
- 1Freeze protocolOriginal model, release, metrics, limits. No candidate yet.
- 2BaselineRun the original. Development results go to training, sealed results stay hidden.
- 3Approve and trainApproval requires a current baseline.
- 4Attempt reviewPaid experts diagnose a sample. Findings shape the next round.
- 5Freeze candidateOnly now does it attach to the protocol.
- 6CompareSame protocol, paired with the baseline. Experts sign off.
Two separate decisions
Technical completion
The pipeline ran, parameters changed, the model reloaded, and evidence is valid.
Efficacy
The pre-agreed quality and regression criteria were met.
Done but no gain
A customer may accept an informative failure under a research contract. Sales must not rewrite it as improvement.
Before opening the test, freeze candidate, original, metric, target, thresholds, inference settings, attempts, seeds, missingness rule and analysis. Repeated attempts on one scenario measure variability, not extra tasks, so aggregate by scenario group. A grouped paired bootstrap can estimate the change.
Billing alerts are late. Stop spend before it happens.
- 1Approval reservesResources, time, retries, evaluation, contingency
- 2Trainer checksIts own runtime and token limits
- 3Watchdog stopsCan kill a stuck trainer, separately
- 4Batch timeoutOff by default, so set it. Add queue and startup deadlines.
- 5ReconcileCompare estimates with actual billing
What to measure
| Category | Measure |
|---|---|
| Expert work | Accepted and rejected authoring, qualification, review, rework, adjudication, compensation |
| CPU | App baseline, environment and verifier runtime, scanning, exports |
| GPU | Runtime including startup, failed attempts, retries, evaluation, validation, stop delay |
| Storage | Inputs, mirrors, trajectories, checkpoints, logs, backups |
| Network | NAT, endpoints, cross-zone, model downloads, exports |
| Staff | Environment, ML debugging, audits, support, security, manual operations |
Use accepted-task cost, experiment cost per usable scored rollout, and pilot cost against revenue, with the counts beside them. Start from real quotes for the chosen region, and track cash and pre-credit cost so free credits do not flatter the pilot.
Thirteen threats, each with a test
| Threat | Control | Proof before launch |
|---|---|---|
| Contributor reads another customer's work | Grants, RLS, object authorization, private caches | Cross-tenant role matrix |
| Model reads reward answers | Separate verifier role, no label tool | Prompt, file, schema, error and network probes |
| Task content becomes executable UI | Text rendering, sanitized markup | Stored-XSS and malicious uploads |
| Tool reaches network or host files | Typed allowlist, no shell or URL tool | SSRF, traversal and metadata tests |
| Bad image or dependency steals secrets | Reviewed pinned images, SBOM, minimal roles | Provenance and secret-access review |
| Duplicate dispatch drains budget | Dispatch token, lease, fence, watchdog | Ambiguous-submit fault injection |
| Stale worker publishes a checkpoint | Current lease and fence, validation | Complete-after-cancel tests |
| Shared GPU host leaks assets | Project lane, encrypted scratch, host terminated between tenants | Host and volume cleanup evidence |
| Operator tampers with results | Append-only audit, immutable reports, independent review | Review history, correction path |
| Download link leaks | Short expiry, no URL logging, no public bucket | Expiry and revocation tests |
| Backup restores deleted data | Deletion register outside the restored state | Restore-and-delete drill |
| Test leaks through a person | One side per project, enforced in the database, sealed baseline | Second-side grant and read denials |
| Lab weights leave the lab | Execution in their account, no export role, agreed metrics only | No-egress test in a rehearsal account |
Production access and audit
Give people short-lived access under their own names. Break-glass access needs a reason, an expiry and a review afterward. Send audit evidence to a restricted account, and do not lock erasable customer prompts away forever without a legal basis.
Every alert has one owner
Platform
ML
Environment
Budget owner
A missing heartbeat for five minutes goes to platform and ML together, who check provider and worker state before restarting. Use one correlation ID from API to evaluation, and keep prompts, tokens and credentials out of ordinary logs.
Stop a runaway run
- 1Commit cancelBlock new episodes, renewals and promotion
- 2TerminateCancel jobs, revoke sessions, stop environments
- 3VerifyNo duplicates, instances, sessions or uploads left
- 4CloseKeep logs and record cost, only after stop is confirmed
Four more runbooks
Verifier defect
- 1QuarantineVerifier and releases
- 2PreserveOld code, scores, reports. Find downstream via lineage.
- 3FixFailing test, then an independently reviewed version
- 4Rescore or rerunThen issue a corrected report
Database or app outage
- 1FreezeWrites and dispatch
- 2RestoreTo a separate instance, verify integrity
- 3ReplayDeletions and holds. Reconcile jobs and payables.
- 4ValidateLogin, isolation, queues, uploads, then switch
Leaked credentials or assets
- 1RevokeSessions and grants
- 2BlockObjects, then rotate secrets
- 3StopAffected workloads
- 4NotifyCheck containment at the enforcing service
Close a project
- 1FreezeWork, then settle records
- 2ExportAgreed deliverables
- 3RevokeAccess and compute
- 4RetainApply schedule, record what stays
What each environment can prove
GPU-free laptop
Real AWS only
Real GPU only
- 1Build onceImmutable image, SBOM, digest
- 2NonprodReviewed plan, additive migrations
- 3StagingCritical flows, permissions, GPU checks
- 4ApproveThen backward-compatible schema
- 5ProductionRoll services, verify health
- 6Roll backImages only. Destructive changes need a repair plan.
Fifteen work packages, in dependency order
Handoff: evidence this plan cannot supply
- CompatibilityTested dependency and model lock, region quota and price.
- ContractsReal OpenAPI, migrations, authorization matrix, storage policies.
- EnvironmentEnvironment and verifier reports, independent task review.
- TrainingReal GPU update, full checkpoint, clean reload, recovery.
- EvaluationFrozen protocol, separate test access, uncertainty, honest result.
- OperationsMeasured limits, restore, cancel, security, incident and cost drills.
- DeliveryAuthorized delivery, support owner, settlement, project close.
The path beyond the first build
Frontier labs
Never assume a lab will send unreleased weights. The lab account path runs our signed images in their account. If they run the optimizer themselves, call it environment delivery.
Data and scale
Add connectors one source at a time, keeping raw, normalized, reviewed and released objects apart. Add a warehouse or orchestrator on measured need. Distributed training is a new tested plan.
Primary references
- OpenEnv walkthrough
- TRL OpenEnv
- TRL GRPO
- TRL vLLM
- Qwen3-1.7B
- AWS Batch GPU jobs
- AWS Batch job states
- AWS Batch timeouts
- AWS Batch SubmitJob
- SQS at-least-once
- Transactional outbox
- PostgreSQL row security
- RDS backups
- S3 presigned URLs
- ECS task roles
- Fargate security
- Cognito authorization
- GitHub Actions AWS OIDC
- OWASP authorization
- OWASP file uploads
- FastAPI
- SQLAlchemy transactions
- Next.js App Router
- TanStack Query
- ClamAV
- WCAG 2.2