An agent that learns from a replay buffer (a memory of past transitions it keeps re-training on) has to decide which old experience to keep and how often to reuse it. The usual answer is "keep the most recent data and sample it uniformly," because old transitions come from earlier, worse behavior and bias learning. We argue this answer is wrong for one specific kind of data: records of the agent hitting, or nearly hitting, a safety constraint. As a safe agent improves it stops producing such events. First-in-first-out eviction then removes the few it has, and the estimate of where danger lies degrades. This is the "safety paradox" identified by Breaking Safety Paradox with Feasible Dual Policy Iteration, and it shows up as sudden cost spikes late in training. That paper fixes the paradox with a second, deliberately reckless policy that goes out and violates constraints to refill the buffer. The fix works, but it pays for boundary data with real violations during training.
Our claim is that most of this problem comes from how the buffer is managed, not from a shortage of data. A transition in which the agent crossed a hazard stays a correct fact about the world after the policy that produced it has changed. It goes stale only when the world changes. We therefore propose to give the cost critic (the network that predicts future constraint cost) a protected memory of boundary transitions. That memory would be exempt from age-based eviction and sampled at a fixed share of every batch. Entries would be removed only when fresh local evidence contradicts them. If the claim holds, off-policy safe learning can keep sharp safety boundaries without the deliberate crashes that active probing requires. The same design would also handle environments whose safety rules shift, where keeping every old violation creates "phantom hazards."
Core Claim
The stale-data literature treats staleness as one quantity measured by age or by policy mismatch. Methods such as Experience Replay with Likelihood-free Importance Weights (LFIW) train a classifier to tell recent from old transitions and downweight old ones. Its justification is that the value update contracts cleanly only on data matching the current policy. We separate two causes of staleness. The first is policy drift, which changes how data should be weighted. The second is world drift, which changes whether a stored label is still true. For the reward critic, policy drift is the main concern, and standard replay or LFIW is appropriate. For the cost critic, the error that matters sits at the edge of the safe region, which the current policy almost never visits. Old boundary transitions are therefore the most valuable data it has, and they should be removed only on evidence of world drift.
This division yields a prediction that can fail. Applying LFIW to the cost critic of a safe agent should make the safety paradox worse. The current policy's recent data contains no violations, so the classifier drives the weights of old violations toward zero. A protected boundary memory should make the paradox better. If neither effect appears, the claim is wrong.
Relation to Prior Work
Three papers motivate the proposal by documenting the gap. The FDPI paper proves that sparse violations inflate the error of the feasibility estimator, and reports that its baseline SAC-FPI's buffer "drops below 1%" violation samples in the final 10% of training. FDPI keeps roughly ten times more. FDPI obtains those samples by running a KL-constrained adversarial policy in the environment and correcting the resulting shift with importance sampling. Our proposal collects no deliberate violations and only changes what is kept and how it is sampled. Revisiting Safe Exploration in Safe Reinforcement learning introduces EMCC, a measure of how long the agent stays in consecutive unsafe steps, and the Circle2D benchmark. It shows off-policy methods such as SAC-Lag have erratic EMCC during training, but does not explain why. We test whether replay composition is the cause. Off-Policy Safe Reinforcement Learning with Cost-Constrained Optimistic Exploration (COX-Q) names sparse failure transitions in the buffer as its open weakness and explicitly leaves replay correction for rare breaches to future work. We take up that item.
Two lines of work constrain the design. Off-Policy Primal-Dual Safe Reinforcement Learning (CAL) counters cost underestimation from buffer shift with pessimism: an upper confidence bound over an ensemble of four to six cost networks, plus an augmented Lagrangian. It does not identify or evict stale data, and ensemble pessimism cannot stand in for boundary samples that have been evicted. We treat CAL as a strong competitor and a possible host for our memory. Provably Efficient Model-Free Algorithms for Non-stationary CMDPs handles world drift by periodically wiping all data, which gives zero-violation guarantees in tabular and linear settings but discards valid data everywhere. That result shows world drift really must be handled. Our design aims to handle it locally.
Two papers supply methods we reuse. Replay Buffer with Local Forgetting (LOFO) evicts only within the neighborhood of recent experience, using learned state embeddings. It shows this recovers adaptation where FIFO buffers fail, "requiring two orders of magnitude less data" in MiniGrid, but it knows nothing about costs. We borrow its neighborhood idea for our validity gate. Smart Forgetting for Safe Online Learning with Gaussian Processes blocks eviction of any data point whose removal would break a stability guarantee. That is our "never forget a safety fact without cause" principle in a small, kernelized setting. We carry the principle to deep replay without the Lyapunov machinery. Context-Aware Safe Reinforcement Learning for Non-Stationary Environments also oversamples near-miss transitions under changing dynamics, but it needs a known physics prior and a model-predictive controller. Ours is model-free.
Research Program
The method has three parts added to a standard safe off-policy learner; we use SAC-Lag and SAC-FPI as hosts.
The first part is admission. A transition enters the boundary memory if it incurred cost, or if it lies within a short window of steps before a costly transition. We also admit near misses, defined as transitions whose Monte Carlo cost-to-go over the next $H$ steps exceeds a threshold. The memory has a fixed capacity and uses reservoir replacement among boundary items only. It never competes for space with ordinary transitions.
The second part is sampling. Each cost-critic batch draws a fraction $\rho$ from the boundary memory and $1-\rho$ from the main buffer. Bellman targets for all items are recomputed with the current policy's next action. This is already standard off-policy practice, and it is why an old transition's label $(s,a,c,s')$ stays usable after the policy has moved. The reward critic samples only from the main buffer. The actor sees the cost critic as usual.
The third part is the validity gate, which handles world drift. Each boundary item keeps its stored immediate cost. Fresh transitions are embedded with a contrastive encoder as in LOFO, and we track the local disagreement between each fresh transition's observed cost and the stored costs of its nearest boundary items. When disagreement in a neighborhood exceeds a threshold calibrated on stationary runs, the items in that neighborhood are evicted. Disagreement can take two forms: new costs where memory says none, or repeated zero cost where memory says cost.
The gate has a limitation that we state up front. A cautious policy rarely returns to a region it believes is dangerous, so hazards that have vanished can persist in memory. That failure costs reward rather than safety, and we measure its size directly instead of hiding it. The analysis half of the program asks two questions. Across training, how do the violation fraction in cost-critic batches and the cost critic's error on the current policy's near-boundary states track late-stage cost spikes and EMCC? Does restoring that fraction by retention alone reproduce FDPI's benefit?
Baselines
The naive reference point is SAC-Lag with a single FIFO buffer and uniform sampling. It shows what happens with no special treatment of boundary data. Beside it we run SAC-FPI, the feasibility-based learner whose buffer violation ratio FDPI reports falling below 1%. It is the direct "before" condition for our memory. PPO-Lag from the SafePO library in Safety Gymnasium serves as the on-policy reference, since its data is never stale. That paper reports PPO-Lag reaching "a 98% reduction in safety violations compared to standard PPO, with only a 45% drop in total reward" on velocity tasks.
The strongest existing method on this exact question is SAC-FDPI. It reports "the lowest constraint violations (near-zero) across all 14 environments while simultaneously matching or exceeding the reward returns" of CPO, PPO-Lag, SAC-Lag and SAC-FPI. We found no per-environment return or cost values reported on Lacuna for SAC-FDPI, so we will rerun it rather than quote it. Beating it has a specific meaning. We must match its final evaluation cost and return within the confidence interval over seeds, while incurring significantly fewer cumulative training-time violations, because FDPI's dual policy spends violations and we do not.
CAL is the strongest pessimism-based competitor. We found no numeric result on Lacuna beyond its reported "order of magnitude fewer samples" than on-policy methods. We run it with and without our boundary memory to test whether the two are complementary.
For the non-stationary settings, the competitor is a deep analogue of the periodic-restart strategy from the Triple-Q paper, wiping the buffer at a tuned interval. It is joined by LOFO applied unchanged to the shared buffer. No reported result was found on Lacuna for either method on safety benchmarks.
Fairness rules apply to every method. All methods share network sizes, total environment steps, cost budgets and seeds, with ten seeds per condition. Each method receives the same hyperparameter search budget over its own key knobs: $\rho$ and memory size for us, KL radius for FDPI, ensemble size and confidence width for CAL, restart interval for restarts. Search runs on two held-out tasks.
Two ablations isolate the ingredients. The first is the ungated reservoir: boundary memory with no validity gate. The second is the gate applied to the ordinary buffer with no protected memory.
Why not just…?
Why not just keep every violation forever and oversample it? This is the most serious threat, and it is also our ungated ablation. In stationary tasks we expect it to perform about as well as the full method. That outcome would support the core claim, because it would locate the safety paradox in buffer management. The gate is justified only by non-stationary tasks. If the ungated reservoir also adapts well after a relaxed or tightened constraint, we will drop the gate and report the simpler method.
Why not just use prioritized replay on cost-critic error? The FDPI paper argues that prioritized replay can only reweight transitions still in the buffer. Under FIFO eviction the violations are gone before priorities can matter. Large Batch Experience Replay further shows that priorities go stale because they refresh only when sampled. We include cost-prioritized replay over a standard FIFO buffer as an extra baseline. If it matches the protected memory, retention is not the operative factor.
Why not just shrink the buffer or restart it periodically to avoid staleness? LOFO shows that small FIFO buffers forget distant state regions. FDPI's buffer statistics imply that a short window would flush rare violations within episodes. Restarts discard valid boundary data along with stale data. The tightened-constraint task measures how much this costs in training violations.
Why not just collect boundary data actively, as FDPI does? Active probing works, but it is incompatible with settings where violations during training are unacceptable. The EMCC paper treats safety during training as the core requirement. Our cumulative training-violation and EMCC comparisons against SAC-FDPI settle whether retention can replace probing.
Proposed Experiments
Stationary experiments use the Safety-Gymnasium navigation and velocity tasks from the FDPI evaluation, including SafetyPointGoal1, the Car goal tasks and SafetyHopperVelocity-v1, together with Circle2D levels 1 to 4 for EMCC. Non-stationary experiments build two LoCA-style shifts. In the first, the velocity limit on the Safety-Gymnasium velocity tasks is tightened or relaxed at mid-training. In the second, the Circle2D hazard zone is relocated. Relaxing the limit tests the phantom-hazard failure. Tightening it tests how quickly the agent responds to new danger.
The metrics are final return and cost, cumulative training violations, and EMCC. We also count late-training spikes, defined as evaluation windows after the halfway point in which episode cost exceeds twice the budget. Two diagnostics complete the set: the boundary fraction in cost-critic batches, and the cost critic's error against Monte Carlo cost on near-boundary states of the current policy.
Three checks decide the proposal. First, on stationary tasks, SAC-FPI with boundary memory must remove late spikes and approach FDPI's final cost with fewer training violations. Second, LFIW applied to the cost critic must measurably increase spikes relative to LFIW applied to the reward critic only. This checks the predicted mechanism. Third, under constraint shifts, the gated memory must adapt faster than the ungated reservoir after relaxation and incur fewer violations than periodic restarts after tightening. Failing the first check falsifies the central claim. Failing the third leaves a simpler and still useful result.
References
- Breaking Safety Paradox with Feasible Dual Policy Iteration
- Experience Replay with Likelihood-free Importance Weights
- Revisiting Safe Exploration in Safe Reinforcement learning
- Off-Policy Safe Reinforcement Learning with Cost-Constrained Optimistic Exploration
- Off-Policy Primal-Dual Safe Reinforcement Learning
- Provably Efficient Model-Free Algorithms for Non-stationary CMDPs
- Replay Buffer with Local Forgetting for Adapting to Local Environment Changes in Deep Model-Based Reinforcement Learning
- Smart Forgetting for Safe Online Learning with Gaussian Processes
- Context-Aware Safe Reinforcement Learning for Non-Stationary Environments
- Safety Gymnasium: A Unified Safe Reinforcement Learning Benchmark
- Large Batch Experience Replay