State migration
On this page
- Level 1: structs migrate by themselves
- Level 2:
Hotcode.Versioned - Adopting it on a module that is already running
- Why
downgradelives in the newer module - Level 3: write
code_change/3 - Behaviours hosted by a library
- Phoenix channels and LiveViews
- Habits that make upgrades safe
- ETS tables
- What is not migrated
- Hooks for what only you know
Replacing a module's code is the easy half of a hot upgrade. The hard half is that processes already running it hold state shaped by the old code. This guide covers the three levels at which Hotcode deals with that, from "do nothing" to "write the migration yourself", and when to use each.
| level | you write | handles |
|---|---|---|
| 1. automatic struct migration | nothing | a defstruct gained or lost fields |
2. Hotcode.Versioned |
one function per version step | state that changed meaning |
3. code_change/3 |
the callback by hand | anything, and anything Versioned does not fit |
Use the lowest level that is enough.
Level 1: structs migrate by themselves
If your GenServer keeps its state in structs, adding or removing a field needs no code at
all. A real example (examples/pulse, where every Phoenix channel keeps one in its assigns):
# v1
defmodule Pulse.Counter do
defstruct n: 0
end
# v2: one new field
defmodule Pulse.Counter do
defstruct n: 0, last: nil
end
Deploying v2 rebuilds every live %Pulse.Counter{} in every affected process with the new
field set. Fields that still exist keep their values, new fields get the struct's defaults,
removed fields are dropped. It walks the whole state (nested maps, lists, tuples, structs
inside structs), and the same function runs backwards on rollback.
Hotcode.StructMigrator is pure map manipulation:
iex> old = %{__struct__: Acct, balance: 10, legacy: :x}
iex> defaults = %{__struct__: Acct, balance: 0, currency: "EUR"}
iex> Hotcode.StructMigrator.migrate(%{acct: old}, %{Acct => defaults})
%{acct: %{__struct__: Acct, balance: 10, currency: "EUR"}}
What it does not do: it cannot reach into ETS (see Hotcode.Table),
:persistent_term or the process dictionary, and it cannot guess the meaning of a changed field. If balance used to hold
euros and now holds cents, that is level 2.
Which processes:
- those whose callback module changed;
- when a struct changes shape, any process running code under
allowed_prefixesthat holds it in its state, even though its own module did not change. A LiveView is the typical case: it runsPhoenix.LiveView.Channelbut reports{MyAppWeb.PageLive, :mount, 3}, holds your structs in its assigns, and is found by inspecting its state. A Phoenix channel is the same: it runsPhoenix.Channel.Serverbut reports{MyAppWeb.RoomChannel, :join, 3}(checked on a running node byexamples/pulse). Nothing is suspended unless the state really holds the struct, so processes that call each other are not frozen together. A channel or LiveView whose own module changed also gets itscode_change/3, see Phoenix channels and LiveViews; - processes of modules you list in
config :hotcode, carriers: [...]: for code outsideallowed_prefixesthat holds your structs, for example Bandit.DelegatingHandler holding a WebSocket handler's state; - processes of a library that hosts your behaviour (GenStage,
gen_event, a wrapper), when you list the library inconfig :hotcode, hosts: [...]: see Behaviours hosted by a library.
Level 2: Hotcode.Versioned
When state changes meaning rather than shape, say so, one version step at a time:
defmodule Cart do
use Hotcode.Versioned, vsn: 3
# upgrade: vN -> vN+1
def upgrade(1, s), do: %{items: Enum.map(s.items, &{&1, 0}), total: 0} # names become {name, cents}
def upgrade(2, s), do: Map.put(s, :currency, "EUR")
# downgrade: vN -> vN-1, needed for rollback
def downgrade(3, s), do: Map.delete(s, :currency)
def downgrade(2, s), do: %{items: Enum.map(s.items, &elem(&1, 0))}
end
code_change/3 is generated. Deploying v1 → v3 runs upgrade(1) then upgrade(2).
Rolling back v3 → v1 runs downgrade(3) then downgrade(2). A release that changes the
module's code but not its vsn needs no step in either direction: the state is left as it is
(examples/pulse v9 changes its ticker that way, and rolls it back).
Rules the macro enforces:
- A missing step is an error. If no
upgrade(2, _)clause matches and a process is at v2, the deploy aborts and everything is undone, instead of running new code on a state it does not understand. It is reported as{:no_step, :upgrade, 2}. - A step that raises is an error, reported as
{:step_failed, :upgrade, 2, message}. That includes aFunctionClauseErrorraised inside a clause that matched (a helper that did not match, say): only a call toupgrade/2itself with no clause for the step is:no_step. - A release that could not be rolled back is refused, before it is loaded. While the
process is suspended and the old code is still the only code loaded, the loader runs the
new
upgrade/2chain and then thedowngrade/2chain on a copy of the process's state (with its structs already in the new shape, exactly what a rollback would see), from a copy of the new module loaded under another name. If an upgrade or downgrade step is missing or raises, the deploy is refused before the release is loaded (loaded: falsein the error), with{:cannot_roll_back, {:no_step, :downgrade, 3}}and a message such as "MyApp.Cart has no downgrade(3, _) clause: add one so this deploy can be rolled back". Without this check you would find out at rollback time, when the process would have to be killed. This meansupgrade/2anddowngrade/2must be pure functions of the state: the loader calls them once more on a copy, outside the process, and throws the result away. - Only forward jumps and explicit downgrades. Deploying an older version over a newer one by plain deploy is refused; use rollback.
GenServer options go through the macro: use Hotcode.Versioned, vsn: 2, restart: :temporary, shutdown: 10_000 (any option other than vsn: and gen_server: is given to use GenServer).
gen_server: false leaves use GenServer out and only generates code_change/3, for a module
whose process a library runs: a Phoenix channel or LiveView, see below.
Adopting it on a module that is already running
A module without Hotcode.Versioned has no state version: its @vsn is the compiler's MD5 of
the module. Adding use Hotcode.Versioned, vsn: 1 to it can be a hot deploy: the running state
is taken as version 1 and kept as it is, and rolling that release back leaves the state alone
too. So the first versioned release must not change the state; change it in the next one:
# release A, hot: the state is whatever the unversioned module kept
use Hotcode.Versioned, vsn: 1
# release B, hot: the first real step
use Hotcode.Versioned, vsn: 2
def upgrade(1, s), do: Map.put(s, :history, [])
def downgrade(2, s), do: Map.delete(s, :history)
Going from an unversioned module straight to vsn: 2 or higher is refused before anything is
loaded, with {:unsupported_transition, old, 2} and the message "MyApp.Cart cannot go straight
to vsn 2: the running code is not a use Hotcode.Versioned release, so the shape of its state is
unknown. Deploy it as vsn: 1 first...": nothing says which upgrade/2 step the live state
needs. A beam without attributes (its old version unknown) is refused the same way.
Every migration failure carries a message next to its reason, naming the module, the
function and the step, and mix hotcode.deploy prints it in full. examples/pulse shows two
refusals: v4 (upgrade/2 raises on the live state) and v5 (no downgrade(2, _) clause).
Why downgrade lives in the newer module
On rollback the processes hold new-shaped state while the new code is still loaded. Only the
new code knows how to reshape its own state back. So Hotcode downgrades first, then reloads
the old code. A downgrade also cannot invent information the old shape has no room for:
in the example above, rolling back drops the prices. A downgrade can only keep what the old
shape can hold, so be deliberate about what you promise.
Level 3: write code_change/3
For anything else, use the standard OTP callback. Hotcode calls it through
:sys.change_code/4, in the process, while it is suspended:
def code_change(old_vsn, state, _extra) do
{:ok, transform(old_vsn, state)}
end
old_vsn is the module's @vsn (an integer if you set one, otherwise a list with the
module's MD5). On rollback it is {:down, vsn} where vsn is the version being returned to.
Struct migration has already run by the time code_change/3 is called, so it sees structs in
the new shape.
Behaviours hosted by a library
A use GenStage module does not run in its own gen_server: GenStage does, and keeps your
module in its state. The VM reports the process as {GenStage, :init, 1} (a gen_event manager
as {:gen_event, :init_it, 6}, a wrapper Wrap as {Wrap, :init, 1}), so a deploy that
changes your module does not find it by default: its code_change/3 is not run and its structs
keep their old shape. Tell Hotcode where to look:
config :hotcode,
hosts: [
GenStage, # built in: %GenStage{mod: your_module, state: your_state}
:gen_event, # built in: one user module per installed handler
{MyLib.Wrap, :mod, :state}, # a gen_server host keeping %{mod: ..., state: ...}
{MyLib.Other, {MyApp.Hosts, :read}} # read/1 gets the host's state, returns
] # user_module, {user_module, user_state} or nil
For each process of a listed host, the deploy reads its state (:sys.get_state) and, when the
user module is one the patch changes, suspends the process, migrates the structs in its whole
state and calls :sys.change_code/4. That runs the host's code_change/3, which must pass
it on to yours: GenStage's does, a wrapper you write must too. A consumer written for it:
defmodule MyApp.Consumer do
use GenStage
@behaviour Hotcode.Versioned
@vsn 2
def init(:ok), do: {:consumer, %{seen: 0, last: nil}}
def handle_events(events, _from, s), do: {:noreply, [], %{s | seen: s.seen + length(events)}}
def upgrade(1, s), do: Map.put(s, :last, nil)
def downgrade(2, s), do: Map.delete(s, :last)
# GenStage.code_change/3 calls this with your state, not GenStage's
def code_change(old, s, extra), do: Hotcode.Versioned.code_change(__MODULE__, 2, old, s, extra)
end
Rollback works as for any process: the newer module's code_change({:down, vsn}, ...) runs
before the old code is loaded. The rollback pre-flight of Hotcode.Versioned (refusing a
release without downgrade/2) needs the user state, so it runs for GenStage, :gen_event,
{Host, mod_key, state_key} and a function returning {module, state}, and is skipped for
{Host, mod_key} and a function returning only the module.
A gen_statem host (a Postgrex.ReplicationConnection, a protocol library's connection)
is listed the same way and found by {Host, :init, 1}. Its state is {state_name, data}: the
{Host, mod_key} and {Host, mod_key, state_key} entries read those keys from data when it is
a map, and a {Host, {M, F}} reader receives the whole tuple. :sys.change_code/4 runs the
host's code_change/4, so your module's code change runs only if the host forwards it:
# in the host (or a wrapper you own): pass the change on to the hosted module
def code_change(old_vsn, name, %{mod: mod} = data, extra) do
{:ok, state} = mod.code_change(old_vsn, data.state, extra)
{:ok, name, %{data | state: state}}
end
Postgrex.ReplicationConnection defines no code_change/4: with
{Postgrex.ReplicationConnection, {MyApp.Hosts, :read}} its processes are suspended across the
switch and the structs in their state are migrated, but no code change of yours runs. Keep the
state a replication handler carries across a deploy in structs, or read new keys with defaults.
The test with a forwarding host is test/hosted_statem_test.exs.
Not covered: Broadway is not built in. Its stages are GenStage processes whose GenStage
callback is Broadway's own (Broadway.Topology.ProcessorStage, ...), which defines no
code_change/3; your module sits in that stage's state. A {GenStage, {M, F}} entry (it
replaces the built-in GenStage one: one entry per host, the last wins) whose function returns
state.mod or, for a Broadway stage, state.state.module, gets such processes suspended and
their structs migrated, but no
code_change/3 of yours runs (a Broadway module keeps no state of its own besides context).
Supervisor.start_link(children, opts) reports {:supervisor, Supervisor.Default, 1}: there is
no module of yours to migrate. A host process busy for more than 5 seconds is only
struct-migrated (its user module is unknown), with a warning.
Phoenix channels and LiveViews
A channel process runs Phoenix.Channel.Server and a LiveView process runs
Phoenix.LiveView.Channel, two gen_servers of Phoenix's, and Phoenix sets their initial call
to your module: {MyAppWeb.RoomChannel, :join, 3}, {MyAppWeb.PageLive, :mount, 3}. When a
deploy changes that module (its @behaviour says Phoenix.Channel or Phoenix.LiveView), the
loader suspends those processes, migrates the structs in their state, and runs
:sys.change_code/4. Both Phoenix servers forward that to your module's code_change/3, with the
socket as the state. No hosts: entry is needed. Without a code_change/3 in your module
only the structs change: a new assign is not added to the sockets already open.
To migrate assigns, use Hotcode.Versioned with gen_server: false (use Phoenix.Channel or
use Phoenix.LiveView already set up the process):
defmodule MyAppWeb.RoomChannel do
use MyAppWeb, :channel
use Hotcode.Versioned, vsn: 2, gen_server: false
def upgrade(1, socket), do: %{socket | assigns: Map.put(socket.assigns, :history, [])}
def downgrade(2, socket), do: %{socket | assigns: Map.delete(socket.assigns, :history)}
# join/3, handle_in/3, ...
end
The rollback pre-flight reads the socket out of the process, as for any Hotcode.Versioned
process, and refuses a release without its downgrade/2 before it is loaded. Adopt it at
vsn: 1 first, as above. A code_change/3 written by hand works too; in a LiveView it must
return {:ok, socket}, since Phoenix.LiveView.Channel matches on that (an {:error, _} shows up
as a failed migration with a badmatch in the reason, and the deploy is reverted).
Where Versioned is more than you need, read a new assign with a default
(Map.get(socket.assigns, :theme, :light)) or keep the data in a struct whose new field has a
default (level 1).
Limits:
- A LiveComponent runs inside its LiveView's process, and
Phoenix.LiveView.Channelkeeps its assigns beside the socket, not in it: nocode_change/3reaches them. Structs in them are migrated; read new component assigns with defaults. - A channel or LiveView whose own module did not change, but that holds a changed struct, gets struct migration only.
- The transport process of a websocket (where
UserSocketassigns live) is not a channel: on Bandit list Bandit.DelegatingHandler incarriers; on Cowboy it is not reached. A Cowboy connection process reports the initial call{:cowboy_clear, :connection_process, 4}(or:cowboy_tls), andcarriersonly match{Module, :init, 1}, so listing a Cowboy module there does nothing. Whether:sys.replace_state/2on acowboy_websocketprocess would reach the handler state was not tested. On Cowboy, keep the transport-level state free of structs whose fields change (or read new fields with defaults), and put per-connection state that must follow the code in the channel processes. - Checked against the Phoenix 1.8 and LiveView 1.2 sources (
Phoenix.Channel.Server.code_change/3,Phoenix.LiveView.Channel.code_change/3). Hotcode's tests run stand-ins with the same initial call, state shape and forwarding, not Phoenix itself.
Habits that make upgrades safe
- Expand, then contract. Release N adds the new field and reads both shapes; release N+1 removes the old. Any two adjacent versions then stay compatible, which matters for rollbacks and for messages sent between nodes during a rollout.
- Keep messages compatible across two versions. Hotcode migrates state; it cannot rewrite messages already in flight or arriving from nodes still on the old version.
- Do not store anonymous functions in state, ETS or timers. A fun is bound to the module
version that created it and goes stale after the second deploy that replaces that module (Hotcode keeps one displaced
version until the next deploy). Store
{module, function, args}or an exported capture (&Mod.fun/1). Hotcode does not see them: lingering code means a process still running the old version (a loop that never made a remote call), not a fun that points at it. The Credo rules find the common cases in your source. - Test your migrations. An
upgrade/2is a pure function. Test each step and the chain, includingdowngrade, with ordinary unit tests or property tests.
ETS tables
Process state is migrated; the rows of an ETS table are not. When a deploy changes what a table
stores, the new code reads rows the old code wrote, and every read crashes or returns nonsense
until something rewrites them. Hotcode.Table does for rows what Hotcode.Versioned does for
state: one step per version, a downgrade for rollback, and a deploy that cannot be undone is
refused.
defmodule MyApp.Sessions do
use Hotcode.Table, vsn: 3, name: :sessions # a public, named :set by default
def upgrade(1, {id, user}), do: {id, user, %{}}
def upgrade(2, {id, user, meta}), do: {id, user, Map.put(meta, :seen, 0)}
def downgrade(3, {id, user, meta}), do: {id, user, Map.delete(meta, :seen)}
def downgrade(2, {id, user, _meta}), do: {id, user}
end
# in the process that owns the table, instead of :ets.new/2
{:ok, :sessions} = MyApp.Sessions.create()
A step returns the new row, :delete, or a list of rows (a key may change, a row may become
several). Deploying a release whose vsn is higher than the one the rows are in runs the chain
over every row before processes are migrated; a rollback runs the newer module's
downgrade/2 steps before the old code is loaded. If any step is missing or raises, or the
chain cannot be walked back (checked on a sample of the rewritten rows), the deploy is refused
and the table is exactly as it was: the rows go through a copy, and the copy is the undo. The
same chain runs once before the release is loaded, on a copy of the rows, so a release refused
for its table is never loaded (see
refused before or after loading).
Three things to know:
- The table is
:public, because the loader rewrites it from its own process. A:protectedor:privatetable is refused when the module is compiled. - Writers. The rows are replaced from a copy. A row written by a process the deploy does not
suspend, while it runs, can be lost. Write the table from one process the deploy suspends, or
give rows their version and define
row_vsn/1: rows already at the target are left alone, and a deploy can run with the writers still going. - Size. The copy is every row in memory, twice. For a table of many gigabytes keep a version in each row and upgrade rows when they are read.
A table also outlives its owner. create/0 makes the keeper (a process of Hotcode's) the
table's heir. When the process that owns it is replaced (Hotcode.Swap, Hotcode.AppSwap) or
dies, the table is not deleted: the next create/0, in the new owner, takes it over with its
rows. A table you already have is registered with Hotcode.Table.adopt(table, MyApp.Sessions, 1), saying which version its rows are in. Hotcode.Table.versions/0 lists them.
What is not migrated
- ETS tables made with plain
:ets.new/2(useHotcode.Table),:persistent_term, the process dictionary. - State of processes that are not
gen_server,gen_statemor supervisors started throughproc_lib. A plainspawnloop never leaves the code version it started in; it shows up as lingering and blocks the next deploy until it exits. AgentandTaskprocesses, which overwrite their initial call with the user's function and are skipped on purpose.- The assigns of a LiveComponent, and the assigns of a channel or LiveView without a
code_change/3beyond their structs (see Phoenix channels and LiveViews). - Closures. A closure in a migrated state keeps pointing at the module version that made it and
raises
:badfunonce that version is purged (at the next deploy of its module). The plan reports those it finds in the states it reads as:closure_in_state, with a path such asstate.callbacks.0; replace them with&Mod.fun/nor{M, F, A}before the next deploy of that module, or setconfig :hotcode, block_on_closure_in_state: trueto refuse such deploys.
What to do instead:
:persistent_term: version the key when the value's shape changes ({MyApp.Limits, 2}), so old and new code read different terms, and write the new one in anafter_deploy/1hook (see Hooks). Erase the old key in a later release.Agent: convert it to a GenServer (use Hotcode.Versioned, vsn: 1, adopted hot as above) before its state changes shape.
Memory during a migration. Struct migration and code_change/3 run inside the process and
build the new state while the old one is still referenced, so for a moment the process heap holds
both. A process with a max_heap_size (Process.flag(:max_heap_size, ...), or +hmax for every
process) set to kill near its limit can be killed in the middle of its migration: its state is
then lost (its supervisor restarts it fresh), and the deploy is undone or carries on depending on
the moment it died. The checks on copies (before loading) run in a
separate process, which receives a copy of the state. Leave headroom for twice the largest state,
or raise the limit for the duration of the deploy.
Hooks for what only you know
Hotcode.Hook lets your application run its own steps (reload configuration, warm a cache,
refuse a deploy while a billing run is active). See the
operations guide.