RL environments field guide
05 / High-level design

What runs where, and what fails how

System boundaries, ownership and failure containment, in six views: context, control, execution, the full loop, deployment and lineage.

Plan, not a product. Nothing here is built or measured yet.9 min read7 diagrams
01 / Priorities

When goals conflict, this order wins

Security and experiment correctness beat throughput. A job pauses when evidence or authorization is uncertain, and the UI says so.

PriorityOutcomeHow the design gets it
1 Scientific validityA real update and a fair comparisonFrozen manifests, supported trainer, separate evaluator, immutable reports
2 Data isolationEveryone sees only what they mayPer-request grants, row security, separate test storage, scoped roles
3 Financial controlA failed job cannot keep spendingReservations, one compute slot, reconciliation, outside watchdog
4 Work preservationA crash never erases accepted workTransactions, immutable submissions, append-only decisions, backups
5 RecoveryOperators can stop, explain and hand overDurable attempts, state machines, incident records, restore drills
6 Small-team deliveryShips without a distributed platformModular monolith, managed services, one ML recipe, manual low-volume work

Supported first release

One capability familyOne typed-tool environmentOne open-model family and adapter recipeOne GPU attempt globallySeveral invited experts and reviewersManual recruiting, contracts, payment
Uploaded codeBrowser controlLive credentialsEvery modelDistributed frontier training
Ten engineering principles, and the check for each
PrincipleThe rule hereHow a reviewer checks it
High cohesionA task module owns revisions, a run module owns approvalA review rule change touches no cloud adapters
Dependency inversionUse cases depend on narrow contractsDomain code imports no FastAPI, SQLAlchemy or boto3
Single ownershipOne module writes each piece of stateNo payment write hidden in a task route
CompositionRecipe joins model, tools, scorer, trainerNo inheritance tree for future environments
Explicit stateCommands state revision, actor, transitionInvalid moves fail before any side effect
Immutable evidenceRevisions, manifests, scores, reports are versionedCorrections link a new record
Least privilegeRoles get only needed rows, objects, keysTests use production-style roles
At-least-onceConsumers tolerate duplicates and unknownsFault tests show one business effect
SimplicityOne database and recipe until measured needNo generic framework built ahead of demand
ObservabilityCommands trace to work, cost, resultCorrelation IDs link API through report

Business rules live in a pure core with no framework or cloud calls, and a thin outer layer does the input and output. Use SOLID only where it improves these boundaries. Events give durable notification, and PostgreSQL stays the record, so no event sourcing or CQRS is needed.

02 / Reading this page

Each view answers one question at one zoom level

Boxes stay at one level per diagram. A person, a Python class and a server replica never share a picture.

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.
03 / Context

Who touches the system

Experts, on two sidesTrain the model, orbenchmark itPlatform and MLoperatorApproves and runs projectsFrontier labBrings a checkpoint,accepts resultsExpert-to-RL platformTasks, environments, realtraining and evidenceCognitoAuthenticates peopleModel registryLicensed open weightsPayment providerSettles approved paysubmits work anddecisionsapproves budgetsand runsreads permittedreportsrequestsloginimports apinnedrevisionsettlementevidenceoperator executes payment by hand
Cognito authenticates, but the application grants project access. Mirrored models keep running if the registry is down. The company stays accountable even where services are managed.
04 / Control

Applications that manage people, work and approvals

CONTROL APPLICATIONSUserHTTPSWebNext.js. Renders rolescreens.Control APIFastAPI. Authorizescommands, recordsdecisions.PostgreSQL 17State, revisions,approvals, outboxPrivate S3 and KMSVersioned inputs andoutputsControl workerDispatch, reconcile,packageSQSWith DLQExecution appsTrainer and evaluatorAPIrequestsonetransactionclaims outbox,leasesscoped transfersmanifestsBatch: one approved job definitionheartbeat,finalization
An accepted command commits state, receipt, audit and outbox together, so the user can close the browser right after the receipt.
ContainerOwnsDoes not own
WebForms, role queues, bounded cache, saved-state feedbackDatabase writes, authorization, training
Control APISessions, briefs, revisions, approvals, reservations, grantsLong GPU work, a second copy of verifier logic
Control workerOutbox, dispatch, reconciliation, scans, exportsSilent edits to frozen experiments
PostgreSQLTransactions, constraints, evidence metadataMulti-gigabyte weights, open analytics
SQSDurable hints that work existsRun status, exactly-once GPU work, task bodies
Private S3Pinned objects, encrypted assets, weightsPermission decisions based on a filename

The watchdog needs its own failure path and permission to stop compute, even when the dispatcher is stuck.

05 / Execution

Applications that sample, act, score and update

SCOPED INPUTSHIDDEN FROM THE MODELTraining inputsTrainer reads onlySealed testEvaluator readsonlyTrainer runnerPyTorch, TRL, PEFT.Samples and updates.Evaluation runnerCompares original andcandidateAttempt artifactsScoped writesEpisode brokerFastAPI. Ownssessions andlimits.EnvironmentTyped tools,deterministic stateRuntime schemaEpisode state,actionsVerifierScores final statePrivatejudgmentVerifier readsonlyreadsreadstraces,checkpointsmetricsauthorized episodesevaluation episodesreset, typedactionsfrozen statereferenceatomicreads finalstatereads
Each sensitive input has one reader. The trainer cannot reach the sealed test. The evaluator cannot reach hidden answers. Only the verifier reads those.

A task failure

A valid outcome that can score zero.

Model made a mistakeHit a declared limit

An environment failure

An unscorable rollout with no reward.

Service downReplay mismatch

The trainer uses the supported TRL and OpenEnv integration, with no new optimizer. Model-generated text never becomes a shell command or SQL query. See the score contract.

06 / The full loop

Benchmark, train, benchmark again, with a wall between

One checkpoint goes to both sides. Only the frozen candidate crosses the wall.

TRAINING SIDEBENCHMARK SIDEStarting checkpointTraining tasksExpert authors, a separatereviewerDevelopment baselineShows where the model failsRL runFrozen config, newweightsAttempt reviewPaid experts diagnose a frozensampleTest tasksWritten and reviewedby this sideSealed baselineResult hidden fromtrainingComparisonSame protocol, pairedresultsSign-offExperts audit, ownerapprovessame checkpointfailures totargetsampledattemptsfindings, nextroundfrozen candidate, the only thing that crosses
Experts who see sealed results never write training tasks, or the test would leak through people. Attempt reviews change the next round's tasks, never a stored score.

The baseline is a gate

Saved before trainingRequired for approvalInvalid if inputs change

People help, the optimizer trains

Reviews sit between runs, not per rolloutNew tasks mean a new linked runDemonstrations are a declared stage

One side per project

Enforced in the databasePay and access differ by sideA person can switch only on a new project
07 / Data

Who reads and writes each class of data

One managed PostgreSQL with logical schemas per owner. These are ownership boundaries, not separate servers.

DataReadsWritesExtra rule
Contributor profileContributor, authorized opsIdentity and opsCustomers see no workforce data
Draft and submitted taskAuthor, reviewer, project staffTask operationsSubmitted is immutable, judgment is separate
Training releaseML operator, training workloadRelease publisherRights checked at use time
Final-test releaseEvaluation owner and workloadRelease publisherTrainer cannot list, read, decrypt or request
Hidden expected resultsVerifier, controlled reviewTask-quality flowNo model tools, logs or public links
Weights and trajectoriesAuthorized ML and evaluationScoped attempt prefixConfidential, no outside telemetry
Customer deliveryCustomer, delivery operatorsDelivery moduleShort-lived, pinned, revocation recorded
Sealed baseline resultsEvaluation owner, benchmark expertsEvaluation runnerHidden from the training side until the candidate freezes
Development baselineML operator, training expertsEvaluation runnerUsed to choose what to train next
Attempt reviewsTraining side, evaluation ownerAssigned reviewerTraining split only, stored scores never change
08 / Deployment

The customer pilot on AWS

The internal demo can run locally with temporary GPU compute. This is the hardened version.

ONE PRODUCTION AWS ACCOUNT, ONE REGIONZONE AZONE BBrowserPublic ALB and TLSWeb taskFargateAPI taskFargateRDS primaryRDS standbySynchronousAPI taskFargateWeb taskFargateControl workerPlus a separatewatchdogBatch EC2 GPUProject lane, min 0InternalALBHTTPSBrokerEnvironmentVerifierVPC endpoints, private API pathsS3, KMS, Secrets Manager, SQS, ECR, logsHTTPS 443PRIVATE VPCreplicatesboundedsubmitscopedendpointpoliciesNo database or GPU worker has public inbound access.A NAT gateway alone is not an egress allowlist.
Same-origin web and API behind one load balancer. Control services span two zones. The verifier runs in its own task, because containers in one Fargate task share resources and networking.
2AWS accounts, production and nonproduction
2availability zones for control and RDS
4 h / 15 minproposed restore and recovery point, to measure
1GPU slot across training and evaluation
The network allowlist
Public subnets: load balancers and controlled egressApp subnets: private Fargate tasksIsolated subnets: RDSGPU: its own security group and lane
FromToWhy
Public browserPublic ALB, 443User HTTPS only
Public ALBWeb and API tasksRouted requests and health checks
API tasksRDS, 5432 with TLSAuthorized transactions
Control workerRDS, private AWS endpointsOutbox, jobs, scoped artifacts
Trainer or evaluatorInternal broker, approved endpointsScoped episodes, input reads, own writes
BrokerEnvironment and verifierTyped operations, protected scoring
Environment roleRestricted runtime schemaEpisode state and receipts only
Verifier roleFrozen state, judgment objectsScoring only, read-only
Migration roleDatabase via deployment pathReviewed schema changes only

Service TLS does not grant project access, so validate the attempt token and purpose per request. Do not mix customer data on reused GPU hosts: drain, terminate and verify scratch deletion before another tenant. This AWS design is the proposed backend. The published guide stays on Vercel and provisions nothing.

09 / Lab account

Taking a lab's checkpoint without taking its weights

Built after the open-weight proof and the first delivery. A lab should not have to send unreleased weights to a new vendor.

OUR ACCOUNT: CONTROLTHE LAB'S ACCOUNT: EXECUTIONControl app and databasePeople, tasks, approvals, recordsSigned release bundleImages, manifests, test assetsOur expertsNamed people, approved by the labTrainer and evaluatorAWS Batch in their account, under their keysBroker, environment, verifierInstalled from the signed bundleRaw tracesNever leaveLab checkpointNever leavesnarrow role: submit, inspect,stopheartbeats, checksums, agreedmetricsreviewed installreview attempts insidelab-approved tools
Control stays with us and execution moves to the lab. Weights and raw traces never cross, and the lab can revoke our role at any time.

Crosses to the lab

Signed imagesPurpose-specific manifestsTask and test assetsJob requests through the narrow role

Crosses back

Heartbeats and job stateChecksums and digestsAgreed metricsThe report the lab approves

Never crosses

Weights and adaptersRaw traces and promptsLab credentialsAnything outside the contract
What the contract must settle first
QuestionDefault to propose
Who may start training?Named operators of ours, within a lab-approved budget
Who sees weights?Lab staff, and our workload role only while a run holds a lease
Where are rewards computed?In the verifier, inside the lab's account
How are code updates reviewed?Signed bundle, lab review, new rehearsal
What telemetry can leave?Job state, digests and agreed metrics only
Who can review attempts?Named experts, using lab-approved tools
How are incidents handled?Shared contacts, and the lab can revoke first
Who owns the outputs?Checkpoints stay with the lab, tasks by contract

The first supported lab cloud is AWS. Another cloud needs a new provider adapter and its own rehearsal. If the lab runs the optimizer itself, call it environment delivery, not our managed run.

10 / Lineage

One bad source can be traced to every result it touched

Source assetAnd rightsversionTask revisionAcceptedDatasetreleaseDigestTraining runManifestCheckpointCompleteEvaluationReviewedDeliveryCustomerQuarantine or rights revocationA new eligibility record, bytesunchangedblocks new use, keepshistorytraces impactrecall or correction assessment
Solid arrows are provenance. Deleting a source does not remove what a model learned, so operators decide to stop, rescore, retrain, correct or contact the customer.

A release pins exact revisions, digests, verifier version and split grouping. Rights can expire later without changing the frozen record, because eligibility is a separate record checked at use. One ZIP holding every asset is not a safe training bundle, so the exporter emits a separate manifest per purpose.

11 / Critical flows

Ten moments where work must not be lost or doubled

FlowDurable boundaryOn failureContract
Reviewer acceptsRevision, decision, payable, audit, outboxStale draft conflicts, replay returns the receiptTask
Dataset publishesImmutable release and group splitsOne defect blocks publicationRelease
Baseline recordedFrozen protocol, evidence manifestA failed run leaves no baseline, so approval stays blockedBaseline
Run approvedDigest, baseline, approval, reservation, queueConcurrent approvals cannot double-reserveApproval
Job submittedIntent before the call, result afterUnknown goes to reconcile, never blind resubmitDispatch
Model actsState, journal, receipt togetherReplay returns the result, never a second writeEpisode
Candidate savedShard manifest plus clean loadPartial or stale output is never promotedCheckpoint
Attempt reviewedSealed decision, finding, payableReplay returns the receipt, and the score stays unchangedAttempt review
Lab lane registeredRehearsal report, attestation, role referenceA revoked role stops work and blocks new jobsLab lane
Comparison deliveredProtocol, report, manifest, fresh grantMissingness and regressions stay visibleEvaluation

Consistency

Strong

OwnershipRevisions and acceptanceCompensation owedApprovalBudget reservation

Eventual, and shown as pending

Cloud job observationsScansDerived exportsCost reconciliation

Reads use the primary database, so nothing shows stale data from a replica. A button drawn from an old browser cache grants nothing, because the API rechecks every command.

3tenants
25contributors
5reviewers
2ML operators
5,000revisions per project
8concurrent episodes
1GPU attempt
Sizing method

A test boundary, not market sizing. Estimate episodes as active runs × groups × generations per group, capped at eight sessions. Profile reset, action, score and cleanup at p50 and p95. A slow verifier idles an expensive GPU, so measure useful scored rollouts per GPU hour, not just tokens. Token arrays and checkpoint shards can dominate storage, so set cleanup policy before a large run. More GPU concurrency needs fairness, reservations, isolation and a revised cap.

12 / Containment

Each failure stays in its own box

If this failsContainmentRecovery evidence
Browser or webDraft writes commit on their ownResume a draft, keep conflicts
API replicaStateless, durable sessions, idempotencyRepeat a request after termination
Worker or queueOutbox, leases, safe consumersCrash between send and ack, one effect
EnvironmentAction journal and deterministic replaySame digest, or invalidate the episode
VerifierOwn process, version and permissionsQuarantine without rewriting scores
GPU or trainerBounded job, heartbeats, checkpointsReal interruption resumes supported state
DatabaseFailover, backups, no local-only dataRestore, replay deletions, reconcile jobs
Cloud submitDispatch token and fenced start claimTwo jobs cannot both get write authority
Link to a lab's accountLeases expire, local watchdog stops workStop drill with the link cut, then reconcile

Platform owns

AvailabilityCloud state

ML owns

Invalid tracesNumeric failureWeight changes

Environment owns

Task stateReward defects

Operations owns

DisputesRightsSettlementCustomer contact

The watchdog stops jobs without the trainer's cooperation, with deadlines for both queue wait and startup. Termination is best effort, so reserve overhead and reconcile afterward.

Proving the two hardest boundaries

Experiment validity. Freeze group splits, models, templates, generation budgets, tools, scoring, missingness and analysis. Choose checkpoints on development data, and keep the final test sealed until the candidate and protocol freeze.

Security. Managed identity, per-request grants, strict input validation, role-specific storage and decryption, protected labels and reviewed images. Treat task text, uploads and generated text as untrusted.

Release evidence covers allowed and denied flows, real GPU updates, clean-process loading, budget-stop drills, ambiguous dispatch, cancellation races, checkpoint corruption, restore, deletion replay and customer delivery.

13 / Decisions

Sixteen decisions, and what would reopen each

IDDecisionWhyReconsider when
01Modular monolith, separate worker and executionOne source of rules, separate permissionsTeams or measured scale demand a split
02PostgreSQL for transactions and small runtime stateAtomic claims, budgets, action receiptsRuntime writes hurt control latency
03Outbox plus SQS, no event sourcingReliable without a replay platformLong workflows outgrow recorded jobs
04Separate broker, environment, verifier permissionsModel-side execution cannot reach judgmentNever just to save a container
05TRL GRPO, OpenEnv, one adapter recipeReuse support, limit compatibility workA buyer or experiment supports another
06One GPU lane, one attempt at a timeControls cost, staleness and isolationPaid demand justifies a tested scheduler
07Immutable content, separate eligibilityKeeps history, blocks revoked useKeep at any scale
08Same-origin web and API, server sessionsSimple, no browser-held tokensA public client or SSO needs review
09S3 manifests, version IDs, checksumsReproducible artifacts outside SQLVolume needs a catalog, integrity stays
10One region, two zonesRecovery without multi-region workResidency or measured reliability
11Manual payment and expert allocationCorrect accounting before automationReconciliation repeatedly delays projects
12No automatic efficacy claimFinishing and improving are differentKeep for every release and raise
13Saved baseline required before approvalNo improvement claim without a beforeKeep for every engagement
14One expert side per person per projectStops the test leaking through peopleKeep at any scale
15Human review between runs, not per rolloutKeeps training synchronous and affordableA tested human-reward recipe justifies more
16Lab execution in the lab's accountLabs keep weights, we keep the workflowA lab explicitly authorizes our infrastructure

Changing one takes a short record with the problem, measured evidence, alternatives, migration, security and experiment impact, and tests. Do not add a technology because a larger lab uses it at another scale.

Build gates

  1. G0 ScopeBrief, rights, capability, region, terms, budget
  2. G1 CompatibilityReal run, tokens, update, reload, GPU measured
  3. G2 FoundationReal roles, denied tests, CI, restore
  4. G3 ProductionAccepted batch, pay record, saved baseline
  5. G4 ExecutionApproval to recovery under injected faults
  6. G5 EvidenceFair test, audit, cost, clean load, delivery
  7. G6 Lab readyRehearsal, no-egress, revocation, lab review
Primary references
PreviousSystem design