Checks we run
On this page
A hot deploy is checked at several points: in your editor, in your tests, before a patch is built, when it reaches a node, before it is loaded, and after. This page lists them. Each section is built from the docs in the source, so it stays in step with the code.
Before you ship
Static checks
17 Credo rules read your source and flag what a hot deploy cannot handle. They are listed on Credo rules.
mix hotcode.check [credo options] [paths]
Runs Credo with the Hotcode rules (Hotcode.Credo) and
nothing else. Which files are read (files: %{included: ..., excluded: ...}) comes from the
default configuration in your own .credo.exs; --strict, --format json, paths and every
other Credo option pass through.
mix hotcode.check
mix hotcode.check --strict --format json lib/
mix hotcode.check --all # your own configuration and checks too, plus Hotcode's
It needs no change to your configuration: the rules are added for this run, whatever your
checks: section says. To have them in every mix credo run, install them once with
mix hotcode.credo.install.
Test helpers
use Hotcode.Test deploys the next version of your modules into the test VM and asserts that the process, its state and a way back survive. See Test helpers.
The adoption audit
Hotcode adoption audit: a read-only scan of an Elixir project.
elixir skills/hotcode/scripts/audit.exs PROJECT_DIR [--json] [--all] [--exclude DIR]...
It reads source, config and deployment files and prints, grouped by hazard, what a hot
deploy with Hotcode would trip on, with file:line and a one-line fix, plus the clues about
how the project is deployed. It never writes to the project. Built-ins only (no Mix.install),
so it runs with plain elixir on Elixir 1.17 or later.
The scan is textual: a finding is a lead to read, not a verdict. Comments and heredocs (@moduledoc, @doc, ~H""" templates) are skipped.
It looks for these, and prints each with file, line and a one-line fix. A finding is a lead to read, not a verdict. The last column says whether a hot deploy cannot fix it and a release restart is needed. See Using Hotcode with a coding agent.
| finding | severity | what to do | needs a restart |
|---|---|---|---|
| :protected or :private ETS table | warn | Hotcode.Table needs :public; keep it plain (rebuild or flush in after_deploy/1) or make it public | no |
| :telemetry handler attached with a closure or local capture | warn | attach &__MODULE__.handle/4 (an external capture); telemetry detaches a handler whose module was replaced twice |
no |
| Agent | warn | Agent state is never migrated; convert to a GenServer if its shape changes | no |
| Application callback module | warn | any change to this module is blocked (:application_callback); keep it tiny and move logic out, or ship it with a restart | yes |
| NIF or @on_load module | warn | replacing it is blocked; ship a new module beside the old one (NIF facade) or restart | yes |
| anonymous function or local capture that may be kept | warn | if it is stored (state, opts of a long-lived process, ETS, persistent_term, a message), use &Mod.fun/n or {M, F, A} | no |
| behaviour hosted by a library | warn | list the host in config :hotcode, hosts: [...] or its code_change/state migration is skipped; see the hazard reference | no |
| handler registered as fn for a route, socket or event | warn | a library that keeps it in each connection or in a registry calls it after the second deploy of this module: :badfun; pass &Mod.fun/n | no |
| logger filter or handler given a closure or local capture | warn | pass &__MODULE__.filter/2 (external capture) |
no |
| module list read from the .app file | warn | a hot-loaded module is not in Application.spec(app, :modules); build such registries from Hotcode.Loader.modules(app) and rebuild them in after_deploy/1 when report.new or report.removed is set | no |
| process loop that calls itself locally | warn | call __MODULE__.name(...) so the loop moves to new code; until then a deploy of this module is refused while it runs (:lingering_old_code) |
no |
| protocol implementation outside your prefixes (defimpl or @derive) | warn | it is not shipped in a patch (:protocol_impl_not_shipped); changes to it need a release | yes |
| side effect in a Supervisor init/1 | warn | a deploy that changes this supervisor runs init/1 again; move :ets.new/persistent_term/attach into a worker or Application.start/2 | no |
| terminate/2 closes a socket, port or OS process without Hotcode.Swap.swapping?/0 | warn | wrap the close in unless Hotcode.Swap.swapping?() |
no |
| :persistent_term write | info | not migrated; a value written at boot keeps its old shape after a deploy (re-put it in Hotcode.Hook.after_deploy/1) | no |
| Phoenix channel or LiveView | info | a deploy runs the module's code_change/3 on the socket; without one a new assign is not added: use Hotcode.Versioned, vsn: N, gen_server: false, or read new assigns with defaults | no |
| Process.put (process dictionary) | info | not migrated; keep long-lived state in the callback state instead | no |
| already uses Hotcode | info | check the module is covered by tests (Hotcode.Test) | no |
| call or message across nodes | info | during a roll both releases must understand it: change formats in three releases (readers, writers gated by Hotcode.Cluster.applied?/1, cleanup) | no |
| children listed inline in Application.start/2 | info | adding or removing a top-level child needs a restart; move the list into a Supervisor module with init/1 | yes |
| dynamic or :temporary child | info | Hotcode.Swap cannot replace it; it can only be upgraded in place | no |
| file embedded at compile time | info | the patch build must have the same file; content changes ship as module changes | no |
| gen_statem | info | use Hotcode.Versioned does not fit (it is a GenServer); write code_change/4 by hand | no |
| hand-written code_change | info | keep it, or port its steps to Hotcode.Versioned upgrade/2 and downgrade/2 | no |
| job queue or scheduler | info | a long job runs displaced code; veto deploys while jobs run (Hotcode.Hook.before_deploy/1) or drain first | no |
| plain :ets.new table | info | rows are not migrated and the table dies with its owner; use Hotcode.Table if rows change shape or must outlive a replaced owner | no |
| plain process (spawn / Task.start / start_child with fn) | info | not migrated; while it runs on displaced code the next deploy of its module is refused (:lingering_old_code) | no |
| port or external OS process owned by a process | info | never swap or restart the owner (the OS process dies with it); upgrade it in place only | no |
| reads priv/ at runtime | info | a patch carries beams only: priv/ files (static assets, templates, migrations) change only with a release | yes |
| side effect in Application.start/2 | info | runs once at boot; a hot deploy never re-runs it (use a Hotcode.Hook after_deploy/1 to redo it) | yes |
| value read at compile time | info | a patch carries the value of the machine that built it: build in the release's toolchain and config, MIX_ENV=prod | no |
When a patch reaches a node
Who may send it
- the node is not locked and not in failure lockout (
Hotcode.Guard) thresholddistinct trusted keys signed the statement (Ed25519)- the statement is a deploy for this
audience, inside its time window, withseqgreater than the last accepted one - the patch's SHA-256 equals
bundle_sha256(the signature covers the patch) - the patch unpacks, and its manifest matches its beams
- policy: every module touched must match
allowed_prefixes, and none may be part of Hotcode, Erlang/OTP or the Elixir standard library
Step 6 is blast-radius control, not isolation: code you are allowed to deploy can
still do anything your application can. What it prevents is a stolen signing key
being used to replace :crypto, :ssl, :code or Hotcode's own checks.
The rule is by module name with no exception for protocols: String.Chars.MyApp.Money
(defimpl String.Chars, for: MyApp.Money) is outside "MyApp", and the consolidated
String.Chars it needs is a standard-library module, so neither is allowed. The
security guide explains why ("Protocol implementations").
Brakes
Operational brakes around deploys:
- kill switch:
Hotcode.lock/0makes the node refuse everything untilHotcode.unlock/0;config :hotcode, locked: truestarts it locked - failure lockout: 5 rejected envelopes in a minute refuse deploys for 5 minutes. Anonymous traffic never counts, so strangers cannot lock operators out
- request challenges: HTTP requests are signed over a single-use challenge issued by this node
Why challenges are stateless
A challenge is random || expiry || HMAC(node_secret, random || expiry). Issuing one
stores nothing, so an anonymous client can neither exhaust memory nor evict an
operator's outstanding challenge by asking for thousands. The secret is random per
boot and per node, so a challenge is worthless to any other node and after a
restart. Single use is enforced by remembering only the challenges that were used by
a valid signature, which is bounded by what trusted key holders actually do.
Analyzer findings
Preflight checks: looks at what a patch changes and flags the cases hot loading cannot or should not handle.
Each finding is %{severity: :block | :warn | :info, module: mod | nil, code: atom, message: binary}.
:block findings abort the deploy unless it is forced.
| code | severity | why |
|---|---|---|
:otp_mismatch |
block | beams from another OTP release may not load |
:elixir_mismatch |
warn | stdlib/consolidated protocol layout may differ |
:build_env |
warn | the patch was compiled in a Mix environment other than prod: a release runs prod code, with its compile_env and config |
:removed_exports |
warn | a changed module no longer exports functions the loaded one does: an MFA in a job queue, a message in flight or a capture elsewhere that names them fails with :undef |
:self_upgrade |
block | the loader cannot replace itself while running |
:nif |
block, warn if the module is new | replacing a NIF library is unsafe (processes die on purge); a NEW module replaces nothing |
:on_load |
block, warn if the module is new | @on_load runs on every load; same distinction |
:application_callback |
block | the module has the Application behaviour (any function of it changed): Application.start/2 does not run again, so the change would not apply |
:dependency_bump |
info, warn (pre-release) | an application changes version by semver patch/minor, see Hotcode.Semver |
:major_bump |
block, warn if the signers accepted it | a major bump, a downgrade or a non-semver version of an application: breaking by contract |
:supervisor |
warn | its running children are reconciled after the deploy (Hotcode.Supervision), or only reported with supervision: :report |
The plan (Hotcode.Loader.plan/1, a dry run, every deploy) adds findings that need the running
node:
| code | severity | why |
|---|---|---|
:closure_in_state |
warn, block with block_on_closure_in_state: true |
a process the deploy touches keeps a closure defined in a patched module (Hotcode.Closures): :badfun once that version is purged. Extra keys: process, processes, path, closure_module |
:closure_scan_sampled |
info | struct_scan: [max_processes: n] capped the states read for closures |
:struct_scan_limit |
block | a struct change would read more states than struct_scan: [max_processes: n] |
:cross_node_contract |
warn | the app calls, on other nodes, a function the patch removes or adds (Hotcode.CrossNode). Extra keys: caller, function, change |
Preflight
Every node is asked for a preflight (Hotcode.Loader.preflight_binary/1: the signature
threshold, audience, expiry, replay counter, base code, requires, module policy, analyzer
blocks, the before_deploy veto and lingering old code) before any node is touched, so a patch
that one node would refuse never runs on the others, not even briefly. Only a failure the
preflight cannot predict (a health check, a crash while loading) rolls nodes back.
Checks on copies, before loading
From the notes in Hotcode.Shadow:
A module of a patch, loaded under another name before the patch itself is loaded, so its
functions (a table's upgrade/2 and downgrade/2, a Hotcode.Versioned chain, a struct's
defaults) can be run on copies of the live data while every process still runs the old code.
No process can reach a shadow: nothing refers to its name.
The beam is renamed by rewriting atom 1 of its atom table (the module name) and every
occurrence of that atom in its literal table. Inside the shadow, __MODULE__, %__MODULE__{}
and remote calls to itself all name the shadow. Terms going in are renamed the same way
(to_shadow/2) and terms coming out are renamed back (from_shadow/2), so a clause that
matches %__MODULE__{} sees the live state as the real module would.
What a shadow cannot reproduce: calls to OTHER modules of the same patch reach their old
versions (or nothing, for a new module). raises_trusted is false for a shadow whose code
calls another module of the patch: an exception raised inside it may come from that, and only
a run on the loaded code can tell. A module with @on_load is never shadowed (loading it
would run its hook).
Fail safe: a module left without a shadow is not checked before loading, only after (load,
check, undo), so a release is never accepted on the strength of a check that did not run.
Any reason other than @on_load is unexpected (a beam this rewriting does not understand):
it is logged once per reason and reported as telemetry [:hotcode, :shadow, :unavailable].
The deploy sequence
Applies a Hotcode.Bundle to the running node without restarting anything.
All deploys on a node are serialized through this GenServer.
Sequence:
- plan: diff by beam MD5, run
Hotcode.Analyzer;:blockfindings abort (unlessforce: true), thenc:Hotcode.Hook.before_deploy/1may veto - snapshot the binaries being replaced (rollback needs them)
soft_purgethe old-code slot of every touched module. Processes still on two-versions-ago code get a GC first (they often only hold stale references); if any remain we ABORT instead of letting a hard purge kill them- find the processes that must change with the code: gen_server/gen_statem/
supervisor processes whose callback module changed, plus processes of
configured
:carriers, plus processes of configured:hosts(GenStage, gen_event, ...) whose hosted user module changed, plus (when a struct changes) processes running code underallowed_prefixesthat answer:sysand whose state holds it, plus processes whose initial call is in a changed module (a Phoenix channel or LiveView runs its module inside Phoenix's server), and:sys.suspendthem. Messages queue, sockets stay open - check on copies, before loading: the new modules are loaded under other names
(a shadow: no process can reach it) and run on copies of the rows of every
Hotcode.Tablethey own (before step 4's suspension) and of the state of every suspendedHotcode.Versionedprocess (after it): upgrade chain, then downgrade chain. A failure refuses the release with nothing loaded (loaded: falsein the error) :code.prepare_loading+:code.finish_loading: every module switches at once- per process, in pid order: auto-migrate changed structs in its state
(
Hotcode.StructMigrator), then:sys.change_code(yourcode_change/3orHotcode.Versioned) - any failure: reverse the processes already migrated (with the NEW code still
loaded, which is the only code able to downgrade its own state), then load
the old binaries back (
loaded: truein the error). A process whose downgrade fails is killed so its supervisor restarts it clean - resume everything, soft-purge, persist the patch (
Hotcode.Store), notify hooks and telemetry
See How it works for which refusals come before loading and which after.
After it loads
Health gates
Health gate used between nodes of a rollout. By default a node is healthy when its loader answers. Add your own check with
config :hotcode, health_check: {MyApp.Health, :ready?, []} # returns :ok | true | {:error, _} | false
It runs ON the node that was just upgraded.
Rolls a patch across nodes one at a time, gating each step on a health check
(Hotcode.Health), and undoing the nodes already done if a later one fails.
Deadman rollback
config :hotcode, convergence: [mode: :auto, after_ms: 60_000, attempts: 3]
:auto does everything :converge does, and undoes a release that the cluster could not
follow, but ONLY a release whose signed statement carries "auto_rollback"
(mix hotcode.build --auto-rollback-after 120s): the signers authorized that undo when they
signed the deploy. The stack entry of such a release keeps the policy, its seq and when it
was applied on each node (Hotcode.Loader.status/0, head). Without it nothing is ever undone.
The coordinator is the lowest node name among the nodes that run the head release; every
other node only watches. It acts when all of this holds, in this order (deadman_plan/3):
- the reachable nodes form one line (
lineage/0is:behind), never a fork; - the head's entry on this node carries the policy, was applied after the last automatic
rollback (no cascade) and was not acted on already (
{version, seq}); - the policy's
after_mshas passed since this node applied it, and every lagging node has been on its release at least that long; - a strict majority of the nodes in the table (
expected_nodesincluded) is:up; - no unreachable node was last seen running the head, and no node at all runs a patch that
requiresit; - every lagging node answers that it gave up pulling (
converge.state == :failed, or the policy'sattemptsreached); - the roll lock (
{Hotcode.Rollout, _}, what a roll holds) is free on every node involved, taken without waiting, and held for the undo.
Then Hotcode.Loader.auto_rollback/2 runs on each node on the head, which checks again,
locally: mode :auto, this exact entry on top, policy present, not required by a newer entry,
not locked. Afterwards audit :cluster_auto_rollback (coordinator, version, seq, nodes,
laggards, why), telemetry [:hotcode, :cluster, :auto_rollback] (metadata result: :ok | :error), and on every node report().converge is %{state: :rolled_back, auto_rollback: info}. If any node refuses or fails, :cluster_auto_rollback_failed and :rollback_failed
instead, and nothing is retried for that release: an operator decides.
See Clusters and mixed versions for the whole story.