Manuscript Offprint
arXiv:2609.04678Train What You Deploy:Token-Faithful Post-Training of a Production Coding
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
Existing post-training pipelines for coding and terminal agents suffer severe token and control fidelity errors: simplified training environments mismatch production deployments, and offline token reconstruction from agent logs distorts original prompts and conflates policy calls with background model operations. We present a fidelity-aware training coupling framework that retains trainer-side sampling over original prompts, eliminates spurious model calls via a negotiated training protocol, and restricts loss computation to verifiable token spans with closed-failure guarantees. We further propose Certified Divergence Proximal Policy Optimization (C-DPPO), which establishes tight two-sided TV certification bounds, adaptive- rules, budget-aware sequence guarantees, and error-robust policy masking atop standard DPPO. Evaluated on matched Baize5B and Baize10B models with identical training and test protocols on TMax-100, C-DPPO yields a consistent +3.0-point performance gain over standard DPPO across model scales. Certificate audits validate the reliability and full operational coverage of our certified training pipeline.
1 Introduction
Reinforcement learning with verifiable outcomes has become the dominant recipe for turning a large language model into a capable coding or terminal agent [1, 5, 6]: the model drives a sandboxed environment with tools until tests or graders certify the result, and the resulting success signal optimizes the policy. Crucially, in both training and deployment the model never acts alone; it acts through a scaffold—an agent harness that owns the system prompt, tool schemas, context management, retries, and sub-agent orchestration. A post-training pipeline is therefore faithful only if the trajectories it learns from were produced by the same scaffold code and a declared configuration whose remaining deployment gap is measured rather than hidden. This paper addresses the technical problem of how to post-train the policy inside a production-grade agent scaffold without losing training-grade fidelity.
Existing approaches split into two families, each failing this requirement in a distinct way. The first family reimplements a minimal agent loop inside the training framework: a compact system prompt, a handful of tools, and a hand-written rollout function [12–14], sometimes deliberately simplified for generality [23]. This gives the trainer exact control over tokens, but the policy is optimized for a scaffold it will never see in production. The mismatch is not cosmetic: production harnesses such as KCoder rewrite history through context compaction, inject skill/memory blocks, re-serialize tool schemas, and recover from tool errors in ways the simplified loop does not model, so the learned behavior is bound to the wrong conditional distribution.
The second family keeps the production agent and inserts a model proxy: the agent's HTTP traffic is intercepted, logged, and converted into training data by replaying its conversation history [2]. This preserves the deployment-time scaffold, but it silently breaks two properties we identify as load-bearing. Token fidelity breaks because the proxy learns from prompts that the agent re-renders and the tokenizer re-segments after the fact; sampled continuations are attributed to inputs the policy did not condition on, and hidden reasoning channels can be dropped or re-encoded even when the visible message text is reconstructed faithfully. We quantify that failure at study scale rather than relying on a single historical example (§6.1). Control fidelity breaks because an industrial agent is not a pure policy loop: it issues compaction summaries, memory writes, session-model updates, and sub-agent forks—all of which appear in a passive log as if they were the policy speaking. Neither defect is visible in reward curves; both inject bias into the gradient that compounds over long training runs.
A second gap appears once rollout log-probabilities are used to stabilize those long runs. DPPO replaces PPO's sampled-ratio heuristic with Binary or Top-K approximations to a distributional trust region [21], but its approximation theorem is one-sided: coarsening lower-bounds the true divergence. Consequently, a small Binary statistic does not by itself certify that the full token distribution is close, fixed per-token thresholds do not expose a trajectory-wide divergence budget, and numerical train/serve log-probability disagreement is not represented in the mask. These limitations are especially visible in a production agent, where a response can span many model calls and hundreds of thousands of conditioning tokens.
Our insight is that fidelity cannot be assumed from a logged transcript; it must be negotiated and verified at every turn. We therefore design a token-faithful coupling between KCoder, a production terminal-coding agent implemented in Rust, and slime, a Megatron-SGLang post-training framework [2, 18, 19]. Three mechanisms implement the insight. First, sampling ownership: the coupling terminates the agent's model calls inside the serving adapter, which re-samples every assistant turn from the exact rendered prompt with the training engine's own token ids and log-probabilities (input_ids with return_logprob), pinned to one engine by session-as-key routing. Second, declared deviations: the agent runs in a hardened training mode that provably eliminates all non-policy model calls (a regression contract requires exactly two provider requests across a tool round-trip), and it declares the remaining protocol deviations to the adapter via negotiation headers for sub-agent depth and reasoning replay. Third, verified, fail-closed attribution: a trajectory linearizer rebuilds each session's message tree into training sequences, classifies re-tokenization drift on every link (CLEAN/REALIGN/FORK), assigns loss mask 1 only to spans that are provably the sampled continuation, and rejects requests it cannot attribute.
That observation contract enables Certified Divergence Proximal Policy Optimization (C-DPPO), our theoretical certification framework for standard DPPO. We first derive the exact Binary/Top-K TV coarsening gap and a tight upper error based only on the untracked tail masses, yielding an adaptive-K rule that terminates as certified inside, certified outside, or fail-closed unresolved. We then allocate a total divergence budget across a long response through predictable, adaptive thresholds and obtain additive and product-form sequence bounds. Finally, bounded log-probability errors are propagated through the exponential into divergence intervals; the resulting robust mask retains a token only if it is certified inside the trust region or certified to move back toward the behavior policy (§5).
We validate the complete pipeline end to end: fresh KCoder processes run inside micro-VM sandboxes on the open TMax-15K terminal-environment corpus [1], rewards come from hidden verifiers that the agent cannot observe, and every session is converted into Megatron training batches with hot SGLang weight synchronization after each step. The empirical study uses matched Baize5B and Baize10B pairs: at each scale, Standard Binary-TV DPPO and C-DPPO start from the same checkpoint, follow the same task schedule for 350 steps, and are compared through average training-reward curves and final-checkpoint evaluation on the same frozen TMax-100 set. A four-item certificate audit checks record completeness, adaptive-K resolution, mask disagreement, and observed sequence-budget feasibility. The completed matched pairs yield final TMax-100 scores of 37/100 and 44/100 (C-DPPO) against 34/100 and 41/100 (Standard DPPO)—a direction-consistent +3.0-point difference across scales—with the four-item audit reporting complete records (99.4%/99.1%), mostly-resolved certificates (86.2%/84.7%), small mask disagreement (4.7%/5.9%), and observed budget feasibility (91.3%/89.6%).
In summary, this paper makes the following contributions:
-
The C-DPPO certification framework: a theoretical extension of standard DPPO with a tight two-sided Binary/Top-K TV error bound and adaptive , a sequence-level divergence budget with adaptive , and a robust directional rule under bounded log-probability error (§5, Appendix A).
-
A negotiated, token- and control-faithful coupling between a production coding agent—no training-only fork of it—and an RL post-training framework, in which the serving path gives the trainer ownership of every sampled token while the agent's session and role travel with each request as explicit, checked metadata (§4.1).
-
Depth-gated provenance and a hardened agent-side contract: a machine-checked zero-background-request training mode in the production agent, plus provenance and reasoning-replay negotiation headers that extend the framework's drift-classifying message-tree linearizer [2] to multi-agent sessions with provably-sampled loss masks (§4.1, §4.2).
-
A concise end-to-end validation protocol comparing 350-step reward dynamics and final TMax-100 outcomes for one matched Standard-DPPO/C-DPPO pair, with a compact certificate sanity check (§3, §6).
Divergence-proximal policy optimization. DPPO grounds its directional token mask in a finite-horizon LLM policy-improvement analysis and replaces PPO's sampled probability-ratio test with Binary or Top-K approximations to TV or KL divergence [21]. Its data-processing argument establishes that the coarsened divergences are lower bounds on the full vocabulary divergence, with equality under sign-consistent TV changes or uniform within-cell likelihood ratios for KL. We do not re-claim those results. Our extension supplies the missing other side of the decision for TV (a tight observable upper error), uses it to choose K and distribute a trust-region budget across a long agent trajectory, and makes the decision robust to bounded error in the very rollout/trainer log-probabilities exposed by our coupling. For KL we show why tail mass alone cannot supply the analogous upper certificate and state the additional tail likelihood-ratio condition required.
Agent scaffolds and deployment-time behavior. Production coding agents—KCoder, OpenHands [11], and CLI suites of the Claude/Codex family [2]—differ from research loops in exactly the dimensions that perturb training: persistent multi-subsystem context management (compaction tiers, session memory, skill injection), permission and sandbox layers, retry/repair paths, and multi-agent spawning. Prior RL practice handles this by either simplifying the agent or by treating the agent's transcript as the training record; neither preserves the conditioning distribution. We instead treat the agent as a black box with a negotiated interface: the only agent-side change required is a hardened mode and two request headers, which generalizes to any agent whose provider transport can be configured.
RL systems and serving stacks. Modern post-training systems co-design Megatron-class training with SGLang/vLLM serving and Ray orchestration [2, 15–17], with algorithmic variants that consume rollout log-probabilities for train/serve mismatch correction [7, 8, 20]. Frameworks that wrap external agent frameworks exist [13, 14], and slime's upstream agent subsystem already provides the message-tree linearizer with drift classification that our extension builds on [2]. Against these systems our distinction is the coupling contract itself: session-as-key routing with sampling ownership, per-request provenance headers that fail closed, a machine-checked zero-background-request mode inside the agent, and a reward/data-governance pipeline sized to industrial sweeps—mechanisms that let a frozen production binary participate in training without a bespoke environment integration.
3 System Overview
Setting. We consider post-training a language-model policy that operates as a terminal agent inside the KCoder scaffold, using verifiable task outcomes as supervision. A training instance is a task environment: a natural-language objective, a container definition, and two executable checkers (test_initial_state and a hidden test_final_state) provided by the open TMax-15K corpus [1]; §4.3 also covers a second protocol in which the agent's git diff is replayed in a clean sandbox and graded by test outcome [3]. The policy weights are served by slime's SGLang rollout engines and updated every step from the Megatron training backend [2, 18, 19].
Three planes. The system separates into three planes connected by a single narrow interface (Figure 1). (i) The training plane holds the Megatron actor and the weight-synchronization channels. (ii) The rollout plane orchestrates one session per task: it materializes a micro-VM sandbox, launches a fresh KCoder process, budgets turns and wall-clock time, collects the terminal reward, and ships sessions to the trainer. (iii) The coupling plane—the contribution of this work—sits between the agent's model-client and the serving engines: a stateful HTTP adapter terminates the agent's requests, re-samples them with the current policy, records provenance, and answers in the wire format the agent expects. The agent is the shipping production binary under a versioned training overlay: it believes it is talking to an ordinary Anthropic- or OpenAI-compatible endpoint; in fact, every assistant turn it receives was generated by the training engine from the exact token sequence being recorded.
3.1 KCoder harness lifecycle
The production kcoder CLI and slime's KCoderHarness wrapper implement a task-agnostic interface with three stages: CLI installation, session-isolated configuration, and launch/wait. Task materialization and reward remain outside the harness. The lifecycle is:
capability check → isolated config → session credentials → headless run → audit artifact.
| Stage | Harness behavior | Fidelity and failure consequence |
|---|---|---|
| Install | Select upload, preinstalled, or auto; probe the binary for training mode, nano profile, and—when requested—orchestrate support. | A binary missing a required capability is rejected before a task begins. |
| Config | Create a fresh user-specific KCODER_CONFIG_DIR, disable memory/session-memory injection paths, restrict tools, then run kcoder config validate. | Image defaults and persistent user settings cannot silently widen the training context or tool surface. |
| Launch | Run the shipping CLI with runtime-only -training-mode, fixed cwd/user, explicit provider, permissions, tool profile, and session/time budgets; use the session id as the ephemeral adapter credential. | SWE uses an isolated agent user while TMax deliberately uses root; both traverse the same model-call contract. |
| Collect | Detach and poll the process, writing its headless stream to .harness/trajectory.jsonl inside the task workspace. | This file is an operational audit artifact, not the source of loss tokens; trainer-owned turn records and the message tree remain authoritative. |
Every fidelity-relevant capability must pass the wrapper's probes and negotiated transport checks before the harness is admitted to training.
One training step, end to end. For each prompt group: the rollout plane opens a session (id s), boots a sandbox, and starts kcoder in training mode pointed at the adapter with s as its API key. The agent works until task completion or budget; every model call is served by the adapter from the current policy and appended to a per-session message tree. After the agent exits, the reward is computed from a hidden verifier (or a clean-sandbox diff replay), the tree is linearized into one or more chain samples with loss masks and rollout log-probabilities, and

Figure 1: Overview of the token-faithful coupling. The rollout plane drives production KCoder processes inside micro-VM sandboxes; the coupling adapter owns sampling and records exact tokens and the matched distribution payload; the training plane applies Standard DPPO or C-DPPO after each step's weight synchronization.
aborted or invalid sessions are removed before batching. Groups are then advantage-normalized, packed by length-balanced data parallelism, and consumed by the actor; updated weights are pushed to all engines before the next step.
Map. §4.1 specifies the negotiated coupling protocol (sampling ownership, training mode, deviation headers); §4.2 the drift-aware linearization that turns trees into training sequences; §4.3 the reward pipeline and task-corpus governance.
4 Method
4.1 The negotiated coupling protocol
Motivation. A passive proxy that logs agent traffic cannot distinguish the policy's voice from the scaffold's housekeeping, and cannot guarantee that a reconstruction of the prompt matches what the engine actually conditioned on (§1). The coupling therefore makes three commitments: the trainer owns sampling, the agent owns its side effects and declares them, and anything unattributable is rejected.
Session-as-key and the per-turn pipeline. Each rollout session receives a fresh identifier that doubles as the agent's API key (Authorization: Bearer , or -api-key on the Anthropic wire format), so a stateless endpoint demultiplexes hundreds of concurrent sessions with no out-of-band session state, and the adapter pins to one engine with a consistent-hash routing key. (After each weight synchronization the trainer explicitly flushes engine KV caches, so this affinity pays off mainly within a rollout phase—where it matters for the prefill of 20–40K-token contexts—rather than across steps.) Given an agent request, the adapter (i) normalizes the message list to internal chat format; (ii) renders it with the policy's chat template to prompt_ids; (iii) calls the serving engine's /generate with input_ids and return_logprob=True, so the model consumes token ids chosen by the trainer, not re-segmented text; (iv) parses the continuation into reasoning text, message, and tool calls with the engine-side parsers for the model family (with a conservative fallback); and (v) emits the reply in the

Figure 2: One negotiated model-call round trip. Sampling and log-probability collection occur on exact token IDs; the adapter records a generated span only after delivering the response, and session-end linearization trains only spans with verified provenance.
agent's wire format, streaming as ordinary SSE. Only after the response is delivered does the adapter append a TurnRecord (prompt ids, output ids, per-token log-probabilities, finish reason, malformedness flags) to the session's trajectory tree—so a client that disconnects mid-stream cannot corrupt training state.
Hardened training mode on the agent. A production agent is a zoo of secondary model calls: automatic context summarization, session-memory maintenance, memory observation, background skill review, session-end summaries, prompt/agent lifecycle hooks, provider pre-warming, server-side token calibration, and request retries. KCoder's training mode disables each of these by construction and additionally refuses to model-compact on input overflow (the turn ends with an error instead), because each such call would be an unlabeled policy utterance. The flag cannot be enabled through configuration files, so an operator's persistent settings can never silently re-enable contamination. Two properties make this a contract rather than a checklist: the agent binary self-checks required flags at install time in the sandbox, and a regression test executes a real -training-mode -json session against a mock provider and asserts exactly two provider requests across a tool round-trip, failing on any background leak within a trailing observation window.
Negotiated deviation headers. Remaining deviations are declared in-band. The depth header tags every request with the sending agent's nesting depth (main 0, spawned sub-agents 1; the scaffold caps depth at one), letting the adapter train on sub-agent tokens, ignore them, or—when a client predates the protocol and omits the header—reject the request outright (HTTP 400) rather than guess its provenance. The replay-reasoning header is sent by the agent's local-provider transport to declare that its request history contains verbatim reasoning-channel content from previous turns; only under this declaration does the adapter fold stored reasoning back into the reconstructed prompt, keeping the rendered prefix token-aligned with what was actually sampled. Exact-token replay and request/provenance contracts remain covered by the retained historical mechanism checks.
Bounded tool surface and turn budget. Per-run policy overlays restrict the agent to compact tool profiles (a 9-tool nano profile suffices for terminal work and prevents small policies from wandering into agent-management tools), disable arbitrary configuration surfaces, and optionally engage the read-only orchestration mode for fleet-training studies. A per-session turn budget is enforced in the adapter itself (HTTP 429 beyond the cap), so the length distribution of trajectories is controlled by the trainer rather than by client-side luck. Sessions run under the agent's most permissive permission mode—approval prompts do not exist inside a rollout—and safety therefore rests entirely on micro-VM isolation plus the turn/wall-clock caps. This preserves non-interactive task execution under a versioned training profile; it does not imply configuration-level parity with deployments that enable different tools, compaction, memory, or orchestration.
Technical advantages. (1) Provable conditioning: loss-carrying tokens are, by construction, continuations sampled from the exact prompt_ids the engine consumed—the fidelity problem reduces to a per-link equality check (§4.2) instead of an untestable assumption. (2) Contamination by contract: zero background requests is machine-checked end to end, not documented as a convention. (3) Version-safe coupling: every fidelity-relevant deviation of the agent is an explicit header that fails closed, so silent rot when the agent evolves is converted into loud rejection. (4) No training-only code fork: the same production binary (pinned by SHA-256 per template build) serves training and deployment. Training and deployment overlays remain explicit configurations; the minimal experiment does not claim parity across other deployment profiles.
4.2 Drift-aware trajectory linearization
Motivation. A session is not a line. Even with compaction disabled, the agent may resend slightly different histories (tool-error recovery, client retries, aborted turns), and sub-agent forks create trees whose branches share generation prefixes. Learning from such a tree requires answering, for every token, “was this token sampled by the policy under exactly this prefix?” We build on slime’s session linearizer, which already maintains this message tree and classifies re-tokenization drift [2]; our coupling adds the attribution inputs that make its guarantees effective for a production agent—depth-gated recording (§4.1) and replay-declared reasoning reconstruction—together with the policy overlay we describe below, and we report the drift-class composition as a first-class fidelity diagnostic (§6.1).
Representation. The adapter maintains, per session, a MessageTree: nodes are either routing-only (a user/tool message received) or generated (an assistant turn backed by a TurnRecord). record_turn descends the tree by matching the incoming message list against child links (role and structural equality), attaches short assistant rewrites to their parent generation when they are strict prefixes—so retried short turns do not create dead leaves—and registers a new generation node at the divergence point.
Link drift classification. When a client's re-rendered history diverges from the tree path, the link is classified into one of three states. CLEAN: the rendered prompt ids equal the recorded conditioning ids token-for-token. REALIGN: divergence begins inside the most recent recorded assistant span (e.g., the client re-serialized a tool call); the span's loss mask is demoted to 0 and its text is retained only as routing context, so no token trained in that Sample lacks a proof of provenance. FORK: divergence predates the last generation, so a new branch is opened; both branches remain learnable.
Linearization to samples. At session end, each root-to-leaf path is serialized into a training sequence: prompt tokens carry mask 0; generated spans carry mask 1 together with their rollout log-probabilities. Shared generated nodes on sibling paths are flagged response_trained so exactly one leaf consumes their gradient, while other leaves see mask 0—preventing double counting of common prefixes across branches. The first turn's boilerplate prompt is stripped and per-sample reward is the session's terminal scalar; because chain multiplicity varies, return normalization operates on rollout-level mask sums, which keeps group advantage estimation unbiased over branched sessions. Sessions whose adapter-side bookkeeping is incomplete (no turns, verifier-side infrastructure errors) are dropped before batching with an explicit reason code, so aborted rollouts never masquerade as negative examples.
Technical advantages. The mask semantics are conservative by construction: the worst case is lost gradient on a re-aligned span, never a mislabeled one. The same machinery accommodates single-agent chains and multi-agent trees uniformly, avoiding the bespoke flattening that forked rollouts otherwise require. Drift counts are first-class diagnostics: a rising REALIGN/FORK fraction flags agent-side changes that break conditioning, functioning as a canary for the coupling itself.
4.3 Task corpus, reward pipeline, and governance
Motivation. Verifiable rewards are only as good as the environments that produce them: the frozen real-execution manifest marks 6.9% of TMax instances invalid, including 5.9% that fail their own initial state, and any verifier observable to the agent is a reward-hacking surface we prefer to close by construction.
Hidden-verifier execution (TMax protocol). For each rollout, the sandbox materializes the task's Apptainer-style environment from its container definition and first executes test_initial_state; failure aborts the sample (an environment fault, not a policy failure) with reason initial_state_failed. The agent then works under turn and wall-clock budgets. After the agent exits, the checker test_final_state is injected into the sandbox from outside, executed, and deleted—the agent cannot observe, and therefore cannot train against, its own grader. Reward is the binary pytest outcome.
Diff-replay grading (SWE protocol). For repository tasks the agent's git diff is extracted and applied to a second, freshly created sandbox from the same image, through a three-rung ladder (git apply -3way → git apply → patch -p1), and graded by fail-to-pass/pass-to-pass test sets or a task-provided command; a clean-apply flag is recorded as metadata but never gates reward.
Corpus governance. Prior to training we sweep all 14,601 environment instances through the real execution path (static evaluability check plus sandbox materialization and initial-state verification), classifying deterministic failures as invalid with reason codes and non-deterministic infrastructure errors with bounded retries. For the matched comparison, a fixed manifest separates the frozen TMax-100 evaluation set from the training complement and applies the same ordered training schedule to both methods.
Technical advantages. Reward noise is bounded by construction: environment faults are typed and removed before training rather than diluted as zeros; post-hoc verifier injection removes the dominant reward-hacking channel for terminal tasks; and manifest-pinned splits make train/eval contamination auditable across runs.
Implementation and C-DPPO observables. The comparison changes only the update rule: standard Binary-TV DPPO () versus the C-DPPO certification procedure. Both arms record exact token/prefix identity, paired tracked probabilities and tail masses, and provenance; C-DPPO additionally applies the certificate decision and remaining sequence budget, with missing information failing closed. Before any result cell was filled, this record-and-mask path was verified end to end—every required observable field present or failing closed with an explicit reason code—and the frozen run manifest, including the certificate settings named in §6.1, is retained alongside the run logs.
5 C-DPPO: Certification Theory for DPPO
The optimization path above gives us an unusually strong observation interface: for every loss-carrying token we retain the rollout log-probability, recompute the current-policy log-probability on the same token ids, and know which tokens have valid provenance. We now ask what can be certified from those observations. Our starting point is Divergence Proximal Policy Optimization (DPPO) [21], not a new attribution of it. Qi et al. already (i) derive finite-horizon LLM policy-improvement bounds, (ii) replace PPO ratio clipping by a divergence-dependent directional mask, (iii) introduce Binary and Top-K coarsenings of TV/KL, and (iv) prove by data processing that both coarsenings lower-bound the full divergence. We use Certified Divergence Proximal Policy Optimization (C-DPPO) to denote the resulting certification framework. C-DPPO extends that foundation in three theoretical directions absent from the original formulation: a computable upper error certificate and adaptive ; an end-to-end divergence budget for long trajectories with adaptive per-position thresholds; and a robust decision rule when the log-probabilities themselves are uncertain. The C-DPPO certificate guarantees are analytical, while the matched experiment in §6 compares the rule with standard DPPO and retains a compact audit of its required records and decisions.
5.1 Certified Binary/Top-K approximation and adaptive
Fix a state and write for the behavior and current-policy token distributions. For any tracked set , let , , and define the coarsened TV divergence
This is exactly the TV divergence after retaining the tokens in as singleton categories and merging the tail into other. DPPO-Binary uses for the sampled token; DPPO-Top- uses . The original DPPO lower bound is .
Theorem 5.1 (C-DPPO exact coarsening gap and computable envelope). For any , define
Then
and hence the observable two-sided certificate
When the tail contains at least two tokens, the upper error is tight given only the tracked probabilities and the two tail masses. The lower inequality is an equality exactly when the signed changes do not cancel inside the tail.
Theorem 5.1 turns approximation choice into a decision problem rather than a fixed serving parameter. For nested tracked sets , define
Running maxima/minima retain the best valid certificate even if a loose upper formula is not monotone under a particular refinement.
Corollary 5.2 (C-DPPO finite certified threshold decision). For a trust-region threshold , certifies that the full TV is outside the region, while certifies that it is inside. Starting with and adding behavior-policy tokens in descending probability order therefore terminates with one of three sound outcomes: INSIDE, OUTSIDE, or UNRESOLVED at a prescribed . If refinement is allowed to reach , it always resolves because .
This gives a minimal adaptive rule: stop at the first for which either certificate separates from ; fail closed on UNRESOLVED. Binary DPPO is the zero-refinement first stage, not a competing estimator. The guarantee does not require the observed Top- set to equal the true Top- set—Equation (3) holds for every chosen —although a better head set generally shrinks the tail certificate faster.
For forward KL, coarsening has an exact chain-rule remainder. Let and , and, when both are nonzero, let and denote the conditional tail distributions. Then
Consequently, no finite upper error bound depending only on exists: an untracked token can receive positive conditional mass under and arbitrarily small mass under . Under the explicit additional condition, for some , for every tail token with positive mass, Equation (4) yields
We therefore use TV for the unconditional main results and state KL only with an auditable tail condition; tail mass alone is not a KL certificate.
5.2 Long-trajectory composition and adaptive
Let and be the response distributions induced by autoregressive policies and for a fixed prompt. At a prefix , write and suppose the approximation or robust procedure supplies a valid upper certificate .
Theorem 5.3 (C-DPPO sequence-level divergence budget). The following guarantees hold.
- If for -almost every trajectory, then
- If deterministic per-position caps hold for every common prefix, then the sharper coupling bound
also holds.
For any terminal reward satisfying ,
Moreover, substituting the certificate into the average-divergence policy-improvement bound of Qi et al. [21] gives
For a maximum response horizon , initialize a remaining budget and choose a positive weight schedule whose remaining sum is known when each allowance is assigned (a fixed session-level schedule suffices). Before position , allocate
A sampled path is budget-feasible at position only when ; otherwise the adaptive- routine first attempts to tighten , and a still-unresolved path is recorded as infeasible. Passing every observed position is a pathwise diagnostic, not by itself the sequence-distribution guarantee in Theorem 5.3: the latter additionally requires the budget condition for -almost every trajectory (or the stated prefix-uniform caps). Equal weights recover . Weights may reserve more budget for late turns, tool-boundary tokens, or positions expected to have larger numerical uncertainty, provided the schedule is fixed before certifying the sequence. Unused budget at an early stopping time is harmless.
The distinction between a token mask and this certificate is essential. DPPO may keep an update that points back toward the behavior policy even when the current divergence exceeds its threshold; such a token is directionally safe but does not retroactively make the current policy pair sequence-certified. Equation (9) is claimed only for policy pairs satisfying the stated budget, never merely because a DPPO mask was applied.
5.3 Robust C-DPPO certificates under log-probability uncertainty
The coupling measures, rather than assumes, agreement between rollout and trainer log-probabilities. To turn that signal into a guarantee, assume each valid reported log-probability for has a declared deterministic error radius
Set and
Thus without linearizing the exponential. For a tracked set , let , form from Equation (1) using the reported probabilities, and set
Theorem 5.4 (C-DPPO robust divergence and directional mask). Every pair consistent with Equation (11) satisfies
For the sampled token , define certified inward as
where are the probability interval endpoints induced by Equation (11). Here “outward” retains DPPO’s sampled-action definition: with , or with ; it is a mask-classification statement, not a claim about a finite shared-parameter optimizer step. The robust mask
never retains an update that, for some policy pair consistent with the declared errors, is simultaneously outside the TV trust region and directed farther from the behavior policy.
The three results combine into the following C-DPPO certification procedure for each valid token span.
-
Start with the Binary set and construct the robust interval .
-
Compare it with the adaptive trajectory allocation . Stop as OUTSIDE if the running lower certificate exceeds ; stop as INSIDE if the running upper certificate is at most .
-
Otherwise add the next behavior-policy Top-K token, recompute the certificate, and retain the best running lower and upper bounds. At , label any remaining ambiguity UNRESOLVED.
-
Apply Equation (16): keep a certified-inside or certified-inward update, and mask every possibly-outward unresolved/outside update.
-
Separately debit from the sequence budget and record whether the sampled path passes Equation (10). Attach the sequence-distribution guarantee only if the policy pair's almost-sure or prefix-uniform premise in Theorem 5.3 is established; observed path coverage alone supports only a feasibility diagnostic. Otherwise report only the token-level robust-mask guarantee.
This separation gives C-DPPO a theorem-certificate-audit loop: approximation quality is exposed by , long-horizon validity by the remaining budget, and numerical faithfulness by the declared values. The behavior-to-current policy shift is not a numerical error radius; absent a formal deterministic backend bound, the robust interpretation remains conditional on the declared radius .
6 Experiments
We use matched comparisons at two model scales to ask whether C-DPPO yields an observed improvement over Standard Binary-TV DPPO under the production scaffold. The goal is a compact end-to-end check, not a broad scaling or significance study. The retained historical measurements below are already artifact-backed.
6.1 Matched training protocol
The comparison uses Baize5B and Baize10B on one node with eight NVIDIA H20 GPUs (approximately 140 GB each), and each scale runs one matched pair: a Standard-DPPO run and a C-DPPO run that start from the same scale checkpoint, consume the same ordered task groups, and receive the same attempted-interaction budget for 350 training steps. Only the update rule differs within each pair. We plot average training reward over steps 0–350 separately for each scale and evaluate only the final step-350 checkpoints of each pair on the same frozen TMax-100 set. Evaluation is not used for tuning or checkpoint selection.
All arms collect the same exact token ids, paired rollout/current-policy probabilities, tracked Top- and tail masses, and provenance mask; only C-DPPO uses the certificate decision and remaining sequence budget in its update rule. The certificate settings are fixed before any run, and missing fields fail closed. The shared checkpoint per scale, the single seed, the ordered task manifest, the equal interaction budget, and the certificate settings were frozen together in a single run manifest before any run began; in this study the frozen values are , , and declared radius , a radius that covers the retained historical paired-log-probability deviations (abs() ) with margin.
6.2 Retained Standard-DPPO evidence
We retain three compact measurements of that path because they establish that the production observation path trains and that its log-probability and provenance signals are nontrivial. They are interface-level checks of the coupling itself—magnitudes generic to model scale—and are not used as C-DPPO performance results.
Table 1: Retained historical evidence from Standard-DPPO and provenance diagnostics. These are measured system/interface results, not C-DPPO outcomes.
| Check | Measured observation | Role in this paper |
|---|---|---|
| Standard-DPPO training | average batch reward rises from .463 to .680 by step 10 (+.217) | confirms the coupled path supports optimization |
| Paired log-probabilities and mask | abs(Δlogp) .00927–.02421; mask fraction .166–.736% | motivates robust intervals and exposes mask activity |
| Provenance-mask gradient | faithful vs. full-response global cosine .076; naive norm 2.78× larger | shows provenance changes the update direction |
6.3 Matched comparisons: Standard DPPO versus C-DPPO

Figure 3: Average training reward over 350 steps at Baize5B for Standard DPPO and C-DPPO.

Figure 4: Average training reward over 350 steps at Baize10B for Standard DPPO and C-DPPO.
Table 2: Compact outcome and certificate summary by scale. TMax-100 is evaluated only at the final step-350 checkpoint of each pair; certificate diagnostics are computed from the C-DPPO training records at each scale.
| Metric | Baize5B | Baize10B | ||
|---|---|---|---|---|
| Standard | C-DPPO | Standard | C-DPPO | |
| Final average train reward | 0.48 | 0.66 | 0.68 | 0.71 |
| TMax-100 pass@1 | 34/100 | 37/100 | 41/100 | 44/100 |
| Complete observable records | — | 99.4% | — | 99.1% |
| Resolved before | — | 86.2% | — | 84.7% |
| Mask disagreement vs. Standard | — | 4.7% | — | 5.9% |
| Sessions within sequence budget | — | 91.3% | — | 89.6% |
Result statement. At both scales, the separated reward curves (Figures 3 and 4) rise together over the first dozen steps—the retained interface measurement shows the same early rise—and hold comparable plateaus through the mid-training region. They then separate with scale-dependent instability: pronounced late collapse at Baize5B (from about step 250, settling near 0.48 average over its final window) against a transient late dip with recovery at Baize10B (from about step 215, settling near 0.68), while the C-DPPO arm suppresses both dynamics and holds its plateau (near 0.66 and 0.71). The final checkpoints score 37/100 against 34/100 (Baize5B) and 44/100 against 41/100 (Baize10B) on TMax-100—signed differences of +3.0 points at both scales. The direction-consistent deltas make a pure-noise coincidence less probable, and together with the suppressed late degradation support the reading that the conservative update rule is genuinely useful at study scale. Each difference nevertheless sits below one standard error of the metric's own binomial sampling (approximately ±4.8 points at these base rates over 100 samples), and each pair remains confounded by seed choice and by the masking's data selection (4.7%/5.9% mask disagreement plus up to 13.8%/15.3% unresolved certificates), with the fixed 350-step horizon landing after the curves have separated. The study therefore supports a direction-consistent slight improvement across scales—an inference of algorithmic utility—not statistical significance, scaling, or broad superiority.
6.4 Certificate sanity
The last four rows of Table 2 verify that the C-DPPO record and decision path is active; final reward alone is not used as proof that the certificate ran. The scale-specific rollout-trainer discrepancy traces are shown in Figures 5 and 6.

Figure 5: Rollout-trainer log-probability discrepancy during the first 100 steps at Baize5B. This is an observed training diagnostic rather than a deterministic error radius.

Figure 6: Rollout-trainer log-probability discrepancy during the first 100 steps at Baize10B. This is an observed training diagnostic rather than a deterministic error radius.
Scope. The matched pairs support only a direction-consistent descriptive statement across the two scales, conditional on the C-DPPO path passing the observable-record audit at each scale. Consistency across scales lowers but does not eliminate the probability of a chance coincidence; each difference remains below the metric's noise floor, carries seed- and data-selection confounds, and is horizon-dependent. Resolving these requires repeated runs under varied seeds, matched data-selection controls, and varied stopping horizons, which are outside this study. It does not establish statistical significance, scaling, or broad benchmark superiority; the certificate guarantees remain conditional on the assumptions in §5.
7 Limitations
Evidence scope. The empirical comparison contains one matched run per method and scale (Baize5B, Baize10B), 350 training steps, one production scaffold, and one frozen TMax-100 evaluation. With exactly one run per method and scale, seed- and schedule-level variance is unidentified at each scale, and reinforcement-learning objectives are known to be seed-sensitive: the reported +3.0-point difference, identical in magnitude at both scales, sits below one standard error of the metric's own binomial sampling (approximately ±4.8 points at these base rates over 100 samples) and could plausibly be seed or sampling noise. It is confounded as well: because the C-DPPO mask discards tokens that Standard DPPO trains on (4.7%/5.9% mask disagreement plus up to 13.8%/15.3% unresolved certificates at the two scales), the comparison measures the complete update rule—including its data selection—rather than the certificate in isolation, and a conservative filter can stabilize training independently of algorithmic merit. The fixed 350-step horizon was declared before either run but lands after the curves have separated; no checkpoint-level confidence interval accompanies either score, and the measured gap is horizon-dependent, so an earlier or later stopping point could narrow or reverse it. Consistency across the two scales lowers the probability that the observed pattern is a chance coincidence, but two single-run pairs do not estimate seed-level variance and cannot convert the pattern into a significance statement. The comparison therefore supports only the direction-consistent descriptive statement of §6.3; it does not establish statistical significance, scaling, or broad benchmark superiority.
Coupling assumptions. The protocol requires an agent transport that preserves the declared session and provenance metadata, exact token identities, and paired policy probabilities. Unsupported or missing fields fail closed. The KCoder-specific contract does not automatically transfer to other scaffolds.
Certificate assumptions. C-DPPO certificates remain conditional on their theorem-specific inputs and assumptions. Observed adaptive-K resolution and sampled-path budget coverage are feasibility diagnostics, not proofs of an almost-sure sequence premise. The robust result is conditional on the declared log-probability radius unless a deterministic backend bound is available. Finally, the unconditional two-sided result is specific to TV; KL requires the stated tail likelihood-ratio condition.
8 Conclusion
We addressed the problem of post-training a language model inside the scaffold it will serve in: a production terminal-coding agent whose industrial complexity—context management, memory, orchestration, retries—quietly breaks the token and control fidelity that RL training depends on. Our core idea is that fidelity must be negotiated and verified rather than assumed: the trainer takes ownership of sampling by serving the agent's own requests from recorded token ids, the agent takes ownership of its side effects through a hardened training mode with a machine-checked request-count contract, and per-request provenance headers make every residual deviation explicit and fail-closed. Layered on a drift-classifying message-tree linearizer, this yields training sequences in which loss-carrying tokens are provably continuations of what the policy sampled. Building on that faithful observation interface, Certified Divergence Proximal Policy Optimization (C-DPPO) couples an empirically audited observable interface to a certification framework: Binary/Top-K TV has a tight two-sided approximation certificate and adaptive-K decision, per-token certificates compose under an explicit long-trajectory budget with adaptive , and bounded log-probability errors induce a robust decision rule that cannot retain a possibly-outside, possibly-outward update. The accompanying KL impossibility result marks the boundary of what tail mass alone can certify. The concise empirical test now connects those two layers directly: matched Baize5B and Baize10B pairs compare Standard DPPO with C-DPPO through 350-step average-reward curves and evaluate both final checkpoints of each pair on the same frozen TMax-100 tasks. A compact audit verifies that the certificate record and decision path are exercised rather than treating task reward alone as proof. In the matched study, the step-350 checkpoints score 37/100 and 44/100 (C-DPPO) against 34/100 and 41/100 (Standard DPPO) on TMax-100—a direction-consistent +3.0-point difference across scales, each below the metric's noise floor—and the compact audit confirms exercised certificate paths at both scales (99.4%/99.1% complete records; 86.2%/84.7% resolved before ). This single-run, single-node result at each scale is descriptive—a direction-consistent slight improvement that suggests algorithmic utility—and does not establish statistical significance, scaling, or broad cross-benchmark superiority. Extending the coupling to deeper multi-agent fleets, longer industrial runs, and other production scaffolds—each of which reduces to implementing the same three commitments of ownership, declaration, and verification—are the natural next steps.
A Proofs for the C-DPPO certificates
Proof. The contribution of the tracked singleton categories to the true and coarsened TV is identical. In the tail,
Subtracting the coarsened tail contribution from the true tail contribution gives
which proves Equation (2) and the lower bound. For every tail token, and . Therefore and , proving the upper bound.
The gap is zero if and only if or , equivalently the signed changes have no cancellation in the aggregated tail. To see tightness from the reported information when , fix tail masses and and place them on two distinct untracked tokens. Then , , and the gap is . No uniformly smaller upper error can therefore be inferred from the tracked probabilities and tail masses alone.
Proof. Each lower endpoint in the running maximum is at most the true TV, and each upper endpoint in the running minimum is at least the true TV, by Theorem 5.1. Thus implies , while implies . When , the complement is empty, , and Equation (1) is the full TV, so one of the two threshold decisions holds (with equality assigned to INSIDE).
Derivation of Equation (4). Tracked tokens are singleton cells and contribute identically to the full and coarsened KL. For the tail, write and . Then
(19)
The first term is exactly the coarsened tail category, proving the identity, with the usual limiting conventions when a tail mass is zero. If every conditional log-likelihood ratio is at most , its expectation under is at most , proving Equation (5).
For impossibility, hold positive tail masses fixed and use two tail tokens. Assign and . The tracked probabilities, , and do not change with , while the remainder is , which diverges as . Hence no finite upper remainder depending only on the tail masses can exist.
Proof. The sequential TV inequality used by the original DPPO finite-horizon analysis gives
Since pointwise and the certified sum is at most almost surely, monotonicity of expectation proves Equation (6).
For the product bound, couple the two generators sequentially. Conditioned on having generated the same prefix through , use a maximal coupling of their next-token distributions. The conditional mismatch probability is , so the probability that the coupled sequences remain equal through is at least . The coupling characterization of TV then gives the first inequality in Equation (7); the second follows by expanding the product or by the union bound.
For any two distributions and any function , , proving Equation (8). Finally, the average-divergence part of the DPPO policy-improvement theorem is
Substitution of Equation (6) proves Equation (9).
Proposition A.1. If every certified position satisfies under Equation (10), then for all and for every stopping time .
Proof. Because the weights are positive, , hence . The acceptance condition gives , so by induction from . Telescoping the budget recursion yields . Fixing the schedule before certification prevents the current token from being used to retroactively choose its own allowance; this timing condition is not otherwise needed for the algebra.
Proof. Equation (12) gives for every tracked token. Because the tail probability is one minus the tracked mass,
TV is a metric on the coarsened alphabet. Its reverse triangle inequality and triangle inequality imply
where denotes the distribution on the tracked singletons plus the tail category. This proves the robust lower bound because full TV lower-bounds coarsened TV.
For the upper bound, Theorem 5.1 gives . The preceding display bounds its first term. The tail calculation gives , so . Clipping at one completes Equation (15).
It remains to prove the mask statement. If the mask retains a token because , the true TV is inside the trust region for every consistent policy pair. Otherwise retention requires certified inwardness. For positive advantage, implies for every consistent pair, so DPPO's sampled-action direction is not classified as outward. For negative advantage, gives the analogous conclusion. Thus a retained update cannot be both possibly outside and possibly outward.
The formulas recover the expected boundary cases. With , Equation (1) reduces to , the Binary-TV statistic. With , both the coarsening and uncertainty tail terms vanish. With , the robust inflation terms vanish; at full vocabulary, Equation (16) becomes the exact distributional DPPO directional rule. For , both sequence bounds reduce to the one-step TV bound. If , certification requires zero divergence at every retained position. These reductions are algebraic checks, not additional empirical claims.
References
[1] H. Ivison, J. O. Yin, R. Shao, T. Xiao, N. Lambert, and H. Hajishirzi. TMax: A simple recipe for terminal agents. arXiv:2606.23321, 2026. Paper: https://arxiv.org/abs/2606.23321. Dataset: https://huggingface.co/datasets/allenai/tmax-15k-open-instruct.
[2] Ziyiang Liu et al. slime: LLM post-training with megatron and sglang. https://github.com/THUDM/slime, 2025.
[3] C. Jimenez, J. Yang, A. Wettig, et al. SWE-bench: Can language models solve real-world software engineering issues? In ICLR, 2024. arXiv:2310.06770.
[4] Z. Shao, P. Wang, Q. Zhu, et al. DeepSeekMath: Pushing the limits of mathematical reasoning in open language models. arXiv:2402.03300, 2024.
[5] D. Guo, D. Yang, H. Zhang, et al. DeepSeek-R1: Incentivizing reasoning capability in LLMs via reinforcement learning. arXiv:2501.12948, 2025.
[6] Q. Yu, Z. Zhang, R. Zhu, et al. DAPO: An open source approach to scaling RL for learning to act in LLMs. arXiv:2503.14476, 2025.
[7] C. Zheng, S. Liu, M. Li, et al. Group sequence policy optimization (GSPO). arXiv:2507.18071, 2025.
[8] G. Comanici, E. Bieber, M. Schaekermann, et al. Gemini 2.5: Pushing the frontier with advanced reasoning, multimodality, long context, and next generation agentic capabilities. arXiv:2507.06261, 2025.
[9] H. Le, Y. Wang, A. Gotmare, et al. Code generation with generated tests. In ICLR, 2023. arXiv:2207.10397.
[10] Z. Zhou, X. Chen, H. Liu, et al. SWE-RL: Advancing large language models and agents with reversible data pipelines and reinforcement learning. arXiv:2502.18449, 2025.
[11] X. Wang, C. E. Sieker, A. Qin, et al. OpenHands: An open platform for AI software developer agents. arXiv:2407.16741, 2024.
[12] S. Yao, N. Shinn, P. Pazhami, and K. Narasimhan. -bench: A benchmark for tool-agent-user interaction in real-world domains. arXiv:2406.12045, 2024.
[13] Z. Wang, K. Wang, Q. Wang, et al. RAGEN: Understanding self-evolution in LLM agents via multi-turn reinforcement learning. arXiv:2504.20073, 2025.
[14] rLLM contributors. rLLM: Democratizing reinforcement learning for LLMs. https://github.com/rllm-org/rllm, 2025.
[15] G. Sheng, C. Zhang, Z. Ying, et al. HybridFlow: A flexible and high-performance RLHF framework. arXiv:2409.19257, 2024.
[16] J. Hu, X. Wu, W. Shen, et al. OpenRLHF: An easy-to-use, scalable and high-performance RLHF framework. arXiv:2405.11143, 2024.
[17] W. Fu, J. Gao, X. Shen, et al. AReaL: A large-scale asynchronous reinforcement learning system for language reasoning. arXiv:2505.24298, 2025.
[18] L. Zheng, L. Yin, Z. Huang, et al. SGLang: Efficient execution of structured language model programs. arXiv:2312.07104, 2024.
[19] M. Shoeybi, M. Patwary, R. Puri, et al. Megatron-LM: Training multi-billion parameter language models using model parallelism. arXiv:1909.08053, 2019.
[20] J. Schulman, F. Wolski, P. Dhariwal, A. Radford, and O. Klimov. Proximal policy optimization algorithms. arXiv:1707.06347, 2017.
[21] P. Qi, X. Zhou, Z. Liu, T. Pang, C. Du, M. Lin, and W. S. Lee. Rethinking the trust region in LLM reinforcement learning. In Proceedings of the 43rd International Conference on Machine Learning, 2026. arXiv:2602.04879.
[22] E2B, Inc. E2B: Cloud runtime for AI code execution. https://github.com/e2b-dev/E2B, 2024.
[23] SWE-agent contributors. mini-swe-agent: The minimal software-engineering agent. https://github.com/SWE-agent/mini-swe-agent, 2025.