Flag pump sensors that leave their forecast band, in a durable monitoring loop that survives crashes and pauses for a human decision.

Anomaly monitoring

Code available on GitHub. See Time series models for setup, the container image, and model loading.

A forecast with calibrated quantiles is also an anomaly detector: if a sensor’s readings land outside the forecast’s 1-99% band, something changed that the history didn’t predict. This tutorial monitors a fleet of three pumps, each reporting vibration, bearing temperature, and discharge pressure every minute. For each 30-minute window, a monitor:

  1. forecasts the window from the last two days of readings,
  2. waits for the window’s readings to arrive,
  3. flags the window if the readings leave the forecast band, and
  4. after two flagged windows in a row, pauses for an operator to decide whether to dispatch a maintenance crew.

A monitor is a long-running loop with side effects: it pages people and waits for hours. The loop is built from traces, durable sleep, and an external condition, so a crash doesn’t re-send alerts that were already recorded, lose the wait, or forget a decision.

            flowchart LR
    R1[read history<br/>trace] --> F[forecast window<br/>trace]
    F --> S[durable sleep]
    S --> R2[read actuals<br/>trace]
    R2 --> Sc{outside<br/>band?}
    Sc -- no --> R1
    Sc -- yes --> A[send alert<br/>trace]
    A --> C{"2 in a row?"}
    C -- no --> R1
    C -- yes --> H[/operator:<br/>dispatch crew?/]
    H --> R1
        

Run it

python anomaly_monitor.py

The script crashes each monitor once, in its fifth window, to show recovery. When pump-02 trips, the run pauses on a condition named dispatch-pump-02-<minute>. Answer in the UI, or from the CLI. flyte get condition lists the paused conditions with their action names, and flyte signal condition takes the action name:

flyte get condition <run-name>
flyte signal condition <run-name> <action-name> true

If nobody answers within 15 minutes, the monitor dispatches the crew.

The sensor feed

The feed is simulated, so the tutorial runs anywhere. Each pump follows a planned duty cycle: idle overnight, high load from 10:00 to 14:00 and 18:00 to 20:00, normal otherwise. Vibration, temperature, and pressure follow the load. Starting at a set window, pump-02’s bearing begins to fail, and its vibration and temperature ramp up.

anomaly_monitor.py
def operating_mode(minutes):
    """Planned duty cycle: 0 = idle (00-06h), 2 = high load (10-14h, 18-20h), 1 = normal."""
    import numpy as np

    hour = (np.asarray(minutes) // 60) % 24
    return np.where(
        hour < 6,
        0,
        np.where(((hour >= 10) & (hour < 14)) | ((hour >= 18) & (hour < 20)), 2, 1),
    )

def simulate(asset: str, start: int, end: int, fault_asset: str, fault_start: int):
    """Deterministic readings for minutes [start, end): a pure function of the asset
    and the minute, so re-reading a window always returns the same values."""
    import numpy as np

    minutes = np.arange(start, end)
    seed = sum(map(ord, asset))

    def noise(k):  # hash-based Gaussian noise, stable per (asset, minute, variate)
        u1 = np.modf(
            np.abs(np.sin(minutes * 12.9898 + seed * 78.233 + k * 37.719)) * 43758.5453
        )[0]
        u2 = np.modf(
            np.abs(np.sin(minutes * 93.9898 + seed * 47.233 + k * 11.131)) * 24634.6345
        )[0]
        return np.sqrt(-2 * np.log(np.clip(u1, 1e-9, 1))) * np.cos(2 * np.pi * u2)

    mode = operating_mode(minutes)
    ambient = np.sin(2 * np.pi * ((minutes / 60) % 24 - 9) / 24)
    vibration = 0.5 + 1.5 * mode + 0.15 * noise(0)
    temperature = 45 + 8 * mode + 3 * ambient + 0.4 * noise(1)
    pressure = 2 + 1.5 * mode + 0.05 * noise(2)

    if asset == fault_asset:  # a failing bearing: vibration and heat ramp up
        since = np.clip(minutes - fault_start, 0, None)
        vibration = vibration + 0.06 * since**0.9
        temperature = temperature + 0.05 * since

    return np.stack([vibration, temperature, pressure]), mode

Readings are a pure function of the pump and the minute, so reading the same window twice returns the same values, as a historian query would. Plant time is compressed: each 30-minute window passes in cycle_seconds of wall-clock time, 20 by default.

The traced steps

Each step with an external effect or a costly result is a function decorated with @flyte.trace. A trace records its inputs and outputs. When the task retries, a traced call that already completed returns its recorded output instead of running again.

anomaly_monitor.py
@flyte.trace
async def read_sensors(
    asset: str, start: int, end: int, fault_asset: str, fault_start: int
) -> dict:
    """Stand-in for a query against your plant historian."""
    values, mode = simulate(asset, start, end, fault_asset, fault_start)
    return {"values": values.round(4).tolist(), "mode": mode.tolist()}

@flyte.trace
async def forecast_window(
    model: str, history: dict, observed: list[bool], future_mode: list[int], horizon: int
) -> dict:
    """Forecast all three variates jointly, conditioned on the planned operating mode.

    `observed` is False for readings in windows already flagged as anomalous. The
    model treats them as missing, so it keeps forecasting healthy behavior instead
    of learning the fault as the new normal.
    """
    import numpy as np

    forecaster = load_forecaster(TIMESTRAL_MODELS[model], MONITOR_CPUS)
    context = np.asarray(history["values"], dtype="float32")[None]  # (1, 3, T)
    mask = np.repeat(np.asarray(observed)[None, None], context.shape[1], axis=1)
    modes = np.asarray(history["mode"] + future_mode, dtype="float32")[
        None, None
    ]  # (1, 1, T + H)
    forecast = forecaster.forecast(
        context,
        prediction_length=horizon,
        observation_mask=mask,
        categorical_known_covariates=modes,
    )
    quantiles = forecast.quantiles[0].numpy()  # (3, H, 21)
    return {"quantiles": quantiles.round(4).tolist()}

@flyte.trace
async def send_alert(asset: str, window_start: int, message: str) -> str:
    """Stand-in for a pager or ticketing call. As a trace, it runs once per window,
    even if the monitor crashes and replays after sending it."""
    print(f"ALERT {asset} @ minute {window_start}: {message}", flush=True)
    return f"alert-{asset}-{window_start}"

forecast_window uses two Timestral features:

  • Multivariate forecasting. All three sensors go through the model as variates of one series, (1, 3, T), so the model forecasts them jointly.
  • Categorical known-future covariates. The duty cycle is planned, so the operating mode is known for the forecast window too. Passing it as categorical_known_covariates lets the model anticipate the 10:00 shift to high load instead of flagging it.

The monitoring loop

anomaly_monitor.py
@monitor_env.task(retries=2)
async def monitor_asset(
    asset: str,
    start_minute: int,
    cycles: int,
    horizon: int,
    context_minutes: int,
    cycle_seconds: int,
    model: str,
    fault_asset: str,
    fault_cycle: int,
    alert_threshold: float,
    crash_at_cycle: int,
) -> AssetReport:
    import numpy as np

    attempt = flyte.ctx().attempt_number
    fault_start = start_minute + fault_cycle * horizon
    report = AssetReport(asset=asset, attempt=attempt)
    consecutive = 0
    flagged: list[int] = []  # start minutes of anomalous windows

    for cycle in range(cycles):
        t0 = start_minute + cycle * horizon
        history = await read_sensors(asset, t0 - context_minutes, t0, fault_asset, fault_start)
        minutes = np.arange(t0 - context_minutes, t0)
        observed = ~np.isin(minutes - (minutes - start_minute) % horizon, flagged)
        future_mode = operating_mode(np.arange(t0, t0 + horizon)).tolist()
        forecast = await forecast_window(
            model, history, observed.tolist(), future_mode, horizon
        )

        # Wait for the window's readings to arrive. On a retry, the sleep only
        # waits out whatever time is left since it first started.
        await flyte.durable.sleep.aio(cycle_seconds)

        if attempt == 0 and cycle == crash_at_cycle:
            raise flyte.errors.RuntimeSystemError(
                "SimulatedCrash", f"{asset} monitor crashed in cycle {cycle}"
            )

        actual = await read_sensors(asset, t0, t0 + horizon, fault_asset, fault_start)
        outside = score(actual["values"], forecast["quantiles"])
        anomaly = max(outside.values()) >= alert_threshold
        consecutive = consecutive + 1 if anomaly else 0
        if anomaly:
            flagged.append(t0)

        chart = ""
        if anomaly:
            worst = int(np.argmax(list(outside.values())))
            chart = fan_chart_svg(
                history["values"][worst][-4 * horizon :],
                forecast["quantiles"][worst],
                actual["values"][worst],
                title=f"{asset} {VARIATES[worst]}, window starting minute {t0}",
            )
            report.alerts.append(
                await send_alert(
                    asset,
                    t0,
                    f"{VARIATES[worst]} outside forecast band {outside[VARIATES[worst]]:.0%}",
                )
            )
        report.windows.append(
            WindowResult(start=t0, outside_band=outside, anomaly=anomaly, chart=chart)
        )

        # Two anomalous windows in a row: ask a human whether to dispatch a crew.
        if consecutive == 2 and not report.dispatched:
            report.dispatched = await request_dispatch(asset, t0, outside)

    return report

Durable sleep

flyte.durable.sleep.aio(cycle_seconds) stands in for waiting until a window’s readings exist. It records when it first started. If the task crashes during the wait and retries, the sleep waits only for the time that remains, and returns at once if that time has passed.

Replay after a crash

The example raises flyte.errors.RuntimeSystemError in cycle 4 of the first attempt. The task has retries=2, so it runs again from the top. The retry replays cycles 0 through 3 from the trace record: no sensor reads, no forecasts, and no repeated alerts for windows that were already alerted on. It resumes live work at cycle 4.

Replay requires the loop to make the same calls in the same order on every attempt. Here, everything the loop decides comes from traced outputs or from the task’s inputs, so a replayed attempt reaches the same state as the first one. Don’t branch on the wall clock or unseeded randomness in a loop like this. For the current time, use flyte.durable.now(), which is recorded once and replayed.

Don’t learn the fault

A forecast model adapts to its context. Once a slow fault is in the history, the model forecasts it as the new normal, and the anomaly stops being flagged after its first window. The loop prevents this by passing readings from flagged windows as unobserved, through Timestral’s observation_mask. The model treats them as missing and keeps forecasting healthy behavior, so a growing fault keeps getting flagged.

Ask a human

After two flagged windows in a row, request_dispatch creates an external condition and waits for a typed answer.

anomaly_monitor.py
async def request_dispatch(asset: str, window_start: int, outside: dict[str, float]) -> bool:
    """Pause the monitor until an operator answers. No answer in 15 minutes
    means dispatch: for a failing bearing, a false alarm is the cheaper mistake."""
    summary = ", ".join(f"{k} {v:.0%}" for k, v in outside.items())
    condition = await flyte.new_condition.aio(
        f"dispatch-{asset}-{window_start}",
        prompt=f"{asset} has left its forecast band for two windows ({summary}). Dispatch a crew?",
        data_type=bool,
        timeout=timedelta(minutes=15),
    )
    try:
        return await condition.wait.aio()
    except flyte.errors.ConditionTimedoutError:
        return True

The monitor pauses at condition.wait.aio() until an operator signals it from the UI, the CLI, or flyte.remote.Condition. If the 15-minute timeout passes first, the monitor dispatches the crew, because a missed bearing failure costs more than a wasted visit. The condition is part of the run’s record, so the decision and when it was made are visible alongside the forecasts that prompted it. See External conditions.

Watch the fleet

monitor_fleet runs one monitor per pump in parallel and renders a report: a row of windows per pump, alerts, dispatch decisions, and how many attempts each monitor took. Each anomalous window has a fan chart with the history, the forecast bands, and the actual readings.

anomaly_monitor.py
@monitor_env.task(
    report=True,
    # The trigger is created inactive; activate it with
    # `flyte update trigger hourly-fleet-monitor timestral-monitor.monitor_fleet --activate`.
    triggers=flyte.Trigger(
        "hourly-fleet-monitor",
        flyte.Cron("0 * * * *"),
        inputs={"trigger_time": flyte.TriggerTime},
        auto_activate=False,
    ),
)
async def monitor_fleet(
    assets: list[str] = ["pump-01", "pump-02", "pump-03"],
    cycles: int = 8,
    horizon: int = 30,
    context_minutes: int = 2880,
    cycle_seconds: int = 20,
    model: str = "28M",
    fault_asset: str = "pump-02",
    fault_cycle: int = 3,
    alert_threshold: float = 0.2,
    crash_at_cycle: int = -1,
    trigger_time: datetime | None = None,
) -> list[AssetReport]:
    # Plant time starts at 08:00 so the run crosses the 10:00 shift to high load.
    start_minute = 14 * 24 * 60 + 8 * 60
    reports = await asyncio.gather(
        *(
            monitor_asset(
                asset,
                start_minute,
                cycles,
                horizon,
                context_minutes,
                cycle_seconds,
                model,
                fault_asset,
                fault_cycle,
                alert_threshold,
                crash_at_cycle,
            )
            for asset in assets
        )
    )
    await render_report(reports, trigger_time or await flyte.durable.now.aio())
    return list(reports)

Run it on a schedule

The triggers argument attaches a cron trigger that runs the fleet monitor at the top of every hour. flyte run ignores triggers. They take effect when you deploy the task:

flyte deploy anomaly_monitor.py monitor_env

The trigger is created inactive (auto_activate=False). Activate it in the UI, or with flyte update trigger hourly-fleet-monitor timestral-monitor.monitor_fleet --activate. Each run receives its scheduled time as trigger_time. See Triggers.

Adapt it to your plant

  • Replace read_sensors with a query against your historian, and send_alert with your pager or ticketing call. Keep both traced. A trace records an output only after the call returns, so if the process dies after the pager accepts an alert but before the trace is recorded, the retry sends it again. Pass a stable deduplication key, such as (asset, window_start), so the pager drops the duplicate.
  • Check for an open work order before asking for a dispatch. Within a run, each pump is dispatched at most once, but runs don’t share state. The simulated feed replays the same fault every run, so with the hourly trigger active, every run asks again, and dispatches the crew if nobody answers.
  • Replace the simulated duty cycle with your real production schedule, or with any other state you know in advance.
  • Tune alert_threshold, the fraction of readings outside the band that flags a window. With a 1-99% band, about 2% of healthy readings fall outside by chance.