# CredoHotUpgrades

Credo rules that catch Elixir code that cannot survive a BEAM hot code upgrade.
A hot upgrade replaces the code of a running module without restarting the node, which means some patterns that are harmless in an ordinary release become real bugs: a closure that outlives the module version that built it, a process that never re-enters its loop through the module, a side effect that silently runs a second time.
Every rule here catches one of those patterns in source, before a release is even built, the same way `mix credo` already catches other classes of bugs.

The mechanism itself (`appup`, `relup`, `release_handler`) and the practices a hot-upgradable project follows are documented in [deployex/beam-hotupgrades](https://github.com/deployex/beam-hotupgrades).
This package exists to check a codebase against that guide automatically, in CI and in an editor, rather than by reading it every time.

> **What a clean run means.** The checks are pattern-based, like the rest of Credo, not a full data-flow analysis.
> They catch what they are looking for and nothing else, read a rule's explanation for what that is before trusting a clean run.

## What this is not

This is a linter, not an upgrade mechanism.
It has no node, builds nothing, and boots nothing.
It will not tell you that a struct gained a field with no matching `code_change/3`, or that a supervisor's child list changed between two releases, those are a *diff between two builds*, which is [Jellyfish](https://github.com/deployex/jellyfish)'s job, verified for real by [relup-guard-elixir](https://github.com/deployex/relup-guard-elixir) booting an actual release and applying an actual upgrade.
This package only looks at one version of the source, for patterns that are wrong regardless of what the other version looks like.

Run it first, in the same step that already compiles the project, because it costs milliseconds.
Run `relup-guard-elixir` after, because it costs a real release build and boot, and because it catches a different, overlapping-but-not-identical class of bug.

## Install

```elixir
# mix.exs
{:credo, "~> 1.7", only: [:dev, :test], runtime: false},
{:credo_hot_upgrades, "~> 1.0", only: [:dev, :test], runtime: false}
```

Add the plugin to your `.credo.exs` (creating one if you have none):

```elixir
%{
  configs: [
    %{
      name: "default",
      plugins: [{CredoHotUpgrades.Plugin, []}]
    }
  ]
}
```

The plugin registers every check below, there is no list to maintain by hand, and a new check arrives with a `credo_hot_upgrades` upgrade.
That one line is enough in a `.credo.exs` that lists its own `checks: %{enabled: [...]}` too, the file `mix credo.gen.config` writes. Credo drops what a plugin registers there, so the plugin adds the checks the project does not name.
Then, as part of the step that already compiles the project:

```
mix compile && mix credo --strict
```

Turn a specific rule off the way you would any Credo check:

```elixir
checks: %{disabled: [{CredoHotUpgrades.Check.NoNif, []}]}
```

Silence a single line you know is fine the same way:

```elixir
# credo:disable-for-next-line CredoHotUpgrades.Check.ClosureInState
```

### Supported versions

CredoHotUpgrades follows the same support policy as [DeployEx](https://github.com/deployex/deployex) and [Jellyfish](https://github.com/deployex/jellyfish): the last two major Erlang/OTP releases.
The `elixir: "~> 1.19"` requirement in `mix.exs` tracks the lowest Elixir version that still runs on the older of those two OTP releases.
CI runs both ends of that range on every pull request, see `.github/workflows/ci.yml`.

| | Policy | Currently |
|---|---|---|
| Erlang/OTP | last 2 major releases | 28, 29 |
| Elixir | lowest version supporting the older OTP release above | `~> 1.19` |
| Credo | the version the checks are written against | `~> 1.7` |

As these move forward the floors move with them, and a dropped OTP release is a breaking change for this package too.

### Umbrella projects

An umbrella is set up the same way: the two dependencies in the `mix.exs` of the umbrella, and one `.credo.exs` at its root with the plugin line.
`mix credo` run from the root looks at every application, and the test files of each one, under `apps/<app>/test/`, are left out like those of a single project.

To run `mix credo` from inside one application, that application needs the two dependencies in its own `mix.exs` as well, or Mix does not find the task there.
It still reads the `.credo.exs` of the umbrella, Credo looks for it in the directories above.

## The checks

Each one is a real, verified failure mode, not a guess.
The order follows where each pattern appears in [deployex/beam-hotupgrades](https://github.com/deployex/beam-hotupgrades), so the two can be read side by side.
Where a check's finding was checked against OTP source or a live node rather than assumed, that is noted.

| id | check | catches | fix |
|---|---|---|---|
| `CHU0001` | `CompileTimeEnv` | a module attribute that reads `Application.get_env`/`System.get_env` at compile time, baking in the build machine's value | read the value in a function, where it is used |
| `CHU0002` | `ClosureInState` | a closure kept in the state a `GenServer` callback returns, in `:ets`, `:persistent_term`, `Process.put`, or a message | keep data or `{module, function, args}`, or `&__MODULE__.name/arity` with the function public |
| `CHU0003` | `TelemetryLocalHandler` | `:telemetry.attach`/`attach_many` given a local or anonymous handler, which fails after the module is replaced | attach `&__MODULE__.name/4` with the function public |
| `CHU0004` | `LoggerLocalFilter` | `:logger.add_primary_filter`/`add_handler_filter` given a local or anonymous filter, removed silently on the same failure | pass `{&__MODULE__.name/2, arg}` with the function public |
| `CHU0005` | `ClosureInOptions` | a closure kept in a child spec or a library's own options (`configure:`, `tag_values:`, and the rest) | pass `&__MODULE__.name/arity` with the function public, or `{module, function, args}` |
| `CHU0006` | `OnLoad` | `@on_load`, which runs again on every hot upgrade that loads the module, not only at boot | make the function safe to run more than once, or do the work in a supervised process |
| `CHU0007` | `LocalReceiveLoop` | a hand-written loop that calls itself by its bare name inside a `receive`, and never leaves the code version it started on | call `__MODULE__.name(...)` to recurse |
| `CHU0008` | `LocalAcceptLoop` | the same problem, for a loop built around `:gen_tcp.accept`/`:ssl.transport_accept`/`:socket.accept` instead of `receive` | call `__MODULE__.name(...)` to recurse |
| `CHU0009` | `ProcessDictionaryState` | `Process.put/2` in a `GenServer` callback, data `code_change/3` can never see or migrate | keep the value in the state the callback returns |
| `CHU0010` | `ApplicationStartSideEffects` | a side effect in `Application.start/2` that a hot upgrade will never re-run, among them any call whose result is not used | do the setup in a supervised process, or expose a function an upgrade can call again |
| `CHU0011` | `NoNif` | a module that loads a NIF, with `:erlang.load_nif/2`, `use Rustler` or `use Zig`, whose native code a hot upgrade cannot replace in place | deploy in full a release that changes the module or its shared object |
| `CHU0012` | `SupervisorInitSideEffects` | a side effect in a supervisor's `init/1`, which a hot upgrade of that supervisor runs a second time | do it in a child of the supervisor, which is started once |
| `CHU0013` | `LiveViewClosure` | a closure kept in a LiveView socket by `attach_hook`, `assign`, or the `dom_id:` of a stream, which crashes the open page after its module is replaced | use `&__MODULE__.name/arity` with the function public, or keep data and call the function where it is used |
| `CHU0014` | `CacheWithoutCodeChange` | a `GenServer` that fills a `:persistent_term` or an ETS table and defines no `code_change/3`, so the cache keeps the shape the old code wrote | define `code_change/3` and rebuild the cache in it |

`CHU0001`, `CHU0004`, `CHU0006`, `CHU0009` and `CHU0012` were each checked against OTP 29 source and a live BEAM node before being written: a module attribute really does freeze its build-time value, `:logger` really does remove a filter that raises the same way Telemetry detaches a failing handler, `@on_load` really does run again on a reload, `code_change/3` really does see only the state a callback returns and never the process dictionary, and `supervisor:code_change/3` really does call `Module:init(Args)` again.

Each warning ends with the fix in that last column, and `mix credo explain <file>:<line>` gives the reasoning behind it.

Test files are left out by default, a test attaches a handler with an anonymous function or sends one in a message as a matter of course, and is never hot upgraded.
Give a check its own `files:` in `.credo.exs` to change what it looks at:

```elixir
checks: %{extra: [{CredoHotUpgrades.Check.ClosureInState, files: %{excluded: []}}]}
```

## For coding agents

[`usage-rules.md`](usage-rules.md) is written for an agent that works on a project using these checks: how to run them alone with output it can parse, the fix for each one, and when a warning may be silenced.
It ships in the Hex package, at `deps/credo_hot_upgrades/usage-rules.md`.

## What it does not catch

Anything that needs two versions to compare: a struct that gained a field with no matching `code_change/3`, a child added to or removed from a supervisor, a consolidated protocol a release adds.
Those are Jellyfish's and relup-guard's job, not this one's, see [What this is not](#what-this-is-not).

A function passed as an attribute inside a `~H` template, `<.table sort={&sort/2}>`, is not seen: the template is a string to Credo, not code.

A closure stored through several indirections (a variable built in one function, passed through two more, then stored in a fourth) may not be caught, each rule matches the shapes in its own examples, not every path a value could travel to reach the same sink.

## Releasing

Bump `@version` in `mix.exs` in its own PR, merge it to `main`, then from `main`:

```
mix release
```

Tags the commit, pushes it and the tag, and publishes to Hex.

## License

[MIT](LICENSE).
