Deviation Flagging: the rule/threshold Gate that produces "deviation" Triggers
This guide covers how DeviationFlagging in engine/deviation_flagging.py implements Deviation Flagging. It is a rule/threshold Gate pattern, not one hardcoded feature. Each use case that needs deviation or anomaly detection configures its own trigger, data source and threshold or rule expression through the Configuration Schema, the same pattern chunking strategy uses per node type.
It serves two use cases, the SPC explainer and the Costing Milestone variance explainer. Both are real threshold-comparison checks.
This module is the producer side only
Evaluating a data point and enqueueing a "deviation" TriggerQueueEntry for an over-threshold point is not itself a logged Task run. This follows the same convention as ingest_and_enqueue in engine/ingestion_pipeline.py: enqueueing is producer-side and unlogged, and the consumer's run is what gets logged.
The consumer is the scheduled-check batch in engine/case_triage.py. It claims a "deviation"-typed entry and logs it under the Task Execution logging (see case-triage-and-summarization.md).
The two modules never import each other. Both read and write "deviation" as a plain trigger_type string, so they are decoupled at the code level.
1. Register each use case's own rule
from engine.deviation_flagging import DeviationRule, DeviationRuleRegistry, ThresholdOperator
rules = DeviationRuleRegistry()
rules.register(
"spc_measurement",
DeviationRule(field="reading", op=ThresholdOperator.GT, threshold=upper_control_limit),
)
rules.register(
"costing_milestone_variance",
DeviationRule(field="variance_pct", op=ThresholdOperator.GT, threshold=5.0),
)
Data streams
data_source names a data stream: the series of DataPoints one rule governs, under the caller's own name for whichever use case's data it is. It is a Node Type's Configuration Schema value, so each use case configures its own.
- There is no generic fallback. An unregistered
data_sourceraisesConfigValidationError(DeviationRuleRegistry.rule_for). That is a config error, not a runtime case with a safe default threshold to fall back to. - Not the Node's data source. A data stream is not the Node's data source, meaning the connected system it reads (
opcua,mqttordatabase_log). The field keeps the namedata_sourcebut holds a stream's name. DeviationRuleRegistry.registered_data_sourceslists the data streams that have a rule.
The rule's fields
field,opandthresholdtellDeviationFlagginghow to evaluate a point, never what it means.descriptionis optional, human-readable context an integrator's Configuration Schema can set, such as"Ultrasonic weld-strength check, bond fixture station". When set,check_batchcarries it into the enqueuedTriggerQueueEntrypayload asrule_description. A consumer like the summarization call inengine/case_triage.pyotherwise only ever sees the rawDataPointvalues, and would have nothing to name beyond the barefieldkey.
Operators
ThresholdOperator covers:
gt,ge,ltandlefor numeric thresholds;eqandnefor an exact-value check instead, useful for a boolean condition encoded as0.0or1.0.
DataPoint.values is typed dict[str, float], so a genuine string category isn't representable here. Categorical checks are possible in principle, but neither of the two use cases above needs one.
2. Build the Gate over an already-populated registry
from engine.deviation_flagging import DeviationFlagging
from engine.trigger_queue import TriggerQueue
trigger_queue = TriggerQueue()
flagging = DeviationFlagging(rules, trigger_queue)
trigger_queue is optional. A caller that only asks whether a point is outside its rule (check) needs none. check_batch on one built without a queue raises KindredError.
3. Run one scheduled check
from engine.deviation_flagging import DataPoint
points = [DataPoint(id=stable_id, data_source="spc_measurement", values={"reading": 112.4}), ...]
fired = flagging.check_batch(points) # list[TriggerQueueEntry], one per over-threshold point
A within-threshold point contributes nothing to the returned list. Finding nothing over threshold is a normal, legitimate terminal outcome, not a failure case needing special handling.
DataPoint.id must be stable across redelivery of the same real-world measurement. This is the same idempotent-ID contract that trigger_id follows in engine/ingestion_pipeline.py. The id becomes the enqueued TriggerQueueEntry's own id directly. Re-running check_batch over an already-flagged point is a silent no-op at the queue (TriggerQueue.enqueue's ON CONFLICT DO NOTHING), not a second Trigger instance.
To evaluate a single point without enqueueing anything, call flagging.check(point). It returns a DeviationBranch (DEVIATION or WITHIN_THRESHOLD), or raises ConfigValidationError (see below).
Fail-closed cases
- A point missing the field its own rule expects raises
ConfigValidationError.DeviationRuleRegistry.rule_forraises the same error for an unregistereddata_source. Both are config/data mismatches between what aDeviationRuledeclares and what aDataPointcarries, and neither is a silentKeyError. - A
NaNreading always resolves toDEVIATION, regardless of operator.- Python's ordering comparisons silently resolve every
gt,ge,ltandlecheck againstNaNtoFalse, and!=toTrueunconditionally. That would otherwise mask a genuinely bad reading asWITHIN_THRESHOLD, or spuriously fire annerule regardless of threshold. _gate_evaluatespecial-casesNaNto fail closed instead. This is the same conservative-on-unknown-data stance the Sign-off Gate's inferred branch takes regardless of confidence score.- How the payload is built.
check_batchbuilds that point's enqueued payload withpoint.model_dump_json()(json.loads'd back into a dict), notmodel_dump(mode="json"). The latter leaves a non-finite float as a bare Pythonnanorinf. Plainjson.dumps(whatTriggerQueue.enqueue'sJsonb(...)wrapping uses) renders that as the tokenNaNorInfinity, which RFC 8259 does not allow, and Postgres'sjsonbcolumn rejects it outright.DataPoint'sser_json_inf_nan="strings"config makesmodel_dump_json()emit"NaN"instead, a valid JSON string a consumer can still recognize as the original non-finite value.
- Python's ordering comparisons silently resolve every
check_batchisolates a per-pointConfigValidationError. One point failing either of the two checks above doesn't abort evaluation of the rest of the batch. This is the same "one bad item doesn't stop the rest" policy thatprocess_batchinengine/case_triage.pyapplies to aCaseSummarizationError.check, called directly on a single point, still raises.
Pitfalls
- This module doesn't own the scheduler. Like
engine/case_triage.py, it does not schedule itself. Something callscheck_batchperiodically with whatever data points a site's own polling produced.DeviationFlagginghas no cron or timer logic. - No
ActivityLogEntryis written here.- If a caller needs an audited trail of every scheduled check's own run (not just the resulting
"deviation"entries thatengine/case_triage.pylater logs), that is a separate wrapper aroundcheck_batch. It uses the same Task Execution logging composition every other Task-shaped consumer uses. - This module deliberately stays a plain, synchronous Gate, symmetric with
ingest_and_enqueue's unlogged enqueue. - It also means a
ConfigValidationErrorswallowed bycheck_batch(above) leaves no logged trail either. A caller that needs one should catch it itself around a per-pointcheckcall rather than relying oncheck_batch's silent skip.
- If a caller needs an audited trail of every scheduled check's own run (not just the resulting
check_batchstill returns an entry for an already-enqueued point. The returned list reflects which points evaluated toDEVIATIONthis run, not which rows were newly inserted. CheckTriggerQueue.enqueue's return value directly if that distinction matters to a caller.
Release: v0.11.0