Hindsight Compilation of Robot Skill Libraries Under Domain Randomization

Language-model coding agents can now write short programs that control a robot arm. The better systems also save programs that worked into a reusable skill library, so later tasks can call them instead of reasoning from scratch. These systems share one wasteful habit: when a generated program fails at its intended task, they throw it away or retry it. A failed "put the cube in the bin" program often does something useful anyway. It may leave the cube grasped and lifted, or stacked on the wrong block. We propose to keep those accidents. When a program fails, we record what it actually achieved, relabel the program as a solution to that outcome, and file it in the library as a new skill. This is the hindsight trick from goal-conditioned reinforcement learning, applied to programs instead of individual motor actions.

The catch is physical. In a simulator, an accidental outcome may be a fluke of one particular friction value or object mass, and a library full of flukes will not survive a real robot. So the second half of the idea is to turn domain randomization, which is usually a training-time noise source, into an admission test. A relabeled program joins the library only if it reproduces its claimed outcome across a batch of randomized physics and visual conditions. The claim is that this pairing, hindsight relabeling to grow the library and randomization to decide what the library may keep, builds long-horizon manipulation skills faster than success-only compilation at equal simulation and model budget. We further claim that the resulting library transfers to hardware better than a library relabeled without the admission test.

Where this sits

Knowledge compilation means turning slow step-by-step reasoning into cached procedures that execute directly. It has a long history. Soar's chunking converts problem-solving traces into production rules (Knowledge Level Learning in Soar). Explanation-based learning generalizes a single worked plan into a reusable schema (Acquiring Schemata Through Understanding and Generalizing Plans). We reuse the schema idea of lifting constants into variables when a trace is stored.

Modern compilers mostly learn from successes, and they are the direct foils here. CaP-X synthesizes successful code traces into a skill library, benchmarks coding agents across 187 robosuite, LIBERO-PRO and BEHAVIOR tasks, and deploys to real arms. When a program fails, it either repairs toward the original goal through test-time debugging at 6.8 to 23.8 seconds per iteration or discards the attempt. Agent Workflow Memory induces parameterized workflows from successful web trajectories and discards failures. HERAKLES compiles successful chained sub-goals into atomic skills, but only in the 2D Crafter world. NeSyPr keeps failures, but only in a negative memory bank that suppresses them during decoding, and it works over symbolic states without physical transfer. None of these reinterprets a failure as a success for a different goal. That reinterpretation is the ingredient we add.

Hindsight relabeling supplies the method. Hindsight Experience Replay replaces an unachieved goal with a state the episode actually reached, and this made sparse-reward Fetch manipulation solvable. AgentHER carries the idea to language-agent traces. It verifies relabels with two LLM judges at 97.1% precision and reports 2x data efficiency over success-only fine-tuning on WebArena and ToolBench. It stays in software and produces fine-tuning data, not a compiled library. We keep its lesson that relabels must be verified. We replace judge models with simulator ground truth, which is exact in robotics, and we add the requirement that the relabel hold across physical variation, which has no counterpart on the web.

Two papers constrain the design. Complex Robotic Manipulation via Graph-Based Hindsight Goal Generation shows that naive hindsight relabels outcomes that are not reliably reachable and fails completely in cluttered scenes: 0% for HER on FetchPushLabyrinth, against 80% for its graph-aware variant. We read our admission test as a sampling-based substitute for its reachability check. Asymmetric Actor Critic shows that simulator ground truth can supervise learning while the deployed policy sees only randomized images. We use privileged state the same way, to decide which predicates a program achieved, and never at deployment.

Core claim and mechanism

Programs are written over parameterized behavior primitives (reach, grasp, push, release) of the kind MAPLE showed to be learnable and transferable. The proposer is an LLM coding agent. Each generated program is executed in $K$ domain-randomized copies of the scene, with varied masses, frictions, damping, textures, lighting and camera pose. We compute the set of symbolic predicates true at the end of each run from privileged simulator state, for example on(a,b), grasped(a), inside(a,bin).

For a failed program, a candidate relabel is any predicate conjunction $g'$ that the program changed from the initial state and that is not already covered by a library entry. The candidate is admitted if

$$\hat p(g') = \frac{1}{K}\sum_{k=1}^{K} \mathbb{1}[g' \text{ holds at the end of run } k] \ge \tau,$$

where $\tau$ is a reliability threshold. On admission, object identities in the program and in $g'$ are lifted to variables. The observed initial predicates are recorded as a precondition, and $g'$ becomes the entry's effect.

At test time no LLM is called in the inner loop. A fast symbolic chainer composes library entries whose effects satisfy the goal, and a pose estimator trained with visual randomization binds object variables to scene coordinates. This is compilation in the classic sense: deliberation happens during library growth and is cached for execution. The LLM is invoked only when chaining fails, and the program it writes enters the same generate, relabel and admit loop.

Because admitted outcomes include partial progress, the library forms its own curriculum. "Grasp and lift" skills appear before stacking is ever achieved, and stacking programs then chain them. HERAKLES reports this kind of progression in Crafter, but only from successes.

Research Program

The work proceeds in three stages. The first stage builds the loop on robosuite (robosuite), using its Panda arm with operational-space control. The task set includes Lift, Stack, Pick-and-Place and Nut Assembly, plus composed long-horizon variants built from them. We add a predicate extractor over robosuite object states. A matching RLBench (RLBench) setup tests whether the method carries to a different simulator and to longer tasks.

The second stage runs budget-matched growth experiments. Every method receives the same count of LLM calls, the same number of simulated rollouts and the same wall-clock time. We track three things: which library entries originated as hindsight relabels, whether those entries appear in final solutions, and how held-out task success grows over the budget.

The third stage tests transfer. Libraries are evaluated under physics ranges wider than training, and, where hardware is available, zero-shot on a Franka arm on the Stacking and Cleanup-style tasks where MAPLE reported real-robot results.

Baselines

The naive reference is the same coding agent with no library. It writes a fresh program per task, retries up to the shared budget, and uses no debugging loop. Every other method should beat it, and the size of that gap shows how much compilation matters at all.

The strongest direct competitor is success-only compilation in the style of CaP-X's CaP-Agent0: an identical proposer, primitives, randomized execution and library format, where only programs that achieve their intended goal are admitted. It is the right foil because it isolates hindsight relabeling as the sole difference. We run it with the same $K$, the same $\tau$ applied to intended goals, and the same budget. Beating it means higher held-out success at matched budget on tasks where the proposer's initial success rate is below about 5%. The reported point of reference is CaP-X's CaP-RL raising Qwen 2.5 Coder on Cube Lift from 25% to 80% (CaP-X). We will rerun rather than borrow that number, because its protocol differs.

The strongest learned-policy competitor on robosuite is MAPLE, reported at 90% average success across its tasks against 19% for atomic-action SAC (MAPLE). ManipGen reports 97% in robosuite simulation and 76% across 50 real tasks (Local Policies Enable Zero-shot Long-horizon Manipulation). Those numbers come from their own task sets. We will retrain MAPLE on our composed tasks with the same randomization and the same simulated-step budget. Our method should match it on single-stage tasks and exceed it on compositions it never trained on. We do not expect to beat ManipGen's 3,500-policy distillation on raw coverage, and we will report it only as context.

The key ablation is unverified hindsight: relabels are admitted from a single nominal-physics run with $K=1$. This isolates the use of randomization as the admission test. A second ablation keeps verification but uses randomization only as training noise for the pose estimator.

Why not just…?

Why not just run more rollouts and keep only successes? In simulation, rollouts are cheap, so hindsight might only buy a constant factor. This is the most serious threat. We will plot held-out success against budget for success-only compilation at 1x, 2x and 4x our budget. If success-only compilation at 2x matches us, the contribution is modest. We expect a qualitative gap only on compositions whose initial success probability is near zero, where success-only compilation has nothing to compile. AgentHER's 2x data-efficiency result in software is the motivating evidence, but not proof for physical tasks.

Why not just train a flat goal-conditioned policy with HER and domain randomization? That recipe worked for single-stage Fetch tasks (Asymmetric Actor Critic). On multi-stage robosuite tasks, however, atomic-action SAC reached only 19% against MAPLE's 90%, and flat HER stalled at 0% in obstacle-rich scenes (G-HGG). We include flat SAC+HER with randomization as a baseline so that this failure is measured on our tasks rather than assumed.

Why not just use AgentHER-style relabeling to fine-tune the coding model instead of building a library? This is plausible, and the two approaches may be complementary. A fine-tuned coder still pays LLM latency at every step, while the library executes without the model. We will compare our method against a coder fine-tuned on the same admitted relabel pairs, on both success and per-decision latency.

Why not just let a coding agent debug at test time? CaP-X measures 6.8 to 23.8 seconds per debugging iteration, and debugging pushes toward the original goal rather than banking what was accidentally achieved. We report success per second of deliberation for both.

Decisive checks

Three results would settle the proposal. First, on low-base-rate compositions, hindsight compilation must beat success-only compilation at matched budget, and the gap must persist at 2x budget for success-only. Second, most solutions to held-out tasks must use at least one entry that entered the library through hindsight. Third, the unverified-hindsight ablation should equal or beat the full method under nominal physics but fall behind it under widened physics ranges and on hardware. That pattern would show that randomization, used as an admission test, filters out fluke skills. If the second check fails, the relabels are clutter. If the third fails, the verification step is unnecessary and the idea reduces to hindsight alone.