Designing a Rule Engine That Complements Your ML Model

2026-11-28来源 dev.toEnglish

Every IoT alerting system I have seen work in production has rules in it, even the ones that also have models. The rules are not a legacy artefact to be removed. They encode knowledge that models cannot learn from the data available: that the pump must not run dry, that a maintenance window suppresses alarms, that a 3σ deviation at 2 a.m. with no operator on shift should become a ticket rather than a page.

This post is about building the rule layer deliberately rather than letting it accrete.

Five jobs rules do better than models

1. Hard safety limits. A model can be wrong; an interlock must not be. temp > 120 °C → cut power belongs in deterministic code with a test, not in a neural network with a confidence score.

2. Physics and plausibility. A flow reading of 900 m³/h on a 400 m³/h line is a sensor fault, not a process anomaly. No amount of training data makes a model responsible for arithmetic.

3. Context gating. "Alarm only if the machine is in RUN mode and not in MAINTENANCE." This is state, not signal, and it is usually not in your training set.

4. Corroboration requirements. "Model score > 0.8 and (vibration RMS rising or temperature rising)." Requiring two independent signals before paging a human is the single most effective precision improvement available.

5. Escalation and suppression policy. Who gets woken, when, and how often. This is organisational policy expressed as code.

Model the rule inputs explicitly

The rule engine should never reach into the raw signal. Give it a typed fact set that both the model and the rules populate:

from dataclasses import dataclass, field from typing import Literal @dataclass class MachineFacts: device_id: str mode: Literal["off", "idle", "run", "maintenance", "fault"] ts: float # raw aggregates vib_rms: float vib_crest: float temp_c: float temp_rate: float # K/min current_a: float # model outputs anomaly_score: float # 0..1, calibrated anomaly_label: str # e.g. "bearing_wear" # context minutes_since_start: int maintenance_until: float | None = None sensor_health: dict[str, float] = field(default_factory=dict) 

Making facts explicit does two things: it gives you a single place to see what a rule can know, and it makes the engine trivially testable — you construct a MachineFacts and assert the outcome. No harness, no clock mocking.

A rule shape that stays readable

I have seen elaborate DSLs and I have seen 4,000 lines of if statements. The version that survives contact with a maintenance team is a list of dataclasses with a condition and an action:

from dataclasses import dataclass from typing import Callable Severity = Literal["info", "warn", "critical", "safety"] @dataclass(frozen=True) class Rule: id: str severity: Severity when: Callable[[MachineFacts], bool] message: Callable[[MachineFacts], str] # a rule can gate other rules: if it fires, lower-severity rules are muted mutes: tuple[str, ...] = () needs_corroboration: bool = False 

And the evaluation loop, kept deliberately small:

def evaluate(facts: MachineFacts, rules: list[Rule]) -> list[dict]: fired, muted = [], set() for r in sorted(rules, key=lambda r: _sev_rank(r.severity), reverse=True): if r.id in muted: continue try: ok = r.when(facts) except Exception as e: # a broken rule must not kill the loop fired.append({"rule": r.id, "severity": "info", "msg": f"rule error: {e}"}) continue if not ok: continue if r.needs_corroboration and not _corroborated(facts): continue fired.append({"rule": r.id, "severity": r.severity, "msg": r.message(facts)}) muted.update(r.mutes) return fired def _sev_rank(s: Severity) -> int: return {"safety": 3, "critical": 2, "warn": 1, "info": 0}[s] def _corroborated(f: MachineFacts) -> bool: rising = f.temp_rate > 0.5 or f.vib_crest > 3.0 return f.anomaly_score > 0.75 and rising 

Four properties are worth preserving in whatever engine you build:

  • Rules are ordered by severity, not by insertion order. A safety rule firing should mute the informational noise it implies.
  • A broken rule logs and continues. In a 500-rule system, one KeyError from a new sensor field should not stop the safety interlock.
  • Corroboration is a first-class concept. Encoding it as needs_corroboration makes "we only page on two-signal agreement" reviewable policy rather than scattered logic.
  • Muting is explicit. Cascading alerts are the number one noise source; see the next post.

Where the model sits in the flow

Three patterns, in increasing order of safety:

A) model → rule (rules post-process the score) B) rule → model → rule (rules gate, model scores, rules decide) C) rule ──┐ ├─→ policy → alert (rules and model are independent voters) model ─┘ 

Pattern B is the one I recommend by default. A rule gates whether the model is even relevant (mode, sensor health, warm-up), the model scores, and then rules turn the score into a decision with corroboration and suppression. Pattern C works well for critical assets where you want the rule path to keep functioning with the model offline.

Pattern A is the one to avoid, because it makes the model responsible for everything upstream. If the sensor is disconnected and returns NaN, a raw score > threshold comparison will either crash or, worse, compare false and report "normal". Guard at the boundary:

HEALTHY = lambda f: all(h > 0.5 for h in f.sensor_health.values()) RULES = [ Rule("sensor.unhealthy", "warn", when=lambda f: not HEALTHY(f), message=lambda f: "degraded sensors: " + ", ".join(k for k, v in f.sensor_health.items() if v <= 0.5), mutes=("model.anomaly", "vib.high")), Rule("safety.overtemp", "safety", when=lambda f: f.temp_c > 120.0, message=lambda f: f"overtemp {f.temp_c:.1f} C", mutes=("model.anomaly",)), Rule("model.anomaly", "critical", when=lambda f: f.mode == "run" and f.anomaly_score > 0.80, message=lambda f: f"{f.anomaly_label} (score {f.anomaly_score:.2f})", needs_corroboration=True), Rule("vib.high", "warn", when=lambda f: f.mode == "run" and f.vib_rms > 7.1, message=lambda f: f"vibration RMS {f.vib_rms:.2f} mm/s"), ] 

Note sensor.unhealthy muting the model rule. Reporting "anomaly" when the sensor is broken is the fastest way to lose operator trust — and it is a rule's job to know the difference, because the model cannot.

Rules need the same engineering as code

Treat the rule set as production code, with all that implies.

Table-driven tests. One test per rule, plus the interactions that matter:

import pytest def facts(**kw): base = dict(device_id="p1", mode="run", ts=0.0, vib_rms=1.0, vib_crest=2.0, temp_c=40.0, temp_rate=0.0, current_a=10.0, anomaly_score=0.0, anomaly_label="none", minutes_since_start=999, maintenance_until=None, sensor_health={"vib": 1.0, "temp": 1.0}) base.update(kw) return MachineFacts(**base) def test_overtemp_mutes_model(): out = evaluate(facts(temp_c=130.0, anomaly_score=0.99), RULES) ids = [a["rule"] for a in out] assert "safety.overtemp" in ids assert "model.anomaly" not in ids def test_model_needs_corroboration(): assert evaluate(facts(anomaly_score=0.99), RULES) == [] out = evaluate(facts(anomaly_score=0.99, temp_rate=1.2), RULES) assert [a["rule"] for a in out] == ["model.anomaly"] def test_broken_sensor_suppresses_signal_rules(): out = evaluate(facts(sensor_health={"vib": 0.0, "temp": 1.0}, vib_rms=99.0), RULES) ids = [a["rule"] for a in out] assert ids == ["sensor.unhealthy"] 

Version the rule set by hash. Include the hash in every alert payload. When someone asks "why did we not page on this?", you need to know which rules were live at that timestamp — and rules change far more often than models.

Bound the rule count per severity. If critical has more than ~20 rules, the severity loses meaning. Rule sprawl is real; review quarterly and delete rules that have not fired in six months (they are either wrong or dead).

Prefer rules over model retraining for policy changes. Moving a threshold is a five-minute change with an audit trail. Retraining does not belong in an incident response.

The small win that pays for the whole engine

If you implement nothing else from this post, implement this: severity ordering with muting. When a machine goes into fault, its twenty derived sensor alerts are noise. A single machine.fault rule that mutes everything downstream from the same device typically removes 60–80% of the alert volume in a bad incident, without losing a single actionable signal.

That is the bridge into the next post, which is entirely about making alert volume smaller and more informative.

Next: Alert Deduplication and Flap Suppression — Cutting IoT Alert Noise by 90%.

原文:https://www.a8q9.cn/en/article/designing-a-rule-engine-that-complements-your-ml-model-2da159.html

相关文章