Catching hot-deploy mistakes while you write the code

On this page

Hotcode.Analyzer inspects a patch at deploy time and refuses or warns about what hot loading cannot handle. That is the last line of defence, and it is late: the code is written, reviewed and built. Hotcode also ships Credo rules that find the same mistakes in the source, in your editor and in CI, plus one that nothing finds at deploy time.

Set up

Credo is an optional dependency, so list it in your own project next to Hotcode:

# mix.exs
{:credo, "~> 1.7", only: [:dev, :test], runtime: false},
{:hotcode, "~> 0.1"}

Run the rules once, with no configuration:

mix hotcode.check
mix hotcode.check --strict --format json lib/

mix hotcode.check runs the seventeen rules and nothing else, with your own .credo.exs (files, --strict, --format, paths and every other Credo option apply). Add --all to run your own Credo checks too. Exit status is Credo's: 0 when clean, 16 when a rule found something, so a CI step fails by itself.

Or install them for every mix credo run:

mix hotcode.credo.install

This adds {Hotcode.Credo.Plugin, []} to the plugins of your .credo.exs (creating the file if there is none, extending an existing plugins: [...] list, and printing the line to add instead of touching a configuration it does not recognise). By hand:

# .credo.exs
%{
  configs: [
    %{
      name: "default",
      plugins: [{Hotcode.Credo.Plugin, []}]
    }
  ]
}

The plugin registers the rules, so new ones arrive with a Hotcode upgrade and there is no list of checks to maintain. Turn one off the way you would any Credo check:

checks: %{disabled: [{Hotcode.Credo.Check.NoNif, []}]}

Your .credo.exs calls into a dependency, so compile first (mix deps.compile, or mix compile; an editor integration does this for you). The rules read source, so they are hints; silence one where you know better with # credo:disable-for-next-line Hotcode.Credo.Check.NoNif.

The rules

HC0001 Hotcode.Credo.Check.OnLoad

defmodule MyApp.Cache do
  @on_load :warm      # flagged
  def warm, do: :ok
end

@on_load runs on every load, and a hot deploy loads the module on a live node. The analyzer blocks a deploy that replaces such a module (the signers can force it); a new one only warns. Warm caches from Application.start/2, a supervised process or a Hotcode.Hook.

HC0002 Hotcode.Credo.Check.NoNif

:erlang.load_nif/2 makes a module a NIF module. Replacing the library under running processes kills them when the old code is purged, so the analyzer blocks it. Keep NIF modules stable across hot deploys, and let the code that changes call them.

HC0003 Hotcode.Credo.Check.ClosureInState

The one that no deploy-time check can see, because the code is correct on the day it ships:

def init(_), do: {:ok, %{on_done: fn r -> notify(r) end}}   # flagged
def handle_cast({:watch, f}, s), do: {:noreply, %{s | cb: &helper/1}}   # flagged
def a, do: :ets.insert(:jobs, {id, fn -> run() end})   # flagged

An fn, and a capture of a local function, points at the version of the module that built it. 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, in a process that was fine for weeks. It is flagged when it is kept: in the state a GenServer callback returns, and in :ets.insert, :persistent_term.put, Process.put, or a GenServer.cast/call message. A closure used on the spot (Enum.map(xs, fn ... end)) is not.

{:ok, %{on_done: &MyApp.Notifier.notify/1}}      # external capture: always the current code
{:ok, %{on_done: {MyApp.Notifier, :notify}}}     # or a {module, function} to apply

HC0004 Hotcode.Credo.Check.VersionedChain

defmodule Counter do
  use Hotcode.Versioned, vsn: 3
  def upgrade(1, s), do: s        # no upgrade(2, _): flagged
  def downgrade(3, s), do: s      # no downgrade(2, _): flagged
end

Deploying v1 to v3 runs upgrade(1) then upgrade(2); a rollback runs downgrade(3) then downgrade(2). A missing step makes the deploy, or the rollback, abort at the moment a process has to migrate. Literal integer clauses are checked; a clause with a variable first argument is taken to cover every version.

HC0006 Hotcode.Credo.Check.LocalReceiveLoop

def loop(state) do
  receive do
    msg -> loop(handle(msg, state))             # flagged: a local call never leaves the old code
  end
end

A process that loops by calling its own function without the module name stays on the version it started on forever, runs old code after a deploy and blocks the next one (lingering code). Call __MODULE__.loop(...). A GenServer is fine: its loop is the library's.

HC0007 Hotcode.Credo.Check.ProtocolImplOutsidePrefix

defimpl String.Chars, for: MyApp.Money creates String.Chars.MyApp.Money, which is outside allowed_prefixes. It would not help to ship it anyway: protocols are consolidated, and the new implementation only dispatches once the consolidated String.Chars (a standard-library module) is replaced too, which no patch may do. A patch that adds it carries on without it (mix hotcode.build prints a warning: naming the module, and the summary carries a :protocol_impl_not_shipped finding) and the first to_string/1 raises Protocol.UndefinedError. Deploy implementations of standard-library protocols with a release. The checked protocols are Enumerable, Collectable, Inspect, String.Chars, List.Chars and JSON.Encoder; add a dependency's protocol (say Phoenix.HTML.Safe) with protocols: when its prefix is not in your allowed_prefixes. Why the policy has no exception for this: security guide.

HC0008 Hotcode.Credo.Check.HostedBehaviour

use GenStage, use Broadway and gen_event processes run the library's loop, so by default Hotcode does not find them by your module: code_change/3 is not run, changed structs in their state are not migrated. List the host in config :hotcode, hosts: [GenStage, :gen_event] (or {Host, mod_key, state_key} / {Host, {M, F}} for another library) and the deploy reads your module out of the host's state and migrates the process. Broadway has no built-in entry and runs no code_change/3 of yours. See State migration.

HC0009 Hotcode.Credo.Check.SupervisorInitSideEffects

After a deploy changes a supervisor, Hotcode calls its init/1 again to compare children. An init/1 that does :ets.new, :persistent_term.put, :telemetry.attach or Application.put_env does it twice.

HC0010 Hotcode.Credo.Check.CompileTimeEnv

@url Application.get_env(...) and System.get_env(...) in a module attribute are read when the module is compiled: a patch carries the value of the machine that built it. Read configuration at runtime.

HC0005 Hotcode.Credo.Check.TelemetryLocalHandler

:telemetry.attach with an fn or a local capture: telemetry detaches the handler, silently, once a second deploy has replaced the module. Attach &MyApp.Telemetry.handle/4.

HC0011 Hotcode.Credo.Check.TerminateClosesSockets

def terminate(_reason, state), do: :gen_tcp.close(state.socket)   # flagged

A GenServer or :gen_statem whose terminate closes a socket or a port (:gen_tcp, :ssl, :gen_udp, :socket, Port.close) or stops a listener (:ranch, :cowboy, ThousandIsland) without calling Hotcode.Swap.swapping?/0. During a Hotcode.Swap the sockets have already been handed to the replacement process, the old process's terminate still runs, and any process can close a socket: the client is dropped and the swap returns {:error, {:closed_in_terminate, ports}}. Skip the close when swapping?/0 is true. Only the body of terminate is read; a close inside a helper it calls is not seen.

HC0012 Hotcode.Credo.Check.ClosureInOptions

children = [{Task, fn -> warm_cache() end}]                              # flagged
{Postgrex, configure: fn opts -> Keyword.put(opts, :password, secret()) end}   # flagged
summary("phoenix.endpoint.stop.duration", tag_values: &tags/1)            # flagged

The same mistake as HC0003, in options that a library keeps: a child spec is kept by its supervisor and used again at every restart, a pool keeps configure: and after_connect:, a Telemetry.Metrics reporter keeps measurement:, tag_values:, keep: and drop:, :ssl keeps sni_fun: and verify_fun:. After the second deploy that replaces the module, the next restart, connection or metric event fails with :badfun. Flagged: {Task, fn} and {Agent, fn}, start: {M, :f, [fn ...]}, and a closure under one of the option names in keys: (the list above). Use &MyApp.Cache.warm/0, {MyApp.Repo, :configure, []} or &MyApp.Telemetry.tags/1.

HC0013 Hotcode.Credo.Check.LoggerLocalFilter

:logger.add_primary_filter(:health, {&drop_health/2, []})   # flagged

:logger keeps its filters for the life of the node. A filter that is an fn or a local capture fails with :badfun once a second deploy has replaced the module, and :logger then removes it: what it dropped or redacted is logged from then on. Flagged in :logger.add_primary_filter, add_handler_filter, add_handler and the set_/update_ config functions. Use {&MyApp.LogFilters.drop_health/2, []}.

HC0014 Hotcode.Credo.Check.LocalAcceptLoop

defp accept_loop(listen) do
  {:ok, socket} = :gen_tcp.accept(listen)
  serve(socket)
  accept_loop(listen)        # flagged
end

HC0006 for loops that wait in :gen_tcp.accept, :ssl.transport_accept, :socket.accept or a recv instead of receive. The loop stays on the code it started on, is not a gen_server so it cannot be suspended, and blocks the next deploy as lingering code. Call __MODULE__.accept_loop(listen), or let ThousandIsland or Ranch own the loop. A recursive recv that reads one body and returns is fine: disable the check on that line.

HC0015 Hotcode.Credo.Check.DeriveOutsidePrefix

@derive {Inspect, except: [:secret]}   # flagged
defstruct [:id, :name, :secret]

@derive writes the defimpl for you, so it has the limit of HC0007: a new or changed derived implementation (a new struct, a changed only:/except:) is not shipped by a patch. The protocols checked are the same as HC0007's; add Jason.Encoder to protocols: when Jason is not in your allowed_prefixes. The line is flagged even when nothing about it changes, since the rule cannot know what a patch will carry.

HC0016 Hotcode.Credo.Check.ProcessDictionaryState

def init(_opts) do
  Process.put(:config, %Config{})   # flagged
  {:ok, %{}}
end

code_change/3, Hotcode.Versioned and struct migration see the state a GenServer's callbacks return, not its process dictionary. A release that changes what is stored there leaves the old value under the new code. Flagged in init/1 and the handle_* callbacks of a module that uses GenServer or Hotcode.Versioned. OTP's own keys (:"$callers") are ignored.

HC0017 Hotcode.Credo.Check.ApplicationStartSideEffects

def start(_type, _args) do
  :ets.new(:rates, [:named_table, :public])   # flagged
  Supervisor.start_link(children(), strategy: :one_for_one)
end

Application.start/2 runs at boot only: a hot deploy does not run it again, so a patch cannot change a table, a :persistent_term, a telemetry handler or a logger filter set up there, and a patch that changes the application module is refused (:application_callback). Do the setup in a supervised process (use Hotcode.Table for a table whose layout changes) or in an after_deploy/1 hook.

A demonstration

The pulse example contains a deliberate mistake: release 5 of its ticker forgets a downgrade/2 step, so the node refuses it at deploy time. The rule finds it without a node:

$ mix credo --checks Hotcode.Credo examples/pulse/versions/v5/lib/pulse/ticker.ex
[W] vsn 2 has no downgrade/2 step from v2: rolling back through v2 aborts
    examples/pulse/versions/v5/lib/pulse/ticker.ex:6 #(Pulse.Ticker)

(and the two NIF modules of the example are flagged by HC0001 and HC0002: they are there to show a forced NIF swap.)

In CI

Run mix compile && mix hotcode.check --strict in the job that compiles the project, before the deploy job: the rules need no node and no key, and a failure costs seconds, where the analyzer's refusal costs a pipeline run. See Deploying from CI.

The rules read the code; they cannot see what a deploy does to a running process. For that, run the deploy itself in a test: assert_survives_redeploy/3 turns HC0003 (a closure kept in state) and HC0006 (a local receive loop) into a failing test, see Testing your hot deploys.