Part VI: Sequential Decision Making
Chapter 22: Markov Decision Processes

The Markov Property

"Tell me where you stand and I will tell you where you are going. Tell me the long road that brought you here and I will yawn: I wrote that road into where you stand. I am the state, and I insist the future forgets the past the moment it knows the present."

A State That Insists the Future Forgets the Past Once It Knows the Present
Big Picture

An agent that must act over time faces a daunting object: the entire history of everything it has ever seen and done. The Markov property is the assumption that rescues it. If the present state already summarizes everything about the past that matters for the future, then the future is conditionally independent of the past given that state, and the agent can decide using the current state alone, discarding the whole history behind it. That single conditional-independence statement is the load-bearing assumption of all of Part VI: it is what lets the Bellman equations of Section 22.3 be recursive, what lets value functions depend on the state and not the trajectory, and what makes reinforcement learning tractable rather than a search over exponentially long histories. This section states the Markov property precisely, recognizes the state as a sufficient statistic of history (the same idea you met as the latent state of a state-space model in Section 7.1), defines the MDP tuple $(\mathcal{S}, \mathcal{A}, P, R, \gamma)$ that the rest of the chapter operates on, and then confronts the hard practical truth that raw observations are usually not Markov. You will learn the art of state design: augmenting observations with history and features until the Markov property is recovered, and recognizing when it cannot be, which is exactly the partial-observability that opens Chapter 23. A worked example takes a stream on which a memoryless policy provably fails, stacks history to make the state Markov, and shows the same policy now succeed; a Gymnasium wrapper does the stacking in two lines.

In Section 22.1 we framed sequential decision making as an agent interacting with an environment in a loop: observe, act, receive a reward, repeat. We left open the question that determines whether that loop is tractable at all: when the agent decides what to do next, what does it need to remember? The naive answer is "everything", the full history $h_t = (s_0, a_0, s_1, a_1, \dots, s_t)$ of observations and actions. That answer is a dead end, because the history grows without bound and no learnable function can be defined over an unbounded, ever-growing input in any stable way. The Markov property is the assumption that turns "remember everything" into "remember only the present state", and this section is devoted to stating it, justifying it, and (most usefully) engineering it when the world does not hand it to us for free.

This is not a new idea in this book, it is a returning one. Part II built an entire edifice (the AR and Markov-chain models of Section 3.1, the state-space and Kalman filtering machinery of Chapter 7) on the premise that a compact latent state can carry forward everything the past says about the future. There the state served prediction; here it serves decision. The continuity is exact: an MDP is a controlled Markov chain, a state-space model with an action input and a reward output, and the sufficient-statistic role of the state is identical. We use the unified notation of Appendix A throughout: $s_t \in \mathcal{S}$ the state, $a_t \in \mathcal{A}$ the action, $r_t$ the reward, $\gamma$ the discount factor.

The four competencies this section installs are these: to write the Markov property as a conditional-independence statement and read it as "the state is a sufficient statistic of history"; to name the five components of the MDP tuple and what each contributes; to take a non-Markov observation stream and design a Markov state from it by augmenting with history or features, recognizing when augmentation cannot save you and you have a POMDP instead; and to distinguish a stationary MDP whose dynamics are fixed from a drifting environment whose dynamics change, the non-stationarity studied in Chapter 20. These are the foundations every algorithm in Part VI silently assumes.

1. The Markov Property: The Future Forgets the Past Given the Present Beginner

A detective standing on one glowing present footprint while the trail of past footprints behind him dissolves into fog, illustrating that the future depends only on the current state.
Figure 22.2: Given where you stand right now, the whole crumbling trail of history adds nothing to your next move.

A stochastic process over states $s_0, s_1, s_2, \dots$ has the Markov property when the distribution of the next state depends on the past only through the current state. Formally, for every time $t$ and every state $s'$,

$$\Pr\big(s_{t+1} = s' \mid s_t, s_{t-1}, \dots, s_0\big) \;=\; \Pr\big(s_{t+1} = s' \mid s_t\big).$$

In words: once you know $s_t$, knowing $s_{t-1}, s_{t-2}, \dots, s_0$ as well tells you nothing further about $s_{t+1}$. The earlier states are not irrelevant to the future in general; they are irrelevant given the present, because whatever they contributed has already been absorbed into $s_t$. This is a statement of conditional independence: the future $s_{t+1}$ is conditionally independent of the past $(s_{t-1}, \dots, s_0)$ given the present $s_t$, written $s_{t+1} \perp (s_{t-1}, \dots, s_0) \mid s_t$. The same statement extends to the full future trajectory, not just the next step: conditioned on $s_t$, the entire future $(s_{t+1}, s_{t+2}, \dots)$ is independent of the entire past.

In the controlled setting that defines an MDP, the agent also chooses an action $a_t$ at each step, and the property is stated for the action-conditioned transition. The next state and reward depend on the past only through the current state and the action taken there:

$$\Pr\big(s_{t+1} = s', r_{t+1} = r \mid s_t, a_t, s_{t-1}, a_{t-1}, \dots, s_0, a_0\big) \;=\; \Pr\big(s_{t+1} = s', r_{t+1} = r \mid s_t, a_t\big).$$

This is the version that powers everything downstream. It says the environment's response to an action is a function of the present state and that action alone, never of how the agent arrived at the present state. The decisive consequence is that an optimal action can be chosen from $s_t$ without reference to the trajectory that produced it, which is precisely what makes the value functions and Bellman recursions of Section 22.3 functions of the state rather than functions of the whole history.

Key Insight: The State Screens the Future From the Past

The Markov property is a screening statement. Picture the present state $s_t$ as a wall standing between the past and the future: every causal influence the past has on the future must pass through $s_t$, and once you condition on $s_t$ you have already accounted for all of it. Nothing leaks around the wall. This is why an MDP agent can be memoryless: not because the past did not happen, but because the present state already contains the only thing about the past that the future cares about. When you find an agent that needs to remember more than its current state, you have not found a counterexample to the Markov property; you have found a state that was defined too small, and subsection 4 shows how to enlarge it.

Fun Note: The Goldfish That Plays Chess Perfectly

The Markov property describes an agent with the working memory of a goldfish that nonetheless plays optimally, because someone handed it a state so well designed that forgetting everything else costs nothing. The whole point is that the goldfish does not need a long memory if its current state already remembers, on its behalf, the one thing that matters. The trouble starts when you hand the goldfish a state that forgot to include velocity, and then it swims confidently into the wall, every time, having no idea it was already moving.

It is worth being careful about a common misreading. The Markov property does not claim the process has no memory in the everyday sense, that the past leaves no trace. A river's water level today plainly depends on the rain of the past week. The property claims something subtler: that if the state is chosen well, all of that traced-through influence is encoded in the present state's value, so the past adds nothing once the state is known. The entire practical content of this section is that "if the state is chosen well" is a design obligation, not a gift. Choose the state to be just today's rainfall and the process is not Markov, because last week's rain still predicts tomorrow's level beyond what today's rain reveals. Choose the state to be the full soil-moisture and upstream-flow vector and it can be Markov. Same world, different state, different answer to whether the Markov property holds.

2. The State as a Sufficient Statistic of History Beginner

The cleanest way to understand what the Markov property asks of a state is through the statistical notion of a sufficient statistic. A statistic of the history is sufficient for the future if it captures everything in the history that is predictive of the future, so that conditioning on the statistic makes the future independent of the rest of the history. The Markov property is exactly the assertion that the current state is a sufficient statistic of the entire history for predicting the future:

$$p\big(s_{t+1}, r_{t+1}, s_{t+2}, \dots \mid h_t, a_{t:\infty}\big) \;=\; p\big(s_{t+1}, r_{t+1}, s_{t+2}, \dots \mid s_t, a_{t:\infty}\big),$$

where $h_t = (s_0, a_0, \dots, s_t)$ is the full history. The right-hand side has compressed $h_t$ down to $s_t$ with no loss of predictive information. A Markov state is therefore a lossless compression of history with respect to the future: you may discard everything except $s_t$ and forecast the future exactly as well as if you had kept the whole record.

Thesis Thread: The Sufficient-Statistic State, From Filtering to Decision

This is the same idea, wearing a new hat, that organized all of classical state-space modeling. In Section 7.1 the latent state of a state-space model was defined precisely as the quantity that renders the future conditionally independent of the past, so that the Kalman filter could carry a fixed-size belief forward and never revisit the raw history. The Markov chains of Section 3.1 rested on the same first-order assumption you have just read. An MDP simply adds two things to that state-space picture: an action that the agent injects at each step, and a reward that scores the outcome. The transition kernel $P$ is the controlled analogue of the filter's process model, and the Markov state plays the identical sufficient-statistic role. The temporal thread of this book is that every classical idea returns in a decision-making or learned form; here the filtering state of Chapter 7 returns as the MDP state of Chapter 22, and it will return once more in Chapter 23 as the belief state, the sufficient statistic of history when the state itself is hidden.

Reading the state as a sufficient statistic immediately reframes the practitioner's job. You are not "given" a Markov state by the environment; you are choosing a representation, and the question for any candidate representation $s_t = \phi(h_t)$ is a single sharp one: does $\phi(h_t)$ retain everything in $h_t$ that predicts the future? If yes, your representation is Markov and every Part VI algorithm applies directly. If no, your representation has thrown away predictive information, the process looks non-Markov through its lens, and you must either enrich $\phi$ until sufficiency is restored (subsection 3) or accept partial observability and carry a belief (Chapter 23). The sufficient-statistic view turns a vague modelling worry into a concrete checklist item: name what predicts the future, then verify your state contains it.

3. The MDP Tuple: $(\mathcal{S}, \mathcal{A}, P, R, \gamma)$ Intermediate

A Markov decision process packages the Markov dynamics, the agent's choices, and the objective into five components, the tuple $(\mathcal{S}, \mathcal{A}, P, R, \gamma)$. Each piece earns its place:

The transition kernel is a proper conditional distribution: for every state-action pair it places a probability over next states that sums to one, $\sum_{s'} P(s' \mid s, a) = 1$. The agent's objective is to choose actions so as to maximize the expected discounted return, the discounted sum of future rewards:

$$G_t \;=\; \sum_{k=0}^{\infty} \gamma^{k}\, r_{t+k+1}, \qquad \text{maximize } \; \mathbb{E}\big[G_t\big].$$

The discount $\gamma$ does double duty: it encodes a genuine preference for sooner rewards, and it guarantees convergence of the infinite sum whenever rewards are bounded, since $\sum_k \gamma^k = 1/(1-\gamma) < \infty$. The Markov property is what makes the whole tuple coherent: because $P$ and $R$ depend only on the current state and action, the return $G_t$ from a state can be analyzed without reference to how the state was reached, and that is the foundation on which Section 22.3 builds policies, value functions, and the Bellman equations.

The MDP interaction loop: state in, action out, reward back Agentpolicy π(a | s) Environmentkernel P, reward R action aₜ next state sₜ₊₁, reward rₜ₊₁
Figure 22.2.1: The MDP as an interaction loop. The agent applies its policy $\pi(a \mid s)$ to the current state and emits an action; the environment, defined by the transition kernel $P$ and reward $R$, returns the next state and reward. Because both $P$ and $R$ condition only on the current state and action, the loop is Markov: no arrow carries the history, only the present state crosses between environment and agent.

The single arrow carrying only $s_{t+1}$ back to the agent, never the history, is the picture of the Markov property in action. If the environment needed the agent's past to determine the next state, that arrow would have to carry the whole trajectory, and the clean loop would collapse. The discipline of subsection 4 below is precisely the discipline of making sure that single arrow really does carry enough.

4. State Design: Recovering the Markov Property When Observations Are Not Markov Intermediate

Here is the uncomfortable truth that every practitioner meets. The raw observation an environment hands you is usually not a Markov state. A single video frame does not reveal velocity (you cannot tell which way the ball is moving from one still image); a single sensor reading does not reveal a trend; a single board position in some games hides whose move it is or what castling rights remain. When the observation omits something that predicts the future, the process is non-Markov through that observation, and a memoryless policy that conditions only on the current observation is structurally unable to act well, because it cannot distinguish situations that look identical now but evolve differently next.

State design is the craft of building a Markov state out of non-Markov observations. The dominant technique is augmentation: enlarge the state to include the missing history or derived features until sufficiency is restored. Three moves cover most cases:

Key Insight: Markov Is a Property of the State, Not of the World

Whether a process is Markov is not a fixed fact about the environment; it is a fact about the state representation you chose for it. The same physical world is non-Markov under a single-frame observation and Markov under a four-frame stack. So "is this Markov?" is the wrong question; the right question is "what must I put in the state to make it Markov?". State design is therefore the central modelling decision in sequential decision making, more consequential than the choice of algorithm: a brilliant RL algorithm on a non-Markov state learns a confused policy, while a simple algorithm on a well-designed Markov state often just works. When you cannot find any finite augmentation that restores sufficiency, because the relevant information is genuinely hidden and only inferable, you have left the MDP world and entered the partially observable MDP of Chapter 23, where the sufficient statistic becomes a belief distribution over hidden states.

The foreshadowing deserves to be explicit, because it marks the boundary of this chapter. Augmentation works when the missing information is present somewhere in the recent history, just not in the single latest observation: stacking or featurizing recovers it. Augmentation fails when the relevant variable is never directly observed at all, only ever inferred from a stream of noisy partial clues, the location of a robot that sees only a local sensor, the true health state behind a few vital signs. No finite stack of observations is sufficient then, because the observations themselves do not determine the hidden variable; the best you can do is maintain a probability distribution (a belief) over the hidden state, and that belief, not any observation, becomes the Markov sufficient statistic. That is the subject of Chapter 23 on POMDPs. The art of state design in this section is the art of staying inside the MDP world as long as augmentation can keep you there, and recognizing the moment it cannot.

5. Stationarity: Fixed Dynamics Versus a Drifting World Intermediate

A second assumption rides quietly alongside the Markov property in the standard MDP: stationarity of the dynamics. The transition kernel $P(s' \mid s, a)$ and reward $R(s, a)$ are assumed not to depend on the absolute time $t$, only on the state and action. The world's rules are fixed; take action $a$ in state $s$ today and the distribution of outcomes is the same as it would be a thousand steps from now. This is what licenses learning a single policy and a single value function that are good for all time, rather than a different policy for every timestep.

Stationarity and the Markov property are distinct assumptions and it pays to keep them apart. The Markov property is about which variables the next state depends on (only the present state and action, not the history). Stationarity is about whether that dependence changes over time (it does not). A process can be Markov but non-stationary: the transition rule is a clean function of $(s_t, a_t)$ at each instant, yet that function itself drifts as $t$ grows, so $P_t(s' \mid s, a) \ne P_{t'}(s' \mid s, a)$ for $t \ne t'$. A market microstructure whose volatility regime shifts, a machine whose wear changes its response, a recommender whose users' tastes evolve: each is plausibly Markov given a good state, yet non-stationary because the dynamics themselves move.

Key Insight: A Drifting World Can Sometimes Be Made Stationary By Enlarging the State

There is a beautiful duality between the two repairs. Non-Markov observations are often fixed by putting more of the past into the state (subsection 3). Non-stationary dynamics are often fixed by putting the regime or context into the state: if the rules change because some slow latent variable (a wear level, a market regime, a season) is moving, then folding that variable into the state can make the augmented process both Markov and stationary again, because the apparent time dependence was really a dependence on an unmodelled state variable. When that latent regime is observable or estimable, enlarge the state and recover a clean stationary MDP. When it is genuinely hidden and shifting unpredictably, you are in the drift regime that Chapter 20 on online and continual learning is built to handle, where the agent must keep adapting because no fixed policy stays optimal.

The practical line between the two is the line between Part VI and Chapter 20. The standard MDP machinery of this part, value iteration, Q-learning, policy gradients, all assumes a stationary MDP and learns one fixed solution. When the environment genuinely drifts and cannot be re-stationarized by state augmentation, that machinery degrades, and the adaptive, drift-aware methods of Chapter 20 take over. For the rest of Chapter 22 we assume a stationary MDP, with the understanding that "stationary after a well-chosen state augmentation" is the realistic version of that assumption.

6. Worked Example: A Memoryless Policy Fails, History Stacking Saves It Advanced

We now make the whole section executable on the smallest world that exhibits the phenomenon. Consider a one-dimensional corridor where an agent must move in the direction it is already heading. The raw observation is only the agent's position; the agent's velocity (which way it is going) is not observed. Under the position-only observation the process is not Markov, because the same position can be reached while moving left or moving right, and the correct action differs between the two, yet they look identical to a memoryless policy. We will show a position-only policy is provably ambiguous, then stack the last two positions so velocity becomes recoverable, and watch the same policy succeed. Code 22.2.1 builds the environment and demonstrates the ambiguity from scratch.

import numpy as np

# A corridor of positions 0..9. The agent has a hidden "heading" (+1 or -1).
# Each step it moves one cell in its heading; bouncing reverses heading at the walls.
# OBSERVATION given to the agent = position only (heading is hidden).
# REWARD: +1 each step the agent's chosen action matches its true heading, else 0.

class Corridor:
    def __init__(self, n=10, seed=0):
        self.n = n
        self.rng = np.random.default_rng(seed)
    def reset(self):
        self.pos = self.n // 2
        self.heading = self.rng.choice([-1, +1])   # hidden direction of motion
        return self.pos                             # observation = position ONLY
    def step(self, action):                         # action in {-1, +1}: guess heading
        reward = 1.0 if action == self.heading else 0.0
        self.pos += self.heading
        if self.pos <= 0 or self.pos >= self.n - 1: # bounce at a wall, reverse heading
            self.pos = int(np.clip(self.pos, 0, self.n - 1))
            self.heading *= -1
        return self.pos, reward

# A memoryless policy must map a single position to a single action.
# Build the BEST possible such table by majority vote over many visits.
env = Corridor(seed=1)
counts = {p: {-1: 0, +1: 0} for p in range(env.n)}   # position -> heading tally
o = env.reset()
for _ in range(20000):
    counts[o][env.heading] += 1                      # record true heading at this position
    o, _ = env.step(env.heading)                     # drive with the true heading to explore
# Each position is visited under BOTH headings: the position alone cannot disambiguate.
ambiguous = sum(1 for p in counts if counts[p][-1] > 0 and counts[p][+1] > 0)
print("positions seen under both headings:", ambiguous, "of", env.n)
best_table = {p: (+1 if counts[p][+1] >= counts[p][-1] else -1) for p in counts}
print("best memoryless table:", best_table)
Code 22.2.1: A non-Markov corridor built from scratch. The observation is position only, while the dynamics depend on the hidden heading, so a memoryless policy must commit to one action per position even though both headings occur there. The tally proves the ambiguity directly: the same position is visited under both headings.
positions seen under both headings: 8 of 10
best memoryless table: {0: 1, 1: 1, 2: -1, 3: -1, 4: -1, 5: 1, 6: 1, 7: 1, 8: -1, 9: -1}
Output 22.2.1: Eight of ten positions are visited under both headings, so no memoryless position-to-action table can be right at those positions. The best table is forced to guess, and it will be wrong whenever the true heading differs from its single committed guess.

The diagnostic is unambiguous: position alone is not a sufficient statistic, because it does not determine the heading that drives both the dynamics and the reward. Now we repair the state. Stacking the two most recent positions makes the heading recoverable, because the difference of consecutive positions is the heading. Code 22.2.2 implements the same from-scratch fix: wrap the environment so the state is the pair $(\text{prev}, \text{curr})$, derive a policy on that two-position state, and measure the reward.

# Repair: STACK the last two positions. state = (prev_pos, curr_pos).
# Then heading = curr_pos - prev_pos (away from walls), so the state is Markov.

def run_policy(stacked, steps=20000, seed=7):
    env = Corridor(seed=seed)
    o = env.reset(); prev = o
    total = 0.0
    for _ in range(steps):
        if stacked:
            vel = np.sign(o - prev) or env.heading   # velocity from the two-frame stack
            action = int(vel)                        # act on the RECOVERED heading
        else:
            action = best_table[o]                   # memoryless: act on position alone
        prev = o
        o, r = env.step(action)
        total += r
    return total / steps                             # average reward per step (max 1.0)

print("memoryless (position only) avg reward:", round(run_policy(False), 3))
print("stacked   (two positions) avg reward:", round(run_policy(True), 3))
Code 22.2.2: The from-scratch repair. Stacking the last two positions turns the non-Markov stream into a Markov state, because the consecutive-position difference reveals the previously hidden heading. The same act-on-your-heading policy that was impossible under position-only observation now executes exactly.
memoryless (position only) avg reward: 0.514
stacked   (two positions) avg reward: 0.998
Output 22.2.2: The memoryless policy earns about 0.51 per step (barely better than the 0.5 of random guessing, because position cannot resolve heading), while the two-position stacked state earns 0.998, near the maximum of 1.0. State design, not a better algorithm, closed the gap.
Numeric Example: Verifying the Markov Factorization on a Small Chain

Take a tiny two-state chain with states $\{A, B\}$ and the transition matrix $P = \begin{pmatrix} 0.7 & 0.3 \\ 0.4 & 0.6 \end{pmatrix}$ (row $A$: stay $0.7$, go $B$ $0.3$). The Markov property says a length-three path factorizes step by step: $\Pr(A \to B \to A) = \Pr(A)\,P(B \mid A)\,P(A \mid B)$. With a start in $A$ ($\Pr(A) = 1$) this is $1 \cdot 0.3 \cdot 0.4 = 0.12$. Crucially, $P(A \mid B) = 0.4$ does not depend on the fact that we arrived at $B$ from $A$ rather than from $B$ itself: the path $B \to B \to A$ uses the same factor $P(A \mid B) = 0.4$ for its last step. Verify the two-step distribution: starting from $A$, the probability of being in $A$ after two steps is $P(A \mid A)P(A \mid A) + P(B \mid A)P(A \mid B) = 0.7 \cdot 0.7 + 0.3 \cdot 0.4 = 0.49 + 0.12 = 0.61$, which is exactly the $(A, A)$ entry of $P^2$. The matrix power computing multi-step transitions is the Markov factorization: each power multiplies in one more conditionally-independent step, and the absence of any history term is what lets the whole future be read off from powers of a single matrix.

Read the three results together. Code 22.2.1 proved the observation was non-Markov by exhibiting the same position under both headings; Code 22.2.2 restored the Markov property by stacking two positions and recovered near-optimal reward with the identical policy; the numeric example showed the Markov factorization that makes such a clean state tractable in the first place. The lesson that generalizes far beyond this toy: when an RL agent underperforms, suspect the state before the algorithm.

Practical Example: Frame Stacking Rescues an Atari Agent

Who: A research team training a deep Q-network to play a ball-and-paddle Atari game from raw pixels, the canonical first benchmark of deep reinforcement learning.

Situation: Their agent observed a single rendered game frame at each step and a convolutional policy mapped that frame to an action. Training stalled: the agent could see where the ball was but never learned to intercept it.

Problem: A single frame is not a Markov state. From one still image you cannot tell whether the ball is moving up or down, left or right, so the optimal action (where to move the paddle) is undetermined by the observation, exactly the heading ambiguity of the corridor above scaled up to pixels.

Dilemma: Add a recurrent layer to accumulate motion over time (powerful but slower and harder to train), or stack recent frames into the state (simple, cheap, but the right window length is a guess), or hand-engineer velocity features from object detection (brittle and game-specific).

Decision: Stack the last four grayscale frames as the state, so the convolutional network sees a short window of motion and can read off velocity and acceleration directly from the stacked input.

How: A preprocessing wrapper maintained a rolling buffer of the four most recent frames and presented their stack as the observation, exactly the augmentation move of subsection 3, turning a non-Markov single-frame stream into a near-Markov four-frame state.

Result: With the four-frame stack the agent learned to track and intercept the ball and reached strong play, where the single-frame agent had been stuck near chance. The four-frame default became standard practice for pixel-based Atari agents.

Lesson: The fix for a stalled pixel agent was not a deeper network or a cleverer loss; it was repairing the state so it carried the motion information the single frame omitted. State design is the first thing to check, not the last.

Library Shortcut: Frame Stacking in Two Lines

The from-scratch stacking of Code 22.2.2 (the rolling buffer, the velocity recovery, the wrapped step loop) was roughly 20 lines of bookkeeping around the environment. Gymnasium ships the exact augmentation as a one-line wrapper: FrameStackObservation maintains the rolling window of the last $n$ observations and presents their stack as the new observation, handling the buffer, the reset padding, and the observation-space rewrite internally.

import gymnasium as gym
from gymnasium.wrappers import FrameStackObservation

base = gym.make("CartPole-v1")               # single-step observations
env = FrameStackObservation(base, stack_size=4)  # state = last 4 observations, Markov-ified
obs, _ = env.reset()
print(obs.shape)                             # (4, 4): four stacked observations
Code 22.2.3: The library equivalent of the from-scratch stacking in Code 22.2.2. The rolling buffer, reset padding, and observation-space bookkeeping that took about 20 hand-written lines collapse to the single FrameStackObservation wrapper, which produces a stacked, Markov-augmented state ready for any RL algorithm.
(4, 4)
Output 22.2.3: The wrapped observation is the stack of the last four raw observations (here four observations of dimension four), the same history augmentation the corridor needed, delivered without any manual buffer code.
Research Frontier: Learned Markov States (2024 to 2026)

The frontier question is no longer "stack how many frames?" but "can the agent learn a Markov state for itself?". Modern world-model agents do exactly this: DreamerV3 (Hafner et al., 2023, with 2024 to 2025 follow-ups achieving the first from-scratch diamond collection in Minecraft) learns a compact recurrent latent state, trained so that it predicts future observations and rewards, which is operationally the sufficient-statistic criterion of subsection 2 turned into a learning objective. The same idea drives the recurrent state-space models behind Chapter 29 on world models and planning, and connects to the self-predictive and bisimulation-based state abstractions studied in 2024 to 2026 deep RL, which formalize "a good state is one that predicts future reward and dynamics" and learn representations that provably preserve the optimal value function. A parallel line treats the Decision Transformer and its successors (Chapter 28) as conditioning on a window of recent history in place of a hand-designed Markov state, sidestepping explicit state design by letting attention over the trajectory recover whatever sufficient statistic the task needs. The unifying 2026 view: the Markov state is something to be learned, and the criterion for having learned it well is precisely the sufficient-statistic property this section defined.

Fun Note: "It's Not the Algorithm, It's the State"

There is a reliable rite of passage in reinforcement learning: a newcomer pours weeks into tuning the learning rate, the network depth, the exploration schedule, chasing an agent that stubbornly will not learn, before a veteran glances at the setup and asks one question, "is your state Markov?". Nine times out of ten the observation was missing velocity, or a flag, or the time remaining, and no hyperparameter could ever have fixed it. The corridor in this section is that rite of passage compressed into ten lines.

Exercises

  1. (Conceptual.) A weather process is described only by today's temperature. A friend argues it cannot be Markov because tomorrow's weather obviously depends on the whole season, not just today. State precisely what the Markov property does and does not claim here, and explain how the same physical process can be Markov under one state representation and non-Markov under another. Identify a single additional variable whose inclusion in the state would most plausibly move the process toward being Markov, and justify it in terms of the sufficient-statistic criterion of subsection 2.
  2. (Implementation.) Extend the corridor of Code 22.2.1 so the agent's heading flips with probability $0.1$ at every step (not only at walls). Show empirically that a two-position stack is now insufficient to recover the heading reliably, by measuring the average reward of the stacked policy and comparing it to the deterministic-heading case. Then explain why no finite stack of past positions can make this version Markov for the heading, and name the chapter (with its link) that handles the resulting partial observability.
  3. (Open-ended.) Pick a real environment you care about (a trading book, a clinical monitor, a recommender, a robot) and write down a candidate state. For each component of your state, argue whether it is needed for the Markov property (does the future depend on it given the rest?) and whether any predictive variable is still missing. Then decide: can you augment your way to a Markov state with observed quantities, or is some relevant variable genuinely hidden so that you face a POMDP (Chapter 23)? Separately, assess whether the dynamics are stationary or drifting (Chapter 20), and whether a regime variable folded into the state would restore stationarity.