RL environments field guide
04 / Build overview

Keep the app small and the evidence safe

Model training stays out of web requests, and the data that judges training stays out of reach. Here is what to build it with and how it runs.

Plan, not a product. Nothing here is built or measured yet.7 min read4 diagrams
01 / The choice

A modular app, one database, isolated ML jobs

API, worker, environment and trainer run as separate processes. Domain rules stay in one codebase.

OptionProves RLKeeps review, access and pay historyHigh concurrencyLight to run before a buyer
Notebook and scriptsyesnonoyes
Modular app (chosen)yesyespartlyyes
Kubernetes and workflow engineyesyesyesno
The chosen design keeps the full customer workflow and limits the supported workload.

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
WordWhat it means here
RolloutOne complete attempt by the model at one task.
CheckpointA saved copy of the model's weights at one moment.
AdapterA small trainable add-on. The base model stays frozen underneath it.
BaselineThe saved score of the starting model, taken before any training.
Sealed testTasks that training can never read, kept for the final comparison.
VerifierProtected code that scores an attempt. The model cannot see or reach it.
UnscorableThe infrastructure failed, so there is no score at all. This is different from scoring zero.
TenantOne customer. Their data must never reach another customer.
IdempotentSending the same request twice has the same effect as sending it once.
OutboxA to-do note saved with the data it describes, so a crash cannot lose it.
LeaseA time-limited right to act that must keep being renewed.
FenceA number that rises with each attempt, so writes from an old worker get rejected.
ReconcileAsk the cloud provider what really happened before acting on a guess.
DigestA fingerprint of a file. If one byte changes, the digest changes.
ManifestA signed-off list of the exact files and versions a step used.
QuarantineBlock something from new use while keeping its history intact.
RLSRow-level security: the database itself filters rows by tenant.
02 / Stack

A short list of boring technology

Next.js, React, TypeScriptScreens, no business writesTanStack QueryBounded, tenant-keyed cacheFastAPI, PydanticValidation and authorizationPython workerOutbox, dispatch, reconcileCognitoLogin and MFA, roles stay in SQLRDS PostgreSQL 17Records, leases, audit, outboxSQS with dead-letterDurable hints, not job stateS3 with KMSVersioned private artifactsECS FargateWeb, API, broker, environment, verifierAWS Batch EC2 GPUApproved attempts onlyTRL GRPO, PEFT, OpenEnvOn PyTorch and TransformersTerraformReviewed plansGitHub Actions OIDCNo long-lived keysOpenTelemetry, CloudWatchTraces, no raw promptsBrowserControlStateExecutionDelivery
Dark: the two control processes. Green: durable state. Red: the GPU lane that spends money and touches weights.

Not needed for the first release

RedisKafkaVector databaseFeature storeKubernetesCustom training algorithmWebSockets

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
LayerChoiceNote
WebNode 24, supported Next.js release, TanStack QueryPin after the web compatibility check
APIPython 3.12, FastAPI, Pydantic, UvicornGenerate OpenAPI from the real models
DatabaseRDS PostgreSQL 17, SQLAlchemy 2, Alembic, psycopgSmall Graviton instance to test first. RDS Proxy only if measured.
IngressRoute 53, ACM certificate, HTTPS load balancer/api/* to FastAPI, the rest to Next.js
StorageS3 with SSE-KMS, versioning, lifecycle rulesSeparate training and evaluation access
Images and secretsECR, Secrets Manager, KMS, workload IAM rolesImmutable images, controlled credentials
File checksIsolated ClamAV, strict parsers, type validationA clean scan does not mean safe to run
GenerationTransformers first, vLLM after a compatibility checkUse TRL's supported integration
AuditCloudTrail, restricted audit bucketShort-lived, attributable production access
Testspytest, real PostgreSQL, API contract tests, Playwright, small real GPU suiteCovers what unit tests cannot prove
Repository layout
PathOwns
apps/webScreens, generated API client, browser tests
services/apiRoutes, auth, domain services, transactions
services/workerOutbox, queue, dispatch, reconciliation, exports, cleanup
services/episodesBroker and environment sessions
services/verifierPrivate scoring, versioned rules, adversarial tests
trainingPinned recipe, bridge, preflight, checkpoint validation, GPU tests
evaluationFrozen protocols, statistics, audit inputs, reports
packages/domainValidated manifest types and task contracts
infraTerraform, with no secret values
tests/integrationDatabase, permissions, queues, boundaries, end-to-end
docsDecisions, 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/v1Rule
/api/authBrowser login only, outside the versioned API
/me, /organizations, /projectsServer checks current grants every time
/projects/{project_id}/invitationsIntended identity, expiry, one-time acceptance
/assignments, /claimsAtomic lease, one active owner
/tasks, /tasks/{task_id}/revisionsRevision precondition, immutable once submitted
/reviews, /adjudicationsAuthor conflict and stale target fail first
/assets/upload-intents, /assets/{asset_id}/completeThe browser never picks a key
/environment-versions, /verifier-versionsReviewed pipeline or authorized engineer only
/dataset-releasesAll members pin immutable versions
/model-versions, /training-runsApproval binds digest, budget and approver
/checkpoints, /evaluations, /reportsNo final test for training roles
/deliveries, /deliveries/{delivery_id}/downloadsRights rechecked before every link
/payables, /settlementsNo direct money movement in the MVP
/audit-eventsBounded queries, no mutation route
/internal/attempts, /internal/episodesWorkload audience and current attempt only
/projects/{project_id}/sidesOne side per person, per project
/evaluations with a kindBaseline first, then comparison against it
/attempt-samples, /attempt-reviewsTraining split only, scores never change
/execution-lanesLab lanes need a passing rehearsal and an attestation

Exact request behavior is in the LLD. Generate OpenAPI from the real Pydantic models.

03 / Three deployments

Prove it cheaply, harden it, then go inside a lab

Internal proof

Build and demonstrate before paying for always-on.

App and environment run locallyAuthorized synthetic dataPrivate cloud storageTemporary GPU laneLabel which tier made the evidence

External pilot

Must pass the release gates.

Separate production accountTwo zones, Multi-AZ RDSTwo web and two API tasksNo public database or GPUProject-scoped GPU laneOn-demand first, Spot only after a real interruption test

Lab account

After the first delivery, for a lab's checkpoint.

Control stays with usExecution runs in their accountTheir keys and storageWeights and raw traces stay thereRole they can revoke at any time

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
0.5 vCPU / 1 GiBweb task
1 vCPU / 2 GiBAPI task
8 h / 30 minsession absolute and idle
5 sjob status poll, with backoff
100maximum page size
14 daysautomated database backup

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.

04 / Background work

Never lose an event, and expect to see it twice

ONE DATABASE TRANSACTIONCommandAuthorized andvalidatedDomain rowsAcceptance, payable, approvalOutbox eventIDs and revision only. Noweights, secrets or prompts.PublisherClaims a batchSQSMay delivertwiceWorkerLoads current state,claims a leaseA crash right after sendingpolledacts only if the current state allows itduplicatearrives, sameresult
The outbox solves the database-and-queue dual write. It does not make outside providers exactly-once, so consumers must tolerate repeats.
5 deliveries, then dead-letterBackoff with jitterReconcile active jobs every 30 sOrphan scan every 5 minReconcile even if provider events arriveA long GPU job never waits inside a queue message

A file upload is never trusted

  1. 1AuthorizeCheck assignment, type, size and quota. Server picks a random key.
  2. 2SignShort-lived POST policy, 5 minutes to start.
  3. 3QuarantineVerify bytes, type, size, checksum and content.
  4. 4BindPin the verified version, so a replay cannot replace it.
  5. 5Clean upRemove unbound and expired objects.
ArchivesExecutablesMacrosHTMLRemote fetch URLs
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.

05 / The RL run

One episode and one update, on one GPU

UNTIL TERMINAL STATE OR LIMITGPU trainerEpisode brokerEnvironmentVerifierArtifact storageStart episode with task andpolicy versionReset isolated state fromfrozen fixtureObservation and allowed toolsValidated tool actionApply with sequence numberObservation and terminal statusAuthoritative final state, private task referenceValid reward, or an unscorable errorCheck complete group and token masksGRPO loss, gradients, optimizer stepCheckpoint shards and completion manifest
The model sees only task text, allowed observations and tool definitions. Rewards return outside model-visible messages.
The nine-step run
  1. ClaimGet the start lease, verify the manifest, approval, assets and rights.
  2. LoadCheck special tokens, template, tool encoding, adapter targets, precision and gradient flow.
  3. OpenTraining tasks only. Approved number of sessions, current policy pinned.
  4. SampleEach task's attempt group, with real tokens, log probabilities, limits and score validity.
  5. ValidateComplete groups, masks, likelihoods and reward parts. Apply the unscorable-group rule.
  6. OptimizeThe pinned trainer's GRPO objective. Record loss, gradients, reward spread, eligible tokens.
  7. SyncUpdate the generation policy before the next batch. No stale server or mixed adapter state.
  8. SaveVerified checkpoints on schedule, with development evaluation for selection.
  9. 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

48 GiBsingle-GPU candidate, g6e.2xlarge
8 / 64 GiBvCPUs and host memory
4starting group size
Base weightsTrainable parametersGradientsOptimizer stateActivationsInference KV cacheGeneration groupsFramework overhead

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

Mirror approved weights to private storagePrefer safetensorsRemote model code stays offCustom code needs source review and an isolated test

Proof the weights changed

Counts as proof

Finite numeric differences in trainable tensorsOptimizer-step evidenceFrozen base stays frozenA clean reload that works

Does not

A renamed fileA changed checksumA rising average rewardA mocked optimizer
06 / Evaluation

A separate job, a separate role, a sealed test

RoleTrain releaseDev releaseSealed testHidden answersCandidate
Traineryeswrites
Training expertstasksfailures
ML development evaluatoryesyes
Final evaluatoryesyes
Benchmark expertsaudit
Verifieryes
Environment
Filled: this role can read it. Blank: storage and API both deny it. Even the final evaluator reaches hidden answers only through the verifier.

Benchmark, train, benchmark again

  1. 1Freeze protocolOriginal model, release, metrics, limits. No candidate yet.
  2. 2BaselineRun the original. Development results go to training, sealed results stay hidden.
  3. 3Approve and trainApproval requires a current baseline.
  4. 4Attempt reviewPaid experts diagnose a sample. Findings shape the next round.
  5. 5Freeze candidateOnly now does it attach to the protocol.
  6. 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.

07 / Spending

Billing alerts are late. Stop spend before it happens.

  1. 1Approval reservesResources, time, retries, evaluation, contingency
  2. 2Trainer checksIts own runtime and token limits
  3. 3Watchdog stopsCan kill a stuck trainer, separately
  4. 4Batch timeoutOff by default, so set it. Add queue and startup deadlines.
  5. 5ReconcileCompare estimates with actual billing
What to measure
CategoryMeasure
Expert workAccepted and rejected authoring, qualification, review, rework, adjudication, compensation
CPUApp baseline, environment and verifier runtime, scanning, exports
GPURuntime including startup, failed attempts, retries, evaluation, validation, stop delay
StorageInputs, mirrors, trajectories, checkpoints, logs, backups
NetworkNAT, endpoints, cross-zone, model downloads, exports
StaffEnvironment, 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.

08 / Threats

Thirteen threats, each with a test

ThreatControlProof before launch
Contributor reads another customer's workGrants, RLS, object authorization, private cachesCross-tenant role matrix
Model reads reward answersSeparate verifier role, no label toolPrompt, file, schema, error and network probes
Task content becomes executable UIText rendering, sanitized markupStored-XSS and malicious uploads
Tool reaches network or host filesTyped allowlist, no shell or URL toolSSRF, traversal and metadata tests
Bad image or dependency steals secretsReviewed pinned images, SBOM, minimal rolesProvenance and secret-access review
Duplicate dispatch drains budgetDispatch token, lease, fence, watchdogAmbiguous-submit fault injection
Stale worker publishes a checkpointCurrent lease and fence, validationComplete-after-cancel tests
Shared GPU host leaks assetsProject lane, encrypted scratch, host terminated between tenantsHost and volume cleanup evidence
Operator tampers with resultsAppend-only audit, immutable reports, independent reviewReview history, correction path
Download link leaksShort expiry, no URL logging, no public bucketExpiry and revocation tests
Backup restores deleted dataDeletion register outside the restored stateRestore-and-delete drill
Test leaks through a personOne side per project, enforced in the database, sealed baselineSecond-side grant and read denials
Lab weights leave the labExecution in their account, no export role, agreed metrics onlyNo-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.

09 / Operations

Every alert has one owner

Platform

API errorsQueue age, dead lettersUnknown or duplicate jobsBackup or scanner failure

ML

Non-finite lossZero parameter changeUnscorable or equal-reward groupsInvalid traces

Environment

Stale sessionsFailed cleanupInvalid rewards

Budget owner

Unapproved spendNear duration capIdle GPU

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

  1. 1Commit cancelBlock new episodes, renewals and promotion
  2. 2TerminateCancel jobs, revoke sessions, stop environments
  3. 3VerifyNo duplicates, instances, sessions or uploads left
  4. 4CloseKeep logs and record cost, only after stop is confirmed
Four more runbooks

Verifier defect

  1. 1QuarantineVerifier and releases
  2. 2PreserveOld code, scores, reports. Find downstream via lineage.
  3. 3FixFailing test, then an independently reviewed version
  4. 4Rescore or rerunThen issue a corrected report

Database or app outage

  1. 1FreezeWrites and dispatch
  2. 2RestoreTo a separate instance, verify integrity
  3. 3ReplayDeletions and holds. Reconcile jobs and payables.
  4. 4ValidateLogin, isolation, queues, uploads, then switch

Leaked credentials or assets

  1. 1RevokeSessions and grants
  2. 2BlockObjects, then rotate secrets
  3. 3StopAffected workloads
  4. 4NotifyCheck containment at the enforcing service

Close a project

  1. 1FreezeWork, then settle records
  2. 2ExportAgreed deliverables
  3. 3RevokeAccess and compute
  4. 4RetainApply schedule, record what stays
10 / Shipping

What each environment can prove

GPU-free laptop

Task workflowsAPI and verifier testsData validationDeterministic replay

Real AWS only

IAM and S3 policyCognitoBatch behaviorQueue duplicates, cancel, recovery

Real GPU only

Memory fitRL optimizationCUDA compatibilityCheckpoint resume
  1. 1Build onceImmutable image, SBOM, digest
  2. 2NonprodReviewed plan, additive migrations
  3. 3StagingCritical flows, permissions, GPU checks
  4. 4ApproveThen backward-compatible schema
  5. 5ProductionRoll services, verify health
  6. 6Roll backImages only. Destructive changes need a repair plan.

Fifteen work packages, in dependency order

01ContractBrief,rights02 ML fitT-0603 CloudRestoretest07ExecuteT-03, T-0404 AccessT-1005ExpertsT-0106QualityT-0208ReleasesT-0509 JobsT-06, T-0810EvaluateT-0711DeliverT-09, T-1112 RepeatNo hiddensteps13BaselineT-12, T-1314ReviewsT-1415 LabT-15ML fit also feeds jobs, as does cloud
Each box names its acceptance suite. A saved baseline must exist before jobs can run, and the lab path comes after the first delivery. Build vertical workflows, so the early proof exposes ML and environment problems first.
Handoff: evidence this plan cannot supply
  1. CompatibilityTested dependency and model lock, region quota and price.
  2. ContractsReal OpenAPI, migrations, authorization matrix, storage policies.
  3. EnvironmentEnvironment and verifier reports, independent task review.
  4. TrainingReal GPU update, full checkpoint, clean reload, recovery.
  5. EvaluationFrozen protocol, separate test access, uncertainty, honest result.
  6. OperationsMeasured limits, restore, cancel, security, incident and cost drills.
  7. 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
PreviousRequirements