STAFFCHAPTER 30

AI in network operations: prediction, optimisation and what to verify

A detector that cries wolf teaches the night shift to stop listening. Learn the jobs AI does in a mobile network, build the baseline it has to beat, and learn what to check before anything acts on its own

55 MINHOW MOBILE NETWORKS WORKUPDATED 2026-11-13
PREDICT

An alarm rule is wrong on 0.1% of healthy 15-minute windows, one in a thousand. A network has 10,000 cells, and each cell reports 96 windows a day. About how many false alarms does the NOC receive each day?

‘AI in the network’ covers at least five different jobs, with different data, different risks and different people who have to trust them. Most of what runs in operations today is statistics: a baseline, a forecast, a threshold that moves with the clock. That is not an insult. A learner who can build and score that baseline can judge any vendor’s model, because the vendor’s model has to beat it. Where the techniques are more elaborate, the questions in this chapter stay the same.

Five jobs, five risks

Job What goes in What comes out Who acts on it How it fails
Forecasting Months of traffic counters per cell Expected load by hour and day Planners (the planning chapter, 4.1) A trend breaks: a promotion, a new road, a rival’s outage
Anomaly detection Live counters and KPIs An alarm: this window is unlike normal The NOC False alarms; silence about a slow decay
Root-cause suggestion Alarms, topology, change records, signalling A ranked guess at the cause The engineer A confident guess with no evidence behind it
Closed-loop optimisation, including energy saving Counters and configuration A changed parameter or a carrier switched off The system, perhaps after approval Two loops fighting over one setting; a wrong change made at scale
Assistants (summaries, search over runbooks and tickets) Tickets, runbooks, text Text The engineer Plausible text that is not grounded in the data

The column that matters most is the fourth. A forecast advises a planner who has weeks to check it. A detector interrupts a person. A closed loop changes the network without anyone. Each step towards acting alone shortens the time in which a person can catch a mistake, so the evidence you need before trusting it grows with it.

Where it sits in the standards

3GPP, the body that writes the mobile standards, has put analytics into the architecture in three places. None of them is in the lab, whose core runs no analytics function: the analytics in this chapter you write yourself.

  • Network Data Analytics Function (NWDAF). A function in the 5G core, described in TS 23.288, that other functions can ask for analytics such as the load on a network function or a slice. It first appeared in Release 15 and its data sources and analytics widened from Release 16. From Release 17 it can be split into a part that trains models and a part that serves their results.
  • Management Data Analytics (MDA). In TS 28.104, the management side’s counterpart: an analytics capability on the management side of the network (the tools that configure, monitor and fix it), fed with management data such as performance measurements and alarms, whose results go to other management functions and operator tools.
  • Self-organising networks (SON). Functions that configure and tune the radio network by themselves. For LTE, 3GPP’s use cases include automatic neighbour relations (a cell learns who its neighbours are), mobility load balancing (spreading traffic between cells) and mobility robustness optimisation (reducing failed and unnecessary handovers); TS 28.313 carries SON into 5G. TS 28.310 covers energy efficiency in 5G.

The TM Forum, an industry body, grades how autonomous operations are on six levels from L0 (manual) to L5 (fully autonomous), assessed per scope: one workflow or one domain, not a whole company. Read the level as an answer to one question: for this task, who acts, and who is checking? Marketing claims of ‘an autonomous network’ without a scope and a level tell you little.

Data first

A model is only as good as what it reads. The sources in an operator, and their traps:

  • Counters per cell per quarter-hour, kept by the network itself. They are cheap and complete, but a definition can differ between vendors, and a phone that never reached the network is not an attempt. The rule from the quality-of-service chapter applies: ask for the counting rule before the number.
  • Signalling captures and probes, such as the lab’s recordings. Exact, but heavy to keep.
  • Alarms and tickets. They hold what operators noticed, not what happened. A model trained on past alarms learns past operators.
  • Configuration and change records. The first thing to correlate with a fault, and often the worst kept.

Three traps show up in the lab’s own data. First, a counter in the Prometheus format only goes up while a function runs, so one reading says ‘since start’. The figure you want is the difference between two readings, and a restart sets the counter back to zero, so a naive difference goes negative. Second, a ratio needs the right numerator and denominator. In the lab’s session management function (SMF) the counter of session creation requests appears twice, once with empty plmnid and snssai labels and once labelled for slice 1; both read 50 for 50 phones and appear to count the same requests. Add every series that shares the name and the success ratio is 50/100, an alarm for a network that did nothing wrong. Third, a ratio of nothing is not 100%: a window with no attempts has no success rate, and a rule must say what it does then.

If you train a model, split the data by time, not at random, and keep the labels from the people who will use it. The data leakage lesson shows what happens when the test set has already been seen, and building an eval set shows how to label cases so two people agree.

Start with a baseline

Here is one cell’s registration attempts in a quarter-hour, drawn from the model the lab uses (illustrative, not a real cell). The solid line is what is normal for a weekday. The dotted line is four robust deviations below it. A fixed floor of 100 attempts sits near the bottom, and a dashed line shows what a 30% loss of traffic in the afternoon looks like.

00:0006:0012:0018:0024:0005001,0001,500registration attempts per quarter-hour, one illustrative weekdaynormalfour deviations below normalfixed floor, 10070% of normal14:00 to 17:45

The floor is a good rule for one thing: the cell being completely down at any hour. It cannot see the 30% loss, because 70% of an afternoon’s 250 attempts is still far above 100. The seasonal rule, one baseline per slot, is better, but in this drawing even it keeps the dashed line inside its band all afternoon, since an afternoon is quiet and quiet counts are noisy. Whether a rule catches the loss in the month below depends on the baseline’s memory and on how the noise falls.

How you build the baseline matters more than which model sits on top of it. The lab’s version keeps, for each slot (weekday or weekend, and quarter-hour), the median of the same slot on earlier days, and a spread measured by the median absolute deviation (MAD): the median of how far each value sits from that median. Multiplied by 1.4826 it matches a standard deviation for bell-shaped noise, but a fault or a surge in the history cannot drag it, which an ordinary mean and standard deviation would allow. A floor on the spread (here the square root of the median plus 5% of it) stops a slot with two similar values from making the cell look as if it must never vary. An alarm is a window more than K spreads from its median; the lab starts with K = 4.

The lab runs five rules over one illustrative 28-day series: 2,688 windows, a baseline learned on the first 14 days, and the last 14 days scored. Three things happen in those two weeks. On day 17 there is a match night with double the traffic: real, harmless, and not a fault. On day 20 a promotion lifts traffic by 25% for good. On day 21 the cell goes down for two hours (an outage), and on day 24 a sector is lost for four hours (traffic at 70% of normal, the degradation). What you see:

Rule Alarm windows Outage Degradation The lesson
Fixed floor under 100 8 caught missed Catches only a cell that is down
Seasonal, frozen on days 0 to 13, drops only 8 caught missed No false alarms, but the promotion lifted traffic by 25%, so 70% of normal is 87.5% of the old baseline: growth hid the fault
Seasonal, frozen, both directions 238 caught missed 216 false alarm windows after the promotion: a baseline that never learns pages every evening
Seasonal, rolling 14 days 99 caught missed Learning helps, but the 14-day median still lags the new level
Seasonal, last 3 days of the same type 76 caught caught after 3 windows Adapts fastest, but at K = 5 it misses the degradation again

Two lessons are worth stating plainly. A baseline has a memory, and its length is a trade-off: a long memory is stable and slow to follow a real change; a short one follows change and also learns a slow fault as normal. And the match night, 12 windows of false alarms in every two-sided rule, cannot be removed by any baseline. Only a calendar can tell the detector that a match is on, and in a real network the people who know are not in the NOC. Detection needs a feed of known events and planned work.

Measure the detector, not its demo

A detector is judged by four numbers. Precision is the share of alarms that were real. Recall is the share of real faults it raised. Detection delay is how long after the fault began that the first alarm came. Alarms per day is what the NOC must handle. A vendor quoting ‘accuracy’ alone has said none of them: with 10 real faults in 10,000 windows, a rule that never fires is 99.9% accurate.

Group alarms into incidents before you count them. The lab merges alarm windows within an hour of each other, and the short-memory rule’s 76 alarm windows over 14 days become 33 incidents: 2.4 a day for one cell, of which two were real faults. Scaled to 10,000 such cells the arithmetic gives 23,571 a day. The series is illustrative, so read that figure as an example of the arithmetic, not a forecast. It shows why a per-cell rule has to be tight, why alarms need grouping across cells (one failed link is not a thousand incidents) and why alert design in software operations spends so much effort on what is worth a page.

Two traps in the scoring itself. The first is hindsight: a rule written after reading the windows it is scored on will look better than it is. The second is the label. Ground truth in operations is a decision. The lab’s wrong-key recording, where a phone’s secret key does not match the network’s, is a refusal in one reading and a fault in another (a whole batch of SIMs provisioned with the wrong key would be one). Whichever label you pick changes the score, so agree the labels, and who may decide them, before you tune anything.

Prediction, cause and the assistant

Forecasting is the baseline looking forward. A planner needs expected load by cell and busy hour months ahead, and a seasonal pattern with a trend is a fair start; the work is in the events that break it. Measure a forecast against what happened, in the busy hour, per cell, not as a network-wide average (the quality-of-service chapter shows why the average hides the cell).

Predicting faults is harder. Faults are rare, so labelled examples are few. A warning must also arrive earlier than the repair takes: a model that predicts a failure ten minutes ahead of one that needs a crew four hours away has told you nothing you can use. Ask for the lead time and for the cost of each false warning.

Root-cause suggestion is the most useful and the most dangerous. In the lab’s wrong-dnn recording the registration succeeds and both data sessions are refused with cause 91 (DNN not supported or not subscribed in the slice); what the engineer needs is the frame and the cause code, not a paragraph. A tool that suggests a cause must show the evidence it used (which counter, which window, which message), so the engineer can reject it in a minute. If it cannot show its evidence it is a guess in confident prose, and the hallucination chapter of the AI Engineering course (grounding) explains why such text reads as right whether or not it is.

Assistants that summarise a ticket or find the right runbook save time, and the same rule holds: the answer must point at its source.

Closed loops and energy saving

A closed loop measures, decides and changes the network without a person in between. SON is the standard example: a cell adjusting its handover thresholds, or a controller moving traffic between cells. The danger is not that one loop is wrong but that two are right about different things. In LTE, mobility load balancing wants more handovers away from a busy cell, while mobility robustness optimisation wants fewer premature ones, and both adjust handover settings; unless they are coordinated they can undo each other.

Energy saving is the case that matters where site power is a hard constraint, as it is in much of Nigeria (the transmission chapter, 4.2, covers diesel, solar and batteries). At 03:00 our illustrative cell expects about 230 attempts against about 1,500 at 19:30, so a controller can switch off a carrier or put a cell to sleep overnight and wake it when traffic returns. The anomaly detector then sees a cell with no traffic, which is exactly what the lab’s rule 4 calls an alarm. Two systems each doing their job produce a false alarm every night, and if the controller wakes the cell late, a real harm. The cure is a feed of planned states: the controller tells the detector which cells are asleep on purpose. Silence in a planned state is expected, and silence outside one is an alarm.

Autonomy is a ladder, and each rung needs evidence from the one below:

  1. Advise. The tool writes a ticket; a person decides and acts.
  2. Act with approval. The tool proposes a change with its evidence; a named person approves each one.
  3. Act with rollback. The tool changes within limits, records what it did, and reverts when a guard figure (registration success, say) worsens.
  4. Act alone. Only for changes whose worst case is small and reversible, after a long record at the rung below.

At Lumora, a change to radio parameters on live cells goes through change control whatever proposes it (the operating chapter, 4.4); an automatic loop is a change author that never gets tired, not an exemption.

What to verify before you trust it

Ask The evidence you want What goes wrong without it
Does it beat the simple baseline? The same scoring on the same windows for a seasonal median and for the model You pay for a model that a spreadsheet matches
What is the alarm budget? Alarms per day, grouped into incidents, and who staffs them Alert fatigue and a missed real fault, as in Tolani’s week five
Was it scored on data it was not tuned on? A held-out period, with labels set beforehand by someone outside the team Hindsight and leakage
What happens on known events? Results through a promotion, a surge, a sleeping cell and a restart Nightly false alarms; or an energy saver that fights the detector
Does it drift? A check, per month, of precision and recall, and a rule for retraining A baseline that has learned a fault, or one that has not learned growth
Can it say why? The counters, windows and messages behind each alarm or suggestion An engineer who cannot reject a wrong answer quickly
Who signs a change, and who can stop it? A named approver per rung, a rollback, a kill switch, and what the network does when the tool is off An automatic change nobody owns

A virtual operator on a host network sees none of the host’s models, only their effects. It can still ask which changes the host’s network makes by itself, what notice or record it receives before one touches its subscribers, who approves changes that are not automatic, and which figures show that the automation helps.

LAB Build a baseline, score an alarm rule and catch a false alarm ~50 MIN
YOU NEEDDocker with Compose v2 (steps 1 and 2 read recordings in traces/ with scripts/kpi.sh)Python 3.9 or later on your own machine; steps 1 to 4 use only the standard libraryNo live core and no SCTP: every step works on any machine with Docker. Step 4 uses recorded metrics and says how to take them from a live core

You will turn recordings into windows of counters, write four alarm rules and score them against what you know about each recording, learn why the score cannot be trusted, then build a seasonal baseline over an illustrative month of traffic and measure its false alarms. Work in labs/telecoms. Keep your own scripts in a folder of your own, outside scripts/: mkdir -p ~/mywork.

1. Make a window from each recording and score four rules. Save this as ~/mywork/windows.py. It runs scripts/kpi.sh on twelve recordings, reads the counts from the printed summary, and scores four rules. Each recording stands for one 15-minute counter window; the rules were written after reading these windows, which step 2 returns to.

#!/usr/bin/env python3
"""Turn each recording into one 'window' of counters, then score alarm rules
against what we know about each window. Standard library only.

Run from labs/telecoms:  python3 ~/mywork/windows.py
"""
import re
import subprocess

# (trace, what we know). 'ok' = the network behaved; 'refusal' = it refused a
# phone for a subscriber-side reason and a NOC should not be paged; 'fault' =
# something in the network is broken and a NOC should be paged.
# The five fault recordings are shown as fault-A to fault-E in an order of our
# own, so that this chapter does not give away the fault-diagnosis project.
ALIAS = {"fault-2": "fault-A", "fault-4": "fault-B", "fault-1": "fault-C",
         "fault-5": "fault-D", "fault-3": "fault-E"}
WINDOWS = [
    ("attach-and-browse", "ok"), ("morning", "ok"), ("ims-session", "ok"),
    ("busy-hour", "ok"),
    ("unknown-subscriber", "refusal"), ("wrong-key", "refusal"), ("wrong-dnn", "refusal"),
    ("fault-2", "fault"), ("fault-4", "fault"), ("fault-1", "fault"),
    ("fault-5", "fault"), ("fault-3", "fault"),
]


def read_window(trace):
    out = subprocess.run(["scripts/kpi.sh", f"traces/{trace}.pcapng"],
                         capture_output=True, text=True, check=True).stdout
    w = {"causes": {}}
    for key, word in (("reg", "registrations"), ("pdu", "data sessions")):
        m = re.search(rf"^{word}:\s+(?:(\d+)/(\d+) = |(\d+) tried)", out, re.M)
        if m.group(3) is not None:                       # "0 tried, so 0 accepted"
            w[key + "_ok"], w[key + "_tried"] = 0, 0
        else:
            w[key + "_ok"], w[key + "_tried"] = int(m.group(1)), int(m.group(2))
    m = re.search(r"registrations:.*\n\s+time to accept:\s+median (\d+) ms", out)
    w["reg_median_ms"] = int(m.group(1)) if m else None
    for n, code, name in re.findall(r"^\s+(\d+)\s+(?:registration reject|session reject|5GMM status): (\d+) (.*)$", out, re.M):
        w["causes"][int(code)] = (int(n), name)
    return w


def rate(ok, tried):
    return None if tried == 0 else ok / tried


# Rule 1: the naive one. Registration success below 99% pages the NOC.
def rule1(w):
    r = rate(w["reg_ok"], w["reg_tried"])
    return r is not None and r < 0.99


# Rule 2: registration or session success below 99%, only where there were attempts.
def rule2(w):
    r, s = rate(w["reg_ok"], w["reg_tried"]), rate(w["pdu_ok"], w["pdu_tried"])
    return (r is not None and r < 0.99) or (s is not None and s < 0.99)


# Rule 3: count only failures with a cause the subscriber side explains away
# (11 PLMN not allowed: no such subscriber; 91 DNN not subscribed). Anything
# else, in any number, pages.
SUBSCRIBER_SIDE = {11, 91}
def rule3(w):
    return any(code not in SUBSCRIBER_SIDE for code in w["causes"])


# Rule 4: rule 3, plus a silence rule. A window in which the baseline expects
# traffic (we say it does, always) and no registration was attempted is an alarm.
def rule4(w):
    return rule3(w) or w["reg_tried"] == 0


RULES = [("1 registration success < 99%", rule1), ("2 either success rate < 99%", rule2),
         ("3 failure cause not subscriber-side", rule3), ("4 rule 3 + silence", rule4)]

if __name__ == "__main__":
    data = [(ALIAS.get(t, t), label, read_window(t)) for t, label in WINDOWS]
    print(f"{'window':20s}{'known':9s}{'reg':>7s}{'pdu':>7s}  causes")
    for t, label, w in data:
        causes = ", ".join(f"{c}x{n}" for c, (n, _) in w["causes"].items()) or "-"
        print(f"{t:20s}{label:9s}{w['reg_ok']:>3d}/{w['reg_tried']:<3d}{w['pdu_ok']:>3d}/{w['pdu_tried']:<3d}  {causes}")
    print()
    n_faults = sum(1 for _, label, _ in data if label == "fault")
    for name, rule in RULES:
        fired = [(t, label) for t, label, w in data if rule(w)]
        fp = [t for t, label in fired if label != "fault"]
        hit = [t for t, label in fired if label == "fault"]
        miss = [t for t, label, _ in data if label == "fault" and t not in hit]
        print(f"rule {name}")
        print(f"   fired {len(fired)}; false alarms {len(fp)} {fp}; faults caught {len(hit)} of {n_faults}; missed {miss}")
python3 ~/mywork/windows.py
window              known        reg    pdu  causes
attach-and-browse   ok         1/1    1/1    -
morning             ok         1/1    1/1    -
ims-session         ok         1/1    2/2    -
busy-hour           ok        18/20  18/18   11x2
unknown-subscriber  refusal    0/1    0/0    11x1
wrong-key           refusal    0/1    0/0    111x1
wrong-dnn           refusal    1/1    0/2    91x2
fault-A             fault      0/0    0/0    -
fault-B             fault      0/3    0/0    62x3
fault-C             fault      1/1    0/27   38x27
fault-D             fault      0/1    0/0    95x1
fault-E             fault      0/1    0/0    95x1

rule 1 registration success < 99%
   fired 6; false alarms 3 ['busy-hour', 'unknown-subscriber', 'wrong-key']; faults caught 3 of 5; missed ['fault-A', 'fault-C']
rule 2 either success rate < 99%
   fired 8; false alarms 4 ['busy-hour', 'unknown-subscriber', 'wrong-key', 'wrong-dnn']; faults caught 4 of 5; missed ['fault-A']
rule 3 failure cause not subscriber-side
   fired 5; false alarms 1 ['wrong-key']; faults caught 4 of 5; missed ['fault-A']
rule 4 rule 3 + silence
   fired 6; false alarms 1 ['wrong-key']; faults caught 5 of 5; missed []

The table is the window data: attempts and successes per stage, and the failure causes with counts (11x2 is cause 11 twice; the five fault recordings are renamed fault-A to fault-E, in an order of our own, so that this chapter does not give away the fault-diagnosis project). Rule 1, the naive one, raises six alarms but only three are real: it fires on the busy hour (two phones the network was right to refuse, cause 11, the same two as the quality-of-service chapter) and on two refusals of single phones, and misses two faults: fault-C, where registration is fine and the failures sit in the session stage, and fault-A, where no phone got as far as the core, so there is no rate at all. Rule 2 adds the session rate and catches fault-C, at the price of firing on wrong-dnn, where refusing was the right answer. Rule 3 looks at causes instead of rates and is much quieter. Rule 4 adds a silence rule, an alarm when a window in which traffic is expected has none, and catches all five. Precision and recall: rule 1 is 3 of 6 alarms real (50%) and 3 of 5 faults found (60%); rule 4 is 5 of 6 (83%) and 5 of 5 (100%). Rule 4 assumes a baseline that always expects traffic; a real silence rule needs the planned-states feed from the chapter, or it fires on every sleeping cell.

2. Change one label and score again. In windows.py change ("wrong-key", "refusal") to ("wrong-key", "fault"), so that a SIM whose secret key does not match is counted as something the NOC should hear about, and rerun.

python3 ~/mywork/windows.py | tail -8
rule 1 registration success < 99%
   fired 6; false alarms 2 ['busy-hour', 'unknown-subscriber']; faults caught 4 of 6; missed ['fault-A', 'fault-C']
rule 2 either success rate < 99%
   fired 8; false alarms 3 ['busy-hour', 'unknown-subscriber', 'wrong-dnn']; faults caught 5 of 6; missed ['fault-A']
rule 3 failure cause not subscriber-side
   fired 5; false alarms 0 []; faults caught 5 of 6; missed ['fault-A']
rule 4 rule 3 + silence
   fired 6; false alarms 0 []; faults caught 6 of 6; missed []

Rule 3 now has no false alarms and rule 4 finds 6 of 6 with none. Nothing about the rules changed: the label did. The same rule is scored as 83% precise or 100% precise depending on a decision about one recording, and that decision was made by the person who also wrote the rules. This is hindsight, and it is why a score on the windows used to build a rule is not evidence. Write down who should decide whether a mis-keyed SIM is the NOC’s business, and decide it before looking at the numbers next time.

3. Build the seasonal baseline and run five rules over an illustrative month. Save this as ~/mywork/seasonal.py. The traffic is made up (a seeded generator, the same on every machine) and stands for one cell’s registration attempts per quarter-hour for 28 days. It has a daily double peak, a quieter weekend, 3% growth a week, a match night, a promotion that lifts traffic by 25% from day 20, a two-hour outage and a four-hour loss of a sector.

#!/usr/bin/env python3
"""An ILLUSTRATIVE month of registration attempts for one cell, one count per
15 minutes, and several ways to alarm on it. The data is made up (seeded, so it
is the same on every machine): it is here to show how baselines fail, not what
a real cell looks like. Standard library only."""
import math
import random
import statistics

PER_DAY, DAYS = 96, 28
K = 4.0          # alarm when a window is more than K robust deviations from its baseline
rng = random.Random(45)


def expected(day, q):
    """Attempts expected in quarter-hour q of a day: a morning and an evening
    peak, a quieter weekend, 3% growth a week, and a promotion on day 20 (all illustrative)."""
    h = q / 4
    shape = 0.15 + 0.55 * math.exp(-((h - 8.5) / 2.2) ** 2) + 0.85 * math.exp(-((h - 19.5) / 2.8) ** 2)
    weekend = 0.8 if day % 7 >= 5 else 1.0
    promo = 1.25 if day >= 20 else 1.0        # a promotion from day 20 lifts traffic for good
    return 1500 * shape * weekend * promo * 1.03 ** (day / 7)


EVENTS = {   # (day, first quarter, last quarter): (label, multiplier)
    (17, 76, 87): ("match night: a real surge, not a fault", 2.0),
    (21, 40, 47): ("outage: the cell is down", 0.04),
    (24, 56, 71): ("degradation: a sector lost", 0.70),
}
series, label = [], []
for d in range(DAYS):
    for q in range(PER_DAY):
        m, tag = 1.0, ("level shift" if d >= 20 else "")
        for (ed, a, b), (name, mult) in EVENTS.items():
            if d == ed and a <= q <= b:
                m, tag = mult, name.split(":")[0]
        mean = expected(d, q) * m
        series.append(max(0, round(rng.gauss(mean, math.sqrt(mean) + 0.04 * mean))))   # noise
        label.append(tag)


def slot(i):
    d, q = divmod(i, PER_DAY)
    return (d % 7 >= 5, q)


def baseline(days):
    """Median and robust spread per slot from the given days."""
    by = {}
    for d in days:
        for q in range(PER_DAY):
            i = d * PER_DAY + q
            by.setdefault(slot(i), []).append(series[i])
    out = {}
    for k, v in by.items():
        med = statistics.median(v)
        mad = statistics.median(abs(x - med) for x in v)
        out[k] = (med, max(1.4826 * mad, math.sqrt(med) + 0.05 * med))   # never trust a tiny spread
    return out


def run(name, window_of, two_sided, k=None):
    k = K if k is None else k
    alarms = []
    for i in range(14 * PER_DAY, DAYS * PER_DAY):
        d = i // PER_DAY
        med, sd = baseline(window_of(d))[slot(i)]
        z = (series[i] - med) / sd
        if z < -k or (two_sided and z > k):
            alarms.append(i)
    incidents, last = [], -99
    for i in alarms:                    # alarms within 4 windows (1 hour) are one incident
        if i - last > 4:
            incidents.append([i, i])
        incidents[-1][1] = i
        last = i
    fp_windows = [i for i in alarms if label[i] in ("", "match night", "level shift")]
    found = {}
    for (ed, a, b), (name_, _) in EVENTS.items():
        tag = name_.split(":")[0]
        if tag == "match night":
            continue
        hits = [i for i in alarms if ed * PER_DAY + a <= i <= ed * PER_DAY + b]
        found[tag] = f"caught after {hits[0] - (ed * PER_DAY + a)} windows" if hits else "MISSED"
    sur = [i for i in alarms if label[i] == "match night"]
    shift = [i for i in alarms if label[i] == "level shift"]
    print(f"{name}")
    print(f"  alarm windows {len(alarms)} in {len(incidents)} incidents; "
          f"outside faults {len(fp_windows)} ({len(sur)} match night, {len(shift)} after the promotion); {found}")
    return len(incidents)


if __name__ == "__main__":
    print("expected attempts, one weekday, selected quarter-hours (illustrative):")
    for q in (12, 34, 56, 78):
        print(f"  {q // 4:02d}:{q % 4 * 15:02d}  {expected(0, q):6.0f}")
    print(f"month: {len(series)} windows, {sum(series):,} attempts\n")
    print("fixed floor: alarm when attempts < 100 in a window")
    fl = [i for i in range(14 * PER_DAY, DAYS * PER_DAY) if series[i] < 100]
    got = {t: any(label[i] == t for i in fl) for t in ("outage", "degradation")}
    print(f"  alarm windows {len(fl)}; outside faults {sum(1 for i in fl if label[i] == '')}; caught {got}\n")
    run("seasonal baseline, frozen on days 0-13, drops only", lambda d: range(0, 14), False)
    run("seasonal baseline, frozen on days 0-13, both directions", lambda d: range(0, 14), True)
    run("seasonal baseline, rolling 14 days, both directions", lambda d: range(d - 14, d), True)
    same_type = lambda d: [x for x in range(d - 14, d) if (x % 7 >= 5) == (d % 7 >= 5)][-3:]
    n = run("seasonal baseline, last 3 days of the same type, both directions", same_type, True)
    per_day = n / 14
    print(f"\nthat is {per_day:.1f} incidents a day for one cell; for 10,000 such cells, {per_day * 10000:,.0f} a day")
python3 -I ~/mywork/seasonal.py
expected attempts, one weekday, selected quarter-hours (illustrative):
  03:00     227
  08:30    1050
  14:00     253
  19:30    1500
month: 2688 windows, 1,797,139 attempts

fixed floor: alarm when attempts < 100 in a window
  alarm windows 8; outside faults 0; caught {'outage': True, 'degradation': False}

seasonal baseline, frozen on days 0-13, drops only
  alarm windows 8 in 1 incidents; outside faults 0 (0 match night, 0 after the promotion); {'outage': 'caught after 0 windows', 'degradation': 'MISSED'}
seasonal baseline, frozen on days 0-13, both directions
  alarm windows 238 in 59 incidents; outside faults 230 (12 match night, 216 after the promotion); {'outage': 'caught after 0 windows', 'degradation': 'MISSED'}
seasonal baseline, rolling 14 days, both directions
  alarm windows 99 in 42 incidents; outside faults 91 (12 match night, 78 after the promotion); {'outage': 'caught after 0 windows', 'degradation': 'MISSED'}
seasonal baseline, last 3 days of the same type, both directions
  alarm windows 76 in 33 incidents; outside faults 65 (12 match night, 51 after the promotion); {'outage': 'caught after 0 windows', 'degradation': 'caught after 3 windows'}

that is 2.4 incidents a day for one cell; for 10,000 such cells, 23,571 a day

The first block is the model’s weekday: 227 attempts at 03:00 and 1,500 at 19:30. The fixed floor catches the two-hour outage and misses the sector loss. The baseline learned on days 0 to 13 and set to alarm on drops only is silent for the 14 days apart from the outage, and misses the degradation: with the promotion’s 25% lift, 70% of normal is 87.5% of what that baseline expects. Letting the same baseline alarm in both directions gives 238 alarm windows, 216 of them after the promotion, because it never learned the new level. Refreshing the baseline daily from the last 14 days gives 99 alarm windows, and using only the last three days of the same type gives 76: a shorter memory follows the change, and only that one catches the degradation (after 3 windows, 45 minutes). The match night gives 12 false alarm windows in every two-sided rule. The last line is the alarm budget: 33 incidents in 14 days, 2.4 a day for this one cell, 23,571 a day for 10,000 like it. Real counts are noisier; these numbers are for comparing rules, not for sizing a NOC.

4. Take a ratio from the metrics, and check the numerator and denominator. Save this as ~/mywork/ratio.py. It reads the lines scripts/metrics.sh prints and works out the registration and session success ratios, with and without the double-counting trap.

#!/usr/bin/env python3
"""Read the lines scripts/metrics.sh prints and work out two success ratios.
Standard library only.  Usage: python3 ratio.py < saved-metrics.txt"""
import re
import sys

LINE = re.compile(r'^([a-z_0-9]+)(\{[^}]*\})?\s+([0-9.e+-]+)$')


def read(stream):
    """{metric name: [(labels, value), ...]}  Counters and gauges look alike here."""
    out = {}
    for line in stream:
        m = LINE.match(line.strip())
        if m:
            out.setdefault(m.group(1), []).append((m.group(2) or "", float(m.group(3))))
    return out


def total(series, name, require=""):
    return sum(v for labels, v in series.get(name, []) if require in labels)


m = read(sys.stdin)
reg_req = total(m, "fivegs_amffunction_rm_reginitreq")
reg_ok = total(m, "fivegs_amffunction_rm_reginitsucc")
if reg_req == 0:
    sys.exit("no registration attempts counted: silence is not a success rate")
print(f"registrations     {reg_ok:.0f}/{reg_req:.0f} = {100 * reg_ok / reg_req:.1f}%")

ses_ok = total(m, "fivegs_smffunction_sm_pdusessioncreationsucc")
naive = total(m, "fivegs_smffunction_sm_pdusessioncreationreq")
right = total(m, "fivegs_smffunction_sm_pdusessioncreationreq", require='snssai="1"')
print(f"sessions, every label set summed   {ses_ok:.0f}/{naive:.0f} = {100 * ses_ok / naive:.1f}%   <- a false alarm")
print(f"sessions, snssai=1 only            {ses_ok:.0f}/{right:.0f} = {100 * ses_ok / right:.1f}%")

Feed it the lines the core printed with 50 phones registered and in session, recorded on the lab’s virtual machine on 13 November 2026 (the label sets are copied exactly):

python3 ~/mywork/ratio.py <<'EOF'
fivegs_amffunction_mm_confupdate 50
fivegs_amffunction_rm_reginitreq 50
fivegs_amffunction_rm_reginitsucc 50
amf_session 50
fivegs_smffunction_sm_sessionnbr{plmnid="99970",snssai="1"} 50
fivegs_smffunction_sm_pdusessioncreationreq{plmnid="",snssai=""} 50
fivegs_smffunction_sm_pdusessioncreationreq{plmnid="99970",snssai="1"} 50
fivegs_smffunction_sm_pdusessioncreationsucc{plmnid="99970",snssai="1"} 50
EOF
registrations     50/50 = 100.0%
sessions, every label set summed   50/100 = 50.0%   <- a false alarm
sessions, snssai=1 only            50/50 = 100.0%

A rule built on the summed ratio would page the NOC about a network where all 50 phones registered and opened a session. The unlabelled series appears to count the same requests before the slice is known. A model fed this ratio would learn that 50% was normal or flag every window; no model can detect a wrong definition. With a live core (needs SCTP) start the phones as in the earlier labs and run for f in amf smf; do scripts/metrics.sh $f; done | python3 ~/mywork/ratio.py: you will see your own phone count. With no phone registered, the core prints no non-zero counters, and the script stops with “no registration attempts counted: silence is not a success rate” instead of dividing by zero. The counters are ‘since the function started’: after you stop and start the AMF, read again, and expect the counts to have returned to zero.

Change K = 4.0 to K = 5.0 in seasonal.py and rerun step 3, then try K = 3.0. At K = 4 the last rule gave 33 incidents in 14 days (2.4 a day) and caught the degradation after 3 windows. At K = 3 it gives 43 incidents (3.1 a day) and still catches it. At K = 5 it gives 14 incidents (1.0 a day) and misses the degradation, like the other three seasonal rules. Raising the threshold cut the false alarms, and it cut the real one too. With 10,000 cells, which K would you run, and what second signal would you add so that a 30% loss of traffic is caught without paging the NOC for every noisy afternoon? Then add a planned-state list: make the scoring skip the match night (day 17, quarter-hours 76 to 87) and see how many false alarm windows remain, and who in a real network would own that list.

DECIDE

Laolu's six-week pilot of a vendor's anomaly detector on Lumora's cell counters raised 61 alarms in week one. Tolani's shift closed 58 without action (sleeping cells, a market-day surge, planned work), and a sector failure in week five waited six hours in the queue. The vendor's slide says 92% accuracy, with no definition. Lumora's NOC can spare little time. What does Laolu recommend? All figures are illustrative.

READING
  1. DOC
    3GPP TS 23.288: Architecture enhancements for 5G System (5GS) to support network data analytics services 3GPP

    The specification of the NWDAF, the analytics function in the 5G core: what it can be asked for and how it gets its data. Read the architecture and the list of analytics it defines; skip the procedures on first reading. Pick the latest release in the folder. Read: the clauses on the architecture and on the analytics services.

  2. DOC
    3GPP: Management Data Analytics (MDA) 3GPP

    3GPP's overview of the management-side analytics (TS 28.104), the counterpart of the NWDAF. A short page to start from before you open the specification.

  3. DOC
    3GPP: AI/ML management for 5G systems 3GPP

    3GPP's overview of its work on managing AI and ML models inside the network (TS 28.105). Read it as a list of the things an operator has to keep track of once a model is deployed.

  4. DOC
    TM Forum: Autonomous Networks white paper TM Forum, 2019

    An early TM Forum paper on autonomous networks and the L0 to L5 levels of autonomy. Read the level definitions and the way each is scoped, then ask who acts and who checks at every level. Skip the vision sections on first reading.

  5. PAPER
    The base-rate fallacy and the difficulty of intrusion detection Stefan Axelsson, 2000

    The best short treatment of why a detector with a tiny false-alarm rate is still useless when real events are rarer. It is written about intrusion detection and applies to every alarm. The sections on the arithmetic are the ones to read. Read: ACM Transactions on Information and System Security, vol. 3, no. 3: the argument and the worked arithmetic on false alarm rates.

  6. PAPER
    Anomaly detection: a survey Varun Chandola, Arindam Banerjee, Vipin Kumar, 2009

    A map of what 'anomalous' can mean. The contextual kind (a value odd for its hour) is the one the lab's seasonal baseline targets. Skip the technique-by-technique catalogue first time. Read: ACM Computing Surveys, vol. 41, no. 3: the introduction and the sections on the kinds of anomaly and on contextual anomalies.

  7. PAPER
    Hidden technical debt in machine learning systems D. Sculley and colleagues, 2015

    What it costs to keep a model correct after the first deployment: drift, feedback loops where the model changes the data it learns from, and undeclared consumers. Read it before you let a model's output feed another system. Read: NeurIPS 2015: the sections on changes in the external world and on feedback loops.

  8. BOOK
    Google SRE workbook: Alerting on SLOs Google SRE

    The clearest framework for scoring any alert, and the source of precision, recall and detection time as the figures to ask for. It is about software services; the arithmetic applies to cell counters unchanged. Read: the discussion of precision, recall, detection time and reset time for an alert.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: the network questions a new virtual operator must answer →