RL environments field guide
06 / Low-level design

The contracts that keep it correct

Module ownership, records, command shapes, state machines and tests for the supported MVP. Design contracts, not a claim of working code.

Plan, not a product. Nothing here is built or measured yet.17 min read12 diagrams
01 / Invariants

Sixteen things that must always be true

If a requirement, the HLD and this page conflict, the requirement wins, then the HLD. Fix the conflict before coding.

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 / Modules

Fifteen modules, each the only writer of its state

HTTP routesFastAPI. Session andrequest mapping.Use casesPermissions, transaction,workflowDomain rulesPure values andtransitions. No I/O.PortsUnit of work, artifacts,job providerSQL adapterSQLAlchemy, psycopgArtifact adapterboto3 S3Provider adapterboto3 Batchvalidatedcommandappliesdecisionstyped I/Oimplement
Domain functions take validated values and return a decision or typed error. They never read the clock, network or config.
ModulePublic operationsOwns
identityStart and finish login, resolve and revoke sessionIdentity links, sessions
accessResolve scope, assign side, grant, revoke, authorize purposeMemberships, sides, grants
projectsCreate, revise and approve brief, closeProject, brief versions
workforceInvite, qualify, allocate, claim, renew, releaseAgreements, assignments, claims
tasksSave draft, submit, open rework, quarantineTasks, drafts, revisions
reviewsAssign, decide, adjudicate, review attemptDecisions, acceptance, attempt reviews
releasesValidate, publish, set eligibilityVersions, releases, members
runsFreeze, validate, approve, cancel, classifyIntent, approvals, attempts, reservations
episodesCreate, step, inspect, finish, closeRuntime state, receipts, snapshots
scoringScore state, audit, publish corrected scoreJudgment access, score results
checkpointsRegister, seal, validate, finalizeManifests, validation state
evaluationFreeze protocol, record baseline, compare, sign offBaselines, evaluations, evidence, reports
deliveryAssemble, approve, issue download, record acceptanceManifests, access grants
payablesCreate obligation, adjust, reconcileCompensation, settlement events
operationsOutbox, reconcile, watchdog, register lane, delete, restore auditJobs, leases, lanes, incidents
Key operations and their failure contract
OperationOutputFailure and side effects
RunService.approveRun revision, approval and reservation IDsCommits approval, budget, audit, outbox once. No AWS call.
RunService.request_cancelDurable receiptRevokes new episodes and promotion. Provider stop is async.
TaskService.submitImmutable revision ID and digestStale draft conflicts. Nothing is overwritten.
ReviewService.decideDecision and task-state receiptRejects author conflict. Acceptance and pay share a transaction.
ArtifactStore.read_verifiedStream with verified size and digestMissing version or bad checksum is a typed integrity failure.
JobProvider.submitProvider ID, rejection or unknownNetwork failure after send is unknown, never safe to retry.
JobProvider.inspectVersioned provider observationChanges no business status. The reconciler validates that.
EpisodeService.stepSafe observation and sequenceSame action returns prior result. Changed payload conflicts.
ScoreService.verifyValid score or unscorable errorNo default numeric reward on an error.
CheckpointService.finalizeComplete ID or recorded failureA stale attempt cannot publish or replace a manifest.

Implement these as small services and Protocols after the first compatibility experiment. Test doubles are fine for domain units. A simulated optimizer never passes the training gate. Share generated OpenAPI types with the web client, never ORM models.

03 / Records

The two data maps that matter

PostgreSQL 17, with reviewed Alembic migrations. Every project row carries organization and project IDs, and foreign keys include them.

ProjectTenant ownerAssignmentOne payable work item,terms versionAssignment claimOne current row, leasePayableUnique work item,amountSettlement eventAppend-only, uniquereferenceTaskStable ID and authorTask draftMutable, revision guardTask revisionImmutable, contentdigest, groupReviewreviewer_id differsfrom author_idAcceptanceUnique per revision1..n1..n0..10..11..n0..11..n1..n0..1
The copied author_id on a review is bound to its revision by a composite key, so a CHECK can compare it with the reviewer without trusting the caller.
Dataset releaseImmutable, digestBaselineOriginal model,frozen protocolRelease groupGroup to one splitRelease memberExact revisionTraining runNo test manifestin inputsRun approvalDigest, limitsRun attemptDispatch token,provider ID, fenceRollout groupSealed before useRollout and scoreValid reward, or typed errorCheckpointManifest,validationEvaluationProtocolDeliveryPinsinputrequiredsealed input and the baseline result, on a separatemanifest
A run cannot be approved without a baseline. Provider jobs are stored separately to keep duplicates as evidence, and a release group holds the split, so a member cannot be relabelled.

Column rules

Identity

uuid keys. Composite parent keys with organization and project.

Time

timestamptz in UTC, shown in the user's zone. An end time stays empty until it happens.

Versions

revision bigint, positive, rises with each mutation.

Digests

SHA-256 as 32-byte bytea, shown as lowercase hex.

Money

amount_minor bigint plus currency. No floats or implicit FX.

Over HTTP

Large numbers as decimal strings. Never rounded in the client.

Status

Bounded text and a named CHECK. Provider statuses stay out.

JSON

jsonb for task bodies and recipes only. Keys, money and state are columns.

Deletion and immutability

No blanket cascades. App roles cannot update evidence, and maintenance uses a separate audited role.

CREATE TABLE reviews (
  id                uuid        PRIMARY KEY,
  organization_id   uuid        NOT NULL,
  project_id        uuid        NOT NULL,
  task_revision_id  uuid        NOT NULL,
  author_id         uuid        NOT NULL,  -- copied, then proven by the key below
  reviewer_id       uuid        NOT NULL,
  decision          text,                -- empty until decided, then sealed
  revision          bigint      NOT NULL CHECK (revision > 0),
  created_at        timestamptz NOT NULL,

  FOREIGN KEY (organization_id, project_id, task_revision_id, author_id)
    REFERENCES task_revisions (organization_id, project_id, id, author_id),
  CHECK (reviewer_id <> author_id)        -- nobody approves their own work
);
A pattern to copy, not a tested migration. The foreign key proves the author and the tenant, so the CHECK cannot be fooled by the caller.
Every table and column (63 tables)

Unless a table is marked global, every row also has organization_id uuid, project_id uuid and created_at timestamptz, and foreign keys include the first two. Rows that change also have revision bigint. Money uses _minor bigint with a currency char(3). Digests are 32-byte bytea. This is a proposal: engineers turn it into reviewed migrations and test them.

Identity and access (6)
TableColumnsThe rule that matters
organizationsid uuid, name text, state textGlobal. Owns projects.
usersid uuid, issuer text, subject text, state textGlobal. Unique issuer and subject. No merging by email.
membershipsuser_id uuid, state text, granted_at timestamptz, revoked_at timestamptzUnique organization and user.
project_grantsuser_id uuid, role text, purpose text, state text, expires_at timestamptzUnique project, user, role and purpose. Work grants must match the user's side.
project_sidesuser_id uuid, side text, assigned_by uuidPrimary key is organization, project and user, so a second side cannot exist. Side is training or benchmark.
application_sessionsid uuid, user_id uuid, token_hash bytea, issued_at timestamptz, last_seen_at timestamptz, expires_at timestamptz, idle_expires_at timestamptz, revoked_at timestamptzGlobal. Unique hash. The raw token is never stored.
Projects and people (7)
TableColumnsThe rule that matters
projectsid uuid, owner_id uuid, support_owner_id uuid, state text, region textTop of the tenant boundary.
project_briefsversion int, owner_id uuid, mode text, capability text, rights_policy text, region text, cap_minor bigint, approved_by uuidUnique project and version. Approved versions never change. Mode is internal_demo or customer.
agreementsuser_id uuid, terms_asset_id uuid, terms_version text, accepted_at timestamptz, eligibility_ref textImmutable. No production work without one.
qualificationsuser_id uuid, rubric_version text, decision text, reviewer_id uuid, evidence_ref textImmutable decisions. The latest applicable one is resolved explicitly.
assignmentsid uuid, assignee_id uuid, work_type text, terms_version text, due_at timestamptz, compensation_rule text, state textOne payable work item. Types: task_authoring, task_review, test_authoring, test_review, attempt_review, demonstration.
assignment_claimsassignment_id uuid, claimant_id uuid, lease_until timestamptz, state textOne current row per assignment. Expiry is checked under lock.
upload_intentsid uuid, assignee_id uuid, declared_type text, max_bytes bigint, purpose text, object_key text, expires_at timestamptz, asset_id uuidThe server picks the key. Expired intents are cleaned up.
Tasks and reviews (6)
TableColumnsThe rule that matters
tasksid uuid, author_id uuid, current_revision_id uuid, state textAuthor is stable. Reassigning is an audited step before submission.
task_draftstask_id uuid, body jsonb, judgment_ref text, asset_ids uuid[], saved_at timestamptzOne per task. Every save checks the revision.
task_revisionsid uuid, task_id uuid, revision_no int, author_id uuid, content_digest bytea, judgment_ref text, fixture_ref text, scenario_group_id text, contract_versions jsonb, submitted_at timestamptzImmutable. Unique task and number. A second unique key on ID and author supports the review check.
reviewsid uuid, task_revision_id uuid, author_id uuid, reviewer_id uuid, assignment_id uuid, rubric_version text, decision text, issue_codes text[], rationale text, decided_at timestamptzReviewer differs from author. Sealed once decided.
adjudicationsid uuid, review_id uuid, adjudicator_id uuid, decision text, reason text, decided_at timestamptzA linked record by an independent person. The original review stays.
acceptancestask_revision_id uuid, decision_ref uuid, acceptor_id uuid, accepted_at timestamptzUnique per revision. Immutable.
Pay (3)
TableColumnsThe rule that matters
payablesid uuid, source_work_item_id uuid, beneficiary_id uuid, amount_minor bigint, rule_version textUnique work item, so a replay cannot pay twice.
payable_adjustmentsid uuid, payable_id uuid, amount_minor bigint, reason text, approver_id uuid, reference textAppend-only and signed. The approved total can never go negative.
settlement_eventsid uuid, payable_id uuid, provider text, external_ref text, kind text, amount_minor bigint, evidence_ref textUnique provider and reference. Reversals append.
Assets and versions (5)
TableColumnsThe rule that matters
assetsid uuid, bucket text, object_key text, version_id text, digest bytea, size_bytes bigint, media_type text, scan_state text, source_ref text, sensitivity textPinned after approval. Identical bytes do not transfer rights.
rights_versionsid uuid, asset_id uuid, authority text, allowed_uses text[], recipient_limits text[], expires_at timestamptz, retention text, evidence_ref textImmutable. Current eligibility is a separate record.
environment_versionsid uuid, commit_sha text, image_digest bytea, schema_version text, tool_schema_digest bytea, report_ref textUnique image digest per published version.
verifier_versionsid uuid, commit_sha text, image_digest bytea, score_contract text, reward_components jsonb, audit_ref textImmutable once published.
model_versionsid uuid, source text, source_revision text, weights_manifest_ref text, tokenizer_digest bytea, template_digest bytea, license text, approved_uses text[], attestation_id uuidImmutable. Source is a registry, or a lab attestation with no copy on our side.
Releases (3)
TableColumnsThe rule that matters
dataset_releasesid uuid, manifest_digest bytea, environment_version_id uuid, verifier_version_id uuid, purpose text, publisher_id uuid, published_at timestamptzImmutable after publishing.
release_groupsrelease_id uuid, scenario_group_id text, split textOne row sets a group's split: train, development or test.
release_membersrelease_id uuid, scenario_group_id text, task_revision_id uuid, fixture_ref text, rights_version_id uuidKeyed to the revision's real group, so a member cannot be relabelled.
Runs and budget (5)
TableColumnsThe rule that matters
training_runsid uuid, brief_id uuid, model_version_id uuid, train_release_id uuid, dev_release_id uuid, baseline_id uuid, parent_run_id uuid, recipe_digest bytea, state text, cancel_requested_at timestamptzNo test manifest in inputs. Approval needs a current baseline.
run_approvalsid uuid, run_id uuid, config_digest bytea, approver_id uuid, reservation_id uuid, limits jsonb, retry_allowance int, approved_at timestamptzImmutable, and bound to one exact config.
budget_accountsid uuid, cap_minor bigint, committed_minor bigint, reserved_minor bigintOne per project and currency. Never negative. Updates lock the row.
budget_reservationsid uuid, account_id uuid, intent_ref text, approval_id uuid, parent_reservation_id uuid, amount_minor bigint, consumed_estimate_minor bigint, state textOne active per intent. Evaluation can draw a child allocation.
cost_entriesid uuid, reservation_id uuid, category text, amount_minor bigint, source_ref textAppend-only. Overruns are recorded, never cut to fit.
Execution and lab lanes (6)
TableColumnsThe rule that matters
run_attemptsid uuid, run_id uuid, ordinal int, approval_id uuid, lane_id uuid, fence bigint, dispatch_token text, provider_job_id text, state text, heartbeat_at timestamptz, lease_until timestamptz, failure_code text, parent_checkpoint_id uuidUnique run and ordinal, token and provider ID. One attempt holds authority.
provider_jobsprovider_job_id text, attempt_id uuid, dispatch_token text, discovered_at timestamptz, observation jsonb, is_winner boolean, stop_evidence_ref textKeeps every discovered duplicate. One winner per attempt.
compute_slotsslot_name text, owner_intent text, attempt_id uuid, fence bigint, acquired_at timestamptz, state textGlobal. One row in the MVP. A lost heartbeat alone never frees it.
execution_lanesid uuid, account_ref text, role_ref text, bundle_digest bytea, state text, revoked_at timestamptzLab lanes need a passing rehearsal and an attestation. Every job checks the state.
lane_rehearsalsid uuid, lane_id uuid, account_ref text, bundle_digest bytea, report_ref text, passed boolean, ran_at timestamptzImmutable. A rehearsal is valid for one bundle digest only.
lane_attestationsid uuid, lane_id uuid, checkpoint_ref text, weights_digest bytea, signed_by text, signature bytea, attested_at timestamptzThe lab signs. We hold checksums and never the weights.
Rollouts, scores and review (5)
TableColumnsThe rule that matters
rollout_groupsid uuid, attempt_id uuid, iteration int, task_revision_id uuid, policy_version text, expected_size int, valid boolean, discard_reason textUnique attempt, iteration and group. Sealed before optimizing.
rolloutsid uuid, group_id uuid, ordinal int, episode_id uuid, trace_ref text, terminal_reason text, score_id uuid, policy_version textUnique group and ordinal. Tokens live in restricted objects, not SQL.
score_resultsid uuid, episode_id uuid, final_state_digest bytea, verifier_version_id uuid, valid boolean, total numeric, components jsonb, error_code textImmutable. Valid needs a finite bounded total. Invalid needs an error and no total.
attempt_samplesid uuid, attempt_id uuid, rule_digest bytea, seed bigint, frozen_at timestamptzA frozen selection rule, training split only, with high scores included.
attempt_reviewsid uuid, sample_id uuid, rollout_id uuid, assignment_id uuid, reviewer_id uuid, rubric_version text, finding text, evidence_ref text, decided_at timestamptzImmutable. Has no path to edit a score. Findings: valid_success, model_failure, task_defect, verifier_defect, exploit.
Checkpoints, evaluation and delivery (6)
TableColumnsThe rule that matters
checkpointsid uuid, attempt_id uuid, global_step bigint, manifest_ref text, manifest_digest bytea, validation_state text, validation_ref text, parent_checkpoint_id uuidUnique attempt and step. One manifest per checkpoint.
evaluation_protocolsid uuid, digest bytea, original_model_id uuid, test_release_id uuid, inference_recipe jsonb, sampling jsonb, metrics jsonb, thresholds jsonb, missingness_rule text, stat_method text, frozen_at timestamptzFrozen before any test access, and names no candidate.
evaluationsid uuid, protocol_id uuid, kind text, baseline_id uuid, candidate_checkpoint_id uuid, attempt_id uuid, state text, evidence_ref text, signed_off_by uuidKind is baseline or comparison. A comparison must name its baseline and candidate.
reportsid uuid, evaluation_id uuid, version int, metrics_ref text, analysis_digest bytea, efficacy text, review_decision text, predecessor_id uuidUnique evaluation and version. Immutable once published.
deliveriesid uuid, report_id uuid, checkpoint_id uuid, package_digest bytea, approval_ref text, acceptance_state textPins exact versions. Hidden tests are never included automatically.
delivery_grantsid uuid, delivery_id uuid, user_id uuid, asset_id uuid, purpose text, issued_at timestamptz, expires_at timestamptz, revoked_at timestamptzRights and access are rechecked for every link.
Runtime episodes (3)
TableColumnsThe rule that matters
episodesid uuid, attempt_id uuid, task_revision_id uuid, policy_version text, seed bigint, purpose text, state text, next_sequence int, counters jsonb, deadline_at timestamptz, snapshot_ref textBroker and restricted runtime roles only. No private labels.
episode_actionsepisode_id uuid, action_id uuid, sequence int, payload_digest bytea, safe_result jsonb, state_digest bytea, usage jsonbUnique episode and action, and episode and sequence. Immutable once committed.
episode_snapshotsepisode_id uuid, sequence int, state_ref text, state_digest bytea, frozen booleanThe verifier reads frozen final state only.
Operations (8)
TableColumnsThe rule that matters
outbox_eventsid uuid, aggregate_type text, aggregate_id uuid, aggregate_revision bigint, schema_version int, body jsonb, available_at timestamptz, lease_until timestamptz, published_at timestamptzThe payload never changes. Only a restricted worker marks it published.
inbox_receiptsconsumer text, event_id uuid, result_ref text, completed_at timestamptzUnique consumer and event.
command_receiptsactor_id uuid, route text, idempotency_key text, request_digest bytea, status int, resource_ref text, expires_at timestamptzUnique actor, project, route and key.
job_leasesjob_id uuid, holder text, lease_until timestamptz, fence bigint, state text, last_error textCompare-and-set renewals. Separate from GPU slot ownership.
eligibility_blockstarget_ref text, reason text, scope text, issuer_id uuid, effective_at timestamptz, cleared_by_id uuidAppend-only. A quarantine is never silently erased.
lineage_edgesparent_type text, parent_id uuid, parent_version text, child_type text, child_id uuid, child_version text, relation textUnique edge, indexed both ways. Written with the record that creates the link.
audit_eventsactor_id uuid, action text, resource_ref text, resource_version text, reason text, request_id uuid, correlation_id uuid, occurred_at timestamptzThe app can add but never edit. No raw credentials or prompts.
deletion_requestsscope text, authority text, categories text[], hold_decision text, state text, evidence_ref text, backup_expires_at timestamptzLinked to the register kept outside the database.

Index project queues by tenant, project, state and time. Paginate with a stable timestamp and ID cursor, never a growing OFFSET. Partial index predicates must not depend on the current time. CHECK constraints cannot query other tables, so cross-row rules use composite keys and transactions. Store token counts and durations as numbers with units. lineage_edges is a lookup for tracing impact, and real foreign keys stay in place.

04 / Authorization

Deny by default, in this order

  1. 1AuthenticateOpaque cookie to session
  2. 2Resolve ownerWithout disclosing others' content
  3. 3MembershipVerified, never from a header
  4. 4Operation and purposeAllowed for this role
  5. 5State rulesReviewer identity, side, sealed test
  6. 6Open transactionRecheck contested grants

Workload authority has short clocks

30 sattempt heartbeat
90 sexecution lease, by database time
5 minworkload token lifetime
30 sprovider reconciliation
5 minorphan scan

Heartbeat loss causes investigation and stop behavior, never automatic admission of a replacement. A short token alone is not revocation, so every request also checks current attempt state and lease. A local watchdog stops work when renewal fails past 90 seconds, and a provider watchdog handles a process that ignores it.

Login, tokens and database context

Browser. Cognito authorization code with PKCE, state and nonce, through a maintained library. A __Host-session cookie with Secure, HttpOnly and SameSite=Lax. Keep only the token hash and expiry times on the server. Issue a new session at login and on any privilege change, and ask again before sensitive grants or exports.

Every write. A CSRF token and a checked origin, because a cookie alone gives no CSRF protection. Removing someone from a project blocks their next action, even if Cognito still knows them.

Database. Each request resolves an ActorScope, set with transaction-local settings. RLS uses USING and WITH CHECK. Test with the real app role, which is never an owner, a superuser or BYPASSRLS. Policies enforce tenants, and services enforce reviewer identity, sealed-test purpose and approved use.

Elevated functions. A security-definer function fixes its search_path, names objects in full, revokes public execution and gets its own review and denied-access tests. The environment never gets an open database connection.

Workers. Tokens are signed with an asymmetric KMS key and fixed algorithm, carrying audience, project, run, attempt, fence and purpose. A bootstrap secret is rotated per attempt, exchanged once and never in prompts or logs. A duplicate container cannot get authority after another has won.

05 / Commands

Every write has the same shape

All routes start with /api/v1.

A request carries

Idempotency key, 16 to 128 ASCII charsIf-Match with a positive revisionStrict versioned body, size-cappedRequest ID, server generated

A receipt returns

Resource IDsCommitted revisionAccepted stateStatus URL when async

An error returns

Stable code and messageRequest IDSafe field errorsNo stack, SQL or secrets

What the status codes mean

CodeWhenCodeWhen
201Creation complete409Business conflict, or same key with different payload
202Background work accepted412Stale If-Match
400Malformed422Schema validation
401No or expired session428Missing If-Match
403Known resource, disallowed operation429Rate or quota limit
404Other tenant's data, non-disclosing503Temporary dependency outage
Exact routes: what to send and what comes back
RouteSendGet back
POST /projectsBrief, mode, region, currency, capProject, state, decisions still missing
POST /projects/{project_id}/sidesUser and sideSide row, or side_conflict
POST /assignments/{assignment_id}/claimsKey. Eligibility is worked out by the server.Claim and lease expiry
PUT /tasks/{task_id}/draftIf-Match, content, asset IDsNew draft revision, saved time, issues
POST /tasks/{task_id}/submissionsExact draft revision, keyImmutable revision and digest
POST /assets/upload-intentsType, size, purposeShort-lived POST policy, server-chosen key
POST /assets/{asset_id}/completeUpload intentPinned version and scan state
POST /reviews/{review_id}/decisionIf-Match, revision, rubric, decision, reasonSealed decision and task state
POST /dataset-releasesRevisions, group splits, versions, useValidation job. Publishing is a second command.
POST /evaluationskind, protocol digest, models, sealed releaseEvaluation ID and frozen inputs
POST /training-runsFull manifest and digestsRun, config digest, validation job
POST /training-runs/{run_id}/approvalsDigest, baseline ID, reservation, retries, If-MatchApproval, reservation, queued state
POST /training-runs/{run_id}/cancelReason, keyDurable request. Repeats return the same one.
POST /attempt-reviewsSampled rollout, rubric, finding, evidenceSealed review and payable
POST /internal/attempts/{attempt_id}/startBootstrap proof, provider ID, token, fenceLease and scoped token, or a losing result
POST /internal/attempts/{attempt_id}/finalizeFence, manifest digest, evidenceValidation job. Complete comes later.
POST /deliveries/{delivery_id}/downloadsArtifact and purposeShort-lived link after a fresh rights check

All sit under /api/v1. The browser never picks its own author, reviewer, approver or storage key. Every response carries a request_id.

Critical commands and the event and artifact shapes
CommandNeedsCommits
Submit taskTask ID, exact draft revisionImmutable revision and digest
Decide reviewReview, target revision, rubric, decision, reasonSealed decision, acceptance, payables
Publish releasePassing report, digest, group splits, purposePurpose-specific manifests, release ID
Record baselineFrozen protocol digest, original model, releaseQueued baseline evaluation with its own reservation
Assign sideProject, user, sideOne side row. A second side returns side_conflict.
Approve runManifest digest, report, baseline ID, reservation, bounds, retriesApproval, reservation, queue. No GPU slot yet.
Submit attempt reviewSampled rollout, rubric, finding class, evidenceSealed review, payable, and any follow-up rework or quarantine event
Register lab laneAccount reference, role, bundle digest, passing rehearsal, attestationActive lane. Revocation is checked before each job.
Claim attempt startAttempt, token, provider ID, fence, bootstrap proofLease, or an explicit losing denial
Cancel intentRun revision, reasoncancel_requested, revoked new work, stop event
Finalize checkpointFence, step, sealed manifest, evidenceValidation job. Complete waits for the validator.
Request comparisonBaseline ID, frozen candidate, same protocol digestQueued intent with separate spend
Issue downloadApproved delivery, artifact, purposeShort-lived URL, checksum, size, expiry

Canonical JSON. Versioned, sorted keys, UTF-8, no NaN, duplicate keys rejected. Prefer RFC 8785. A concurrent duplicate waits or gets a bounded in-progress result, and cannot create a second effect.

Events. ID, schema version, aggregate and revision, project, time, correlation ID. Names like task.submitted.v1, task.accepted.v1, release.published.v1, run.approved.v1, attempt.finalization_requested.v1, evaluation.requested.v1, delivery.approved.v1. Never a prompt, weights, secret or signed URL.

Artifact reference. Allowlisted bucket, server-chosen key, pinned version, SHA-256, size, type, sensitivity, purpose and rights version.

06 / Task flow

Submit and accept, each as one transaction

STALE DRAFTCURRENT DRAFTAuthorReviewerControl APIPostgreSQLWorkerPayment runs by hand and is reconciledseparatelySubmit draft with If-Match and idempotency keyLock task, check draftrevision412, local edits are keptInsert immutable revision,event, receipt, then commit201, submitted revision IDDecide on the exact assignedrevisionLock task and review, verifyauthor differsDecision, acceptance,payable, audit, outbox,commitDurable receiptLater, claims accepted-workevent
Review queues never substitute the latest task for the assigned revision. Adjudication adds a linked record and never edits the original.

Lock the task before its review and assignments. Acceptance inserts the unique acceptance and each work item's payable under its agreed rule, because some contracts also pay for rejected or review work. No settlement call happens inside the transaction.

07 / Releases

Publishing a dataset fails on one defect

  1. 1CandidateExact revisions, versions, purpose, group splits
  2. 2ValidateOwnership, acceptance, rights, duplicates, solvability
  3. 3Build manifestsTrain, development, sealed test, judgment, separately
  4. 4Upload stagedVerify digests first
  5. 5PublishShort transaction, recheck, insert, outbox

A changed member invalidates the report, because publication needs the same input digest. Near-duplicate detection flags work for a reviewer, and cannot certify independence alone. Orphan staged objects have no authority and get cleaned up. A later quarantine blocks use through eligibility checks.

08 / Baseline

No training without a saved before

Evaluation ownerControl APIEvaluatorBenchmark expertsTraining sideA changed model, release, verifier or protocol invalidates the baselineFreeze protocol: original,release, metrics, limits. Nocandidate.Run the original ondevelopment and sealed tasksSame tools, limits and seeds policyfor both splitsFinalize baseline evidencemanifestDevelopment results and failure tracesSealed results, restrictedML operator requests run approvalReject unless baseline is completeand current
The protocol freezes with no candidate named, so a result cannot shape the rules it is judged by. Each side sees only its own baseline, and one GPU slot is still enough because this runs before training.

Baseline stays valid while

Same model digestSame release digestSame verifier versionSame protocol digest

A comparison then

Runs the candidate under the same protocol.

Pairs results by scenarioRerun the original only under a declared ruleReports fail to pass and pass to fail
09 / Budget

Approval reserves money before anything runs

A reservation covers

TrainingDeclared retriesPlanned evaluationStartup and stop contingency

Rules

Lock budget, then runQueued intent holds no GPU slotEvaluation draws a child allocationRecord overruns, never truncate

Preflight checks the real stack, rights, tool schema, token handling, gradient flow, save and reload, GPU memory and credentials, and binds a passing report to the exact digest. A database cap is an admission policy and no guarantee about provider billing. Keep reservations until every job and duplicate is reconciled.

10 / Dispatch

An unknown reply is not a failure

ACCEPTEDNETWORK TIMEOUTOperatorControl APIPostgreSQLDispatcherAWS BatchTrainerWeights load only after the lease is won. A loser exits, butits startup still costs money.Approve frozen run,bounded budgetLock budget and run,reserve, outbox,commitClaim slot, newattempt and fence,save intentSubmit allowlisted jobwith dispatch tokenProvider job IDRecord ID, state issubmittedMark dispatch_unknown.Do not resubmit.Reconcile tags, timewindow, job identityStart containerClaim start lease: attempt, provider ID, fenceAtomically admit onecurrent attemptLease and scoped token, or reject
The dangerous moment is a network timeout on submit. The job may exist, so the dispatcher reconciles and never blindly resubmits.

Consuming and reconciling

Outbox and queue

SKIP LOCKED batch with a leaseDuplicates expectedAck only after durable handling5 deliveries before dead-letterOne work-intent ID per event

Provider jobs

Provider auto-retries set to 1Match token, tags, lane, time windowJob name is an aid, not uniquenessRecord every discovered jobIf unprovable, hold the slot and alert

Lease expiry alone does not free the physical GPU slot, because a partitioned worker might still run. Reconcile and stop the old job, close the attempt, then allocate a new fence. Fencing protects accepted changes. It does not make an unreachable process disappear.

11 / State machines

A run, an attempt and a provider job are three things

The run is the intent. An attempt is one execution. A provider job is one observed cloud job, duplicates included.

draftvalidatingawaiting_approvalqueuedexecutingfinalizingcompletedReal update, reloadedcheckpointfailedExact reason recordedcancel_requestedcancelledJobs, sessions closedapproved recoverable next attempt
Winning the start lease moves a run from queued to executing. Completed means a valid technical result, and evaluation has its own state. Any new config means a new run.
ACTIVEpreparedsubmittingIntent savedsubmittedHas providerIDrunningWon the leasefinalizingCandidate uploadedsucceededValidationpasseddispatch_unknownAmbiguous replyfailedTerminalinterruptedTerminalcancel_requestedcancelledProviderstoppedIDleasereconcilesame jobinfralossfrom any activestateabsenceestablishedrejected,deadline,numeric orcorruptAn interrupted attempt never runs again. A new attemptunder the same frozen run may resume a verified checkpoint.
The word succeeded describes an attempt, and completed describes a run. Cancellation reaches cancelled only after the provider stops and resources close.
12 / Episodes

A timeout must never apply an action twice

Step arrivesLock episode firstAction ID seenbefore?Same payload?Expected sequencecurrent?Return the stored result, nomutationaction_payload_conflictApply state, journal, counters,receiptOne transactionepisode_sequence_conflictyesnoyesnoyesno
Checking the action ID comes first, so a retry after a lost response gets its old result even if the sequence has moved on.
OperationNeedsCommits
CreateActive lease and fence, permitted split, eligible task, capacityOne session, pinned fixture, seed, policy, schema, limits
ResetNew episode, verified fixtureInitial digest, sequence zero. A repeat returns the same state.
StepScope, schema match, open episode, budget, action ID, sequencePure transition, journal, receipt, safe observation
InspectSame episode and scopeCommitted, not found or pending
FinishOpen episode or already-frozen terminalFrozen state, termination reason, one verifier request
CloseOwner or expiry workerRelease capacity once, keep evidence
8sessions, initial default
20tool calls
120 sper episode
completedmodel-stoppedinvalid-actiontool-limittoken-limitwall-limitcancelledenvironment-errorverifier-error

Termination reasons are listed above. The last two are unscorable. Replaying fixture plus journal must produce the stored digest, and a mismatch blocks scoring and quarantines the environment version. If future tools have outside side effects, this atomic guarantee no longer holds, so do not hide that change inside step.

13 / RL contract

Zero reward and no reward are different things

Valid score

A real outcome. Zero is a legitimate failure.

Finite bounded totalComponentsVerifier versionState digest

Unscorable

Infrastructure failed. Nothing to learn from.

Typed error codeNo numeric totalNever enters a group

A rollout trace, validated field by field

FieldRule
ProvenanceRun, attempt, fence, group, revision, policy, tokenizer, template, environment, verifier. All in the manifest.
Prompt tokensInteger IDs in vocabulary. The actual input, not reconstructed text.
Completion tokensOrdered sampled IDs and turn boundaries. Empty generation is a recorded outcome.
Eligibility maskSame length. Prompt, observation and padding are zero.
Likelihood dataFinite values aligned to the exact tokens and policy. Never synthesized.
Episode resultOrdered actions, terminal reason, final digest, restricted evidence.
UsageTokens, elapsed time, action count, permitted cost estimate.

One optimization step

  1. 1BatchChoose tasks, freeze the policy version
  2. 2SampleDeclared attempts per task, 4 to start
  3. 3ValidateMembership, policy, masks, scores, limits
  4. 4DiscardA failed group goes whole, with a bounded retry
  5. 5OptimizeTRL's supported GRPO path
  6. 6RecordSettings, reward spread, tokens, parameter deltas

In the adapter recipe the base stays frozen. A zero-initialized adapter factor may show zero gradient early, so check the trainable set over the supported interval instead of requiring every tensor to move each step. Add vLLM only after synchronization tests, and pin an exact version of the integration.

14 / Attempt review

Paid experts help between runs, and scores stay put

People diagnose what the model did. The optimizer still changes the weights.

  1. 1Freeze sampleA recorded rule and seed, training split only. Include high scores.
  2. 2AssignTraining-side experts, with a rubric and an agreed rate
  3. 3ReviewA safe trace view, then a finding with evidence
  4. 4SealImmutable review and one payable
  5. 5ActRoute the finding through versioned work
FindingAction
valid_success
Count itSupports the audit of high-reward attempts.
model_failure
New training tasks for the next roundA new release means a new run, linked by parent_run_id.
task_defect
Rework the taskA new revision, reviewed again.
verifier_defect
Quarantine the verifierRun the verifier-defect runbook.
exploit
Pause the releaseFix under a new version and rerun affected comparisons.

Reviews never edit a score or feed a reward in the first recipe, because the reward stays deterministic. Demonstrations use the same assignment and pay path, and enter as a declared warm-start stage so the report can separate that gain from RL.

15 / Checkpoints

A success marker alone authorizes nothing

uploadingUnique attempt andstep prefixsealedShards and manifestverifiedvalidatingSeparate workerclaims itcompleteClean load,parameter evidenceabandonedinvalidlost lease orexpiredcorrupt orincompatibleEligibility isa separate recordQuarantine blocks use withoutrewriting validation history.
The manifest lists every shard, size, checksum, base revision, config, tokenizer and parent. A separate validator checks it all and loads the model in a clean process.

Resuming

New attempt, new fence.

Verify the checkpoint before buying computeRestore optimizer, scheduler, RNG, data position if testedDiscard in-flight partial groups

A new trajectory

Must be labelled as one.

Weights-only continuation

A new run

Or a reviewed separate phase.

Different model, data, reward, context, optimizer

Use a CPU worker for the first clean-load check. If a GPU loading check is needed, run it serially inside the current attempt after unloading the trainer, never as a hidden second GPU job. Do not promise identical bytes across GPU stacks. State supported versions, deterministic environment behavior and an evaluation tolerance.

16 / Evaluation

Separate job, separate role, frozen first

Evaluation ownerControl APIEvaluatorSealed testReport reviewerCustomerA download link cannot revoke a copy already savedBind the frozencandidate to thebaseline and itsprotocolStart authorizedevaluation attemptRead exact fixtureversions, evaluatorroleCompare matched scenarios, auditmissingnessFinalize metrics andevidence manifestRequest independent reviewApprove immutable report, or request correctionRequest approved artifactRecheck grant, rights, eligibilityShort-lived download and checksum
The protocol froze before the baseline, and only the candidate is new here. Benchmark experts audit and sign off before the report is reviewed. The evaluator cannot train, and the trainer cannot issue itself an evaluation token.

Report covers

Completion and audited completionRewardInvalid tools, violationsLatency, tokens, costSample size, missingnessUncertainty, regressions

Efficacy result

Separate from technical completion.

ImprovedRegressedNo clear changeInconclusive

Scenario groups are the independent units. The analyst picks a paired grouped method before seeing outcomes. An outage uses the predeclared rerun rule for both models. A published report never changes, and a correction links a new version. If final-test feedback informs tuning, retire that test for the new claim.

17 / Delivery and pay

Downloads and payments are checked, not assumed

Assemble

Second engineer loads it clean.

Only rights-permitted assetsExact versions, checksums, licensesAdapter plus exact base referenceA merged model is evaluated separately

Customer acceptance

Never inferred from a download.

AcceptedIssue raisedSupersededWithdrawn

Compensation is its own state machine

  1. ObligationRecorded on the agreed rule
  2. AdjustmentIf needed, approved
  3. InitiatedOutside this product
  4. SettledWith provider evidence
  5. Failed or reversedAppended, never overwritten

A duplicate reference cannot add a settlement twice. Currency mismatches go to review. An export file does not mean paid. Copies a customer already saved are governed by the agreement, because no system can delete them remotely.

18 / Lab lane

Running in a lab's account, in six steps

Built after the first delivery. See the HLD view.

  1. 1AgreeContract settles access, telemetry, ownership
  2. 2RehearseInstall the signed bundle in a separate test account
  3. 3InstallLab reviews and applies it with their keys
  4. 4AttestLab signs the checkpoint's checksums. No copy reaches us.
  5. 5RegisterA lane with its narrow role and bundle digest
  6. 6CloseRevoke the role, stop compute, record what stays

The same contracts

JobProvider gets a lab adapterStart lease, fence, watchdog unchangedFrozen manifests and sides unchanged

Changes for a lab lane

model_versions source is a lab attestationArtifact references point at lab storageReports state who could reach the test

Every job checks

Lane activeRole not revokedBundle digest matchesAttestation matches

If the role is revoked mid-run, dispatch and inspection stop at once. The local watchdog in the lab's account stops work when its lease expires, and the attempt stays unresolved until the lab confirms the stop.

19 / Data lifecycle

Deletion must survive a restore

LATER, AN UNRELATED RESTOREOperations ownerControl APIPostgreSQLDeletion workerS3 and backupsDelivered weights need a recall or retrainingassessmentScoped deletion with aretention decisionRecord it, block new use,trace descendantsWrite restricted deletion-register entryClaim the approved requestDelete current andnoncurrent versionsRecord evidence and backupexpiryRestore after a database incidentRead register beforereopening writesReapply blocks and completeddeletionsRecovery report and open actions
The register lives outside the restored database. Deleting a source does not untrain a model, so resolve withdrawal, retraining or retention explicitly.

Upload accepts

Bound to a presigned POST with a length limit.

TextJSONCSVPNG

Upload rejects

A clean signature scan never means safe to run.

ArchivesExecutablesActive HTMLMacrosRemote URLs

Bytes stay immutable. Rights expiry, quarantine and withdrawal are separate eligibility records, checked at every new release, run start, resume, evaluation and download. Long runs recheck at safe points and stop on material invalidation.

20 / Failure codes

Each failure family has one retry rule

CodeRule
authorization_denied, scope_not_found
No retryReauthenticate or get a legitimate grant.
revision_conflict, review_already_decided
Refresh and resolveNever overwrite.
idempotency_payload_conflict
Fix the callerNever apply the second payload.
asset_unapproved, rights_blocked, release_quarantined
BlockedUntil an authorized decision changes eligibility.
dispatch_unknown
ReconcileNever resubmit blindly.
provider_rejected, capacity_deadline
New approved attemptOnly after absence or stop evidence.
lease_stale, fence_stale, attempt_not_current
StopA worker cannot repair its own authority.
episode_sequence_conflict, action_payload_conflict
Inspect the actionThen decide. No duplicate write.
environment_unavailable, verifier_unavailable
Unscorable groupBounded declared retry.
trace_invalid, reward_invalid, nonfinite_training
Stop and investigateNo auto-fix or fabricated reward.
checkpoint_incomplete, checkpoint_load_failed
Keep unpublishedRetry transfer or make a new candidate.
budget_exhausted, runtime_limit
StopNeeds new explicit approval.
baseline_missing, baseline_stale
BlockedRecord a baseline for the exact inputs.
side_conflict
No retryUse another person, or a new project.
lane_revoked, attestation_mismatch
StopOnly the lab can restore access or re-attest.
5 sdatabase statement ceiling, to measure
2 scontested lock ceiling, to measure

A 429 or 503 may carry retry-after, and the client keeps the same idempotency key when it retries. A timeout on a write never justifies a new request ID.

21 / Client

The web app presents. It never decides.

It does not decide payability, approval, score or ownership.

ScreenMust behave like this
Task editorAutosave with If-Match, show saved time, keep the local edit on 412
ReviewShow the exact revision. Same idempotency key on a transport retry.
Release builderShow input digest and issues. Changes invalidate the report.
Training approvalFrozen config, cost bound, preflight. Changes create a new config.
Run detailPoll with backoff. Show waiting, unknown, active, interrupted, finalizing, cancelled, complete.
EvaluationSeparate completion from efficacy. Show sample size, uncertainty, missingness.
BaselineShow only the viewer's side. Mark a stale baseline and block approval.
Attempt reviewSafe trace, rubric, finding class. Never show or edit a score field.
DownloadsRequest on click, show expiry and checksum, handle revocation.
PaymentsShow owed, initiated, confirmed, disputed. No fake success animation.

Query keys include organization, project, resource and authorization context, and private caches clear on logout or project switch. Hidden buttons never replace API checks. Keyboard use, focus after errors, labels and readable mobile layouts are acceptance criteria.

Configuration and release operations
ApplicationPersistenceArtifact accessQueueExecutionRuntimeML recipeOperations

Validate config at startup and fail on a missing secret reference, schema version, endpoint, image or policy. Never fall back to a permissive local mode in production. Migrate by expand and contract with a dedicated role, and check active trainer callbacks too. A rollback of the image does not undo destructive data changes. Use GitHub Actions OIDC and keep real-cloud and budgeted GPU suites outside the fast CPU checks.

22 / Verification

32 tests, each with an action and an assertion

Unit tests cover pure rules. Real PostgreSQL covers constraints and races. Real cloud covers IAM and providers. Real GPU covers optimization.

L-01 to L-11, access, tasks, money and episodes
TestDo thisMust holdCovers
L-01Reuse a pooled connection across projectsScope does not leakR-52, 53
L-02Submit a draft concurrently, then change payloadOne revision, then a conflictR-08, 09, 46
L-03Accept as author through another roleAPI and database both rejectR-10
L-04Commit acceptance, crash before send, replayOne acceptance and payableR-05, 46
L-05Assign siblings to different splitsPublication names the membersR-12, 26
L-06Read test keys with trainer and environment rolesList, read, decrypt, API all deniedR-22, 27, 54
L-07Approve two runs on a near-empty budgetNo negative available amountR-38
L-08Force unknown submit, discover two jobsOne winner, slot held, costs keptR-47
L-09Expire a lease while the job still runsNo replacement startsR-45, 47, 49
L-10Repeat a lost action, then reuse its IDOriginal once, then a conflictR-15, 16
L-11Crash the environment around commitNo partial state, exact replayR-14, 18, 19
L-12 to L-22, training, evaluation and operations
TestDo thisMust holdCovers
L-12Supply bad reward, mask, policy or groupNo optimizer step uses itR-23, 33, 34, 36
L-13Train the real model on a remote GPUFinite delta, evidence, reloadR-31 to 36
L-14Corrupt a shard, finalize from an old fenceNeither becomes completeR-48
L-15Interrupt and resume full stateNew attempt, links, real costsR-37
L-16Race cancel against completionFirst commit winsR-49
L-17Lose control plane with a hung trainerWatchdog stops compute in boundR-38, 60, 63
L-18Evaluate with deliberate missingnessBoth follow the frozen ruleR-39 to 44
L-19Deliver to a clean environmentLoads, checks, reproducesR-50, 66
L-20Revoke access, replay a settlementNo new URL, no duplicateR-06, 51
L-21Delete, restore older DB, replay registerStays blocked before writes reopenR-57, 62
L-22Additive schema, then roll images backBoth versions operateR-59, 61
L-23 to L-32, the full engagement loop
TestDo thisMust holdCovers
L-23Approve a run with no baselineApproval rejectedR-67
L-24Change the verifier after a baselineComparison refused as staleR-68, 70
L-25Read sealed results as a training roleAPI, storage and report all denyR-69
L-26Grant a second side concurrentlyAPI and database both rejectR-71
L-27Add a training-side author to a sealed releasePublication failsR-72
L-28Build a sample that reaches test attemptsRejected, and the rule is recordedR-73
L-29Replay an attempt reviewOne review and payable, score unchangedR-74, 75
L-30Copy weights out with our role in a rehearsal accountDenied at storage and networkR-78
L-31Revoke our role during a runNo new jobs, watchdog stops workR-79
L-32Install a tampered bundleSignature check fails before startR-77
23 / Build order

Eleven slices, the riskiest first

Estimate dates after slice one. Actual RL, independent review, honest evidence and basic data protection stay required, even in the demo.

  1. One custom task, verifier and real RL runLock, schema, gradients, GPU profile, reload
  2. Identity, grants, schema, storage permissionsDenied-access matrix, pool-reuse test
  3. Agreement, claim, draft, review, payableFull path with race and retry tests
  4. Action journal, scoring, immutable splitsReplay, bypass tests, purpose manifests
  5. Baseline and the two expert sidesApproval gate, side conflict, sealed read denials
  6. Freeze, preflight, approval, outbox, dispatchUnknown-submit, stale authority, spend-stop drills
  7. Checkpoint validation, recovery, cancelCorruption, interruption, race on real compute
  8. Paid attempt review and linked roundsFrozen sample, one payable, score unchanged
  9. Sealed evaluation, report, clean deliveryFair comparison, audit, cost, loading
  10. Backups, deletion replay, handoff, second projectAnother engineer runs the runbooks
  11. Lab lane in a rehearsal account, then a real labNo-egress, revocation, tampered-bundle tests, lab review
Primary references
PreviousHLD