Credo rules
On this page
- HC0001
OnLoad - HC0002
NoNif - HC0003
ClosureInState - HC0004
VersionedChain - HC0005
TelemetryLocalHandler - HC0006
LocalReceiveLoop - HC0007
ProtocolImplOutsidePrefix - HC0008
HostedBehaviour - HC0009
SupervisorInitSideEffects - HC0010
CompileTimeEnv - HC0011
TerminateClosesSockets - HC0012
ClosureInOptions - HC0013
LoggerLocalFilter - HC0014
LocalAcceptLoop - HC0015
DeriveOutsidePrefix - HC0016
ProcessDictionaryState - HC0017
ApplicationStartSideEffects
Credo rules for code that will be hot-deployed: they catch, while you write it, what
Hotcode.Analyzer would block or warn about at deploy time, and what only fails after the
second deploy. Needs Credo in your own dependencies (only: [:dev, :test] is enough).
There are 17 rules, HC0001 to HC0017. Run them with no configuration, or add them to every mix credo run. Setup is in Catching hot-deploy mistakes while you write the code.
mix hotcode.check
mix hotcode.credo.install
The checks read source, so they are hints: each one says what it saw and why. Silence one
with # credo:disable-for-next-line Hotcode.Credo.Check.NoNif when you know better.
This page is built from the rule modules in lib/hotcode/credo/check/ and the table in Hotcode.Credo, so it matches the code.
| rule | what it catches |
|---|---|
HC0001 OnLoad |
@on_load |
HC0002 NoNif |
:erlang.load_nif/2 |
HC0003 ClosureInState |
an fn or local capture kept in state, ETS, a message |
HC0004 VersionedChain |
a use Hotcode.Versioned module with a missing upgrade/2 or downgrade/2 step |
HC0005 TelemetryLocalHandler |
:telemetry.attach with an fn or local capture |
HC0006 LocalReceiveLoop |
a receive loop that calls itself locally |
HC0007 ProtocolImplOutsidePrefix |
defimpl of a standard-library protocol |
HC0008 HostedBehaviour |
use GenStage, use Broadway, gen_event |
HC0009 SupervisorInitSideEffects |
:ets.new, :persistent_term.put, :telemetry.attach in a supervisor's init/1 |
HC0010 CompileTimeEnv |
@attr Application.get_env(...), System.get_env(...) |
HC0011 TerminateClosesSockets |
a GenServer or :gen_statem terminate that closes a socket or port, or stops a listener, without checking Hotcode.Swap.swapping?/0 |
HC0012 ClosureInOptions |
an fn or local capture in a child spec ({Task, fn}, start: {M, :f, [fn]}) or in a long-kept option (configure:, after_connect:, measurement:, tag_values:, keep:, drop:, sni_fun:, verify_fun:) |
HC0013 LoggerLocalFilter |
:logger.add_primary_filter, add_handler_filter, add_handler and config updates with an fn or local capture |
HC0014 LocalAcceptLoop |
a function that waits in accept or recv and calls itself locally |
HC0015 DeriveOutsidePrefix |
@derive of a standard-library protocol |
HC0016 ProcessDictionaryState |
Process.put in a GenServer's init/1 or handle_* |
HC0017 ApplicationStartSideEffects |
:ets.new, :persistent_term.put, telemetry or logger handlers in Application.start/2 |
HC0001 OnLoad
Module Hotcode.Credo.Check.OnLoad · Category warning · Priority high
What it catches. @on_load
Why it breaks a hot deploy. Runs on every load; the analyzer blocks replacing such a module.
@on_load runs every time the module is loaded, and hot loading loads it on a live node.
Hotcode blocks a deploy that REPLACES a module with an @on_load function unless the
signers force it (--force); a new module with one only gets a warning.
Do the work in Application.start/2, a supervised process, or a Hotcode.Hook.
Flagged (from the rule's tests)
defmodule A do
@on_load :setup
def setup, do: :ok
end
Left alone
defmodule A do
@moduledoc "x"
@vsn 2
def setup, do: :ok
end
HC0002 NoNif
Module Hotcode.Credo.Check.NoNif · Category warning · Priority high
What it catches. :erlang.load_nif/2
Why it breaks a hot deploy. Replacing a NIF library kills the processes running it.
Replacing the shared library behind a NIF is unsafe: the old library cannot be unloaded
while processes still run its code, and those processes are killed when the old code is
purged. Hotcode blocks a deploy that replaces a module calling :erlang.load_nif/2
unless the signers force it.
Keep NIF modules stable across hot deploys, and ship changes to them with a release restart, or put the changing logic in a module that calls the NIF. Flagged (from the rule's tests)
defmodule A do
def init, do: :erlang.load_nif(~c"priv/a", 0)
end
HC0003 ClosureInState
Module Hotcode.Credo.Check.ClosureInState · Category warning · Priority high
What it catches. An fn or local capture kept in state, ETS, a message
Why it breaks a hot deploy. The closure points at the code that built it, and fails with :badfun once a second deploy has replaced that module.
An anonymous function, and a capture of a LOCAL function (&helper/1), points at the
exact version of the module that created it. A process that keeps one in its state, or
an ETS row, a :persistent_term or a message that carries one, calls code that stops
existing: Hotcode keeps the displaced version of a module until the next deploy, so
the function works for one more deploy and then fails with :badfun.
# breaks after two deploys
{:ok, %{on_done: fn r -> notify(r) end}}
# always the current code
{:ok, %{on_done: &MyApp.Notifier.notify/1}}
{:ok, %{on_done: {MyApp.Notifier, :notify}}}
HC0004 VersionedChain
Module Hotcode.Credo.Check.VersionedChain · Category warning · Priority high
What it catches. A use Hotcode.Versioned module with a missing upgrade/2 or downgrade/2 step
Why it breaks a hot deploy. A missing step aborts the deploy, or the rollback.
use Hotcode.Versioned, vsn: N upgrades state one step at a time: deploying from v1 to
vN runs upgrade(1, _) ... upgrade(N-1, _), and a rollback runs downgrade(N, _)
... downgrade(2, _). A missing step makes the deploy, or the rollback, abort at the
moment a process has to migrate, which is the worst time to find out.
The check reads literal integer clauses (def upgrade(2, state)); a clause with a
variable first argument is taken to cover everything and the check stays quiet.
Flagged (from the rule's tests)
defmodule Counter do
use Hotcode.Versioned, vsn: 4
def upgrade(1, s), do: s
def upgrade(3, s), do: s
def downgrade(4, s), do: s
end
HC0005 TelemetryLocalHandler
Module Hotcode.Credo.Check.TelemetryLocalHandler · Category warning · Priority high
What it catches. :telemetry.attach with an fn or local capture
Why it breaks a hot deploy. The handler is silently detached once a second deploy has replaced the module.
:telemetry.attach/4 keeps the function it is given. An anonymous function, or a capture
of a LOCAL function (&handle/4), points at the version of the module that attached it:
once a second hot deploy has replaced that module, the next event fails with :badfun and
telemetry silently DETACHES the handler (it logs that it did, and no metric or alert is produced
from then on).
# detached once a second deploy has replaced this module
:telemetry.attach("alerts", [:my_app, :job, :stop], fn _, _, meta, _ -> notify(meta) end, nil)
:telemetry.attach("alerts", [:my_app, :job, :stop], &handle/4, nil)
# keeps working: an external capture always means the current code
:telemetry.attach("alerts", [:my_app, :job, :stop], &MyApp.Alerts.handle/4, nil)
HC0006 LocalReceiveLoop
Module Hotcode.Credo.Check.LocalReceiveLoop · Category warning · Priority high
What it catches. A receive loop that calls itself locally
Why it breaks a hot deploy. The process never moves to new code, and blocks the next deploy as lingering code.
A process that loops by calling its own function WITHOUT the module name (loop(state))
stays on the version of the module it started on, forever: a local call never switches to
newly loaded code. After a hot deploy it keeps running the old code (and Hotcode reports
it as lingering code that blocks the next deploy).
def loop(state) do
receive do
msg -> loop(handle(msg, state)) # stays on the old code
end
end
def loop(state) do
receive do
msg -> __MODULE__.loop(handle(msg, state)) # picks up the new code
end
end
A GenServer does not have this problem: the gen_server loop makes the call for you.
HC0007 ProtocolImplOutsidePrefix
Module Hotcode.Credo.Check.ProtocolImplOutsidePrefix · Category warning · Priority normal
What it catches. defimpl of a standard-library protocol
Why it breaks a hot deploy. Its module name is outside allowed_prefixes and the consolidated protocol it needs is a standard-library module: a patch does not ship it, and calls raise Protocol.UndefinedError until a release does.
The module that defimpl Protocol, for: Type creates is named Protocol.Type. For a
protocol from the standard library that name does not start with your application's
prefix (String.Chars.MyApp.Money), so Hotcode's allowed_prefixes policy does not let
a hot patch ship it. Shipping it would not be enough anyway: protocols are consolidated,
and a new implementation only takes effect once the consolidated protocol itself (here
String.Chars, a standard-library module) is replaced, which no patch may do. A patch
that adds or changes such an implementation carries on WITHOUT it (mix hotcode.build
warns, :protocol_impl_not_shipped), and the first call fails with
Protocol.UndefinedError.
Deploy a new implementation of a standard-library protocol with a release. (Protocols
of your own, under your prefix, are shipped like any other module, consolidated
protocol included. Add a dependency's protocol to protocols: when its prefix is not
in your allowed_prefixes.)
Flagged (from the rule's tests)
defimpl String.Chars, for: MyApp.Money do
def to_string(m), do: "#{m.amount}"
end
Left alone
defimpl MyApp.Printable, for: MyApp.Money do
def print(m), do: m
end
Options
protocols:Protocols from outside your allowed_prefixes (module names). Default:[Enumerable, Collectable, Inspect, String.Chars, List.Chars, JSON.Encoder].
HC0008 HostedBehaviour
Module Hotcode.Credo.Check.HostedBehaviour · Category design · Priority low
What it catches. use GenStage, use Broadway, gen_event
Why it breaks a hot deploy. Unless the host is listed in config :hotcode, :hosts, their code_change/3 is not run and their structs are not migrated.
A process whose behaviour is hosted by a library (GenStage, Broadway, gen_event)
runs the LIBRARY's loop: the VM reports it as {GenStage, :init, 1}, not as your module.
Hotcode finds the processes to suspend and migrate by that callback module, so by
default these are not found: your code_change/3 is not run and a struct in their
state is not migrated.
List the host in config :hotcode, hosts: [GenStage, :gen_event] (built in), or
{Host, mod_key, state_key} / {Host, {M, F}} for another library: the deploy then
reads your module out of the host's state and runs your code_change/3 through the
host's. Broadway is not built in and runs no code_change/3 of yours; keep its state
free of structs that change. Test the deploy.
Flagged (from the rule's tests)
defmodule A do
use GenStage
end
defmodule B do
use Broadway
end
defmodule C do
@behaviour :gen_event
end
Left alone
defmodule A do
use GenServer
end
HC0009 SupervisorInitSideEffects
Module Hotcode.Credo.Check.SupervisorInitSideEffects · Category warning · Priority high
What it catches. :ets.new, :persistent_term.put, :telemetry.attach in a supervisor's init/1
Why it breaks a hot deploy. Hotcode runs init/1 again after a deploy.
After a deploy changes a supervisor, Hotcode calls its init/1 AGAIN, in a scratch
process, to compare the children it would start with the ones running. An init/1 that
creates a named ETS table, writes :persistent_term, attaches a telemetry handler or
sets application env then does it twice: the table creation fails, and the comparison
(so the removal of children) is silently skipped.
Keep init/1 to returning the children. Do such setup in a process of its own, started
before the supervisor, or in Application.start/2.
Flagged (from the rule's tests)
defmodule A do
use Supervisor
def init(_) do
:ets.new(:t, [:named_table])
:persistent_term.put(:k, 1)
Supervisor.init([], strategy: :one_for_one)
end
end
Left alone
defmodule A do
use GenServer
def init(_), do: (:ets.new(:t, [:named_table]); {:ok, nil})
end
defmodule B do
use Supervisor
def init(_), do: Supervisor.init([], strategy: :one_for_one)
end
HC0010 CompileTimeEnv
Module Hotcode.Credo.Check.CompileTimeEnv · Category warning · Priority normal
What it catches. @attr Application.get_env(...), System.get_env(...)
Why it breaks a hot deploy. A patch freezes the build's value, not the node's runtime config.
@setting Application.get_env(...), Application.compile_env(...) and System.get_env(...)
in a module attribute (or at the top of a module body) are read when the module is COMPILED.
A hot patch carries the value of the machine and environment that built it, and keeps it
until the next release: not the runtime configuration the node has now. A build with the
wrong MIX_ENV, or from a machine with other environment variables, ships the wrong value.
Read configuration at runtime (Application.get_env/3 inside a function), or build with
the release's environment (MIX_ENV=prod) and check what the module captures.
Flagged (from the rule's tests)
defmodule A do
@url Application.get_env(:my_app, :url)
@token System.get_env("TOKEN")
@mode Application.compile_env(:my_app, :mode, :dev)
end
Left alone
defmodule A do
@moduledoc "x"
@timeout 5_000
def url, do: Application.get_env(:my_app, :url)
end
HC0011 TerminateClosesSockets
Module Hotcode.Credo.Check.TerminateClosesSockets · Category warning · Priority high
What it catches. A GenServer or :gen_statem terminate that closes a socket or port, or stops a listener, without checking Hotcode.Swap.swapping?/0
Why it breaks a hot deploy. During a Hotcode.Swap it closes the connection handed to the replacement process.
Hotcode.Swap replaces a process with a fresh one and hands its sockets to the new
process before the old one is stopped. The old process's terminate/2 (terminate/3
for :gen_statem) still runs, and a socket can be closed by any process, not only its
owner: a terminate that closes its socket or port, or stops its listener, closes the
connection the new process was about to take over. The swap reports
{:error, {:closed_in_terminate, ports}}, and the client is gone.
Skip what was handed over when Hotcode.Swap.swapping?/0 is true:
# closes the socket the replacement was given
def terminate(_reason, state), do: :gen_tcp.close(state.socket)
# keeps it open during a swap, closes it on any other stop
def terminate(_reason, state) do
unless Hotcode.Swap.swapping?(), do: :gen_tcp.close(state.socket)
end
The rule reads the body of terminate only: a close done in a helper it calls is not
seen.
HC0012 ClosureInOptions
Module Hotcode.Credo.Check.ClosureInOptions · Category warning · Priority high
What it catches. An fn or local capture in a child spec ({Task, fn}, start: {M, :f, [fn]}) or in a long-kept option (configure:, after_connect:, measurement:, tag_values:, keep:, drop:, sni_fun:, verify_fun:)
Why it breaks a hot deploy. The supervisor, pool, reporter or :ssl keeps it, and it fails with :badfun once a second deploy has replaced the module.
Some options are kept for the life of a process: a child spec is kept by its supervisor
(and used again at every restart), a connection pool keeps its configure: and
after_connect: callbacks, a metrics reporter keeps the measurement:, tag_values:,
keep: and drop: functions of every metric, :ssl keeps sni_fun: and verify_fun:.
An anonymous function or a capture of a LOCAL function given there points at the
version of the module that built it, and fails with :badfun once a second hot deploy
has replaced that module: at the next restart of the child, the next connection, the
next metric event.
# breaks after two deploys
children = [{Task, fn -> warm_cache() end}]
{Postgrex, configure: fn opts -> Keyword.put(opts, :password, secret()) end}
summary("phoenix.endpoint.stop.duration", tag_values: &tags/1)
# always the current code
children = [{Task, &MyApp.Cache.warm/0}]
{Postgrex, configure: {MyApp.Repo, :configure, []}}
summary("phoenix.endpoint.stop.duration", tag_values: &MyApp.Telemetry.tags/1)
keys: lists the option names looked at.
Options
keys:Option names whose value is kept for long (atoms). Default:[:configure, :after_connect, :measurement, :tag_values, :keep, :drop, :sni_fun, :verify_fun].
HC0013 LoggerLocalFilter
Module Hotcode.Credo.Check.LoggerLocalFilter · Category warning · Priority high
What it catches. :logger.add_primary_filter, add_handler_filter, add_handler and config updates with an fn or local capture
Why it breaks a hot deploy. :logger removes the filter after the second deploy, and the events it dropped or rewrote go through.
:logger keeps its filters ({fun, extra}) and handler configuration for the life of
the node. An anonymous function, or a capture of a LOCAL function (&drop_health/2),
points at the version of the module that installed it: once a second hot deploy has
replaced that module, the next log event fails with :badfun and :logger REMOVES the
filter (it logs that it did). From then on the events it dropped or rewrote, health
checks or secrets, go through unfiltered.
# removed by :logger once a second deploy has replaced this module
:logger.add_primary_filter(:health, {&drop_health/2, []})
:logger.add_handler_filter(:default, :health, {fn e, _ -> e end, []})
# keeps working: an external capture always means the current code
:logger.add_primary_filter(:health, {&MyApp.LogFilters.drop_health/2, []})
HC0014 LocalAcceptLoop
Module Hotcode.Credo.Check.LocalAcceptLoop · Category warning · Priority high
What it catches. A function that waits in accept or recv and calls itself locally
Why it breaks a hot deploy. The loop never moves to new code, and blocks the next deploy as lingering code.
A loop that waits in :gen_tcp.accept, :ssl.transport_accept, :socket.accept or a
recv, and goes round by calling its own function WITHOUT the module name
(accept_loop(listen)), stays on the version of the module it started on: a local call
never switches to newly loaded code. After a hot deploy it keeps running the old code,
Hotcode reports it as lingering code and refuses the next deploy that would purge it.
It is not a gen_server, so it cannot be suspended either.
defp accept_loop(listen) do
{:ok, socket} = :gen_tcp.accept(listen)
serve(socket)
accept_loop(listen) # stays on the old code
end
def accept_loop(listen) do
{:ok, socket} = :gen_tcp.accept(listen)
serve(socket)
__MODULE__.accept_loop(listen) # picks up the new code
end
Better still, let a library own the accept loop (ThousandIsland, Ranch) and keep your code in its handler callbacks. A loop that only reads one body and returns is fine: disable the check on that line.
Options
calls:Blocking calls that make a recursive function a long-lived loop. Default:[ gen_tcp: :accept, ssl: :transport_accept, socket: :accept, gen_tcp: :recv, ssl: :recv, socket: :recv ].
HC0015 DeriveOutsidePrefix
Module Hotcode.Credo.Check.DeriveOutsidePrefix · Category warning · Priority normal
What it catches. @derive of a standard-library protocol
Why it breaks a hot deploy. Like HC0007: a new or changed derived implementation is not shipped by a patch.
@derive Protocol writes defimpl Protocol, for: YourStruct for you, so it has the same
limit as Hotcode.Credo.Check.ProtocolImplOutsidePrefix (HC0007): the implementation
module is named Protocol.YourStruct (Inspect.MyApp.Event), outside your
allowed_prefixes, and the consolidated protocol it needs cannot be replaced by a
patch. A patch that adds the struct, or changes the derived options (only:,
except:), carries on WITHOUT the new implementation (mix hotcode.build warns,
:protocol_impl_not_shipped): the old one keeps running, or the first call raises
Protocol.UndefinedError.
@derive {Inspect, except: [:secret]} # a new or changed one needs a release
defstruct [:id, :name, :secret]
Ship a new or changed derived implementation with a release. The default list is the
standard library's, as for HC0007; add a dependency's protocol (Jason.Encoder) to
protocols: when its prefix is not in your allowed_prefixes. An @derive on a struct
whose fields and options do not change is harmless: the check flags the line because
it cannot know what a patch will change.
Options
protocols:Protocols from outside your allowed_prefixes (module names). Default:[Enumerable, Collectable, Inspect, String.Chars, List.Chars, JSON.Encoder].
HC0016 ProcessDictionaryState
Module Hotcode.Credo.Check.ProcessDictionaryState · Category design · Priority normal
What it catches. Process.put in a GenServer's init/1 or handle_*
Why it breaks a hot deploy. State kept there is not migrated by code_change/3 or struct migration.
A GenServer that keeps part of its state in the process dictionary (Process.put/2 in
init/1 or a handle_* callback) hides it from a hot deploy: code_change/3,
Hotcode.Versioned and struct migration only see the state the callbacks return. When
a release changes what is stored under that key (a struct gains a field, a map becomes
a list), the process keeps the old value under the new code.
def init(opts) do
Process.put(:config, %Config{}) # never migrated
{:ok, %{}}
end
def init(opts) do
{:ok, %{config: %Config{}}} # migrated with the rest of the state
end
Keys starting with $ (:"$callers", :"$ancestors") belong to OTP and are ignored.
Logger metadata is set with Logger.metadata/1 and is not flagged.
HC0017 ApplicationStartSideEffects
Module Hotcode.Credo.Check.ApplicationStartSideEffects · Category design · Priority normal
What it catches. :ets.new, :persistent_term.put, telemetry or logger handlers in Application.start/2
Why it breaks a hot deploy. start/2 does not run again on a hot deploy, so a patch cannot change that setup.
Application.start/2 runs once, when the node boots. A hot deploy never runs it again,
so what it sets up keeps the shape of the release the node booted from: an ETS table
created there keeps its old options, a :persistent_term keeps its old value, a
telemetry handler or logger filter attached there is not attached again. A patch that
changes this setup changes nothing on a running node. A patch that changes the
application module itself is refused at deploy time (:application_callback).
def start(_type, _args) do
:ets.new(:rates, [:named_table, :public]) # never re-created by a patch
:persistent_term.put(:limits, load_limits()) # never re-read by a patch
Supervisor.start_link(children(), strategy: :one_for_one)
end
Move the setup into a supervised process whose init/1 does it (use Hotcode.Table for
an ETS table whose layout changes), or redo it in an after_deploy/1 hook.