Part I · Foundations of Sequential Decision-Making

4.Markov Decision Processes: The Formalism

S&B ch. 3Tang §3.2Rusty
The Markov property recapitulates the idea of state — a state is a sufficient statistic for predicting the future.
Jens Kober, J. Andrew Bagnell & Jan Peters · TU Delft · Carnegie Mellon · TU Darmstadt
Reinforcement Learning in Robotics — A Survey, IJRR 2013

Chapter 3 removed state to isolate exploration. Now we put it back, and the whole subject changes character. Once an action influences what you face next, the value of an action must account for the future it leads to — and that self-reference, embraced rather than avoided, is the Bellman equation. This chapter derives it in full, proves the fixed-point machinery of Chapter 2 applies to it, and then confesses the thing most textbooks postpone: robots never see the state, so the honest formalism is a POMDP.

Foundation

The finite MDP tuple, returns and discounting, value functions, Bellman expectation and optimality equations derived in full, γ-contraction proofs, and the belief-MDP construction.

Conceptual

Rusty's warehouse as a formal object: click any cell to read its transition distribution, and watch the optimal policy respond to the model rather than to a hyperparameter.

Practical

The rl-core gym — Space, Env and Mdp traits — the abstraction every later chapter builds on, plus exact value solving by linear algebra.

After this chapter you can

  • Write down a finite MDP and compute its dynamics, expected rewards, and returns from the four-argument function p(s′,r|s,a)
  • Derive the Bellman expectation equations for v_π and q_π line by line, naming every step
  • Derive the Bellman optimality equations and explain exactly where linearity dies
  • Prove that both Bellman operators are γ-contractions, and cash the Chapter 2 theorem for existence and uniqueness
  • Explain what a belief state is and why partial observability is the normal case in robotics, not the exception
  • Recognize the same robot task as a different MDP depending on the action-space level you choose

4.1 The finite MDP

A finite Markov decision process is a tuple (S,A,p,γ)(\mathcal{S}, \mathcal{A}, p, \gamma) where S\mathcal{S} and A\mathcal{A} are finite sets of states and actions, γ[0,1)\gamma \in [0,1) is a discount factor, and the dynamics are captured by a single function

p(s,rs,a)P(St+1=s,Rt+1=rSt=s,At=a),p(s', r \mid s, a) \doteq \mathbb{P}\big(S_{t+1} = s',\, R_{t+1} = r \mid S_t = s,\, A_t = a\big),

satisfying srp(s,rs,a)=1\sum_{s'}\sum_r p(s',r \mid s,a) = 1 for every (s,a)(s,a). Everything else is derived from it. Marginalizing the reward gives the state-transition probabilities,

p(ss,a)=rp(s,rs,a),p(s' \mid s, a) = \sum_r p(s', r \mid s, a),

and weighting by reward gives the expected immediate reward,

r(s,a)=E[Rt+1St=s,At=a]=rrsp(s,rs,a).r(s,a) = \mathbb{E}[R_{t+1} \mid S_t = s, A_t = a] = \sum_r r \sum_{s'} p(s', r \mid s, a).

Note the indexing convention, inherited from Chapter 1: the reward Rt+1R_{t+1} arrives after action AtA_t. It is a consequence, not a property of the state you were in.

Rusty's warehouse, fixed once for the rest of Part I. A 12×912 \times 9 grid with shelf blocks removed, leaving about 80 traversable cells. Four actions {N,E,S,W}\{N, E, S, W\}. Slip probability pslip=0.2p_{\text{slip}} = 0.2, split evenly between the two lateral directions. Rewards: +25+25 for reaching the dock, 1-1 per step, 10-10 for bumping a shelf. Discount γ=0.95\gamma = 0.95. Chapters 5, 6 and 7 use these exact numbers, so results are comparable across algorithms.

The warehouse as an MDP

ch04-mdp-editor

Click any floor cell to read its dynamics. The heatmap shows v*, the arrows show the greedy policy π*.

Inspect action
D
-15.523.8V(s)

Selected state

s = 0

v*(s)

-15.5

optimal value

p(s′, r | s, a = )

next s′reward rprobability
1-10.80
12-10.10
0 (blocked)-100.10
sums to1.00

q*(s, a) — one-step lookahead

-23.78
-16.03
-15.52
-23.71

The greedy action is the argmax — this is exactly the operation the Bellman optimality equation performs at every state.

With p_slip = 0 the dynamics are deterministic and the arrows take the shortest path, hugging the shelves. Raise the slip and the optimal policy backs away from the shelving — a −10 bump that happens 10% of the time outweighs the step saved. Nothing about the algorithm changed; the model did.

4.2 Returns, and why we discount

The agent's goal is not to maximize immediate reward but the return — the accumulated reward from time tt onward:

GtRt+1+γRt+2+γ2Rt+3+=k=0γkRt+k+1.G_t \doteq R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}.

For a continuing task this is an infinite sum, and we need it to be finite. If rewards are bounded by RmaxR_{\max}, the geometric series gives

Gtk=0γkRmax=Rmax1γ,|G_t| \le \sum_{k=0}^{\infty} \gamma^k R_{\max} = \frac{R_{\max}}{1 - \gamma},

which is finite exactly because γ<1\gamma < 1. Discounting is not a modelling nicety; without it the objective may not be defined.

The single most useful property of the return is its recursion, obtained by factoring γ\gamma out of everything after the first term:

Gt=Rt+1+γRt+2+γ2Rt+3+=Rt+1+γ(Rt+2+γRt+3+)=Rt+1+γGt+1.\begin{aligned} G_t &= R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots \\ &= R_{t+1} + \gamma\left(R_{t+2} + \gamma R_{t+3} + \cdots\right) \\ &= R_{t+1} + \gamma\, G_{t+1}. \end{aligned}

Everything that follows in this book is, in some sense, this one line taken seriously.

4.3 Value functions and the Bellman expectation equations

A policy π(as)\pi(a \mid s) is a distribution over actions in each state. The state-value function is the expected return from following it:

vπ(s)Eπ[GtSt=s],v_\pi(s) \doteq \mathbb{E}_\pi\left[G_t \mid S_t = s\right],

and the action-value function fixes the first action before following π\pi thereafter:

qπ(s,a)Eπ[GtSt=s,At=a].q_\pi(s,a) \doteq \mathbb{E}_\pi\left[G_t \mid S_t = s, A_t = a\right].

Now the derivation. Every step is either the return recursion, the tower property from Chapter 2, or the definition of expectation.

Theorem 4.1Bellman expectation equation for v_π

For any policy π\pi and all sSs \in \mathcal{S},

vπ(s)=aπ(as)s,rp(s,rs,a)[r+γvπ(s)].v_\pi(s) = \sum_a \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a)\Big[r + \gamma\, v_\pi(s')\Big].

Proof

Start from the definition and substitute the return recursion Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}:

vπ(s)=Eπ[GtSt=s]=Eπ[Rt+1+γGt+1|St=s].v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s] = \mathbb{E}_\pi\left[R_{t+1} + \gamma G_{t+1} \,\middle|\, S_t = s\right].

Expand the expectation over the immediate randomness — which action π\pi chooses, and which (s,r)(s', r) the environment returns:

=aπ(as)s,rp(s,rs,a)[r+γEπ[Gt+1St+1=s]].= \sum_a \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a) \Big[ r + \gamma\, \mathbb{E}_\pi\left[G_{t+1} \mid S_{t+1} = s'\right] \Big].

Two justifications are needed for that line. First, conditioning on St+1=sS_{t+1} = s' inside the bracket is the tower property (Theorem 2.2): we average the return-from-next-step over where we land. Second, replacing Eπ[Gt+1St+1=s,St=s,At=a]\mathbb{E}_\pi[G_{t+1} \mid S_{t+1} = s', S_t = s, A_t = a] with Eπ[Gt+1St+1=s]\mathbb{E}_\pi[G_{t+1} \mid S_{t+1} = s'] uses the Markov property — given ss', the past is irrelevant.

The inner expectation is vπ(s)v_\pi(s') by definition, giving the result. \qquad \blacksquare

The same argument applied to qπq_\pi yields its twin:

qπ(s,a)=s,rp(s,rs,a)[r+γaπ(as)qπ(s,a)].q_\pi(s,a) = \sum_{s',r} p(s',r \mid s,a)\left[r + \gamma \sum_{a'} \pi(a' \mid s')\, q_\pi(s', a')\right].

This is a linear system. With S|\mathcal{S}| unknowns and S|\mathcal{S}| equations, we can write it in matrix form as vπ=rπ+γPπvπv_\pi = r_\pi + \gamma P_\pi v_\pi and solve directly:

vπ=(IγPπ)1rπ,v_\pi = (I - \gamma P_\pi)^{-1} r_\pi,

with the inverse guaranteed to exist by the Neumann-series argument from §2.6. For Rusty's 80-state warehouse this is a trivial linear solve. For a robot with a continuous state space it is hopeless, which is what drives Part II.

4.4 Optimality, and the moment linearity dies

Define a partial order on policies: ππ\pi \ge \pi' if vπ(s)vπ(s)v_\pi(s) \ge v_{\pi'}(s) for all states. There always exists an optimal policy π\pi_* that is at least as good as every other, and all optimal policies share the same value functions:

v(s)=maxπvπ(s),q(s,a)=maxπqπ(s,a).v_*(s) = \max_\pi v_\pi(s), \qquad q_*(s,a) = \max_\pi q_\pi(s,a).

The optimal value function satisfies a self-consistency condition of its own — but now with a maximum where the policy average used to be.

Theorem 4.2Bellman optimality equations

v(s)=maxas,rp(s,rs,a)[r+γv(s)],v_*(s) = \max_a \sum_{s',r} p(s',r\mid s,a)\Big[r + \gamma\, v_*(s')\Big],

q(s,a)=s,rp(s,rs,a)[r+γmaxaq(s,a)].q_*(s,a) = \sum_{s',r} p(s',r \mid s,a)\Big[r + \gamma \max_{a'} q_*(s',a')\Big].

The argument is that v(s)v_*(s) must equal the value of the best action available at ss, evaluated under optimal behaviour thereafter. If some action had a higher one-step-lookahead value, the policy that took it and then behaved optimally would beat π\pi_* — contradiction.

Two consequences follow immediately, and they are the reason this equation is worth its fame.

Greedy is optimal. Any policy that acts greedily with respect to vv_* is optimal. A one-step lookahead using vv_* already accounts for all future consequences, because that is what vv_* encodes. With qq_* it is even easier — no lookahead at all, just π(s)=argmaxaq(s,a)\pi_*(s) = \arg\max_a q_*(s,a). This is why so much of RL is the pursuit of qq_*: get it, and the policy is free.

A deterministic optimal policy always exists for a finite MDP: pick any argmax at each state.

4.5 The contraction, at last

Chapter 2 built the fixed-point machinery. Here is what it was for.

Define the Bellman optimality operator TT_* on value functions by

(Tv)(s)maxas,rp(s,rs,a)[r+γv(s)],(T_* v)(s) \doteq \max_a \sum_{s',r} p(s',r \mid s,a)\left[r + \gamma\, v(s')\right],

and the policy-evaluation operator TπT_\pi analogously with aπ(as)\sum_a \pi(a\mid s) in place of the max. The Bellman equations say precisely that vv_* and vπv_\pi are the fixed points of these operators.

Theorem 4.3Both Bellman operators are γ-contractions in the sup norm

For any value functions u,vu, v,

TuTvγuv,\|T_* u - T_* v\|_\infty \le \gamma\, \|u - v\|_\infty,

and likewise for TπT_\pi.

Proof

Fix a state ss. We use the elementary inequality maxaf(a)maxag(a)maxaf(a)g(a)\left|\max_a f(a) - \max_a g(a)\right| \le \max_a |f(a) - g(a)|, which holds because the maximizer of one function is a feasible choice for the other.

(Tu)(s)(Tv)(s)maxas,rp(s,rs,a)[r+γu(s)]s,rp(s,rs,a)[r+γv(s)]=maxaγsp(ss,a)[u(s)v(s)]γmaxasp(ss,a)u(s)v(s)γmaxasp(ss,a)uv=γuv,\begin{aligned} \left|(T_* u)(s) - (T_* v)(s)\right| &\le \max_a \left| \sum_{s',r} p(s',r\mid s,a)\Big[r + \gamma u(s')\Big] - \sum_{s',r} p(s',r\mid s,a)\Big[r + \gamma v(s')\Big] \right| \\[4pt] &= \max_a \left| \gamma \sum_{s'} p(s' \mid s,a)\big[u(s') - v(s')\big] \right| \\[4pt] &\le \gamma \max_a \sum_{s'} p(s'\mid s,a) \left| u(s') - v(s') \right| \\[4pt] &\le \gamma \max_a \sum_{s'} p(s'\mid s,a)\, \|u - v\|_\infty = \gamma\, \|u - v\|_\infty, \end{aligned}

using sp(ss,a)=1\sum_{s'} p(s'\mid s,a) = 1 in the last step. The rewards cancel exactly because they do not depend on the value function. Taking the maximum over ss on the left gives the claim. \qquad \blacksquare

Now cash Chapter 2's theorem. The space of bounded value functions with the sup norm is complete, so Banach applies and delivers, at no additional cost:

  1. vv_* exists and is the unique fixed point of TT_*;
  2. iterating vk+1=Tvkv_{k+1} = T_* v_k converges to it from any starting point — including the all-zeros initialization every implementation uses;
  3. convergence is geometric at rate γ\gamma, with a computable error bound that tells you when to stop.

That last item is not decoration: it is the stopping rule for value iteration, and Chapter 5's dashboard displays it live.

4.6 The confession: robots never see the state

Everything above assumes the agent observes StS_t. Rusty does not. He has wheel encoders that drift, a lidar that returns noisy ranges, and no oracle telling him which cell he occupies.

The honest formalism is a partially observable MDP — an MDP plus an observation space Ω\Omega and an observation model O(os,a)O(o \mid s', a). The agent sees oto_t, never sts_t.

The standard repair is to maintain a belief bt(s)=P(St=so1:t,a1:t1)b_t(s) = \mathbb{P}(S_t = s \mid o_{1:t}, a_{1:t-1}), a distribution over states. It updates by Bayes' rule: after taking aa and observing oo,

b(s)=O(os,a)sp(ss,a)b(s)sO(os,a)sp(ss,a)b(s),b'(s') = \frac{O(o \mid s', a) \sum_s p(s' \mid s, a)\, b(s)}{\sum_{s''} O(o \mid s'', a) \sum_s p(s'' \mid s, a)\, b(s)},

where the numerator predicts forward and reweights by the observation likelihood, and the denominator normalizes.

The remarkable fact is that the belief is Markov even though the observation is not: bt+1b_{t+1} depends only on btb_t, ata_t and ot+1o_{t+1}. So a POMDP is an MDP over beliefs — all the theory above still applies. The catch is that the belief space is continuous even when S\mathcal{S} is finite, and solving POMDPs exactly is PSPACE-hard.

4.7 The same robot, different MDPs

One more idea before the code, because it reframes everything: the MDP is a modelling choice, not a property of the robot.

Tang and colleagues organize this along three axes. The action-space level may be low (joint torques), mid (task-space velocity commands), or high (temporally extended subroutines). The observation space may be a low-dimensional estimated state vector or raw high-dimensional sensing. The reward may be sparse or dense.

Each combination is a different MDP for the same physical task. Rusty at grid level — this chapter — has 80 states and four actions. Rusty at velocity level has a continuous state and continuous actions. Rusty at torque level, Chapter 13's territory, adds motor dynamics.

Author the warehouse

ch04-warehouse-editor

Wall off a corridor, move the dock, paint a slippery patch. Value iteration re-solves on every edit.

Tool
D
-15.523.8V(s)
slippery patch

Click or drag across cells with the shelf tool selected. The orange path is a rollout of the current optimal policy.

Dock reachable

Yes

a path exists

Sweeps to converge

38.0

value iteration, θ = 1e−5

v* at the start

-15.5

expected discounted return

Rollout return

-3.00

21 steps

Free cells

76.0

32 shelves

Slippery cells

0

none painted

Optimal action, cell by cell

The arrows are argmax_a q*(s,a), recomputed from scratch after every edit. Nothing is cached and nothing is interpolated — this is the Bellman optimality equation solved on the warehouse you just drew.

Try this

  • Trap the robot. Wall Rusty into a pocket and watch v* collapse to the step-cost floor everywhere inside it.
  • Build a shortcut. Clear a shelf block and see how far the value change propagates from that one cell.
  • Make a river. Paint a slippery line across the map, then raise the patch slip until the policy prefers the long way round.
Wall the corridor beside the dock and watch the whole value landscape re-route — the arrows change everywhere, not just at the wall, because value propagates. Paint a slippery patch across the shortest path and the optimal policy will detour around it exactly when the detour is cheaper than the expected cost of slipping. Both are the same lesson: the policy is a consequence of the model, and you just edited the model.
Rustrl-core/src/env.rs
rust
/// A set an observation or action can be drawn from.
pub trait Space {
    type Item;
    fn contains(&self, x: &Self::Item) -> bool;
    fn sample<R: rand::Rng>(&self, rng: &mut R) -> Self::Item;
}
 
pub struct Transition<S> {
    pub next_state: S,
    pub reward: f64,
    pub done: bool,
}
 
/// The black-box view: you may sample the dynamics, never inspect them.
/// This is all a real robot ever offers.
pub trait Env {
    type State: Clone;
    type Action: Copy;
 
    fn reset<R: rand::Rng>(&mut self, rng: &mut R) -> Self::State;
    fn step<R: rand::Rng>(
        &mut self,
        state: &Self::State,
        action: Self::Action,
        rng: &mut R,
    ) -> Transition<Self::State>;
    fn gamma(&self) -> f64;
}
 
/// The white-box view: the full distribution p(s′, r | s, a) is available.
/// Simulators can offer this; reality cannot.
pub trait Mdp: Env {
    fn states(&self) -> &[Self::State];
    fn actions(&self, state: &Self::State) -> &[Self::Action];
 
    /// Every (next_state, reward, probability) triple, summing to 1.
    fn transitions(
        &self,
        state: &Self::State,
        action: Self::Action,
    ) -> Vec<(Self::State, f64, f64)>;
}
The book's gym. Note that Mdp extends Env with the transition distribution: Chapter 5 plans against the white-box view, Chapter 6 learns against the black-box one, and the same warehouse implements both.

4.8 Chapter bridge

The formalism is complete. An MDP is four objects; the return has a recursion; value functions satisfy Bellman equations; those equations are fixed-point conditions for operators that contract at rate γ\gamma; and Banach hands us existence, uniqueness, and a convergent algorithm with a stopping rule.

We also admitted that the state is not observable, that solving the honest version is intractable, and that the MDP itself is something an engineer chooses rather than discovers.

Chapter 5 takes the algorithm Banach promised and makes it real. With pp and rr known, we can compute vv_* by iteration and watch value ripple outward from Rusty's dock — and we will find that evaluation and improvement, alternated, form a pattern so general that every remaining algorithm in this book is a variation on it.

  1. 01Foundation●●Derive the marginals

    From p(s′,r|s,a), derive expressions for p(s′|s,a), r(s,a), and r(s,a,s′). Then compute all three by hand for a slip cell of Rusty’s warehouse using the constants in §4.1.

  2. 02Foundation●●The return bound is tight

    Prove |G_t| ≤ R_max/(1−γ) and construct an MDP where the bound is attained exactly. What does that MDP look like physically?

  3. 03Foundation●●Bellman for q_π

    Carry out the derivation of the Bellman expectation equation for q_π in the same detail as Theorem 4.1, naming where the tower property and the Markov property are each used.

  4. 04Foundation●●The max inequality

    Prove the lemma used in Theorem 4.3: |max_a f(a) − max_a g(a)| ≤ max_a |f(a) − g(a)|. Where would the contraction proof fail without it?

  5. 05Conceptual●●Find the risk-aversion threshold

    In the MDP explorer, start at p_slip = 0 and increase it. Find the slip probability at which the optimal policy first stops hugging the shelves. Explain the trade-off in terms of the q-values shown for that cell.

  6. 06Conceptual●●Horizon and reach

    Set γ to 0.5, 0.9, and 0.99 in the explorer and record how many cells away from the dock the value function remains meaningfully non-zero. Compare against the effective horizon 1/(1−γ).

  7. 07Practical●●Exact policy evaluation

    Implement solve_v_pi using the matrix form v_π = (I − γP_π)⁻¹ r_π with nalgebra, and verify it satisfies the Bellman equation pointwise to 1e−10 with a property test over random MDPs.

  8. 08Practical●●●A POMDP wrapper

    Write NoisyOdometryEnv: a wrapper that hides the true state and emits a noisy observation. Implement a discrete Bayes filter over cells, and measure how localization entropy evolves after a "kidnapping" that teleports Rusty without telling him.

References

Baseline references

  • Sutton, R. S. & Barto, A. G. (2018). Reinforcement Learning: An Introduction. MIT Press, 2nd edition
    Chapter 3 in full: §3.1 the agent–environment interface and the Markov property, §3.3 returns, §3.5 policies and value functions, §3.6 optimal value functions.
  • Kober, J., Bagnell, J. A. & Peters, J. (2013). Reinforcement Learning in Robotics: A Survey. International Journal of Robotics Research 32(11)
    §1.3 and §2 — the state-as-sufficient-statistic framing, and why robotic state is never fully observed.
  • Tang, C. et al. (2024). Deep Reinforcement Learning for Robotics: A Survey of Real-World Successes. Annual Review of Control, Robotics, and Autonomous Systems link
    §3.2 problem formulation — the action-space level, observation space, and reward-density axes used in §4.7.

Further reading & modern sources

  • Bellman, R. (1957). Dynamic Programming. Princeton University Press
    The origin of the principle of optimality and the equations that carry his name.
  • Puterman, M. L. (1994). Markov Decision Processes: Discrete Stochastic Dynamic Programming. Wiley
    The definitive reference. Existence of optimal stationary deterministic policies, and the contraction analysis, in complete rigour.
  • Kaelbling, L. P., Littman, M. L. & Cassandra, A. R. (1998). Planning and acting in partially observable stochastic domains. Artificial Intelligence 101(1–2)
    The belief-MDP construction of §4.6, and the classical algorithms for exact POMDP solution.
  • Papadimitriou, C. H. & Tsitsiklis, J. N. (1987). The Complexity of Markov Decision Processes. Mathematics of Operations Research 12(3)
    The PSPACE-hardness result that explains why nobody solves POMDPs exactly on hardware.