A month ago I wrote a post explaining my experience of developing a charm from scratch for the first time using agents. The result was the pi-hole charm, which you can see here.
The experience was really interesting and left me with quite a few lessons and reflections about this “new normal” we are living through as far as software development is concerned. However, this post is not going to dig further into that experience. Instead, the idea of this post is to explain the technical decisions I made in the code of this charm itself, and why I believe they are an improvement on the widely known reconcile pattern.
Be reconciled with the One who reconciles
Since Juju sends the charm an event for everything that happens, our first approach was to write charms using the pattern we now call “delta charming”; that is, each event is handled by it own method, which do only what is necessary in the context of that event.
However, as our charms started to be used more and more, we began to realise that this pattern had some drawbacks that were not obvious when we started. For example, a charm could receive a config-changed event before it was ready to process it. This forced us to add extra code to handle these race conditions.
That is how, almost without noticing, several teams at the same time started writing charms in a different way. If memory serves, @sed-i first described it under the name “holistic charming” back in July 2023, and it later even evolved into _common_exit_hook, with its own sticker that I still keep:
Some time later, the name of this new pattern evolved into what we know today as reconcile. Although this pattern made our charms’ code much more maintainable and predictable, since with every event received we recalculate what state the charm should end up in, if the code is not written carefully, the side effects can be very annoying. In fact, we have often even believed that the reconcile pattern was not the best one, but the fault lies not with the pattern but with us!
Let anyone who is without sin cast the first stone
We have all, at some point in our lives, written a method similar to this one:
def _generate_prometheus_config(self) -> bool:
"""Construct Prometheus configuration and write to filesystem.
Returns a boolean indicating if a new configuration was pushed.
"""
...
Handy, isn’t it? It generates the Prometheus configuration[1], saves it to the filesystem and returns a boolean indicating whether it changed or not. Simple, and it works.
Now let’s see where it is used. _configure is the method the Prometheus charm runs in response to almost any event, and inside it there is this:
try:
# Need to reload if config or alerts changed.
# (Both functions need to run so cannot use the short-circuiting `or`.)
should_reload = any(
[
self._generate_prometheus_config(),
self._set_alerts(),
]
)
Read the comment again. We left a written warning so that the next person would not “simplify” that any into an or. Why? Because those two functions do not return an answer: they do things, and along the way they tell you whether they managed to do them. Changing any to or does not change the logic; it changes which effects happen.
That is the annoying side effect I was talking about earlier: since _configure runs in response to almost any event, every decision glued to an effect is executed over and over again. The comment is the symptom: when the order of evaluation of a boolean expression matters, it is because that expression has effects.
Now, when you want to test “what happens if nothing changed?”, you discover that your test has more patch decorators than asserts (especially if you count the patch on the test class and on the setUp method), and that what it actually verifies is not the decision but that certain calls did not happen. In fact, let’s look at the test that verifies that the workload is neither restarted nor reloaded when its configuration has not changed:
@k8s_resource_multipatch
@patch("lightkube.core.client.GenericSyncClient")
@patch.multiple(
"ops._private.harness._TestingPebbleClient",
start_services=raise_if_called,
stop_services=raise_if_called,
restart_services=raise_if_called,
)
@patch("prometheus_client.Prometheus.reload_configuration")
def test_no_restart_nor_reload_when_nothing_changes(self, reload_config_patch, *_):
"""When nothing changes, calling `_configure()` shouldn't result in downtime."""
# GIVEN a pebble plan
initial_plan = self.plan
self.assertTrue(self.service.is_running())
for trigger in [
lambda: self.harness.charm._configure(None),
self.harness.charm.on.update_status.emit,
]:
with self.subTest(trigger=trigger):
# WHEN manually calling _configure or emitting update-status
trigger()
# THEN pebble service is unchanged
current_plan = self.plan
self.assertEqual(initial_plan.to_dict(), current_plan.to_dict())
self.assertTrue(self.service.is_running())
# AND workload (re)start is NOT attempted
# (Patched pebble client would raise if (re)start was attempted.
# Nothing else to do here.)
# AND reload is not invoked
reload_config_patch.assert_not_called()
You have to spend time and brainpower to understand what is going on, don’t you? At first glance it is not at all obvious.
The problem is not the test itself. It is that
_generate_prometheus_configdecides and acts in the same place. When that happens, the only way to test the decision is to execute the effect and spy on it.
One of the things I set out to do when I wrote the pi-hole charm was to make decisions testable without mocks, and to keep mocks only where the code touches the machine.
In pi-hole, the same question, what happens if nothing changed?, is tested like this:
def test_converged_machine_yields_only_noop():
# GIVEN a machine that already matches intent
# WHEN the plan is computed
outcomes = compute(converged(), INTENT)
# THEN nothing happens: the literal "safe to run twice" proof
assert outcomes == (Noop(),)
There are no decorators, no simulated container, no patched private ops modules. converged() is not a mock either: it is a value, an instance of SnapPresent where every fact about the machine (the snap installed and pinned, port 53 released, FTL running, the config applied) already matches what the operator asks for.
And what is it testing? This function:
def compute(state: PiholeState, intent: PiholeIntent) -> Sequence[PiholeOutcome]:
"""Decide what to do. No IO, and no exceptions for control flow."""
match state:
case SnapAbsent():
return _bootstrap(intent)
case SnapPresent():
return _converge(state, intent)
case _ as unreachable:
assert_never(unreachable)
compute reads nothing and writes nothing. It receives two values: what is true on the machine (state) and what should be (intent). It returns another value: the sequence of things to do. If the snap is not installed, the plan is the complete installation sequence. If it already is, _converge compares fact by fact against the intent and adds the steps that each difference requires. When it finds none, it ends on this line:
return tuple(outcomes) if outcomes else (Noop(),)
That line is the visible proof that the charm is idempotent: since _converge only adds a step when it finds a difference, on a machine that is already as it should be, it adds none and the plan is (Noop(),). The machine is not touched. And that matters, because Juju can run the charm many times in a row, for different events or by retrying a hook that failed. I will explain this in detail later on.
The difference from the Prometheus charm is not in the test but in where the question “did anything change?” lives. In _generate_prometheus_config it is answered inside the effect: the configuration is written, a hash is compared against another one read from the container, and only then is the answer known.
In pi-hole, reading the machine happens before deciding, in a single fetch, and compute only compares values. What is compared with == does not need mocks.
To be fair, this test does not prove that Noop actually does nothing. That is the job of _apply, the other side of the pattern. All the difficult logic lives in pure functions like compute, where it is tested with ==.
Of course, I have just mentioned things like fetch, compute and _apply without telling you what they are. That is what the next section of the post is for ![]()
Fetch → compute → apply
Well, we have reached the part that gives this post its meaning: explaining how this “new version” of the reconcile pattern that I used in the pi-hole charm works.
But before that, let’s refresh a few facts about charms:
- A hook runs once and then exits. No process stays alive between events. Every hook starts from scratch and has to work out what to do by looking at the workload.
- You cannot assume the order, nor that you will see every event. The Juju documentation is direct: “Generally, no assumptions can be made about the order of hook execution.” In addition, Juju can coalesce events, and a unit can lose leadership while others events happen. Code that only runs on one specific event sometimes never runs.
- A hook can be aborted and run again from scratch. If the unit agent is interrupted in the middle of a hook, Juju “will treat that hook as having failed”, and “users could (and probably will) attempt to re-execute failed hooks”. Therefore, anything a hook does must be safe to repeat.
- The workload can lie. Package managers, service managers and command-line tools can report that a task succeeded even though it did not. An “exit code” is a claim, not proof.
For points 1, 2 and 3, do not ask yourself “What happened?”; ask yourself “What is true now, and what should be true?”. The answer to that last question will guide you in structuring your code.
There are also two questions you should ask about every part of your charm’s code, and both answers must be: “Nothing”.
- What breaks if this runs twice? → because of fact 3: a hook can be retried. This is what we saw with
(Noop(),): inpi-hole, the answer is given by a test. - What breaks if this never runs? → because of fact 2: not every event arrives.
Point 4 has a different answer: verify. We will see where that verification lives later on.
A single entry point
Let’s start with what you probably already know about reconcile: almost every event ends up in a single method, _reconcile. There is no specific handler for any of them, since none of them on its own gives you enough information to act on. config-changed does not tell you which configuration key changed. relation-changed does not tell you how the relation data changed. So all they really mean is “the state of the workload might have changed, go and check”.
The rest have their own handler, and the rule for deciding which ones is not a matter of taste. “A good rule of thumb is this: if an event cannot be deferred, it needs a dedicated handler.” Deferring execution is how we say “not yet”, and these events have no later moment: an action has to respond now, remove is the last chance to clean up, a secret-remove event is the only place where the revision about to be removed is available, and so on.
This is the official guide, where the approach is called holistic (as opposed to delta, which gives each event its own handler). That page is also candid about the trade-offs: it points out that simple workloads tend to work well with delta charms, and that more complex workloads tend to be more robust using the reconcile pattern.
Nothing new so far. The difference lies in how the code is organised once execution reaches _reconcile. Let’s look at it.
How to split the code
A charm written this way is split into two parts, and that split is the central idea. It has a name, functional core, imperative shell[2]:
- One part decides what should happen. It only works with plain values. It never reads or writes the workload, simply because it does not import anything that could. We call this part the core.
- The other part reads and writes the workload. It contains no decisions of any kind. Its job is to translate in both directions. On the way in, it reads the workload and turns it into values: for example, it reads
pihole.tomland builds aSnapPresentfrom what it found. On the way out, it takes what the core decided and turns it into actions: it receives aSetNtpServer(active=False)and runs the command that switches off theNTPserver. We call this part the shell.
When I say “workload”, read it broadly. It is not only the binary running in an OCI image or a system package. It can also be that the charm needs to modify the machine it runs on, to free up a port or install something.
The shell wraps the core: everything that goes into or comes out of the charm passes through it. To know which of the two sides a line of code belongs to, ask yourself two things:
- Does it need the workload in order to run? (reading a file, calling a command, talking to Pebble, or to Juju, etc.): it goes in the shell.
- Does it choose between options based on a piece of data? (an
if, amatch, a comparison): it goes in the core.
If a function does both, it has to be split.
Remember the question “What is true now, and what should be true?”? In the code, each half has a name: what is true is the State and what should be true is the Intent. The difference between the two are the Outcomes. Those are the three kinds of value that cross the boundary between core and shell:
| Value | Answers | Example |
|---|---|---|
| Intent | What should be true? Built from the configuration, the relations and the secrets | “retention_period = 15d” |
| State | What is true now? Built from the current state of the workload | “retention_period = 30d” |
| Outcome | What to do about the difference? A value, not an action | SetRetention("15d") |
And three functions do the work:
| Function | Reads? | Writes? | Job |
|---|---|---|---|
fetch |
yes | no | Gathers every fact that compute needs, in one single read |
compute |
no | no | Compares the State with the Intent. Returns a sequence of Outcomes. |
_apply |
yes (only to verify) | yes | Executes each Outcome; the shell method that executes it checks that it took effect. |
In the following diagram we can see more clearly where each of these components sits:
An “exit code” tells you that the call finished, not that the workload ended up as you wanted. That is why the shell does not stop when it executes an effect: it verifies it. That is the dotted arrow in the diagram. In pi-hole we learned this the hard way, because the snap returned 0 even for keys it silently discards. But it is not an isolated case: the Prometheus charm runs promtool check config after writing the configuration, for the same reason.
You do not need to verify everything on the spot. Verify within the same hook when the next step depends on that result, or when you are about to report the unit’s status: an Active based only on an “exit code” is a promise, not a fact. For everything else, the pattern already verifies by itself. In the next hook, fetch reads the real state again, and if the effect did not take, compute will ask for it again.
And this is how the three work together in a _reconcile, with the same example as the tables:
def _reconcile(self, _: ops.EventBase) -> None:
config = self.load_config(Config, errors="blocked") # validated config
intent = Intent(retention=config.retention) # + relations, secrets
state = fetch(self._workload) # the only read
for outcome in compute(state, intent):
self._apply(outcome)
load_config validates the configuration against a model (in pi-hole it is PiholeConfig, from pydantic). With errors="blocked", if a value is invalid, the unit goes into Blocked and the hook ends before anything is decided.
Notice where each part comes from: the intent is built from Juju (config, relations, secrets) and the state from the workload. Neither is built from the other. That is the basic structure. In pi-hole it looks like this.
In pi-hole, the files are split like this:
| File | Side | What it does |
|---|---|---|
src/pihole_state.py |
core | Intent, State, Outcomes, fetch, compute and status_plan. It imports neither ops nor anything that touches the machine. |
src/pihole_config.py |
core | The pydantic model that validates the configuration. It receives values and returns values. |
src/charm.py |
shell | The only module that imports ops: it receives the events, reads the config from Juju, runs _reconcile and _apply, and reports the status. |
src/pihole.py |
shell | Talks to snapd, to systemd and to the snap’s files. |
src/ftl_api.py |
shell | The HTTP client for the FTL API. |
src/resolved.py |
shell | Frees port 53 from systemd-resolved, and gives it back when the charm is removed. |
The rule that separates the two sides is an import: no core file imports ops or shell modules. fetch lives in the core and still reads the machine because it receives the PiholeFacts Protocol: the shell passes it the object that knows how to read.
The shell modules also have a few small pure functions, such as classify_snap_check in pihole.py or config_mismatch, which interpret what the shell has just read. They live there because interpreting the output of snap-check is knowledge about the snap, not about the domain, and they are tested without mocks like any other pure function.
A concrete example
“Well, all very nice so far, but it is a lot of text and few code examples”, you could rightly say to me. Don’t despair, here we go.
Everything I have been explaining in the post rests on four Python tools. None of them is exotic and all of them are in the standard library, but together they make the pattern work. The code as I show it needs Python 3.12 or later[3], that is, charms with an ubuntu@24.04 base or later.
1. Frozen dataclass
@final
@dataclass(frozen=True)
class SetNtpServer:
"""Enable or disable the FTL NTP server on 123/udp."""
active: bool
@dataclass generates __eq__ from the fields: two instances with the same fields are equal. That is what lets you write assert outcomes == (Noop(),) and nothing more. Without __eq__, a test would have to inspect attributes by hand or, worse, use a mock. frozen=True adds that the instance cannot be modified after it is created, so an outcome that compute returned cannot change on its way to _apply. In addition, @final prevents inheriting from the class, so the union stays closed: nobody can add a subtype that the match does not know about.
Where it is used in
pi-hole:In every value that crosses the boundary. All the outcomes (
SetNtpServerinsrc/pihole_state.py, and the rest of the ones that make upPiholeOutcome), the states (SnapAbsentandSnapPresent), the intent (PiholeIntent) and the core’s statuses (Active,Maintenance,Blocked). Thanks to this, the tests intests/unit/test_pihole_state.pycompare values directly (with==,<orin), without a single mock.
2. Unions: making impossible states impossible to write
The state of the workload is not a class with optional fields; it is the union of two types:
@final
@dataclass(frozen=True)
class SnapAbsent:
"""The snap is not installed on this machine."""
@final
@dataclass(frozen=True)
class SnapPresent:
"""Facts read off the machine. Every field is observed."""
revision: str
pinned_revision: str | None
refresh_held: bool
version: str | None
ftl_enabled: bool
ftl_active: bool
...
type PiholeState = SnapAbsent | SnapPresent
The usual alternative would be a single class with installed: bool and all the other fields as | None. But then, if the snap is not installed, what is the value of ftl_active? None? False? Every consumer would have to guess. With the union the question does not exist: SnapAbsent does not have that field. “Explicit is better than implicit”[4] ![]()
Where it is used in
pi-hole:
PiholeStatefor the state of the machine;PiholeOutcomefor the steps thatcomputecan ask for;UnitStatusfor the statuses; andStatusReport = Report | ReportThenDiagnoseto decide whether the diagnostic has to be run after reporting.
3. match and assert_never: let the type checker warn you
The _apply function is a match over every possible outcome, and it ends like this:
match outcome:
case pihole_state.ReleasePort53():
resolved.disable_stub_listener()
case pihole_state.InstallSnap():
self._pihole.install()
...
case pihole_state.Noop():
logger.debug("converged: nothing to do.")
case _ as unreachable:
assert_never(unreachable)
If tomorrow someone adds a new outcome to the PiholeOutcome type:
type PiholeOutcome = (
ReleasePort53
| InstallSnap
...
| Noop
)
and forgets to handle it in _apply, unreachable stops being of type Never and static code analysis fails. The same closing branch is in every match over a union in the charm, including compute.
Where it is used in
pi-hole:Everywhere a union is consumed.
computeover the state;_applyover the outcomes;_to_ops, which converts the core’s statuses intoopsones; and_on_collect_statusoverReport | ReportThenDiagnose. If one of those unions gains a member and any of thosematchstatements does not account for it, static analysis fails.
4. Protocol: reading without importing
fetch lives in the core, but it needs to read the machine. It solves this like so:
class PiholeFacts(Protocol):
"""The reads `fetch` needs, implemented by `pihole.Pihole`."""
def installed_revision(self) -> str | None: ...
def pinned_revision(self) -> str | None: ...
def refresh_held(self) -> bool: ...
def workload_version(self) -> str | None: ...
def ftl_status(self) -> ServiceStatus: ...
...
def fetch(pihole: PiholeFacts, admin_password: str) -> PiholeState:
...
The core describes which reads it needs, without importing the module that performs them. In production, the shell passes it an instance of Pihole, which does talk to snapd and implements that Protocol. In the tests it is passed a hand-written FactsStub that returns fixed values. The Protocol inverts the dependency: the core does not know about the shell; it is the shell that fulfils the core’s contract.
Where it is used in
pi-hole:
PiholeFactsis insrc/pihole_state.py, andfetchreceives it. It is implemented by two classes that do not know about each other:Piholeinsrc/pihole.py, which in production talks tosnapdand to theFTLAPI, andFactsStubintests/unit/test_pihole_state.py, which returns fixed values in the tests.
Status is a decision too
There is one decision that almost every charm makes in the wrong place: which status to report. The typical case is a collect_unit_status full of if statements that mixes reads of the workload with precedence rules. In pi-hole, the status is decided like everything else, with a pure function:
def status_plan(
state: PiholeState,
intent: PiholeIntent,
failure: Blocked | None,
) -> StatusReport:
statuses: list[UnitStatus] = []
match state:
case SnapPresent():
if dhcp_unservable(state, intent):
statuses.append(Blocked(dhcp_unservable_reason(state, intent)))
if dhcp_port_blocked(state, intent):
statuses.append(Blocked(dhcp_port_blocked_reason(state)))
case SnapAbsent():
pass
case _ as unreachable:
assert_never(unreachable)
if failure is not None:
statuses.append(failure)
return Report(statuses=tuple(statuses))
machine = _machine_status(state)
statuses.append(machine)
if isinstance(machine, Maintenance):
return Report(statuses=tuple(statuses))
return ReportThenDiagnose(statuses=tuple(statuses))
There are two details:
Active,MaintenanceandBlockedare not theopsclasses but the core’s own values, because the core cannot importops. The shell converts them at the end.- The result is not “a list of
statusplus a boolean that says whether the diagnostic has to be run”. They are two distinct types,ReportandReportThenDiagnose, and the shell handles them with amatch. A boolean that decides whether an effect is executed is exactly what we are trying to avoid.
This closes the verification thread: if an effect did not take, the shell raises an error, _reconcile stores it as Blocked, and status_plan reports it. And it is also tested with ==:
def test_a_pushed_failure_stops_the_plan():
failure = Blocked("pushed failure")
report = status_plan(converged(), INTENT, failure)
assert report == Report(statuses=(failure,))
Where it is used in
pi-hole:
status_planis insrc/pihole_state.py, and_on_collect_status(src/charm.py) only calls it, converts with_to_opsand adds. The test I showed is intests/unit/test_pihole_state.py.
Positive side effects
100% test coverage
There is something I was not looking for at the outset but that came on its own: thanks to applying what I have just explained, it was very easy to get 100% coverage in the unit tests, branches included.
$ tox -e unit
...
unit: commands[1]> coverage report
Name Stmts Miss Branch BrPart Cover Missing
------------------------------------------------------------------
src/charm.py 206 0 68 0 100%
src/ftl_api.py 292 0 66 0 100%
src/pihole.py 473 0 114 0 100%
src/pihole_config.py 93 0 30 0 100%
src/pihole_state.py 381 0 106 0 100%
src/resolved.py 63 0 8 0 100%
------------------------------------------------------------------
TOTAL 1508 0 392 0 100%
unit: OK (2.17=setup[0.04]+cmd[2.01,0.12] seconds)
congratulations :) (2.19 seconds)
The credit is not due to having written more tests, but to where the decisions ended up. In a charm where decisions are glued to effects, to reach an if hidden inside a method that writes to the container, you have to mock it and patch whatever is needed so that execution goes through there. Many branches end up uncovered because reaching them costs too much.
Here the decisions live in pure functions, most of them in the core and a few small ones in the shell, next to what they interpret. In a pure function, reaching a branch means building a value: a SnapPresent with port53_released=False and that’s it. The branches that remain in the shell are mostly error handling and verifications, and they are covered with simple fakes, because no state needs to be orchestrated to reach them.
Two clarifications:
- The shell is tested too, but with fakes. The modules that talk to
snapd, to theFTLAPI or tosystemduse fakes ofurlopenand of the filesystem, and the charm tests replace those modules wholesale. What does not needmocksis the decision, not all the code. - The
case _ as unreachable: assert_never(unreachable)branches are excluded from coverage on purpose. It is not cheating:pyrightalready proves they never run, and a test could not reach them without breaking the types.
And one more: 100% coverage does not mean 100% correctness. It means the tests go through all the executable code. What makes these tests valuable is that they verify decisions with ==, not that they go through every line.
A core that can be shared
There is a second benefit I was not looking for either, and it may be even more valuable. It is common to have two charms that manage the same workload: one for Kubernetes and one for machines. A great example are these charms: opentelemetry-collector-k8s and opentelemetry-collector. In cases like this, each charm usually has its own copy of the logic: which configuration to apply, when a restart is needed, which status to report. And those copies drift apart over time.
With this split, that logic lives in the core, and the core does not know whether it runs on a machine or in a pod: it only receives values and returns values. The only thing that changes between the two charms is the shell. On a machine, fetch reads through snapd and _apply runs commands; on Kubernetes, both talk to Pebble. So the core can be extracted into a PyPI package and imported by both charms. A decision is written and tested once, and both charms inherit it.
It does have to be designed carefully, though. Part of the pi-hole core is specific to snaps: SnapPresent knows about pinned revisions and plugs, and there are outcomes such as InstallSnap. That makes no sense on Kubernetes. What gets shared is the part that decides about the workload itself: the FTL configuration, DHCP, the status. The part that decides how it is installed stays in each charm. We have not done this in pi-hole yet, because there is no Kubernetes version, but the split is already in place: the day one exists, the work is moving files, not rewriting them.
Takeaways
If you take away only one idea, let it be this: a function that decides should not act, and a function that acts should not decide. Everything else (the types, the match, the Protocol) consists of tools for upholding that separation.
You do not need to rewrite your charm to get started. Look for any of these signs:
- a method that writes something and returns a
bool; - a test that needs a
patchto reach a decision; - a comment warning you not to change the order of an expression.
When you find one, split the decision out into a function that receives values and returns a value, leave the effect where it was, and test the decision with ==. With a single function you will already see the difference in the test.
When is it not worth it? When the charm hardly decides anything: if it only publishes a databag or starts a service unconditionally, the extra types cost more than they bring. It shines when the workload is complex, has a mandatory order, or lies about what it did.
If you want to dig deeper, the repo has docs/pattern.md, which explains the pattern with a small example that is not pi-hole, and docs/overview.md, a map of what each file does.
Anecdote: the Prometheus charm was the second charm we (The Observability Team) started writing with the then brand-new
opsframework, back in September 2020. Its code is like those petrified specimens discovered by palaeontologists that let them study how a species evolved. In this case the code shows us how charm development withopsevolved: From “delta charming” to “holistic charming” for structuring its code, and fromunittestandHarnesstopytestandScenariofor the tests. ↩︎Gary Bernhardt gave the talk “Boundaries” in 2012, where he explains the basic concepts of this pattern. ↩︎
The minimum version depends on each tool:
Protocol,@finaland dataclasses have existed since Python3.8.matchsince Python3.10.assert_neversince3.11; before that it was intyping_extensions.- The
type PiholeState = SnapAbsent | SnapPresentsyntax (PEP 695) is the one that requires3.12.
If your charm still runs on
ubuntu@22.04(Python3.10), the pattern works just the same: write the alias asPiholeState = SnapAbsent | SnapPresent(or withTypeAlias) and importassert_neverfromtyping_extensions. The pi-hole charm uses Python3.14, which is what ships withubuntu@26.04. ↩︎If you have not read The Zen of Python yet, this is a great moment! ↩︎
