Search and contents

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_source raises ConfigValidationError (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, mqtt or database_log). The field keeps the name data_source but holds a stream's name.
  • DeviationRuleRegistry.registered_data_sources lists the data streams that have a rule.

The rule's fields

  • field, op and threshold tell DeviationFlagging how to evaluate a point, never what it means.
  • description is optional, human-readable context an integrator's Configuration Schema can set, such as "Ultrasonic weld-strength check, bond fixture station". When set, check_batch carries it into the enqueued TriggerQueueEntry payload as rule_description. A consumer like the summarization call in engine/case_triage.py otherwise only ever sees the raw DataPoint values, and would have nothing to name beyond the bare field key.

Operators

ThresholdOperator covers:

  • gt, ge, lt and le for numeric thresholds;
  • eq and ne for an exact-value check instead, useful for a boolean condition encoded as 0.0 or 1.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_for raises the same error for an unregistered data_source. Both are config/data mismatches between what a DeviationRule declares and what a DataPoint carries, and neither is a silent KeyError.
  • A NaN reading always resolves to DEVIATION, regardless of operator.
    • Python's ordering comparisons silently resolve every gt, ge, lt and le check against NaN to False, and != to True unconditionally. That would otherwise mask a genuinely bad reading as WITHIN_THRESHOLD, or spuriously fire an ne rule regardless of threshold.
    • _gate_evaluate special-cases NaN to 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_batch builds that point's enqueued payload with point.model_dump_json() (json.loads'd back into a dict), not model_dump(mode="json"). The latter leaves a non-finite float as a bare Python nan or inf. Plain json.dumps (what TriggerQueue.enqueue's Jsonb(...) wrapping uses) renders that as the token NaN or Infinity, which RFC 8259 does not allow, and Postgres's jsonb column rejects it outright. DataPoint's ser_json_inf_nan="strings" config makes model_dump_json() emit "NaN" instead, a valid JSON string a consumer can still recognize as the original non-finite value.
  • check_batch isolates a per-point ConfigValidationError. 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 that process_batch in engine/case_triage.py applies to a CaseSummarizationError. 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 calls check_batch periodically with whatever data points a site's own polling produced. DeviationFlagging has no cron or timer logic.
  • No ActivityLogEntry is written here.
    • If a caller needs an audited trail of every scheduled check's own run (not just the resulting "deviation" entries that engine/case_triage.py later logs), that is a separate wrapper around check_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 ConfigValidationError swallowed by check_batch (above) leaves no logged trail either. A caller that needs one should catch it itself around a per-point check call rather than relying on check_batch's silent skip.
  • check_batch still returns an entry for an already-enqueued point. The returned list reflects which points evaluated to DEVIATION this run, not which rows were newly inserted. Check TriggerQueue.enqueue's return value directly if that distinction matters to a caller.

Release: v0.11.0