Manuscript Offprint
arXiv:2610.23445RECREG: Recovery-based Shielding for Regular Safety Properties in Reinforcement Learning
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
In many real-world scenarios we need to consider formal requirements, such as safety and constraint compliance, to deploy Reinforcement Learning (RL) agents. In this paper we introduce RECREG, a safe RL framework capable of enforcing non-Markovian regular safety properties via recovery-based shielding. RECREG is a unified approach that supports different levels of a priori knowledge and safety guarantees. The paper primarily focuses on building the theoretical foundations for RECREG in the tabular setting, providing rigorous safety and convergence guarantees that are not present in related work. We provide an extensive set of empirical results using the MASA-Safe-RL library, and we outline an extension of RECREG to deep RL domains using SOTA model-based RL. Our empirical results demonstrate that RECREG achieves efficient learning and matches the theory in this paper.
1 Introduction
Safe Reinforcement Learning (RL) is an active area of research focusing on the training of agents with RL while maintaining some standard of safe behaviour at deployment and possibly during training as well [5]. There exist many competing paradigms in safe RL, the most common being Constrained Markov Decision Processes (CMDPs) [4], which frame safe RL as a constrained optimization problem, enforcing safety through cost functions and expected cumulative cost thresholds; although this approach is often inappropriate in highly safety-critical domains, as it only enforces safety in expectation and often lacks rigorous guarantees [53].
An alternative view comes from formal methods. Methods from this class often leverage some form of Linear Temporal Logic (LTL) [42] to express formal safety constraints and task objectives, enabling expressive and interpretable specifications [14, 25, 26, 40, 47, 53, 54]. Following this line of work, shielding has emerged as a powerful approach for enforcing LTL safety properties in RL [3]. Predicated on ideas like the Simplex Architecture [46], shielding works by monitoring the agent's actions and overriding them with a safe alternative if they propose an action that could lead to a safety violation. Classical approaches to shielding leverage reactive synthesis to build correct-by-construction monitors from formal safety specification and a formal model of the environment called the safety abstraction [3, 10]. The safety abstraction is designed to encode the minimum amount of environment dynamics required to guarantee safety. As such, it is often built from a pessimistic view of the environment derived from prior knowledge, thus classical shielding approaches can only reasonably be applied to known environments or simple safety specifications. This fundamentally departs from the usual RL framework (unknown environment), but does provide strong safety guarantees by construction.
More recent shielding approaches consider probabilistic safety constraints [24, 32]. While these are less pessimistic, they still require knowledge of the transition kernel, using probabilistic model
Preprint.
checking to verify actions. There has however been a shift to lift these assumptions, in particular, by leveraging model-based RL to estimate the unknown environment dynamics and verify actions via forward simulation in the latent space of a recurrent state space model [17, 18, 27, 57], with Gaussian Process dynamics models [19] or ensembles of probabilistic neural networks [20]. RECREG addresses this same question: how can we obtain meaningful safety guarantees when the environment dynamics are unknown?. We summarize our contributions hereafter.
Contributions. To bridge the gap between the strong empirical results achievable by data driven methods (e.g., CMDP, model-based RL) and formally guaranteed safety (classical shielding) we propose RECREG, a unified framework for enforcing regular safety properties that spans multiple levels of a priori knowledge. In a similar fashion to Recovery RL [49], RECREG learns a backup policy trained to maximize safety probability and action replacement (shielding) is implemented by identifying probabilistic safe sets (or “recovery zones”). A central contribution of this paper is in the development of explicit safety guarantees, convergence and optimality results which are missing in prior work [49]. In particular, we identify and formalize three complementary operation modes. In the EXACT mode, RECREG assumes full knowledge of the transition kernel and guarantees safety from the beginning of training. In the MODELBASED mode, RECREG estimates the transition kernel from observed data, then performs on-the-fly verification via finite-horizon reachability analysis, enabling principled shielding under partial model knowledge with statistical guarantees. In the MODELFREE mode, RECREG dispenses with explicit model learning altogether and instead directly estimates the safety critic, yielding a purely model-free shielding mechanism with convergence guarantees. We also use DREAMERV3 [23] to develop a deep RL variant of RECREG that uses latent rollout models and safety critics to provide safety guarantees under correct model calibration. In the tabular setting, we validate that RECREG matches the outlined theory and that comparable approaches cannot reliably enforce safety constraints while maximising task performance. In deep RL we also observe that RECREG is able to reliably reduce safety violations while achieving good returns compared to similar approaches based on the DREAMERV3 architecture. Together these results establish RECREG as a practical and theoretically-grounded approach to safe RL.
Related work. Existing methods for safe RL can roughly be dividing into two camps: (A) methods that incorporate safety into the learning objective, encouraging safe behaviour as an outcome of learning [2, 6, 13, 25, 38, 45, 47, 48, 60], and (B) methods that enforce safety via external mechanisms that directly modify the agent's actions [3, 9, 20, 32, 35, 36, 49]. Methods from camp (B) make up a large portion of “provably safe” RL algorithms [37]. They can also be further divided into hard constraints [3] and probabilistic constraints [9, 24, 32]. Methods based on CMDPs are from camp (A) – they use a cost function, that often represents safety violations, in the learning objective to reduce the probability of unsafe behaviour. CMDPs themselves can be solved via linear programming in the tabular setting [4]. For more complex environments, methods based on Lagrange relaxations and dual-gradient descent [6, 13, 38, 45, 48], and local policy search with gradient projections [2, 60] are popular approaches. While CMDPs provide a convenient framework for learning, they have several limitations. In particular, safety constraints are only enforced in expectation, which do not guarantee that unsafe events will never occur. Furthermore, the discounting accumulated costs also poses issues with constraining limiting behaviour [53].
In contrast, our approach RECREG fits neatly into camp (B), enforcing regular safety properties (more expressive than LTL safety properties) with high probability. LTL constraints have been considered in RL for both task specification [14, 25, 26] and constraint specification [47, 53, 54]. LTL constraints are PAC learnable under specific conditions [53, 59], but optimality under LTL constraints can only be achieved subject to optimal discount factors and Lagrange multipliers [47, 54]. Earlier theoretical work assumed access to a perfect generative model of the environment which can be queried from any state, breaking standard RL assumptions [53]. Recent work on Automata Constrained Q-learning uses reward shaping and penalties to ensure the optimal policy is also safe at convergence although does not provide explicit safety guarantees during learning unlike our approach [40]. For RL with LTL safety constraints, Shielding can be used to enforce constraint compliance [3]. In partially observable settings (e.g., deep RL) safety can be guaranteed if the underlying transition structure is known [12]. RECREG, by contrast, offers a unified framework for safety guarantees even when the transition dynamics or structure are truly unknown.
Another related line of research is Reward Machines [29, 30]; these are closely related to our work as simple reward machines can encode reward functions for learning regular safety properties. While the Reward Machines literature is primarily focused on task specification, there are many key insights such as counterfactual experiences and reward shaping [41] that are used to speed up learning over Reward Machines, which can applied in our framework too.
Reinforcement learning. We follow the usual convention of modelling the environment as a Markov Decision Process (MDP) , where and are finite sets of states and actions respectively; is the set of initial states; is a (generally unknown) transition kernel; and is a reward function. A solution for the RL problem can take the form of a (memoryless, stochastic) policy , which induces a Markov chain with transition kernel . We let denote the set of memoryless policies on . For a given discount factor , the value function of policy is the expected discount return , where denotes the expected value of following in . Similarly, the state-action value function or Q-function, is defined as . Hereafter we drop the superscript when it is clear from the context. The aim of RL is to find an optimal policy such that for all , we have . We write, and to denote the optimal value functions. Note that there always exists an optimal policy in [43].
Safety semantics. We consider a set AP of atomic propositions (or atoms). Then, is the alphabet over AP (e.g., if , then ). The labelling function maps states to sets of atoms (intuitively, those that hold in a given state). A path is a sequence of states which gives rise to a corresponding trace . By standard probability theory, the transition kernel for a policy in induces a probability measure over paths and traces in the Markov chain [7].
Regular safety property. A linear-time property is a safety property if every violating trace has a finite bad prefix, i.e., a finite word that cannot be extended to any trace in . A safety property is regular if its set of bad prefixes forms a regular language. Equivalently, every regular safety property can be represented by a deterministic finite automaton (DFA) that accepts exactly its bad prefixes. Here Q is a finite set of states with initial state ; is a finite alphabet; is the deterministic transition function; and is the set of accepting states. A trace satisfies the safety property iff no finite prefix of the trace is accepted by . It is well known that for any LTL safety property there is a regular language that contains its bad prefixes [7]. Therefore, RECREG can be straightforwardly applied to LTL safety constraints.
Safety probability. Given an MDP with labelling function , the probability of satisfying a regular safety property under policy from state is defined as the probability that the induced traces satisfies the safety property, i.e.,
Equivalently, using the characterization via bad prefixes and the DFA recognizing them, this is the probability that no finite prefix of the generated trace is accepted by . That is,
where denotes the language of words accepted by . Intuitively measures the probability that from following the system never violates in finite time.
Problem Statement. Our objective is to synthesize a policy that maximizes reward while guaranteeing that the safety probability remains above a given threshold. Formally,
(3) where is a user-defined safety lower bound. For regular safety properties more complex than simple invariants, memoryless policies may not be able to achieve the desired bound or act suboptimally under the constraint. In the next section we present a solution to this issue.
3 RECREG: Recovery-based Shielding
This section details the RECREG approach for solving (3). We start by introducing a product MDP construction; defining memoryless policies on an expanded state space that preserves optimality. We then continue by formalizing probabilistic safe sets and how the backup policy is trained, followed by details regarding how the task policy is trained including a safety-aware Bellman operator that guarantees convergence. We then detail each of the three operation modes and corresponding guarantees (safety, convergence, optimality), and finally we conclude this section by providing a high level overview of RECREG applied to deep RL.
Product MDP and reachability semantics. We address (3) by synchronizing MDP states with the DFA for monitoring bad prefixes.
Definition 1 (Product MDP). For a given MDP with labelling function and DFA whose language is precisely the set of bad prefixes for , the product MDP is denoted , with state space , initial states , transition kernel , where if . The product labelling function can also be defined: , where unsafe if ; labelling accepting DFA states as “unsafe”. The action space and reward function remain unchanged.
For convenience we may also write to denote a generic product state and to denote a product path. A key observation we can now make is that the safety probability in (1) reduces to a reachability probability in the product MDP [7] (for proof c.f. Appendix A.1). Formally for a policy from state ,
where and unsafe is an LTL formula that reads “eventually unsafe”. Let,
be defined as the reachability probability, i.e., the probability of reaching a product state labelled “unsafe”, where is the corresponding path measure in the product MDP. Intuitively the safety probability corresponds to the probability of avoiding “unsafe” (accepting) states in the product MDP. This is useful because we can evaluate and quantify the safety probability of a policy from a given state via probabilistic model checking in the product MDP (e.g., via reachability analysis) which is polynomial in the size of the product state space [7]. We now write to denote the set of memoryless policies over , in general these are non-Markovian in the original state space S, and the product states provide the minimum amount of information to learn optimal (safe) policies.
Probabilistic safe set. Even if a state is not labelled “unsafe” it does not mean that it is operationally safe, since there could be some unavoidable high-probability of eventually reaching an “unsafe” state under the current policy. To truly characterize operationally safe states and actions we use the idea of probabilistic safe sets and recoverable actions [1, 49]. We define,
where denotes the probability of paths under but in the first step resolving the non-determinism of the MDP with action . In words, defines the set of states that have a risk level of no more than under policy , and is the state-action analogue. We also define the maximal probabilistic safe sets which exploit the best available policy from each state,
It is not too hard to see that (resp. ) for all and (and ), thus and are maximal, providing the largest set of operationally safe states and actions [1]. These probabilistic safe sets can be viewed as safety value functions constrained by , thus there exists an optimal or maximally safe policy in [1].
Backup (safe) policy. RECREG trains two policies in simultaneously: (i) a task policy , trained to maximize expected discounted reward, and (ii) a backup policy used to characterize the probabilistic safe sets and provide backup actions in the event of a shield override. We first discuss here how the backup policy is trained, before discussing how both policies are reconciled via action replacement or shielding. In particular, we want to train to compute the maximally safe policy and recover the maximal probabilistic safe sets. This can be achieved by solving a stochastic avoidance problem. To this end we introduce the following cost function,
Rather than standard exponential discounted with we use eventual discounting (ED) which assigns equal cost to all violating traces regardless of when violation occurs [54]. Under this criteria minimizing the expected return is equivalent to maximizing the probability of reaching an “unsafe” state as established by Proposition 1.
Proposition 1 (Maximal safe policy). The optimal policy that minimizes the expected return under eventual discounting [54] and with rewards given by (10), is such that for any (is maximally safe).
Action replacement (shielding). We denote the final (shielded) policy that we use during training and deployment as . The safety constraint in (3) is enforced by action replacement or shielding: filtering actions proposed by the task policy , based on our current estimate of the maximally safe set. Formally, fix a sequence of step-wise risk thresholds satisfying and , the shielded policy is then defined as,
In practice, we can use either a fixed for finite episodes with length or a convergent series for the infinite horizon guarantees. Intuitively the shielded policy allows the task policy to act whenever the current (product) state lies within probabilistic safe set (under ). If the condition can be correctly checked then the constraint in (10) is provably satisfied via a simple recursive feasibility argument. Theorem 1 establishes the conditions for when this holds.
Theorem 1 (Constraint satisfaction). Assume that all initial states satisfy the global safety constraint under the safe policy, i.e., . Then if the step-wise risk budgets satisfy , then the shielded policy satisfies , .
Importantly the proof for Theorem 1 is policy-agnostic, i.e., it works for an arbitrary . Furthermore, we do not necessary need to be maximally safe, only “good enough” from the initial states. Although as converges to the maximally safe policy it enlarges . The crux of the problem is how to reliably check , this is the key difference between the three complementary modes of RECREG, with the EXACT mode directly computing via probabilistic model checking to the MODELFREE mode estimating it via online Bellman updates.
This is where our method fundamentally departs from prior work, e.g., Recovery RL [49]. While Recovery RL also uses a separate task policy and backup or recovery policy, its recovery set is defined by a learned safety critic for the composite policy (i.e., ), and the task policy is otherwise trained to maximize task reward in the modified MDP induced by action replacement. Consequently, the safe region used for filtering actions need not coincide with , and may be a strict subset of it, leading to unnecessary interventions and an over conservative shield. In contrast with RECREG as converges, the shield approaches the largest set of actions that can be certified safe under the given risk budget. This distinction is important when task reward and safety are conflicting objective and allows us to obtain principled convergence and optimality guarantees for the task policy later on.
Task policy. Another important detail missing in prior work is how corrected actions are used in the Bellman update for the task policy. During early learning if the shield incorrectly allows unsafe
satisfies .
actions to pass through, the task policy may get stuck proposing high-reward but unsafe actions, unless we add a corrective mechanism. This phenomenon has been observed in robotics environments [18]. Prior work, e.g., Recovery RL [49] manages this by treating the proposed action as the executed action, essentially viewing the action interventions as part of the environment. This doesn’t resolve the issue however, rather we train the task policy with a safety-aware Bellman operator defined as,
where is the maximal state-action probabilistic safe set (9). essentially mimics the effect of action replacement but on value propagation and under reasonable assumptions Proposition 2 establishes that this Bellman operator converges to a Q-function that is reward-optimal under the action restrictions imposed by thr maximal safe set .
Proposition 2. If and for all , then is a -contraction under the sup-norm, , and converges to the unique fixed point , the optimal Q-function subject to the action restrictions imposed by .
In the tabular setting a Q-learning update for can be derived from a stochastic approximation of the fixed point of . When is also being updated simultaneously, must be replaced by in (11). As converges to the maximally safe policy, then will converge to letting the Q-learning update for truly become an approximation of . This is essentially the high-level reasoning used in the proof of Theorem 3 established in the next section.
3.1 RECREG for Tabular RL
In tabular RL, both the state space S and action space A are assumed to be of a manageable size. This setting admits explicit representations of value functions, exact or empirical transition models, and tractable verification of safety over finite horizons via probabilistic model checking [7]. We make the following central assumption for practical and theoretical reasons, which establishes that unsafe actions can be detected within a finite-horizon.
Assumption 1. There exists some finite horizon such that if then (where denotes bounded reachability).
Similar assumptions have been made in prior work [50] which reflect many real-world invariants, such as, a car that has exceeded its minimum stopping distance will inevitably collide with an obstacle in a bounded time, and a submarine that fails to resurface will exhaust oxygen within a finite limit. In practice can be treated as a hyperparameter, increasing it until the desired safety probability is met, or based on prior knowledge of the environment dynamics. Often the maximum distance from initial state to accepting state in the DFA is a good heuristic. Once the minimum is reached, increasing it further does not affect any guarantees, but may incur additional computational overhead.
Both the task policy and safe policy are represented by Q-tables: and . At each step, an action proposed by the task policy is either executed or replaced by a backup action
Algorithm 1 RECREG (Tabular)
Input:
Initialize:
for each episode do
Observe
for do
Sample action .
if then
Update via (11)
Resample action .
Execute and observe .
Update via (11)
Update with and ED [54].
if MODELBASED then
Update with
else if MODELFREE then
Update via (12)
according to . Any rejected action is used to update with the masked Bellman operator , accumulating zero value. The executed action is used to update all Q-tables correspondingly. Algorithm 1 provides a complete overview of the procedure and we continue by addressing each operation mode individually.
Exact. In EXACT mode, the transition kernel P of is assumed to be known (R still unknown). The maximally safe policy and maximal probabilistic safe set are computed offline via dynamic programming and probabilistic model checking in the product MDP [7]. During learning the task policy can be directly updated with with , ensuring optimality and convergence and satisfying the constraint in (3) immediately from the beginning of training.
Model-based. In MODELBASED mode, the transition kernel is unknown and estimated via empirical visit counts. For a given dataset of transitions , let denote the empirical transition kernel. Under Assumption 1 finite horizon reachability probabilities computed with via exact or statistical probabilistic model checking can be used to check . Proposition 3 establishes the conditions for this fact.
Proposition 3. Let and suppose the total variation distance between and is bounded by , i.e., for all . Then exact or statistical model checking with allows only if with probability 1 or w.p. at least respectively.
Furthermore to ensure the conditions of Proposition 3 are met we can, we can obtain a high probability safety guarantee for the MODELBASED mode, based on visit counts for each state-action pair.
Theorem 2. Let and . Under the conditions in Theorem 1 and Assumption 1, and if each is visited at least times, then by using exact (or statistical) model checking with , with shielded policy satisfies the step-wise risk level w.p. at least , and thus satisfies the global safety constraint in (3) w.p. at least .
Model-free. In MODELFREE mode, the finite-horizon safety value function is estimated via,
for . Intuitively by applying a stochastic approximation for the Bellman operator we can directly estimate the finite-horizon reachability probability (under ) by construction of the cost function and the max operator, avoiding model checking entirely. Then checking is implemented as a simple threshold check, i.e., . In Theorem 3 we establish unified convergence for all operation modes of RECREG, the statement is generic but complete and broken down for all operation modes in Appendix A.7.
Theorem 3. Assume: (i) and rewards are bounded and non-negative; (ii) the step-sizes for each Q-approximation satisfy standard stochastic approximation conditions (e.g., and ); (iii) the step-wise risk levels and initial states satisfy the conditions for Theorem 1; and (iv) Assumption 1 holds. Then, in all modes the task Q-iterates ( ) produced by stochastic approximation of converge w.p. 1 to the unique fixed point , i.e., the optimal Q-function subject to the action restrictions imposed by . And the deployed policy satisfies the global safety constraint in (3) w.p. 1.
3.2 RECREG with Deep RL
While the tabular case provides a convenient framework for obtaining concrete guarantees, many interesting applications of RL consider continuous or high-dimensional environments. Results from the tabular setting still hold under the assumption of a suitably accurate dynamics (analogous to the conditions in Proposition 3) [17, 18]. To utilize RECREG in these scenarios we adopt SOTA model-based RL, leveraging DREAMERV3's Recurrent State Space Model (RSSM) for joint dynamics learning and policy optimization [21]. The RSSM is a sequential variational auto-encoder type model that learns latent states and transition dynamics from observations. The RSSM includes a recurrent model , an encoder , a prior/transition predictor , an observation decoder , a reward head , and a termination head . Similar to approximate model-based shielding (AMBS) [17] we augment the RSSM with a cost head to model the cost function introduced in (10). Since the RSSM summarizes history in we can accurately learn the cost function in (10) by back-propagating its gradients through the RSSM to capture the temporal dependencies of the DFA without needing to build the product MDP or synchronize states. Both the task policy and safe policy are implemented as neural networks, with inputs derived from the RSSM latent state.
For distributions and on the finite set we define

Figure 1: Experimental results for the MASA-Safe-RL [16] benchmark. Normalized returns and safety probabilities are averaged over 10 random seeds for the final 100 episodes in training. The dashed horizontal line in the safety probability plots denotes the theoretical safety probability given by Theorem 1. Scores aggregated across all environments are provided in the bottom right corner.
To check if we rollout the latent dynamics with and thereafter for a fixed horizon , evaluating the cost head as a proxy for DFA satisfaction, and averaging over rollouts in parallel to obtain probability estimates. See Appendix B for further details.
4 Experimental Evaluation
Tabular RL. We consider a suite of tabular environments provided by MASA-Safe-RL [16], spanning navigation and control tasks, e.g., grid worlds and Pacman. For complete environment descriptions we refer the reader to Appendix D. The environments chosen cover a range of safety properties, from simple invariants to more complex regular safety constraints specified via automata. The difficulty varies both in terms of state-space size and the complexity of the underlying safety specification. We compare RECREG against several representative safe RL approaches. Logically-Constrained RL (LCRL) [25] incorporates LTL constraints via reward shaping and maximal end components. QL- follows Lagrangian-based approaches to LTL-constrained RL, treating the penalty coefficient as a hyperparameter [47, 53, 54]. Safe Exploration Mask (SEM) [58] learns auxiliary value functions to estimate proximity to unsafe states and controllability, suppressing risky actions by renormalizing the Q function. The conceptually closest baseline is RECOVERY RL [49], which learns a recovery policy to guide the agent back to safe regions although these are specified via safety critics with respect to the task policy, not the safe policy, leading to sub-optimal and overly conservative action replacement strategies. We also include three representative CMDP-based methods: PPO-LAG, TRPO-LAG [45] and CPO [2], adapted to the tabular setting, which enforce constraints in expectation via Lagrangian and trust-region updates respectively. The main results are presented in Fig. 1, with corresponding tabular summaries and full learning curves provided in Appendix C. Across environments, both modes of RECREG consistently achieve the desired safety probability, matching the theoretical constraint in almost all cases. Deviations primarily occur in larger state spaces, where estimation or exploration challenges arise. In contrast, baseline methods exhibit more variable safety performance, reflecting their heuristic nature or reliance on asymptotic guarantees. Even when satisfying the constraint, this often comes at the cost of reduced returns. Overall, RECREG provides a more reliable trade-off between safety and performance. Additional analyses, including runtime (across modes) and ablations (e.g., reward shaping [41] and counter factual experiences [30]), are in Appendix C.3.
Distributing risk in practice. For RECREG, distributing risk across timesteps is non-trivial. A simple baseline is to allocate risk uniformly, enforcing (where is the episode length), although this is typically overly conservative. A less naïve approach maintains a residual budget and updates it over time; however, directly subtracting the full tail risk (i.e.,
◇unsafe)) leads to double-counting of future risk. Instead, we subtract only the immediate risk of violation at each step and propagate the remaining budget by conditioning on survival, yielding a more accurate and less conservative update. The immediate and tail risk can be computed exactly (EXACT) or estimated (e.g., via MODELBASED or MODELFREE). More sophisticated approaches exist, such as PROBSHIELD, which allocates risk across successor states and preserves optimality under the global constraint , but induces a more complex action space that is harder to optimize [24]. Treating as a free hyperparameter is also possible, although it sacrifices the formal guarantees of Theorem 1.
Table 1: Experimental results for PROBSHIELD and RECREG-EXACT. Bold text denotes the best return; grey text denotes algorithms that fail the safety threshold.
| Algorithm | Metric | MediaStreaming | BridgeCrossing | ColourBomb...V2 (Prop. 3) | MiniPacman |
|---|---|---|---|---|---|
| RECREG-EXACT | Ep. Return Safety Prob. | ||||
| PROBSHIELD | Ep. Return Safety Prob. |
We directly compare EXACT-RECREG with PROBSHIELD, both of which assume full knowledge of the transition dynamics and provide formal safety guarantees. Results are summarized in Table 1. Both approaches satisfy the safety constraint across all environments (up to empirical error), PROBSHIELD struggles as its augmented action space scales poorly in the number of actions and successor states. In contrast, RECREG's simpler decision structure achieves stronger returns across the board.
Deep RL. We investigate RECREG with DreamerV3's RSSM [23] on two high-dimensional benchmarks, Atari Seaquest [39] and SafetyGym [45] (with pixel observations). The goal in Seaquest is to rescue divers while managing a limited supply of oxygen that can only be replenished at the surface. We run two separate experiments with two different safety properties and . The first (in LTL) , requires the agent to surface only when carrying a diver, never run out of oxygen, and avoid being hit by enemies (5 DFA-states). The second, , requires that once a diver has been picked up, the agent must return to the surface within 30 steps (31 DFA-states).

Figure 2: Learning curves for Atari Seaquest. Episodic reward and violation rate are averaged over 5 random seeds.
We compare with two representative baseline algorithms: DreamerV3 with the Augmented Lagrangian [56] and approximate model-based shielding (AMBS) [17]. The learning curves are presented in Figure 2, along with tabular summaries in Appendix B. For both properties and , RECREG with DreamerV3 outperforms all the baselines in terms of returns while also achieving a low violation rate. Note that property is closely aligned with “ideal” gameplay, thus the unconstrained DreamerV3 also obtains a low violation rate. Qualitative analysis can be found in the supplementary material. Due to space constraints the learning curves and results for SafetyGym are in Appendix B.
5 Conclusion
We introduced RECREG, a unified approach for enforcing high-probability satisfaction of regular safety properties in RL which, compared to the most closely related literature (e.g., Recovery RL [49]), provides formal safety and convergence guarantees, with optimality under step-wise constraints. The experimental results presented in this paper validate our theoretical claims, and provide further evidence that the separation of reward and safety objectives is an effective strategy towards safety-aware decision making. Future works includes extending to our method to more RL algorithms and other scenarios (e.g., safe control, policy-gradient).
References
[1] Alessandro Abate, Maria Prandini, John Lygeros, and Shankar Sastry. 2008. Probabilistic reachability and safety for controlled discrete time stochastic hybrid systems. Automatica 44, 11 (2008), 2724–2734.
[2] Joshua Achiam, David Held, Aviv Tamar, and Pieter Abbeel. 2017. Constrained policy optimization. In International conference on machine learning. PMLR, 22–31.
[3] M. Alshiekh, R. Bloem, R. Ehlers, B. Könighofer, S. Niekum, and U. Topcu. 2018. Safe reinforcement learning via shielding. In Proceedings of the AAAI Conference on Artificial Intelligence, Vol. 32.
[4] Eitan Altman. 1999. Constrained Markov decision processes: stochastic modeling. Routledge.
[5] Dario Amodei, Chris Olah, Jacob Steinhardt, Paul Christiano, John Schulman, and Dan Mané. 2016. Concrete problems in AI safety. arXiv preprint arXiv:1606.06565 (2016).
[6] Yarden As, Ilnura Usmanova, Sebastian Curi, and Andreas Krause. 2022. Constrained policy optimization via bayesian world models. arXiv preprint arXiv:2201.09802 (2022).
[7] Christel Baier and Joost-Pieter Katoen. 2008. Principles of model checking. MIT press.
[8] Stefan Banach. 1922. Sur les opérations dans les ensembles abstraits et leur application aux équations intégrales. Fundamenta mathematicae 3, 1 (1922), 133–181.
[9] Osbert Bastani, Shuo Li, and Anton Xu. 2021. Safe Reinforcement Learning via Statistical Model Predictive Shielding.. In Robotics: Science and Systems. 1–13.
[10] Roderick Bloem, Bettina Könighofer, Robert Könighofer, and Chao Wang. 2015. Shield synthesis: Runtime enforcement for reactive systems. In International conference on tools and algorithms for the construction and analysis of systems. Springer, 533–548.
[11] James Bradbury, Roy Frostig, Peter Hawkins, Matthew James Johnson, Chris Leary, Dougal Maclaurin, George Necula, Adam Paszke, Jake VanderPlas, Skye Wanderman-Milne, and Qiao Zhang. 2018. JAX: composable transformations of Python+NumPy programs. http://github.com/google/jax
[12] Steven Carr, Nils Jansen, Sebastian Junges, and Ufuk Topcu. 2023. Safe reinforcement learning via shielding under partial observability. In Proceedings of the AAAI Conference on Artificial Intelligence, Vol. 37. 14748–14756.
[13] Yinlam Chow, Mohammad Ghavamzadeh, Lucas Janson, and Marco Pavone. 2018. Risk-constrained reinforcement learning with percentile risk criteria. Journal of Machine Learning Research 18, 167 (2018), 1–51.
[14] Giuseppe De Giacomo, Luca Iocchi, Marco Favorito, and Fabio Patrizi. 2020. Restraining bolts for reinforcement learning agents. In Proceedings of the AAAI Conference on Artificial Intelligence, Vol. 34. 13659–13662.
[15] Richard Durrett and R Durrett. 1999. Essentials of stochastic processes. Vol. 1. Springer.
[16] Alexander W. Goodall, Omar Adalat, Edwin Hamel De-le Court, and Francesco Belardinelli. 2025. MASA-Safe-RL: Multi and Single Agent Safe Reinforcement Learning. https://github.com/sacktock/MASA-Safe-RL/. GitHub repository.
[17] Alexander W Goodall and Francesco Belardinelli. 2023. Approximate Model-Based Shielding for Safe Reinforcement Learning. In ECAI 2023. IOS Press, 883–890.
[18] Alexander W Goodall and Francesco Belardinelli. 2024. Leveraging Approximate Model-based Shielding for Probabilistic Safety Guarantees in Continuous Environments. In Proceedings of the 23rd International Conference on Autonomous Agents and Multiagent Systems. 2291–2293.
[19] Alexander W Goodall and Francesco Belardinelli. 2026. Safe Reinforcement Learning via Recovery-based Shielding with Gaussian Process Dynamics Models. arXiv preprint arXiv:2602.12444 (2026).
[20] Sven Gronauer, Tom Haider, Felippe Schmoeller da Roza, and Klaus Diepold. 2024. Reinforcement Learning with Ensemble Model Predictive Safety Certification. arXiv preprint arXiv:2402.04182 (2024).
[21] Danijar Hafner, Timothy Lillicrap, Ian Fischer, Ruben Villegas, David Ha, Honglak Lee, and James Davidson. 2019. Learning latent dynamics for planning from pixels. In International conference on machine learning. PMLR, 2555–2565.
[22] Danijar Hafner, Jurgis Pasukonis, Jimmy Ba, and Timothy Lillicrap. 2023. Mastering diverse domains through world models. arXiv preprint arXiv:2301.04104 (2023).
[23] Danijar Hafner, Jurgis Pasukonis, Jimmy Ba, and Timothy Lillicrap. 2025. Mastering diverse control tasks through world models. Nature 640, 8059 (2025), 647–653.
[24] Edwin Hamel-De le Court, Francesco Belardinelli, and Alexander W Goodall. 2025. Probabilistic Shielding for Safe Reinforcement Learning. In Proceedings of the AAAI Conference on Artificial Intelligence, Vol. 39. 16091–16099.
[25] Mohammadhosein Hasanbeig, Alessandro Abate, and Daniel Kroening. 2018. Logically-constrained reinforcement learning. arXiv preprint arXiv:1801.08099 (2018).
[26] Mohammadhosein Hasanbeig, Alessandro Abate, and Daniel Kroening. 2020. Cautious reinforcement learning with logical constraints. arXiv preprint arXiv:2002.12156 (2020).
[27] Chloe He, Borja G León, and Francesco Belardinelli. 2022. Do Androids Dream of Electric Fences? Safety-Aware Reinforcement Learning with Latent Shielding. (2022). https://ceur-ws.org/Vol-3087/paper_50.pdf
[28] Wassily Hoeffding. 1963. Probability Inequalities for Sums of Bounded Random Variables. J. Amer. Statist. Assoc. 58, 301 (1963), 13–30.
[29] Rodrigo Toro Icarte, Toryn Klassen, Richard Valenzano, and Sheila McIlraith. 2018. Using reward machines for high-level task specification and decomposition in reinforcement learning. In International Conference on Machine Learning. PMLR, 2107–2116.
[30] Rodrigo Toro Icarte, Toryn Q Klassen, Richard Valenzano, and Sheila A McIlraith. 2022. Reward machines: Exploiting reward function structure in reinforcement learning. Journal of Artificial Intelligence Research 73 (2022), 173–208.
[31] Tommi Jaakkola, Michael Jordan, and Satinder Singh. 1993. Convergence of stochastic iterative dynamic programming algorithms. Advances in neural information processing systems 6 (1993).
[32] Nils Jansen, Bettina Könighofer, Sebastian Junges, Alex Serban, and Roderick Bloem. 2020. Safe reinforcement learning using probabilistic shields. In 31st International Conference on Concurrency Theory (CONCUR 2020). Schloss-Dagstuhl-Leibniz Zentrum für Informatik.
[33] Jiaming Ji, Jiayi Zhou, Borong Zhang, Juntao Dai, Xuehai Pan, Ruiyang Sun, Weidong Huang, Yiran Geng, Mickel Liu, and Yaodong Yang. 2023. OmniSafe: An Infrastructure for Accelerating Safe Reinforcement Learning Research. arXiv preprint arXiv:2305.09304 (2023).
[34] Michael Kearns and Satinder Singh. 2002. Near-optimal reinforcement learning in polynomial time. Machine learning 49 (2002), 209–232.
[35] Bettina Könighofer, Julian Rudolf, Alexander Palmisano, Martin Tappler, and Roderick Bloem. 2021. Online shielding for stochastic systems. In NASA Formal Methods Symposium. Springer, 231–248.
[36] Bettina Könighofer, Julian Rudolf, Alexander Palmisano, Martin Tappler, and Roderick Bloem. 2023. Online shielding for reinforcement learning. Innovations in Systems and Software Engineering 19, 4 (2023), 379–394.
[37] Hanna Krasowski, Jakob Thumm, Marlon Müller, Lukas Schäfer, Xiao Wang, and Matthias Althoff. 2023. Provably safe reinforcement learning: Conceptual analysis, survey, and benchmarking. Transactions on Machine Learning Research (2023).
[38] Qingkai Liang, Fanyu Que, and Eytan Modiano. 2018. Accelerated primal-dual policy optimization for safe reinforcement learning. arXiv preprint arXiv:1802.06480 (2018).
[39] Marlos C. Machado, Marc G. Bellemare, Erik Talvitie, Joel Veness, Matthew J. Hausknecht, and Michael Bowling. 2018. Revisiting the Arcade Learning Environment: Evaluation Protocols and Open Problems for General Agents. Journal of Artificial Intelligence Research 61 (2018), 523–562.
[40] Anastasios Manganaris, Vittorio Giammarino, and Ahmed H Qureshi. 2025. Automaton Constrained Q-Learning. arXiv preprint arXiv:2510.05061 (2025).
[41] Andrew Y Ng, Daishi Harada, and Stuart Russell. 1999. Policy invariance under reward transformations: Theory and application to reward shaping. In Icml, Vol. 99. 278–287.
[42] Amir Pnueli and Roni Rosner. 1989. On the synthesis of a reactive module. In Proceedings of the 16th ACM SIGPLAN-SIGACT symposium on Principles of programming languages. 179–190.
[43] Martin L Puterman. 2014. Markov decision processes: discrete stochastic dynamic programming. John Wiley & Sons.
[44] Aravind Rajeswaran, Igor Mordatch, and Vikash Kumar. 2020. A game theoretic framework for model based reinforcement learning. In International conference on machine learning. PMLR, 7953–7963.
[45] Alex Ray, Joshua Achiam, and Dario Amodei. 2019. Benchmarking safe exploration in deep reinforcement learning. arXiv preprint arXiv:1910.01708 7, 1 (2019), 2.
[46] Danbing Seto, Bruce Krogh, Lui Sha, and Alongkrit Chutinan. 1998. The simplex architecture for safe online control system upgrades. In Proceedings of the 1998 American Control Conference. ACC (IEEE Cat. No. 98CH36207), Vol. 6. IEEE, 3504–3508.
[47] Ameesh Shah, Cameron Voloshin, Chenxi Yang, Abhinav Verma, Swarat Chaudhuri, and Sanjit A Seshia. 2024. Deep Policy Optimization with Temporal Logic Constraints. arXiv preprint arXiv:2404.11578 (2024).
[48] Chen Tessler, Daniel J Mankowitz, and Shie Mannor. 2018. Reward constrained policy optimization. arXiv preprint arXiv:1805.11074 (2018).
[49] Brijen Thananjeyan, Ashwin Balakrishna, Suraj Nair, Michael Luo, Krishnan Srinivasan, Minho Hwang, Joseph E Gonzalez, Julian Ibarz, Chelsea Finn, and Ken Goldberg. 2021. Recovery rl: Safe reinforcement learning with learned recovery zones. IEEE Robotics and Automation Letters 6, 3 (2021), 4915–4922.
[50] Garrett Thomas, Yuping Luo, and Tengyu Ma. 2021. Safe reinforcement learning by imagining the near future. Advances in Neural Information Processing Systems 34 (2021), 13859–13869.
[51] Emanuel Todorov, Tom Erez, and Yuval Tassa. 2012. Mujoco: A physics engine for model-based control. In 2012 IEEE/RSJ international conference on intelligent robots and systems. IEEE, 5026–5033.
[52] Mark Towers, Ariel Kwiatkowski, Jordan Terry, John U Balis, Gianluca De Cola, Tristan Deleu, Manuel Goulão, Andreas Kallinteris, Markus Krimmel, Arjun KG, et al. 2024. Gymnasium: A standard interface for reinforcement learning environments. arXiv preprint arXiv:2407.17032 (2024).
[53] Cameron Voloshin, Hoang Le, Swarat Chaudhuri, and Yisong Yue. 2022. Policy optimization with linear temporal logic constraints. Advances in Neural Information Processing Systems 35 (2022), 17690–17702.
[54] Cameron Voloshin, Abhinav Verma, and Yisong Yue. 2023. Eventual discounting temporal logic counterfactual experience replay. In International Conference on Machine Learning. PMLR, 35137–35150.
[55] Tsachy Weissman, Erik Ordentlich, Gadiel Seroussi, Sergio Verdu, and Marcelo J Weinberger. 2003. Inequalities for the L1 deviation of the empirical distribution. Hewlett-Packard Labs, Tech. Rep (2003), 125.
[56] Jorge Nocedal Stephen J Wright. 2006. Numerical optimization.
[57] Wenli Xiao, Yiwei Lyu, and John Dolan. 2023. Model-based Dynamic Shielding for Safe and Efficient Multi-agent Reinforcement Learning. In Proceedings of the 2023 International Conference on Autonomous Agents and Multiagent Systems. 1587–1596.
[58] Chengbin Xuan, Feng Zhang, and Hak-Keung Lam. 2022. SEM: Safe exploration mask for q-learning. Engineering Applications of Artificial Intelligence 111 (2022), 104765.
[59] Cambridge Yang, Michael Littman, and Michael Carbin. 2021. On the (in) tractability of reinforcement learning for LTL objectives. arXiv preprint arXiv:2111.12679 (2021).
[60] Tsung-Yen Yang, Justinian Rosca, Karthik Narasimhan, and Peter J Ramadge. 2020. Projection-based constrained policy optimization. arXiv preprint arXiv:2010.03152 (2020).
A Proofs
A.1 Theorem 10.52 in [7]
Theorem 4 ([Variant of Theorem 10.52 in [7]). For a fixed policy from state , the safety probability under the path measure ,
where and,
where is the path measure in the product MDP (c.f., Definition 1) under policy .
Proof. For a given DFA we start by recursively defining the extended transition function as . The language accepted by the DFA is then defined as,
Now let D be the safety property whose language is precisely the set of bad prefixes for , then formally,
We continue with the following auxiliary results.
Corollary 1. For any path , there exists a unique run for the trace , denote,
where the and for all . This is easy to see because the transition function is deterministic.
Lemma 1. Consider a fixed path and corresponding run , trace and path (defined in Corollary 1), then,
Proof. (⇒). By definition if and only if . Recall the definition , thus implies that there exists some such that , then by construction (c.f. Definition 1) this implies that .
(⇐). By LTL semantics and Definition 1 (product MDP), unsafe implies that for the unique run there exists such that . We notice that since then once the DFA reaches an accepting state it will remain in an accepting state for the rest of the run, if not we can derive a contradiction (e.g., if there is an unsafe prefix for a trace not in then this violates the definition of a safety property and thus ). Therefore, if there exists such that then , which implies that .
Noticing that the DFA D is deterministic and does not affect the path probabilities in the product Markov chain we supply the following Corollary.
Corollary 2. For every measurable set of paths P in M,
where is defined as before (see Corollary 1). The proof can be found in [7].
It remains to build the appropriate . Let be the set of paths starting in some that refute , i.e.,
and is the set of paths starting in that eventually reach an accepting ('unsafe' labelled) state in the DFA , i.e.,
then by construction (of P and ) we have,
Finally, the probability and are related as follows,
This completes the proof.
A.2 Proof of Proposition 1
Proposition 1 (restated). The optimal policy that minimizes the expected return under eventual discounting [54] and with rewards given by (10), is such that for any (is maximally safe).
Proof. We start by proving the existence of a non-empty maximally safe set for all , under the assumption that there exists at least one policy with non-zero safety probability.
Consider the transition kernel for a fixed policy in the product MDP (c.f., Definition 1). Standard Markov chain results imply that the Markov chain induced by partitions the state space into a disjoint union of transient states (visited finitely many times) and irreducible recurrent classes [15], i.e. . We also denote as the set of states labelled as “unsafe” in the product MDP , i.e., (see Definition 1). Assuming there exists at least one policy with non-zero safety probability, i.e., , s.t. , then we can conclude that,
In words, there exists at least one policy such that there is a recurrent set with no “unsafe” states. Thus which implies for all . Since for all and then for all by our earlier observation. This completes the first part of the proof.
We continue by showing the optimal policy under eventual discounting is also maximally safe. First we define the optimal policy under the eventual-discounted return [54]; discounting only on accepting product states (i.e., product states in ).
where,
We can rewrite this in terms of the expected eventual-discounted return along “safe” and “unsafe” paths,
Now consider the following two facts:
(1) All “safe” paths have a discounted return of zero.
(2) All “unsafe” paths have a discounted return of precisely (as the accepting product state constitutes a strongly connected end component, i.e., once you enter you cannot leave).
Thus,
Given is a constant, then,
To complete the proof we derive a contradiction.
Suppose that the optimal policy (minimizing the eventual-discounted return) is not maximally safe. Then that means there exists some and such that, but . However, by definition we have,
Substituting in our previous result, we have,
Thus implies that , which directly contradicts our assumption that . Therefore, the optimal policy that minimizes the eventual-discounted return must also be a maximally safe policy.
A.3 Proof of Theorem 1
Theorem 1 (restated). Assume that all initial states satisfy the global safety constraint under the safe policy, i.e., . Then if the step-wise risk budgets satisfy , then the shielded policy satisfies , .
Proof. Without loss of generality we fix an initial state and and prove by induction.
Let , be the last time that used an action sampled from the task policy . Consider the following two cases:
(1) No such exists. Then always picks actions , in that case we have , given that, from the theorem statement.
(2) If then the last time that allowed (at timestep ), we verified that , thus for the remainder of the episode we have . By a simple union bound the probability of reaching an unsafe state up until timestep (i.e., at timestep ) is less than . Thus, by union bounding both events we establish the following lower bound on the safety probability,
A.4 Proof of Proposition 2
Proposition 2 (restated). If and for all , then is a -contraction under the sup-norm, , and converges to the unique fixed point , the optimal Q-function subject to the action restrictions imposed by .
Proof. In this proof we aim to show the following:
(1) is a -contraction under the sup-norm (i.e., ).
(2) Iterating on converges to the unique fixed point .
(3) is the optimal state-action value function subject to the action restrictions imposed by .
Contraction property. We define the sup-norm (or max norm) for Q-functions in the metric space on as follows,
The goal is to show that,
We identify the following two cases,
(1) unsafe action under step-wise constraint . Then,
(2) safe action under step-wise constraint . Then,
subtracting,
combining both cases and taking the maximum over establishes (13).
Unique fixed point. (i) and (ii) in the proposition statement are sufficient conditions to apply the Banach Fixed Point Theorem [8], which states (informally), any -contraction in a complete metric space (bounded real-valued functions on ) has: a unique fixed point, which is obtained by iterative application of the operator.
Therefore, starting from any , we let denote the fixed point of the operator . Furthermore, satisfies,
Optimal state-action value function. We argue that the fixed point of the operator , namely is the optimal state-action value function subject to the action restrictions imposed by the maximally safe set . Furthermore, the corresponding greedy policy upper bounds every safe policy in terms of discounted reward. First we establish the following Lemmas.
Lemma 2. For every such that , we have,
Proof. This is a direct consequence of the Bellman operator ; since is a fixed point of ,
and by construction whenever .
Let the set of safe policies be,
And for any safe policy define the policy evaluation operator,
Lemma 3. Monotonicity of the operator For every and for every in the metric space on ,
Proof. The proof is a straightforward argument by cases:
(1) If then both sides are zero, so the inequality holds.
(2) If then is identical to the usual optimality update but maximizing only over safe actions (all unsafe actions have value 0); the expectation under is a convex combination of those same safe actions, thus its value cannot exceed the maximum.
Corollary 3. For any starting function and any safe policy
Taking gives,
which follows from Lemma 3 and because (by the contraction property) and . Thus no safe policy can achieve a higher value than .
Now define the greedy safe policy as,
Since rewards are non-negative, then for all , thus we always implicitly prioritize safe actions first when taking the arg max (recall all unsafe actions have value 0, c.f., Lemma 2). Ties can be broken in the arg max by picking any available safe action, when for example, all safe and unsafe actions have value 0. We require one final lemma before putting it all together.
Lemma 4 (Bellman consistency for ).
Proof. (1) If then both sides are zero, so the equality holds.
(2) If then,
by construction puts all its probability mass on the maximizing action , thus the RHS equals .
Since the value for all unsafe actions is precisely 0 by Lemma 2 and any safe policy (those restricted to only permissible actions) has value upper bounded by (c.f., Corollary 3), with the greedy policy achieving equality (c.f., Lemma 4). Therefore equals:
(1) 0 if ,
(2) if .
Hence is precisely “Q-function subject to the action restrictions imposed by ”.
A.5 Proof of Proposition 3
Before we begin the proof we start with some auxiliary lemmas. First we establish a lower bound on the number of samples required for statistical model checking m. With the transition kernel P.
Lemma 5. Let , , , , and be given. By sampling paths, , with the transition kernel (c.f., Definition 1), we can estimate within an error bound and w.p. at least .
Proof. Formally, let be indicator random variables such that,
Note that unsafe can be checking in time and even parallelized across the batch. Now let,
and notice that,
then by Hoeffding's inequality [28],
Bounding the RHS by and rearranging gives the desired result.
We continue with a variant of the Error Amplification Lemma, which establishes a linear (in H) worst-case error amplification when sampling paths from the empirical transition kernel .
Lemma 6 (Error amplification for path distributions). Let , the start state and be given. Suppose true transition kernel and the empirical transition kernel are such that,
Let and denote the path distributions (at timestep ) for the two Markov chains with transition kernels and respectively. Then the L1-distance between the two path distributions is bounded as follows,
Proof. First we provide formal definitions for the path distributions and . Let,
where,
are the corresponding transition kernels. The probability reads: “the probability of the prefix at time ”. The proof now follows by induction on , for the base case we have,
since the start state is fixed for both. Before we continue with the induction, we make the following observation for any path ,
(14)
holds by the triangle inequality. Now we continue with the induction on t,
(15)
(16)
Here (15) comes from the definition of the L1-distance: . The rest follows from our earlier observations (triangle inequality) and assumptions in the lemma statement.
We continue now with the main proof for Proposition 3. Restating the proposition here.
Proposition 3 (restated). Let and suppose the total variation distance between and is bounded by , i.e., for all . Then exact or statistical model checking with allows only if with probability 1 or w.p. at least respectively.
Proof. For convenience let with probability taken under and let be defined analogously but with probability taken under . Furthermore, let and denote the average path distribution (over the next timesteps) for the two Markov chains under and respectively. Formally,
abusing notation here (by dropping the action a which is now fixed and assumed to be implicit). Before continuing we make the following observation,
(1) Let be a real valued function. Let and be probability distributions over the space , then,
Thus,
Here (21) comes from our preceding observation, (22) and (23) are by construction and (25) comes from the result of Lemma 6 (by substituting in ). This intermediate result is closely related to the simulation lemma [34], which has been proved for the model-based setting (with bounded L1-distance) [44].
Now to put it all together. It has been established that . Thus, if we calculate the quantity via model checking (or similar), then we can obtain an estimate for (i.e., the quantity we are interested in, namely, ). Consider the two cases:
(1) Exact model checking: with the empirical (product) transition kernel , we can precisely calculate via exact probabilistic model checking with matrix multiplications [7].
(2) Statistical model checking: by sampling paths with the empirical (product) transition kernel , we can estimate with an error of up to and with confidence at least . This follows from Lemma 5.
Thus via exact (or statistical model) checking we have established that we can estimate with an error up to w.p. 1 (or at least resp.).
Let denote our estimate for , the final part of the proof concerns how we use our estimate checking if .
To establish the only if direction we take a conservative view of our uncertainty that does not permit “false positives”, i.e., Assuming (by the proposition statement), only if , this holds as follows.
Since we have already established that or at least , then implies that (w.p. or ). Furthermore, under Assumption 1, implies that and thus is allowed only if w.p. 1 or at least .
A.6 Proof of Theorem 2
We start with an auxiliary result for transition kernel estimation. The proof of Theorem 2 follows closely thereafter.
Lemma 7. Let . Then if each is visited at least times, then w.p. at least the empirical transition kernel satisfies for all .
Proof. First for a given dataset let,
and
The by standard results for L1-distances [55], the TV-distance between P and is bounded as follows,
Bounding the RHS from above by and rearranging gives the following lower bound for ,
Finally, taking a union bound over all state action pairs (of which there are many) completes the proof.
Theorem 2 (restated). Let and . Under the conditions in Theorem 1 and Assumption 1, and if each is visited at least times, then by using exact (or statistical) model checking with , with shielded policy satisfies the step-wise risk level w.p. at least , and thus satisfies the global safety constraint in (3) w.p. at least .
Proof. The proof is a relatively straightforward application of Lemma 7 and Proposition 3. Firstly, by Lemma 7, if each is visited at least times, then we have,
w.p. at least . Now that (27) satisfies the conditions of Proposition 3, then exact (or statistical) model checking with allows only if w.p. 1 or at least .
Finally, taking a union bound now over both the L1-distance and model checking procedure gives us a worst case step-wise failure probability . Thus at timestep , allows only if w.p. at least , which by definition provides a step-wise safety guarantee of . On the other hand, if cannot be verified, then by induction it can be shown that the step-wise safety guarantee of holds, using similar reasoning as in the proof of Theorem 1. Taking a union bound over the step-wise failure probability completes the proof.
A.7 Proof of Theorem 3
Theorem 3 (restated). Assume: (i) and rewards are bounded and non-negative; (ii) the step-sizes for each Q-approximation satisfy standard stochastic approximation conditions (e.g., and ); (iii) the step-wise risk levels and initial states satisfy the conditions for Theorem 1; and (iv) Assumption 1 holds. Then, in all modes the task Q-iterates ( ) produced by stochastic approximation of converge w.p. 1 to the unique fixed point , i.e., the optimal Q-function subject to the action restrictions imposed by . And the deployed policy satisfies the global safety constraint in (3) w.p. 1.
Proof. The proof is lengthy and split into several parts, each addressing the three different operation modes of RECREG to a different extent. We summarize the organization below and detail parts are required for convergence of the different operation mode.
-
(MODELBASED and MODEFREE). We establish convergence of the safe policy and corresponding probabilistic safe set to the maximally safe policy and maximal safe set respectively.
-
(MODELBASED and MODEFREE). We establish convergence of the indicator used in the Bellman operator .
-
(EXACT, MODELBASED and MODEFREE) Analysing convergence of the shielded policy defined in Eq. (3) under a perfect indicator .
-
(MODELBASED). Analysing the optimality of under corruptions that might persist as a consequence of using statistical model checking
Convergence of the safe policy. We first formalize the convergence claim for the backup policy with the following Lemma.
Lemma 8 (Convergence of the safe policy). Consider the finite product MDP and without loss of generality assume the accepting set is made absorbing. The cost function in (10) can thus be equivalently defined,
Define the eventual-discounting scheme with state-dependent discount factor,
and consider the update step,
with step-sizes satisfying the Robbins-Monro conditions,
and such that every is visited infinitely often. Further, assuming the initialization,
For each state-action pair define,
Then
as . Consequently, any greedy policy with respect to is maximally safe, and for every product state visited infinitely often,
where is the greedy policy induced by , with a fixed deterministic tie-breaking rule.
Proof. Since is absorbing, every trajectory has a well-defined hitting time,
Under the eventual-discounting convention, no discounting is applied before , and after the process remains in and receives a cost of 1 geometrically discounted by . Hence, for any policy and first action ,
where,
Taking the infimum over policies,
gives the optimal policy that minimizes the eventual-discounted return, which as established in Proposition 1 is a maximally safe policy.
It remains to justify convergence of the update rule under the conditions of the Lemma. Consider the following Bellman operator
for which the update rule in the Lemma statement is precisely the stochastic approximation of the fixed point equation,
The operator is not necessarily a -contraction in the sup-norm as outside of . Thus we require a proper stochastic shortest path condition. Assume that there exists at least one safe policy such that, from every state-action pair with , the accepting set is reached with positive probability in finite time. Equivalently the product MDP decomposes into an absorbing unsafe class and at least one safe recurrent class that is disjoint from . The holds under the assumption of existence of a non-empty maximally safe set which as established in the proof of Proposition 1 is true if there exists at least one safe policy, which in turn follows from the Theorem statement (all initial states have probability not more than of reaching under ).
On any closed safe recurrent class the accumulated cost is precisely zero, while on the accumulated cost is . This is exactly a stochastic avoidance, or stochastic shortest-path, structure associated with the reachability objective.
Under this condition has a unique fixed point on the interval,
and this fixed point is the optimal avoidance value as shown above. Consider writing the update rule equivalently as follows,
where is the martingale-difference noise induced by sampling . Since and for all , and the iterates are initialized in the interval , the update targets are bounded. Thus, the noise has bounded conditional second moment.
Standard stochastic approximation results for finite stochastic shortest-path problems can thus be applied [31]. Furthermore, the usual Robbins-Monro conditions and infinite visitation of every state-action pair implies that, (almost surely) as and for every . Finally, because,
and , minimizing over actions is equivalent to minimizing . Therefore every greedy policy with respect to is maximally safe. Since almost surely and the greedy policy uses a fixed deterministic tie-breaking rule, for every product state visited infinitely often,
This completes the proof.
Convergence of the indicator We provide the following Lemma to establish this result.
Lemma 9 (Convergence of the indicator). Denoting as the time varying empirical indicator for the true function , then
as
Proof. By Lemma 8, converges almost surely to a maximally safe policy. Therefore the reachability probabilities defining converge to those defining .
In the MODELBASED case we argue that almost surely under infinite exploration. Fix a state-action pair visited infinitely often, then given that is a consistent unbiased estimator for, we have,
Since finite-horizon reachability probabilities are continuous polynomials in the transition probabilities over horizon , then this is sufficient to complete the proof for this mode.
In the MODELFREE case (12) is a finite-horizon dynamic-programming recursion for the probability of reaching within steps when the first action is and the safe policy is followed thereafter. Since the horizon is finite, can be evaluated backward from depth . Given each operator is non-expansive and bounded in , and the stochastic approximation thereof has noise that is a martingale-difference sequence with bounded variance, then standard stochastic approximation results [31] yield the following result,
as . Therefore the time-varying indicator converges almost surely to the true maximal safe set indicator . Assumption 1 then does the heavy lifting transferring the finite-horizon check to an infinite-horizon safety guarantee.
Before continuing with the convergence properties of the Q-iterates we formally establish the following assumption which follows from Lemma 9.
Assumption 2 (Eventual correctness of the indicator). For every there exists some (finite, possibly random) time such that,
Thus the indicator may be wrong at first but (almost surely) stops making mistakes.
Convergence of the shielded policy. We provide the following Lemma to establish this result.
Lemma 10. Let be the time-varying analogue for the safety-aware Bellman operator , concretely,
Then under Assumption 2, for the corresponding update step,
with step-sizes satisfying the usual Robbins-Monro conditions and such that every is visited infinitely often. Then with probability 1,
where is the unique fixed point of .
Proof. The only difference between and is where a wrong safety indicator is used. Since all rewards are bounded and non-negative (i.e., for all ), then we have a simple bound,
where is the 0-1 error. By Assumption 2 we have, is eventually zero for all . Thus,
We are now equipped to apply standard stochastic approximation results [31], as we have already established that is a -contraction with a unique fixed point in Proposition 2. Furthermore, the total bias injected into each is bounded (since ), and thus,
thus we meet the sufficient conditions for convergence of the update rule given by,
Noting that as , we have and by uniqueness the Q-iterates for (29) converges (almost surely) with probability 1 to .
Persistent corruptions
Lemma 11 (Optimal policy under -corruptions). Define the -corrupted safety-aware Bellman operator,
where B is the usual Bellman optimality operator defined as,
the Q-iterates for the corresponding stochastic approximation,
converge to,
under the usual Robbins-Monro conditions and such that every is visited infinitely often.
Proof. It can easily be shown that is still a -contraction but perturbed by , i.e., for every function , on the metric space , we have,
Thus the stochastic approximation in (32) converges to a unique fixed point. It remains to determine where this fixed point is in relation to (the fixed point of ).
We define the following quantity,
Noting that for all Q we have,
Then by (30) we have,
then standard perturbation results for -contractions give the desired result,
☐
Conclusion. In EXACT mode, the indicator is computed directly from the true product MDP, so the task update is a stochastic approximation of the fixed Bellman operator . Proposition 2 gives that is a -contraction hence almost surely converges to its unique fixed point .
In MODELBASED mode, Lemma 8 establishes convergence of to the maximally safe policy, and Lemma 9 gives eventual correctness of the safe set indicator. After the almost-sure finite time at which the indicator is correct, the task policy update is again an ordinary stochastic approximation of , and therefore converges almost surely to . When statistical model checking is used, the only additional error is the failure probability . By standard the Hoeffding bounds used in Lemma 5, m samples paths gives failure probability decreasing exponentially in m, thus can be driven to zero rapidly, with only logarithmic dependence on the desired confidence.
In MODELFREE mode, the same conclusion follows from convergence of the finite-horizon safety value function Bellman update established Lemma 9, The learned indicator becomes correct almost surely, after which the task update is again governed by the operator . Therefore, in all three modes,
as . Finally, Theorem 1 applies to the deployed shielded policy which enforces the step-wise risk levels that satisfy . The by construction satisfies the global safety constraint in (3), which completes the proof.
B RECREG with Deep RL
B.1 Overview
RECREG with DreamerV3's RSSM [23] is described in Section 3.2. Here we provide a high level overview. Figure 3 illustrates how the probability is estimated. Algorithm 2 provides the high-level algorithmic framework for DEEP-RECREG.

Figure 3: Estimating the safety probability with RSSM.
Algorithm 2 RECREG with DreamerV3
Input: D, hyperparameters: , m, H.
Initialize: replay buffer D, DreamerV3 parameters , task policy and safe policy .
1: for each episode do 2: Observe observation . 3: for do 4: // Shielding with the latent world model 5: Sample . 6: Using and sample m trajectories . 7: // Compute the probability estimate 8: . 9: if . 10: Execute and observe . 11: Compute DFA state and let . 12: Append to the replay buffer D. 13: if time_to_update then 14: // World model learning 15: Sample a batch B of transition sequences . 16: Update DreamerV3 parameters with maximum likelihood [22]. 17: // Task policy optimization 18: Sample sequences with the task policy . 19: Update the task policy with RL (to maximize reward). 20: Update the corresponding value critics with maximum likelihood. 21: // Safe policy optimization 22: Sample sequences with the safe policy . 23: Update the safe policy with RL (to minimize cost). 24: Update the corresponding value critics with maximum likelihood.
B.2 Implementation Details
Here we provide additional implementation details including environment descriptions and training details.
Atari Seaquest. Seaquest is an Atari 2600 game provided as part of the Arcade Learning Environment (ALE) [39] (c.f., Fig. 4).
• Dynamics: the agent (submarine) can navigate freely in the water.

Figure 4: Seaquest environment
• Action space: Seaquest utilizes the full Atari controller action space (18 distinct actions), which includes all possible combinations of FIRE, UP, DOWN, LEFT, RIGHT.
• State space: Seaquest is partially observable, the observations correspond to pixel images provided by the ALE. The observations are pre-processed and scaled to tensors corresponding to pixel values with RGB information intact.
• Additional modifications: We also use frame_skip=4 (every 4 frames are skipped with the agent's action repeated) and sticky_actions=0.25 (there is a 0.25 chance that the agent's previous action is repeated), which is in line with the recommended settings for Atari games [39].
• Reward function: the agent receives reward for collecting divers and returning them to the surface, and “shooting” enemy sharks and submarines.
• Episode length: .
• Safety properties:
-
property_1 ( ): the agent must only surface with a diver, avoid running out of oxygen and avoid being hit by enemy “sharks” and “submarines”, i.e., .
-
property_2 ( ): the agent must return to the surface in at most 30 timesteps after picking up a diver, i.e., .
• Automaton size: for property_1 and for property_2.
• Cost thresholds:
- RECREG and AMBS: .
– DreamerV3 (Aug. Lag.), PPO-Lag and CPO: 1.0
• Cost coefficient: .
• Model checking horizon: for Property 1 ( ) and for Property 2 ( ).
• All other hyperparameters remained untouched and are detailed in Table 4
SafetyGym. SafetyGym [45] is built on the advanced physics simulator, MuJoCo [51]. In our experiments we use three separate environments: PointGoal1, PointGoal2 and CarGoal1. The first two environment use the Point vehicle for navigation in the environment and the third environment uses the Car vehicle.

(a) Point

(b) Car
Figure 5: Safety Gym vehicles.
• Dynamics: the agent navigates a static environment with one of two vehicles (c.f., Fig 5):
– Point: A simple vehicle that is constrained to the 2D plane. One actuator controls the rotation of the vehicle the other controls its linear movement. The simple control scheme makes the robot easy to control. The corresponding action space is .
– Car: This vehicle exhibits more realistic dynamics, with two independently driven wheels. The mechanics are 3D, although the vehicle mostly resides in the 2D plane. The vehicle has a free moving wheel at the front that is not connected to any actuators. The control scheme is a little more advanced since, rotating, and moving forward and backwards require coordination between the two driven wheels. However, the action space is identical, i.e. .
• Action space: .
• State space: the agent observes pixel images rendered from a front facing camera in MuJoCo. As a result the environment is partially observable.
• Reward function: the agent receives a reward of +1 for entering a goal state (c.f., Fig 6a). The goal state and obstacles are then re-initialized to randomly generated positions.
• Episode length: .
• Safety properties:
-
For PointGoal1 and CarGoal1: hazard
-
For PointGoal2: (hazard vase)
• Automaton size: .
• Cost thresholds:
- RECREG and AMBS: .
– DreamerV3 (Aug. Lag.), PPO-Lag and CPO: 1.0
• Cost coefficient: .
• Model checking horizon:
• All other hyperparameters remained untouched and are detailed in Table 4.

(a) Goal positions
(b) Hazards
(c) Vases
Figure 6: Safety Gym tasks and constraints.
Access to code. The code for the additional experiments on Atari Seaquest is our own private branch of the AMBS code base [17], please refer to https://github.com/sacktock/AMBS (MIT License) for setup instructions. Our private code can be made available upon reasonable request. Furthermore, the implementations for PPO-Lag [45] and CPO [2] were provided by Omnisafe [33], for setup instructions please refer to the Omnisafe code base https://github.com/PKU-Alignment/omnisafe (Apache-2.0 license).
Training details. We has access to 2 NVIDIA Tesla A40 (48GB RAM) GPU and a 24-core/48 thread Intel Xeon CPU each with 32GB-64GB of additional RAM. Each run for Atari Seaquest can take 8 hours to 1 day (per seed) depending on the exact configuration of DreamerV3, in general we see a slow down of factor of roughly 2 when using AMBS and RECREG compared to the unmodified DreamerV3 baseline. Memory requirements may differ depending on the DreamerV3 configuration used, for the xlarge configuration 32GB of GPU memory will suffice.
Statistical significance. Standard error (SE) intervals are provided for each of our experiments in Tab. 2 and Tab. 3. In particular, we report 5 random initializations (seeds) for each experiment. In the learning curves, we plot the non-parametric (bootstrap) 95% confidence intervals, provided by seabornLINEplot with default parameters: errorbar='('ci', 95), n_boot=1000. The error bars capture the randomness in the initialization of the policy parameters (and DreamerV3 world model), the randomness of the environment and any randomness in the batch sampling.
B.3 Atari Seaquest results
We provide tabular results for the Atari Seaquest experiments (c.f., Table 2) and a larger version of Figure 2 from the main text (c.f., Figure 7).
Table 2: Results for the deep RL experiments on Atari Seaquest. The violation rate is scaled by .
| DreamerV3 | Aug. Lag. | AMBS | DEEP-RECREG | PPO-Lag | CPO | ||
|---|---|---|---|---|---|---|---|
| seaquest () | Return | 2440 ± 400 | 706 ± 162 | 2350 ± 340 | 3140 ± 326 | 506 ± 7.57 | 543 ± 47.4 |
| Viol. rate | 5.30 ± 0.657 | 9.83 ± 1.39 | 4.20 ± 0.215 | 4.43 ± 0.187 | 25.6 ± 0.468 | 23.9 ± 1.97 | |
| seaquest () | Return | 2440 ± 400 | 580 ± 54.0 | 2480 ± 483 | 2700 ± 364 | 79.6 ± 10.5 | 342 ± 17.1 |
| Viol. rate | 17.9 ± 5.77 | 1.86 ± 0.891 | 2.00 ± 0.767 | 2.52 ± 0.673 | 16.8 ± 2.17 | 22.0 ± 4.45 | |

Figure 7: Learning curves for Atari Seaquest. Episodic reward and violation rate are averaged over 5 random seeds.
B.4 SafetyGym results
We provide additional results for SafetyGym [45]. Table 3 provides tabular scores for each of the experiments and Figure 8 provides the learning curves.
Table 3: Results for the deep RL experiments on SafetyGym.
| DreamerV3 | Aug. Lag. | AMBS | DEEP-RECREG | ||
|---|---|---|---|---|---|
| PointGoal1 | Return | ||||
| Viol. rate | |||||
| PointGoal2 | Return | ||||
| Viol. rate | |||||
| CarGoal1 | Return | ||||
| Viol. rate | |||||

Figure 8: Learning curves for Safety Gym environments. Episodic reward and violation rate are averaged over 5 random seeds.
Discussion (Safety Gym). AMBS and DEEP-RECREG are almost inseparable with markedly similar performance profiles. Both achieve relatively low violation rates but do not achieve the best returns. Broadly speaking DEEP-RECREG achieves slightly better returns but slightly higher violation rates compared with AMBS across the board. On the other end of the spectrum, the unconstrained DreamerV3 achieves the highest returns but does not meaningfully reduce safety violations. The Augmented Lagrangian has a harder time at reducing safety violations likely due to fluctuating penalties but achieves higher returns than both AMBS and DEEP-RECREG.
Table 4: Hyperparameter details for the DreamerV3-based algorithms: Aug. Lag., AMBS and DEEP-RECREG.
| Name | Symbol | Value |
|---|---|---|
| Replay capacity | ||
| Batch size | ||
| Batch length | - | |
| Number of envs | - | |
| Train ratio | - | |
| Number of MLP layers | - | |
| Number of MLP units | - | |
| Activation | - | LayerNorm + SiLU |
| World Model (shared) | ||
| Number of latents | - | |
| Classes per latent | - | |
| RSSM loss scales | ||
| Predictor loss scales | ||
| Learning rate | - | |
| Adam epsilon | ||
| Gradient clipping | - | |
| World Model (Atari Seaquest) | ||
| Number of layers | - | |
| Number of hidden units | - | |
| Number of recurrent units | - | |
| CNN depth | - | |
| World Model (SafetyGym) | ||
| Number of layers | - | |
| Number of hidden units | - | |
| Number of recurrent units | - | |
| CNN depth | - | |
| Actor Critic (shared) | ||
| Roll-out horizon | - | |
| Discount factor | ||
| TD lambda | ||
| Critic EMA decay | - | |
| Critic EMA regularizer | - | |
| Return norm. scale | ||
| Return norm. limit | ||
| Return norm. decay | - | |
| Actor entropy scale | ||
| Learning rate | - | |
| Adam epsilon | ||
| Gradient clipping | - | |
| DEEP-RECREG (and AMBS) | ||
| Number of samples | ||
| Step-wise risk | ||
| Failure probability | ||
| Lookahead/shielding horizon | ||
| Approximation error | ||
| Cost coefficient (safe policy) | ||
| Augmented Lagrangian | ||
| Penalty multiplier | ||
| Initial Lagrange multiplier | ||
| Penalty power | ||
| Cost coefficient | ||
| Cost threshold | - | |
C Additional Results
Here we provide tabular summaries of the results presented in Figure 1.
Table 5: Experimental results with raw returns. Bold text denotes the best value among algorithms satisfying the safety threshold; grey text denotes algorithms that fail the safety threshold.
| Algorithm | Metric | MediaStreaming | BridgeCrossing | BridgeCrossingV2 | Colour...World |
|---|---|---|---|---|---|
| QL | Ep. ReturnSafety Prob. | ||||
| QL() | Ep. ReturnSafety Prob. | ||||
| RECREG | Ep. ReturnSafety Prob. | ||||
| RECREG-MODELBASED | Ep. ReturnSafety Prob. | ||||
| SEM | Ep. ReturnSafety Prob. | ||||
| LCRL | Ep. ReturnSafety Prob. | ||||
| CPO | Ep. ReturnSafety Prob. | ||||
| PPO-Lag | Ep. ReturnSafety Prob. | ||||
| TRPO-Lag | Ep. ReturnSafety Prob. |
Table 6: Experimental results with normalized returns. Bold text denotes the best value among algorithms satisfying the safety threshold; grey text denotes algorithms that fail the safety threshold.
| Algorithm | Metric | ColourBomb...(Prop. 2) | ColourBomb...V2 | ColourBomb...V2 (Prop. 2) | Colour...V2 (Prop. 3) | MiniPacman |
|---|---|---|---|---|---|---|
| QL | ||||||
| QL( ) | ||||||
| RECREG | ||||||
| RECREG-MODELBASED | ||||||
| SEM | ||||||
| LCRL | ||||||
| CPO | ||||||
| PPO-Lag | ||||||
| TRPO-Lag | ||||||
C.1 Learning Curves (tabular)
Here we provide the learning curves for all our experiments on the tabular environments provided in the MASA-Safe-RL library [16].

Figure 9: Learning curves for Media Streaming.

Figure 10: Learning curves for Bridge Crossing.

Figure 11: Learning curves for Bridge Crossing V2.

Figure 12: Learning curves for Colour Bomb Gridworld (Property 1).

Figure 13: Learning curves for Colour Bomb Gridworld (Property 2).

Figure 14: Learning curves for Colour Bomb Gridworld V2 (Property 1).

Figure 15: Learning curves for Colour Bomb Gridworld V2 (Property 2).

Figure 16: Learning curves for Colour Bomb Gridworld V2 (Property 3).

Figure 17: Learning curves for Mini Pacman.
C.2 Learning Curves (PROBSHIELD)
Here we provide the learning curves for our experiments comparing RECREG-EXACT to PROBSHIELD.

Figure 18: Learning curves for Media Streaming.

Figure 19: Learning curves for Bridge Crossing.

Figure 20: Learning curves for Colour Bomb Gridworld V2 (Property 3).

Figure 21: Learning curves for Mini Pacman.
C.3 Ablation Studies
We conduct a simple ablation study for Colour Bomb Gridworld V2 with Property 2. The DFA for Property 2 has 22 states, meaning the product MDP has 22 times more states than the original MDP. In particular, we ablate the use of counter-factual experiences [30] for training the task and safe policy. We also investigate the effect of two reward shaping mechanisms based on the idea of potential-based reward shaping [41]. First we provide a primer.
Potential-based reward shaping. Potential-based reward shaping is an approach used to typically deal with sparse or delayed reward environments. Potential-based reward shaping provides intermediate rewards of the following form,
where is the potential function. Intuitively this provides the agent with a dense reward signal for moving to ‘more promising’ states with higher potential values. Note that by discounting the potential values with the original discount factor this keeps the set of optimal policies that maximize the original reward function unchanged [41]. Then if the potential function is useful in some sense, this allows us to learn optimal policies more quickly.
Automated reward shaping. Automated reward shaping (RS) for reward machines (RM) was proposed in [30]. We adopt the same methodology here. The potential function is defined over product state space , each automaton state is assigned a potential value . The potential value for each automaton state is then computed by running value iteration with a different discount factor . The cost function for the safe policy is then redefined as,
Intuitively the value function essentially assigns automaton states that are closer to the accepting state with higher values. This in turn penalized the agent for moving closer to the accepting state in the automaton.
Cycle-based reward shaping. This approach is inspired by cycle experience replay [47] which was used for full LTL constraints. The approach is as follows, we first compute the length shortest path through the DFA D, from each automaton state to the initial state , e.g., via breadth-first search. Each automaton state is assigned a value which corresponds to the length of the shortest path from to , which will be used for potential-based reward shaping. This provides an incentive to the agent to return to the initial state as quickly as possible (short cycles), while avoiding the accepting states of the DFA D, which are sink nodes, i.e. . Again, the cost function is redefined as in (34).
Results for RECREG-MODELFREE. Figure 22 provides the learning curves for RECREG-MODELFREE with the two different potential-based reward shaping approaches. First we see that without counter-factual experiences (CFE) the algorithm struggles to converge quickly and achieves a low safety probability due to slower convergence of the safe policy. Automated (Potential) reward shaping destabilizes learning slightly and the algorithm converges suboptimally, whereas cycle-based reward shaping improves learning stability and converges optimally.

Figure 22: Reward Shaping for Colour Bomb Gridworld V2 with RECREG-MODELFREE.
Results for QL- . Figure 23 provides the learning curves for QL- with the two different potential-based reward shaping approaches. Again we see that without counter-factual experiences (CFE) the algorithm struggles to converge quickly. However, in contrast to before both automated (Potential) and reward shaping fully destabilizes learning collapsing the policy to the safest possibly policy (no reward). Whereas cycle-based reward shaping improves both safety and task performance uniformly finding the right balance. This highlights the difficulty with tuning Lagrangian approaches like QL- , subtle shifts in the cost function and penalty magnitudes can break the balance between task performance and safety.

Figure 23: Reward Shaping for Colour Bomb Gridworld V2 with QL- .
C.4 Runtime Analysis
Running a model checking routine at each decision making step inevitable incurs some non-trivial computational overhead. This overhead grows as the size of the MDP or DFA increases. In Tab. 7 we provide a quick runtime comparison for the different operation mode of RECREG on environments of varying size. For reference EXACT and MODELFREE operate at roughly the same speed as the other mode-free tabular baselines (e.g., Q-learning).
Table 7: Frames per second (fps) for different RECREG modes.
| EXACT & MODELFREE | MODELBASED (exact) | MODELBASED (stat. m=10,000) | |
|---|---|---|---|
| media_streaming | ~ 2600fps | ~ 1300fps | ~ 90fps |
| bridge_crossing | ~ 2200fps | ~ 1000fps | ~ 80fps |
| 15 × 15_gridworld (3) | ~ 2000fps | ~ 525fps | ~ 60fps |
| mini_pacman | ~ 2600fps | ~ 250fps | ~ 27fps |
D Environment Details
Here we provide a more complete description of each of the tabular environments considered in the main paper. Please note that all environments are provided as part of MASA-Safe-RL https://github.com/sacktock/MASA-Safe-RL [16]. The exact same implementations are provided in our code submitted in the supplementary material.
Media Streaming. The environment models a simple data-buffer management task, where the agent must regulate packet inflow to prevent buffer underflow.
• Dynamics: packets leave in the data-buffer according to a Bernoulli process with rate .
• Action space:
-
fast adds new packets with rate .
-
slow adds new packets with rate .
• State space: 20 different buffer states .
• Reward function: The agent receives a penalty of -1.0 when choosing the fast action.
• Episode length: .
• Safety property: The buffer must never become empty ( empty).
• Automaton size: .
• Cost thresholds:
-
RECREG (lower-bound): .
-
PPO-Lag / CPO (cost upper-bound): 0.04.
-
QL- (coefficient): 100.0.
-
Rec. RL (step-wise upper-bound): .
• Model checking horizon: .

Figure 24: The Bridge Crossing environment.
Bridge Crossing. In this environment the agent acts in a “slippery” gridworld (c.f., Fig. 24), i.e., there is a 0.04 chance that the agent’s action is ignored and another action is uniformly sampled.
• Dynamics: typical gridworld dynamics with slip probability 0.04.
• Action space:
• State space: different locations in the gridworld .
• Reward function: The agent receives a reward of 1.0 and terminates when entering either the yellow goal states.
• Episode length: .
• Safety property: the agent must avoid all red lava states ( lava).
• Automaton size: .
• Cost thresholds:
- RECREG (lower-bound): .
– PPO-Lag / CPO (cost upper-bound): 0.05.
- QL- (coefficient): 10.0.
– Rec. RL (step-wise upper-bound): .
• Model checking horizon: .

Figure 25: The Bridge Crossing V2 environment.
Bridge Crossing V2. In this environment the agent acts in a “slippery” gridworld (c.f., Fig. 24), i.e., there is a 0.04 chance that the agent’s action is ignored and another action is uniformly sampled.
• Dynamics: typical gridworld dynamics with slip probability 0.04.
• Action space:
• State space: different locations in the gridworld .
• Reward function: The agent receives a reward of 1.0 and terminates when entering either the yellow goal states.
• Episode length: .
• Safety property: the agent must avoid all red lava states ( lava).
• Automaton size: .
• Cost thresholds:
– RECREG (lower-bound): .
– PPO-Lag / CPO (cost upper-bound): 0.01.
– QL- (coefficient): 10.0.
– Rec. RL (step-wise upper-bound): .
• Model checking horizon: .

Figure 26: The Colour Bomb Gridworld environment.
Colour Bomb Gridworld. The access point for this environment in MASA is under the env id: colour_bomb_gridworld. In this environment the agent acts in a “slippery” gridworld (c.f., Fig. 26) with a 0.1 chance that the agent’s action is ignored and another action is uniformly sampled.
• Dynamics: typical gridworld dynamics with slip probability 0.1.
• Action space:
• State space: different locations in the gridworld .
• Reward function: The agent receives a reward of 1.0 and terminates when entering either the blue, pink or yellow states.
• Episode length: .
• Safety properties:
– Property 1: avoid all B states ( ).
– Property 2: if B state is reached the agent must remain there for one additional timestep .
• Automaton size: for Property 1 and for Property 2.
• Cost thresholds:
– RECREG (lower-bound): .
– PPO-Lag / CPO (cost upper-bound): 0.05.
– QL- (coefficient): 10.0.
– Rec. RL (step-wise upper-bound): .
• Model checking horizon: for Property 1 and 2.

Figure 27: The Colour Bomb Gridworld V2 environment
Colour Bomb Gridworld V2. The access point for this environment in MASA is under the env id: colour_bomb_gridworld_v2. In this environment the agent acts in a “slippery” gridworld (c.f., Fig. 27) with a 0.1 chance that the agent’s action is ignored and another action is uniformly sampled.
• Dynamics: typical gridworld dynamics with slip probability 0.1. After entering a coloured goal state, the agent transitions to a random starting (S) state.
• Action space:
• State space: different locations in the gridworld .
• Reward function: The agent receives a reward of 1.0 when entering the (non-terminal) coloured states blue, pink, red, green or yellow states.
• Episode length: .
• Safety properties:
– Property 1: avoid all B states ( ).
– Property 2: if B state is reached the agent must remain there for one additional timestep .
– Property 3: If a B state is reached the agent must reach a M state and remain there for 2 timesteps all within 10 timesteps ( ).
• Automaton size: for Property 1, for Property 2 and for Property 3.
• Cost thresholds:
-
RECREG (lower-bound): .
-
PPO-Lag / CPO (cost upper-bound): 0.025.
-
QL- (coefficient): 10.0.
-
Rec. RL (step-wise upper-bound): .
• Model checking horizon: for Property 1 and 2; for Property 3.

Figure 28: The Mini Pacman environment.
Mini Pacman. The agent (Pacman) operates in a Pacman world, with one ghost and one piece of food (yellow circle) to collect (c.f., Fig. 28). The agent can exit via the bottom right hand corner, although from the initial configuration the ghost is likely to catch the agent if it heads straight for the food or exit.
• Dynamics: typical Pacman dynamics: can only change direction at an intersection and turn around when facing a wall. The ghost follows the path with shortest Manhattan distance to the agent at every point, but with probability 0.6 picks a random action.
• Action space:
• State space: Accounting for all valid configurations for the Pacman’s location, direction and the ghost’s location and direction, there are precisely 8124 game states .
• Reward function: The agent receives a reward of 1.0 when it enters the location with the food present (c.f., Fig. 28); once the food is picked up it disappears.
• Episode length: (no termination upon collecting the food, but can terminate via the exit).
• Safety property: The agent must avoid the ghost for the entire duration of the episode, even after picking up the food ( ghost)
• Automaton size: .
• Cost thresholds:
-
RECREG (lower-bound): .
-
PPO-Lag / CPO (cost upper-bound): 0.01.
-
QL- (coefficient): 10.0.
-
Rec. RL (step-wise upper-bound): .
• Model checking horizon: .
E Hyperparameters and Code
Access to code. The tabular environments are provided by MASA-Safe-RL [16] (MIT license) and implemented with Gymnasium [52] (MIT license). Tabular Q-learning is implemented with numpy in Python, the model checking procedures (both exact and statistical) are implemented with JAX [11] (Apache-2.0 license) which supports vectorized computation on GPU and CPU. For PPO-Lag [45] and CPO [2], we use the implementations provided by Omnisafe [33], the code for running these benchmarks is mostly public facing at https://github.com/sacktock/MASA-Safe-RL our private code can also be made available upon reasonable request, for setup instructions please refer to the Omnisafe code base https://github.com/PKU-Alignment/omnisafe (Apache-2.0 license).
Training details. For collecting all sets of experiments we has access to 2 NVIDIA Tesla A40 (48GB RAM) GPU and a 24-core/48 thread Intel Xeon CPU each with 32GB of additional RAM. Each run for the tabular experiments can take anywhere from several minutes to several hours depending on the number of training steps and the complexity of the environment or safety property being used.
Statistical significance. Standard error (SE) intervals are provided in Table 5 & 6 for each of our experiments. In particular, we report 10 random initializations (seeds) for each experiment. In the learning curves (c.f., Section C.1) and bar charts (c.f., Figure 1), we plot the non-parametric (bootstrap) 95% confidence intervals, provided by seaborn.plot with default parameters: errorbar=('ci', 95), n_boot=1000. The error bars capture the randomness in the initialization of the policy parameters and batch sampling (e.g., for PPO-Lag and CPO), and any randomness in the environment.
E.1 Hyperparameters for Tabular Algorithms
Here we provide hyperparameter details for all of the tabular algorithms tested in MASA-Safe-RL [16]. For more concrete per-environment hyperparameter settings we encourage the reader to study the relevant python scripts provided in the supplementary material.
Table 8: Hyperparameter details for Q-Learning based algorithms: RECREG Rec. RL, QL-λ, SEM, LCRL.
| Name | Symbol | Value |
|---|---|---|
| Q-Learning (shared) | ||
| Learning rate | {0.05, 0.1} | |
| Discount factor | {0.95, 0.99} | |
| Exploration type | - | {Boltzmann, Epsilon-greedy} |
| Boltzmann Temp. | 0.05 | |
| Epsilon start | 1.0 | |
| Epsilon final | 0.05 | |
| Epsilon decay | - | Linear |
| Decay steps | - | 250,000 |
| Counter factual experiences | - | True |
| RECREG | ||
| Model checking type | - | Statistical (for MODELBASED) |
| Number of samples | 8124 | |
| Step-wise risk | Variable (c.f., Section 4) | |
| Failure probability | 0.0001 | |
| Model checking horizon | Variable (c.f., Section D) | |
| Approximation error | 0.0005 | |
| RECREG (Safe policy ) | ||
| Learning rate | {0.05, 0.1} | |
| Discount factor | {0.95, 0.99} | |
| Exploration type | - | {Boltzmann, Epsilon-greedy} |
| Boltzmann Temp. | 0.01 | |
| Cost coefficient | - | 10.0 |
| Rec. RL | ||
| Risk Critic Alpha | 0.1 | |
| Risk Critic Gamma | 0.99 | |
| Step-wise risk | Variable (c.f., Section D) | |
| Q-λ | ||
| Dual variable | {1.0, 10.0, 100.0} | |
| SEM | ||
| metric learning rate | 0.1 | |
| metric discount | 0.95 | |
| metric learning rate | 0.05 | |
| metric discount | 0.999 | |
E.2 Hyperparameters for PPO-Lag and CPO
Table 9: Hyperparameter details for PPO-Lag, TRPO-Lag and CPO.
| Name | Symbol | Value |
|---|---|---|
| PPO-Lag, TRPO-Lag, CPO shared (Tabular) | ||
| Actor learning rate (PPO-Lag) | ||
| Critic learning rate (CPO/TRPO-Lag) | ||
| Discount factor | ||
| Cost coefficient | ||
| Cost threshold | - | Variable (c.f., Section D) |
| Cost gamma | ||
| TD-lambda | ||
| Cost TD-lambda | ||
| Max grad norm | - | |
| Entropy coefficient | - | |
| Update iterations (per epoch) | ||
| Steps per epoch | ||
| CPO, TRPO-Lag shared trust region (Tabular) | ||
| Target KL divergence | ||
| Conjugate gradient iterations | - | |
| Conjugate gradient damping | - | |
| FVP sample frequency | - | |
| Line search steps | - | |
| Line search decay | - | |
| PPO, CPO shared (Atari Seaquest) | ||
| Actor/critic learning rate | ||
| Discount factor | ||
| Cost coefficient | ||
| Cost threshold | - | |
| Cost gamma | ||
| TD-lambda | ||
| Cost TD-lambda | ||
| Max grad norm | - | |
| Entropy coefficient | - | |
| Steps per epoch | ||
| PPO-Lag, TRPO-Lag shared (Tabular and Atari Seaquest) | ||
| Initial Lagrangian multiplier | ||
| Lagrangian learning rate | ||
| Lagrangian upper bound | ||
| PPO-Lag (Tabular and Atari Seaquest) | ||
| Epsilon clip | ||
| Batch size | ||
E.3 Hyperparameter details for PROSHIELD
Table 10: Hyperparameter details for PROSHIELD.
| Name | Symbol | Value |
|---|---|---|
| ProbShieldWrapperDisc | ||
| Initial safety bound | 0.01 | |
| Max VI Steps | - | 10,000 |
| VI Cut off | - | |
| Disc. Granularity | - | 20 |
| PPO (underlying algorithm) | ||
| Num. steps | - | 2048 |
| Num. envs. | - | 1 |
| Batch size | - | 64 |
| training epochs | n_epochs | 10 |
| Discount factor | 0.99 | |
| (GAE) lambda | 0.95 | |
| Clip range | 0.2 | |
| Normalize | - | advantages |
| Ent. coef. | 0.0 | |
| Value coef. | 1.0 | |
| optimizer | - | adam (max_grad=0.5, ) |
| learning rate | - | |
| network | - | 2-layers; 64 units; ReLU |
| optimizer | - | adam (max_grad=0.5, ) |
| learning rate | - | |
| network | - | 2-layers; 64 units; ReLU |