Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions infra/chr/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@
SAMPLES = {
TemplateId.QUEUE_LIMIT: (
{"target": "10.0.0.42", "upload_mbps": 5, "download_mbps": 10},
["+/queue simple add", "name=netcortex-limit-10.0.0.42", "max-limit=5M/10M"],
["+/queue simple add", "name=nc-test-limit-10.0.0.42", "max-limit=5M/10M"],
),
TemplateId.FAILOVER_ROUTE: (
{"primary_gateway": "10.0.2.2", "backup_gateway": "192.0.2.1"},
["check-gateway=ping", "gateway=192.0.2.1", "netcortex:failover_route"],
["check-gateway=ping", "gateway=192.0.2.1", "nc-test:failover_route"],
),
TemplateId.PRIORITY_QUEUE: (
{"uplink": "ether1", "uplink_mbps": 90},
["new-packet-mark=netcortex-priority", "name=netcortex-uplink", "packet-mark=no-mark"],
["new-packet-mark=nc-test-priority", "name=nc-test-uplink", "packet-mark=no-mark"],
),
TemplateId.DNS_SERVERS: (
{"servers": ["1.1.1.1", "8.8.8.8"]},
Expand Down
99 changes: 99 additions & 0 deletions packages/agent/scripts/reliability.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""How often does Gemma produce a valid report with the right template, on e2e-like inputs?

uv run python packages/agent/scripts/reliability.py [--heavy 5 --down 3 --dns 3]

Builds each incident the way the live run sees it, without the database: the stand-in
injector's rows for sim-tower (30 min normal, then the incident for ONSET), the stand-in
detector, and the agent with the worker's settings (thinking off, temperature 0.2).
Needs the model server (OLLAMA_BASE_URL).
"""

import argparse
import asyncio
import random
from datetime import UTC, datetime, timedelta

import pandas as pd
from netcortex_agent import stub_detector, stub_injector
from netcortex_agent.agent import run_investigation
from netcortex_core import (
IFACE_COLUMNS,
PROBE_COLUMNS,
SUBSCRIBER_COLUMNS,
Cause,
MetricsWindow,
)

ONSET = timedelta(seconds=90) # incidents opened 60-150 s after injection in the e2e runs
SITE = stub_injector.SIM_SITE


def frames(parts, as_of: datetime) -> MetricsWindow:
data = [
pd.DataFrame([r.model_dump() for p in parts for r in p[i]], columns=list(columns))
for i, columns in enumerate((PROBE_COLUMNS, IFACE_COLUMNS, SUBSCRIBER_COLUMNS))
]
return MetricsWindow(
as_of=as_of, probe_metrics=data[0], iface_metrics=data[1], subscriber_metrics=data[2]
)


def incident(cause: Cause, seed: int):
rng = random.Random(seed)
now = datetime.now(UTC).replace(second=0, microsecond=0)
start = now - ONSET
window = frames(
[
stub_injector._rows(now - timedelta(minutes=30), start, None, rng),
stub_injector._rows(start, now + timedelta(seconds=1), cause, rng),
],
now,
)
return window, stub_detector.detect(SITE.id, window, frames([], now - timedelta(minutes=30)))


def right_params(cause: Cause, params: dict) -> bool:
template, expected, _ = stub_injector.EXPECTED[cause]
if cause is Cause.DNS_SLOW:
return "192.0.2.53" not in params.get("servers", ["192.0.2.53"])
return all(params.get(key) == value for key, value in expected.items())


async def main(counts: dict[Cause, int]) -> None:
rows = []
for cause, n in counts.items():
for run in range(n):
window, detection = incident(cause, seed=run)
report, stats = await run_investigation(SITE.id, detection, window, site=SITE)
template = stub_injector.EXPECTED[cause][0]
ok = not stats.fell_back and report.template_id == template
ok_params = ok and right_params(cause, report.template_params)
rows.append((cause, ok, ok_params, stats))
print(
f"{cause.value:12} run{run + 1} {stats.seconds:5.1f}s "
f"detector={detection.cause_guess.value:12} "
f"template={report.template_id.value:15} right={'Y' if ok else 'n'} "
f"params={'Y' if ok_params else 'n'} retries={stats.output_retries} "
f"fallback={stats.fell_back} {report.template_params}",
flush=True,
)
for reason in stats.retry_reasons:
print(f" retry: {reason}")
n = len(rows)
print(
f"\n{sum(r[1] for r in rows)}/{n} valid with the right template, "
f"{sum(r[2] for r in rows)}/{n} also with the right params; "
f"{sum(r[3].fell_back for r in rows)}/{n} failed validation twice (fallback), "
f"{sum(r[3].output_retries > 0 for r in rows)}/{n} needed a retry"
)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--heavy", type=int, default=5)
parser.add_argument("--down", type=int, default=3)
parser.add_argument("--dns", type=int, default=3)
args = parser.parse_args()
asyncio.run(
main({Cause.HEAVY_USER: args.heavy, Cause.UPLINK_DOWN: args.down, Cause.DNS_SLOW: args.dns})
)
14 changes: 13 additions & 1 deletion packages/fixes/src/netcortex_fixes/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
"""RouterOS fix templates: the only source of router commands."""

from netcortex_fixes.checker import DryRun, apply, check_fix, dry_run, rollback
from netcortex_fixes.checker import (
ApplyFailed,
DryRun,
apply,
check_fix,
dry_run,
failure_reason,
rollback,
)
from netcortex_fixes.errors import ParamError
from netcortex_fixes.router import RouterClient, RouterError
from netcortex_fixes.templates import (
Expand All @@ -10,17 +18,20 @@
get_template,
load_templates,
render,
tag_for,
templates_for,
validate,
)

__all__ = [
"ApplyFailed",
"DryRun",
"RouterClient",
"RouterError",
"apply",
"check_fix",
"dry_run",
"failure_reason",
"rollback",
"NONE_TEMPLATE",
"ParamError",
Expand All @@ -29,6 +40,7 @@
"get_template",
"load_templates",
"render",
"tag_for",
"templates_for",
"validate",
]
84 changes: 65 additions & 19 deletions packages/fixes/src/netcortex_fixes/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
dry_run: export -> apply -> export and diff -> roll back -> export and compare with the
original. A fix passes only if it applied cleanly, changed something, and rolled back to
exactly the original config.

Every object a fix creates is named after its incident (tag nc-1a2b3c4d), and rollbacks
target only those names. If an apply fails partway, only what it created is undone; config
that existed before is never removed or changed.
"""

import difflib
Expand All @@ -14,7 +18,7 @@
from netcortex_core import FixPlan, Settings, TemplateId, db, get_settings

from netcortex_fixes.router import RouterClient, RouterError
from netcortex_fixes.templates import get_template, render, validate
from netcortex_fixes.templates import TEST_TAG, get_template, render, tag_for, validate


@dataclass
Expand All @@ -24,7 +28,12 @@ class DryRun:
commands: str
rollback: str
diff: list[str] # config lines the fix added (+) or removed (-)
log: str
log: str # ends with "Result: passed" or "Result: FAILED: <reason>"
reason: str = "" # why it failed; empty if it passed


class ApplyFailed(RouterError):
"""A fix could not be applied. The message says what was (or wasn't) undone."""


def router_params(template_id: TemplateId, client: RouterClient) -> dict[str, Any]:
Expand All @@ -47,23 +56,51 @@ def _diff(before: list[str], after: list[str]) -> list[str]:
]


def dry_run(template_id: TemplateId | str, params: dict[str, Any], client: RouterClient) -> DryRun:
def _apply(client: RouterClient, commands: str, rollback: str, tag: str) -> str:
"""Run a fix's commands. On failure, undo only what they created, then raise ApplyFailed."""
before = client.export()
if tag in commands and any(tag in line for line in before):
raise ApplyFailed(f"objects named {tag}-* already exist on the router; nothing changed")
try:
return client.run(commands)
except RouterError as exc:
reason = str(exc)
if not _diff(before, client.export()):
raise ApplyFailed(f"{reason}; nothing was applied, so nothing was rolled back")
try: # partly applied: the rollback targets only this fix's own (tagged) objects
client.run(rollback)
except RouterError as exc:
raise ApplyFailed(f"{reason}; undoing the partial change also failed: {exc}") from exc
leftover = _diff(before, client.export())
if leftover:
raise ApplyFailed(f"{reason}; partial change NOT fully undone: {'; '.join(leftover)}")
raise ApplyFailed(f"{reason}; the partial change was rolled back")


def dry_run(
template_id: TemplateId | str,
params: dict[str, Any],
client: RouterClient,
tag: str = TEST_TAG,
) -> DryRun:
template_id = TemplateId(template_id)
if template_id is TemplateId.NONE:
return DryRun(True, {}, "", "", [], "Template none: no router change to test.")
params = validate(template_id, params | router_params(template_id, client))
commands, rollback = render(template_id, params)
commands, rollback = render(template_id, params, tag)
log = [f"Dry run of {template_id.value} on CHR at {datetime.now(UTC):%Y-%m-%d %H:%M:%S} UTC"]

def result(diff: list[str], reason: str) -> DryRun:
log.append(f"Result: FAILED: {reason}" if reason else "Result: passed")
return DryRun(not reason, params, commands, rollback, diff, "\n".join(log), reason)

before = client.export()
try:
log.append(client.run(commands))
applied = True
except RouterError as exc:
log.append(_apply(client, commands, rollback, tag))
except ApplyFailed as exc:
log.append(f"APPLY FAILED: {exc}")
applied = False
after = client.export()
diff = _diff(before, after)
return result([], f"apply failed: {exc}")
diff = _diff(before, client.export())
log.append("Config change:\n" + ("\n".join(diff) or "(none)"))

try:
Expand All @@ -77,13 +114,12 @@ def dry_run(template_id: TemplateId | str, params: dict[str, Any], client: Route
log.append("NOT RESTORED, differences from the original:\n" + "\n".join(leftover))

checks = {
"applied cleanly": applied,
"changed the config": bool(diff),
"rolled back cleanly": rolled_back,
"config restored exactly": not leftover,
"restored the config exactly": not leftover,
}
log.append("; ".join(f"{name}: {'yes' if ok else 'NO'}" for name, ok in checks.items()))
return DryRun(all(checks.values()), params, commands, rollback, diff, "\n".join(log))
return result(diff, ", ".join(f"not {name}" for name, ok in checks.items() if not ok))


def check_fix(
Expand All @@ -95,8 +131,9 @@ def check_fix(
) -> FixPlan:
"""Dry-run a proposed fix on CHR and store the result in fix_plans."""
client = client or RouterClient.chr(settings)
tag = tag_for(incident_id)
try:
result = dry_run(template_id, params, client)
result = dry_run(template_id, params, client, tag)
plan = FixPlan(
incident_id=incident_id,
template_id=TemplateId(template_id),
Expand All @@ -107,21 +144,27 @@ def check_fix(
dry_run_log=result.log,
)
except RouterError as exc: # CHR down: the plan is stored as not tested
commands, rollback = render(template_id, params)
commands, rollback = render(template_id, params, tag)
plan = FixPlan(
incident_id=incident_id,
template_id=TemplateId(template_id),
params=params,
commands=commands,
rollback=rollback,
dry_run_ok=False,
dry_run_log=f"Dry run could not run: {exc}",
dry_run_log=f"Dry run could not run: {exc}\nResult: FAILED: CHR unreachable",
)
with db.get_pool(settings).connection() as conn:
db.insert_fix_plan(conn, plan)
return plan


def failure_reason(plan: FixPlan) -> str:
"""The reason line a failed dry run ends with, for status notes and events."""
last = plan.dry_run_log.strip().splitlines()[-1] if plan.dry_run_log.strip() else ""
return last.removeprefix("Result: FAILED: ") if last.startswith("Result: FAILED") else ""


def _target(settings: Settings | None) -> Settings:
settings = settings or get_settings()
if settings.apply_target != "chr":
Expand All @@ -132,18 +175,21 @@ def _target(settings: Settings | None) -> Settings:
def apply(
plan: FixPlan, client: RouterClient | None = None, settings: Settings | None = None
) -> str:
"""Apply an approved, dry-run-tested fix to the CHR test router."""
"""Apply an approved, dry-run-tested fix to the CHR test router.

Raises ApplyFailed if it can't; only what this fix created is undone.
"""
if plan.decision != "approved":
raise RouterError("Refusing to apply a fix that has not been approved")
if not plan.dry_run_ok:
raise RouterError("Refusing to apply a fix that did not pass its dry run")
client = client or RouterClient.chr(_target(settings))
return client.run(plan.commands)
return _apply(client, plan.commands, plan.rollback, tag_for(plan.incident_id))


def rollback(
plan: FixPlan, client: RouterClient | None = None, settings: Settings | None = None
) -> str:
"""Undo an applied fix on the CHR test router."""
"""Undo an applied fix on the CHR test router (it removes only this incident's objects)."""
client = client or RouterClient.chr(_target(settings))
return client.run(plan.rollback)
25 changes: 21 additions & 4 deletions packages/fixes/src/netcortex_fixes/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from functools import cache
from pathlib import Path
from typing import Any, Literal
from uuid import UUID

import yaml
from jinja2 import StrictUndefined
Expand Down Expand Up @@ -179,10 +180,26 @@ def validate(
return clean


def render(template_id: TemplateId | str, params: dict[str, Any]) -> tuple[str, str]:
"""(apply commands, rollback commands) for validated params."""
TEST_TAG = "nc-test" # for checks outside an incident (unit tests, the CHR harness)


def tag_for(incident_id: UUID) -> str:
"""The name prefix of every router object one incident's fix creates: nc-1a2b3c4d."""
return f"nc-{str(incident_id)[:8]}"


def render(
template_id: TemplateId | str, params: dict[str, Any], tag: str = TEST_TAG
) -> tuple[str, str]:
"""(apply commands, rollback commands) for validated params.

Objects the fix creates are named after `tag`, and the rollback removes only those, so
fixes for different incidents never collide or remove each other's (or anyone's) config.
"""
if not re.fullmatch(r"nc-[0-9a-z]+", tag):
raise ParamError(f"bad tag {tag!r}")
template = get_template(template_id)
clean = validate(template.id, params)
apply = _jinja.from_string(template.apply).render(**clean).strip()
rollback = _jinja.from_string(template.rollback).render(**clean).strip()
apply = _jinja.from_string(template.apply).render(**clean, tag=tag).strip()
rollback = _jinja.from_string(template.rollback).render(**clean, tag=tag).strip()
return apply, rollback
Loading
Loading