diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..79eb7f5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Unified patch context lines intentionally encode a space followed by tabs. +netopsbench/platform/runtime/assets/*.patch -whitespace diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index bf37973..18102fb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -133,8 +133,8 @@ jobs: python -m pip install --upgrade pip pip install -e ".[dev,agent]" - - name: Generate benchmark assets (xs scale) - run: netopsbench benchmark prepare --scales xs + - name: Generate validation and default benchmark assets + run: netopsbench benchmark prepare --scales xs,medium - name: Run regression suite (no real-environment tests) run: | diff --git a/.gitignore b/.gitignore index 7c58455..6e3446d 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,6 @@ docs/.env.local docs/_legacy/ .playwright-mcp/ CLAUDE* + +# Locally built, reproducible runtime binaries +netopsbench/platform/runtime/_bin/ diff --git a/AGENTS.md b/AGENTS.md index 8580448..4391347 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,10 +104,10 @@ metadata: negative_sample: true ``` -For negative samples, the scenario runner should diagnose a representative -middle `fault_type: none` episode instead of skipping it. That episode waits, -collects healthy observations, and calls the agent. Ordinary `fault_type: none` -episodes that are not selected for diagnosis may still be skipped quickly. +Each scenario has one canonical `episode`. A negative sample uses +`fault_type: none`: it collects a complete healthy observation window and +calls the agent. Do not skip healthy scenarios or restore legacy multi-episode +selection logic. Scoring intent: diff --git a/README.md b/README.md index af1c117..54f5657 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ cd NetOpsBench python -m venv .venv source .venv/bin/activate pip install -e ".[agent]" +python -m netopsbench.platform.runtime.build_tools # verified official Containerlab v0.77.0 netopsbench benchmark prepare --scales xs export OPENAI_API_KEY=... @@ -72,6 +73,8 @@ PYTHONPATH=. python examples/01_run_scenario.py --vendor openai The first successful run produces a `BenchmarkReport` with case-level scores, timing, and artifact paths. For Docker, Containerlab, and runtime setup details, read [Quickstart](docs/content/docs/quickstart.mdx). +Runtime creation uses the official Containerlab v0.77.0 release, with Docker-managed networking and sequential SONiC startup. The installer verifies both the release archive and executable; it does not replace the system Containerlab or modify Docker. Prepare the private tools after installation and configure privileged operations as described in Quickstart. Build the current client image with `docker build -f containers/client/Dockerfile -t netopsbench-client:pingmesh-v2 .`. Pingmesh uses one immutable offline plan for execution, coverage checks, and observation windows. Xlarge has 256 clients and a 66-second minimum window; Fat-tree K12/K18 use 42 seconds. K18 has 405 switches and 324 clients. Regenerate scenario assets with `netopsbench benchmark prepare --scales xlarge,fat-tree-k12,fat-tree-k18` and recreate runtimes after this refactor; previous artifact formats are rejected. `NETOPSBENCH_CLIENT_IMAGE` selects a matching custom image. + ### Run a scenario from Python ```python @@ -100,9 +103,10 @@ NetOpsBench reports detection, fault type, device/interface localization, runtim | Small | CLOS | 6 | 8 | 15 | | Medium | CLOS | 12 | 16 | 28 | | Large | CLOS | 20 | 64 | 52 | -| Xlarge | CLOS | 144 | 128 | 70 | +| Xlarge | CLOS | 144 | 256 | 70 | | Fat-tree K=8 | Fat-tree | 80 | 128 | 70 | | Fat-tree K=12 | Fat-tree | 180 | 144 | 70 | +| Fat-tree K=18 | Fat-tree | 405 | 324 | 70 | **Diagnosis score** is the mean end-to-end case score: healthy cases require the correct verdict, while fault cases receive localization credit only after the fault is detected. **Fault detection F1** measures the fault-versus-healthy decision independently. diff --git a/docs/content/docs/architecture/core-simplification.mdx b/docs/content/docs/architecture/core-simplification.mdx new file mode 100644 index 0000000..3fa52df --- /dev/null +++ b/docs/content/docs/architecture/core-simplification.mdx @@ -0,0 +1,125 @@ +--- +title: Core Simplification Audit +description: 第二轮内部表示、重复执行逻辑与资源清理的精简依据和验证记录。 +--- + +本轮以 `.netopsbench/refactor-round2-before/` 的工作区快照为基线,包含上一轮 +成果和操作者已有未提交改动。公开 SDK、CLI、工具 schema、示例及扩展能力保留; +内部辅助方法和测试替身随新的内部约定迁移。故障分类、评分与冻结 campaign 不变。 + +## 如何判断可删除 + +核对 Python 导入、SDK 懒加载映射、CLI entry points、示例、验收脚本、故障注册表, +并追踪 `read_text` 后送入容器执行的资源。静态入口图最初未到达的四个模块均有 +实际职责:`_bgpd_restore`、`_routing_probe`、`_sonic_probe` 在容器内执行, +`build_tools` 是文档公开的工具链安装入口。它们全部保留。 + +没有发现可以仅凭本次证据整包删除的大块代码。精简针对已确认的重复行为及 +构造器不变量排除的分支。低覆盖率、没有直接 import、仅测试引用,均不单独 +作为删除公开功能的依据。静态可达性分析不能证明所有异常组合都已真实执行。 + +## 逐模块处理 + +| 模块 | 检查结果与处理 | +|---|---| +| models / topology | 规范 manifest 已统一设备列表、角色与有效 MTU;保留 Clos/Fat-tree 构建、公开拓扑投影和配置渲染 | +| toolkit | BGP 角色直接取 manifest.switches;删除分组字典的旧形态分支;保留 SONiC/Linux、接口别名、历史查询和实时 fallback | +| pingmesh | client→leaf 映射直接取 manifest;删除先投影成 agent 拓扑再解析回内部映射的路径;覆盖、ingestion 与异常分析仍各有职责 | +| traffic | 删除旧拓扑字段逐级推断 MTU;共用带宽单位解析,估算仍为浮点数、下发仍为整数;规划、限速、控制事务和客户端就绪验证保留 | +| scenario | 新增一次 begin_case 初始化,两个入口共用;明确初始化案例字段,删除对这些必备成员的 getattr 回退;基线身份、窗口与恢复审计保留 | +| incident / simulator | StepResult 继承共同 transition 字段,保留公开名称、必填 flags、冻结和序列化语义;保留 reset/step、prepare/session 和 terminate_protocol 能力 | +| runtime | 正常销毁与部署补偿共用目录清理和隔离记录;生命周期阶段、bucket 所有权与重试规则继续由各入口明确选择 | +| session | 成功/失败诊断统一 trace 收尾;ATIF 的复制上下文去重只保留一个算法;保留无 recorder 的 tool_calls fallback、失败报告和 Harbor 导出 | +| evaluator / SDK | 共用 DiagnosisResult 基础字段转换,显式保留入口优先级;删除丢弃的 ground-truth index 参数及无职责结果转发;已归一化 evaluator 报告不再二次归一化 | +| agents | AgentHandle、同步/异步诊断及 recorder 是公开扩展链路;保留,不用单一内置 agent 的调用方式裁剪 | +| faults | 注册表、FaultSpec/FaultPack、ActiveFault、周期任务控制与补偿均有调用;保留直接注入和扩展回调,不合并不同故障机制 | +| observability | BGP 采集、事件索引、spool 与确认后删除是不同职责;保留完整数据链路;BGP 两种查询来源仅共用事件分类及输出 | +| client_agent | native 流量/探针进程及控制接口实际部署到设备,保留协议和资源 | +| CLI / scripts / utils | 正式命令、独立验收、工具链安装和容器内脚本保留;取消保护、deadline、计时与路径处理不是死代码 | + +## 具体删除与合并依据 + +| 候选 | 调用链 / 不变量 | 结果与验证 | +|---|---|---| +| BGP 旧设备分组解析 | AgentToolkit 构造器已校验 manifest,内部设备是规范列表 | 改读 manifest;公开 BGP 查询测试及旧实现输出对照 | +| Pingmesh 私有拓扑重解析器 | 仅构造器从 manifest 投影后调用 | 删除 helper;通过真实构造器验证 Clos/Fat-tree 的 attached_switch 映射 | +| MTU 多字段 fallback | traffic 入口先校验 manifest,defaults.link_mtu 必为正数 | 直接取规范值;流量生成与限速测试 | +| 两个带宽解析器 | estimator 与控制器均解释 K/M/G 单位 | 共用解析;调用端保留空值处理及整数转换,不放宽无效下发参数 | +| 两份案例重置 | run_scenario 与 RuntimeEpisodeBackend.prepare 各自重置同类字段 | 调用 begin_case;清空案例证据,保留流量与已验证基线对象 | +| StepResult 字段复制 | 与 SessionTransition 字段相同,只有 valid/case_valid 必填性不同 | 继承字段并显式重声明两个必填项;schema、序列化及 frozen 测试 | +| 两份 trace 写入及引用回填 | 同一个回调的成功/失败分支使用相同落盘参数 | 只保留一次写入,失败信息在进入收尾前构造;已有 tracing/失败报告测试 | +| 两份复制上下文去重 | recorder 规范化与 ATIF 输出重复同一去重状态机 | 共用算法;保持原始 index、上下文顺序及运行事件后的过滤规则 | +| BGP 重复分类与 collection_gap 输出 | fast/snapshot 的时间线不同,分类和字段语义一致 | 保留来源解析;共用输出,5832 组旧/新输出逐项相等 | +| 多处清理错误记录与目录删除 | 正常销毁和补偿都需要验证目录消失并保留隔离状态 | 共用原语;正常销毁按所属 bucket 清理,provision 仅清理本事务创建的 bucket | +| SDK index 与报告转发 | 单 episode ground-truth 不使用 index;registry 返回的 adapter 已返回 BenchmarkReport | 删除内部无效参数和二次归一化;公开 testcase ID、接口和扩展 evaluator 形式不变 | + +仍保留的薄封装有明确用途:SDK 稳定入口、故障注册回调、可替换的观察操作、 +带取消检查/审计/计时的操作方法。没有用动态方法生成或通用大基类替代显式实现。 + +## 统一后的执行关系 + +```mermaid +flowchart TD + M[规范 TopologyManifest] --> P[Pingmesh client映射 / 流量MTU / BGP角色] + B[Benchmark run_scenario] --> C[begin_case] + S[模拟器租约后 prepare] --> C + C --> E[共同 IncidentEngine / ExecutorIncidentBackend] + E --> W[完整基线、故障观察、恢复验证] + D[DiagnosisResult] --> N[共用基础字段转换] + N --> A[SDK 独立评分] + N --> R[运行诊断 payload] + R --> T[一次 trace 收尾] + T --> F[ATIF / 报告] + X[正常 teardown] --> Q[共同清理原语与隔离记录] + Y[provision 失败补偿] --> Q +``` + +诊断入口差异显式保留:SDK 已有 location 时不补平铺字段,runtime 按字段补全; +SDK 可以读取 metadata.evidence 和 findings.tool_calls,runtime 保留其原优先级。 +runtime 耗时取实际计时,SDK 独立评估使用传入 metadata 耗时。缺失诊断仍为 +inconclusive,已有有效评分继续复用。 + +BGP 索引未覆盖窗口时仍查询完整快照;不同来源的状态时间线、前缀时间戳一致性 +及样本数量计算没有合并成假定等价的数据。自定义非 catalog-v2 故障也继续保留。 + +## 单列的行为修复 + +正常 teardown 原来可能漏掉“deployment_started 已置位,但中断发生在阶段结果 +写入前”的资源;现在将该状态视为已开始部署。清理抛错后即使隔离元数据写入 +再次失败,也保留原始异常与内存中的隔离记录,不用持久化异常覆盖根因。 +这些属于清理正确性修复,不作为纯等价重构描述。 + +目录清理统一先尝试本地删除,仍存在时才调用非交互 sudo;最终必须确认目录 +消失。不同入口的 bucket 所有权规则不合并,避免补偿时删除非本事务资源。 + +## 验证与规模统计 + +最终完整离线回归:1252 项通过(274.63 秒)、8 项 real 测试不在离线执行, +2 条第三方 websockets 弃用警告。包含 BGP 双路径组合及已有测试 49 项, +以及显式 Clos / fat-tree-k8 映射及查询测试 12 项。新旧 BGP 输出对照 5832 组相等。 +配置范围内 mypy 检查通过(84 个源文件);Ruff、干净 wheel 契约和差异检查通过。 + +首轮完整回归的 7 项失败来自绕过构造器、缺少新内部成员的测试替身,已迁移 +并复测。健康观测、私有证据隔离、恢复超时等原有断言保留,没有删去失败测试。 +新增公开 StepResult 必填字段、冻结语义、诊断来源优先级、案例重置及清理中断测试。 + +真实验收:medium 的健康、loss、ECMP、route_flapping 及各自后续健康案例 +共 7 例通过;XS 的健康、link_down、bgp_auth_mismatch 及各自后续健康案例 +共 5 例通过。所有案例有效且恢复成功,专用 runtime 的容器、网络和目录均已移除。 +真实 BGP 故障窗口的自动查询路径与强制完整快照回退均返回 spine1、leaf2 的 +`session_down` 证据;自动路径未额外插桩,不据此断言它必然选择了快速索引。 + +| 范围 | 新增行 | 删除行 | 净变化 | +|---|---:|---:|---:| +| 核心 Python | 245 | 449 | -204 | +| 脚本及示例 Python | 0 | 0 | 0 | +| 测试 Python | 232 | 39 | +193 | +| 文档 | 127 | 1 | +126 | + +统计相对本轮开始快照,包含注释和空行;不把上一轮改动或移动文件计算成删除 +收益。核心代码没有搬到脚本/测试目录,核心净减少 204 行。此次收益是减少重复 +行为的维护点,未声称有新的端到端性能提升。 + +逐文件差异统计与验证凭据位于 `.netopsbench/refactor-round2-verification/`; +真实案例记录位于 `.netopsbench/refactor-round2-medium/audit.json` 与 +`.netopsbench/refactor-round2-xs/audit.json`。它们是本地运行产物,不作为源码提交。 diff --git a/docs/content/docs/architecture/meta.json b/docs/content/docs/architecture/meta.json index 56517fe..a1ae0a8 100644 --- a/docs/content/docs/architecture/meta.json +++ b/docs/content/docs/architecture/meta.json @@ -1,4 +1,10 @@ { "title": "Architecture", - "pages": ["system-overview"] + "pages": [ + "system-overview", + "runtime-audit", + "core-simplification", + "state-checked-recovery", + "recovery-v2-audit" + ] } diff --git a/docs/content/docs/architecture/recovery-v2-audit.mdx b/docs/content/docs/architecture/recovery-v2-audit.mdx new file mode 100644 index 0000000..20ab7b0 --- /dev/null +++ b/docs/content/docs/architecture/recovery-v2-audit.mdx @@ -0,0 +1,181 @@ +--- +title: Recovery v2 cleanup audit +description: 单一恢复流程的删除依据、兼容边界与验证记录。 +--- + +> 本页记录历史 v2 行为及实测,包含当时的 600 秒限制。当前策略见 +> [State-checked Recovery](./state-checked-recovery),v3 不再使用基线年龄上限。 + + +## 起点与执行链 + +本轮起点为 `bf09430`。保留用户目录 `presentations/`,不修改冻结场景文件。 + +```text +SDK / CLI:新建 v2,或显式迁移旧场景 + → 部署前验证 recovery_policy + → session 按 runtime 所有权和 keep_runtime 传递销毁意图 + → IncidentEngine / ExecutorIncidentBackend + → 有界健康基线:10 次 / 600 秒 / 环境身份 + → 校准(需要时)→ 注入 → 观察 → 诊断 + → 恢复回调及回读 → 两轮全设备状态检查 + → 状态通过:恢复原基线复用资格 + → 异常后恢复:完整校准;残留或证据不足:失败隔离 + → 保留或外部 runtime:末尾校准 + → 确定销毁:记录跳过末尾窗口,执行并验证销毁 +``` + +完整校准仍是公共执行核心的一项内部能力。`full_window` 只作为私有报告的 +验证等级保留,不再是运行模式;Pingmesh 异常持续性中的同名值语义不同,也保留。 + +## 删除依据 + +| 删除/收敛项 | 原调用者及输入不变量 | 保留的行为与验证 | +|---|---|---| +| 旧恢复模式与版本兼容执行分支 | 所有执行入口现在要求 v2;旧配置在部署或获取租约前拒绝 | 显式迁移、SDK/CLI、旧报告读取测试 | +| `post_recovery_wait_seconds` 及多层参数传递 | 只供旧模式在撤销后固定等待;新流程按条件收敛 | 共享 deadline、收敛重试、双轮状态验证测试 | +| 单次消费基线、独立 epoch 刷新入口 | 所有案例使用有次数和年龄上限的已验证基线 | 第 10/11 次、600 秒、失败失效和环境变化测试 | +| prepare 内独立基线采集/查询分支 | 缺少可复用基线时必须调用统一校准入口 | 完整窗口只采一次;不健康及不完整窗口拒绝执行 | +| `wait_and_observe` 及 executor 转发 | 唯一生产调用者是已删除的旧恢复窗口分支 | 查询时间范围和 deadline 测试迁到采集/分析边界;计时迁到校准入口 | +| 健康案例观察窗口候选与发布回退 | 新流程只有完整校准可以更新健康基线;每例状态恢复不刷新窗口 | 健康案例仍观察和诊断;绝对健康证据缺失不能通过校准 | +| 旧模式末尾再次比较旧 FIB 快照 | 新流程已在两轮实时采集中比较 FIB | 邻居身份、下一跳和再次变化的行为测试保留 | +| `valid_window` 纯转发 | 生产代码没有调用者,测试直接使用 `window_error` | 窗口长度、时间边界及错误原因测试保留 | + +故障注册表、恢复回调、自定义 agent/evaluator、容器资源脚本、遥测 fallback、 +接口别名和历史报告解析不属于本轮废弃项。未将“无直接 import”视为不可达证明。 +未实施 Docker 同阶段采集去重;本轮性能变化来自校准调度策略。 + +## 单列行为修复 + +完整校准失败后记录失败状态,后续状态检查不能重新授予健康基线复用资格。 +校准必须提供绝对不可达、丢包和 MTU 健康证据;缺失不能按零处理。错误窗口 +保存在私有阶段记录中,不进入 agent 输入。对应负向测试检查失败隔离与证据保留。 + +验收脚本的影子校准恢复原基线、消费次数和校准状态,避免影子窗口延长正式 +基线寿命;影子失败仍使验收失败。首次实测发现脚本残留的 `mode` 读取,修复后 +重新运行;失败试跑记录保留,环境已销毁,不计作通过验收。 + +取消边界修复:session 现在也会在 `KeyboardInterrupt` 等中断后执行既定销毁, +并分别保留执行中断和清理错误,避免跳过末尾窗口后遗漏销毁。该路径以生命周期 +回归验证;真实故障验收驱动直接调用 executor,不经过 session 编排层。 + +## 兼容与迁移 + +公开 `RecoveryPolicy` 名称保留,删除 `mode` 参数,版本必须为 2。 +默认最大使用次数为 10、最大窗口年龄为 600 秒。旧场景显式迁移: + +```bash +netopsbench scenario migrate SOURCE --out NEW_DIRECTORY +``` + +输出新的 scenario 摘要及迁移 campaign 身份,保留案例 ID、故障参数和实验配置。 +`migration.json` 及各场景的 `recovery_migration` 记录源文件摘要和原场景摘要。 +目标必须不存在且不能位于源目录内;读取和验证全部场景后才发布输出。 +历史报告不需要迁移;冻结场景不做运行时隐式覆盖。迁移针对现有单 episode +场景,更早的 multi-episode 格式仍需重新生成。 + +## 验证记录 + +2026-11-05 最终源码离线测试:**1282 通过、8 项 real 未纳入**,278.76 秒。 +包括干净 wheel 契约;另有两条既有 websockets 弃用警告。重点恢复/迁移回归 +89 项通过,生命周期及中断补测 5 项通过,验收驱动计数/影子隔离补测 2 项通过;Ruff、配置范围内 Mypy +(85 个源文件)和差异检查通过。真实环境:XS 5 个案例及 5 次影子检查通过;medium 全故障/子机制 27 个案例通过, +25 次撤销残留检查全部拒绝放行;独立 medium 影子验收 28 个案例、28 次完整窗口通过。 +独立 XS 时效实测在首例后真实空闲 610 秒,第二例以 `expired_window` 触发校准; +两例通过,链路恢复出现收敛重试后的补充校准也通过。以上 runtime 均已销毁。设备关闭的正常恢复通过,但其 Containerlab 激活路径 +不经过现有抑制钩子,真实负向测试仍未覆盖。性能结果见下文。原始产物位于 +`.netopsbench/unified-recovery-*` 和 `.netopsbench/unified-performance-*`,不提交到源码。 + +验收分阶段进行,原始报告记录各次源码指纹:全故障/残留验收为 `fcf38632ad02`, +补充完整校准失败保护后的全故障影子验收为 `361ee8248b5f`;之后修改 session +中断收尾,并删除一个前置判断已排除的重复空值分支。最终源码 `8c478114d6df` +通过上述全量离线测试,并用于全部新版性能运行。独立时效测试为删除重复判断前的 +`c3e272b4095c`。真实验收驱动不经过 session 编排层,不能将其当作中断销毁实测。 +历史对照从 `bf09430` 独立导出,使用相同的固定 Containerlab 0.77.0 工具链; +首次因导出目录缺少本地工具清单在部署前失败,修正工具路径后重跑,失败预检记录保留。 + +本次 k=18 容量预检被拒绝:虽然采样时可用内存约 197.4 GB 高于估算需求 +145.7 GB,但现有容量样本最多只有 3 个数据端口,k=18 需要 11/18 端口设备。 +容量规则禁止用这种端口外推直接批准 k=18 部署,因此未绕过预检。 + +## 性能对照(v2,2026-11-05) + +对照为独立导出的 `bf09430` 的 **state_checked v1(5 次 / 600 秒,末尾校准)**, +不是更早的 full_window 模式。新版为 v2(10 次 / 600 秒,确定销毁时跳过末尾校准)。 +medium,1 worker,12 个路由设备、16 个 client、64 条背景流;镜像已缓存, +每批独立部署并销毁。相同案例定义、seed、30 秒观察窗口、采样配置及 minimal +确定性工具脚本,不调用 LLM、不启用影子窗口和残留钩子。三组新旧交替串行运行。 +下表生命周期耗时包含部署、全部案例、所有校准和销毁。 + +| 六例序列,三次平均 | bf09430 | v2 | +|---|---:|---:| +| 序列耗时,含全部校准 | 395.3 秒 | 308.2 秒 | +| 完整生命周期 | 462.8 秒 | 377.3 秒 | +| 部署与预热 | 58.0 秒 | 59.2 秒 | +| 首次完整校准 | 41.5 秒 | 41.0 秒 | +| 第六例前周期校准 | 42.4 秒 | — | +| 末尾完整校准 | 42.5 秒 | —(销毁) | +| 每例恢复 P50 / P95 | 6.72 / 7.39 秒 | 6.47 / 7.18 秒 | +| 仅故障例恢复 P50 / P95 | 6.86 / 7.42 秒 | 6.59 / 7.29 秒 | +| 完整校准次数 / 批 | 3 | 1 | +| 序列 Docker CLI 调用 / 批 | 449 | 411 | +| 序列 Influx 查询 / 批 | 68 | 49 | +| 异常回退 / 案例 | 0 / 18 | 0 / 18 | + +序列耗时减少 **22.0%**,完整生命周期减少 +**18.5%**;序列 Docker 调用减少 +**8.5%**、Influx 查询减少 **27.9%**。 +每例恢复时长基本不变,主要收益来自少做两次完整校准;本轮未改变设备采集实现。 +Docker/Influx 计数覆盖案例及末尾校准,不包含部署与销毁;部署计数在原始记录中单列。 +恢复分位数由各版本 18 个样本(故障例 12 个)线性插值计算。 + +| 轮次 | bf09430 序列 / 生命周期 | v2 序列 / 生命周期 | +|---|---:|---:| +| 1 | 387.6 / 453.9 秒 | 309.1 / 378.8 秒 | +| 2 | 391.0 / 456.2 秒 | 310.0 / 378.8 秒 | +| 3 | 407.3 / 478.1 秒 | 305.5 / 374.3 秒 | + +另各执行一批相同的 **12 例连续序列**,24 例全部通过,无异常回退: + +| 12 例,单次验证 | bf09430 | v2 | +|---|---:|---:| +| 序列耗时 | 698.0 秒 | 619.0 秒 | +| 完整生命周期 | 766.5 秒 | 687.9 秒 | +| 校准位置 | 首次、第 6/11 例前、末尾 | 首次、第 11 例前 | +| 校准耗时(按上述顺序) | 41.3 / 42.9 / 42.0 / 41.9 秒 | 39.7 / 43.0 秒 | +| Docker / Influx 调用 | 860 / 118 | 822 / 100 | + +长序列完整生命周期减少 **10.3%**,周期校准成本已计入。 +短序列的收益比例不能直接外推到长批次、较慢的 LLM 诊断、经常触发异常回退的 +故障组合或未实测的 k=18。长序列仅各测一次,不作为稳定分位数估计。 +所有 60 个性能案例通过;本轮 13 个专用 runtime(含早期失败试跑)均已销毁, +最后按 lab 身份检查 Docker 容器及网络,无残留。 +汇总:`.netopsbench/unified-recovery-verification/performance.json`; +清理核查:同目录 `cleanup.json`。 + +复现新版短序列(使用新的输出目录;两种版本应串行、交替运行): + +```bash +PYTHONPATH=. python scripts/validate_runtime_refactor.py \ + --scale medium --fault-types packet_loss ecmp_misconfig \ + --compact-sequence --sequence-repeats 2 --tool-profile minimal \ + --capacity-sample /path/to/xs-capacity.json --output /path/to/new-output +``` + +长序列使用 `--sequence-repeats 4`。旧版独立快照额外指定 +`--recovery-mode state_checked`;12 例验收仅将旧驱动的 repeats 参数上限从 3 扩为 4, +未修改旧版执行核心。新旧共享显式 `NETOPSBENCH_RUNTIME_TOOLS` 指向的已校验工具链。 + +## 代码变化统计 + +相对本轮起点 `bf09430`,核心 Python 代码新增 189 行、删除 267 行,**净减少 78 行**。 +统计包含新迁移模块,不排除新功能以放大缩减收益;本轮没有移动文件。 +测试增加主要来自显式 v2 夹具迁移、校准与迁移负向测试,不作为核心精简收益。 +完整分类统计保存在 `.netopsbench/unified-recovery-verification/diff-stats.json`。 + +| 分类 | 新增 | 删除 | 净变化 | +|---|---:|---:|---:| +| 核心代码 | 189 | 267 | -78 | +| 测试 | 421 | 147 | +274 | +| 验收脚本 | 27 | 12 | +15 | +| 文档 | 208 | 22 | +186 | diff --git a/docs/content/docs/architecture/runtime-audit.mdx b/docs/content/docs/architecture/runtime-audit.mdx new file mode 100644 index 0000000..67e15dc --- /dev/null +++ b/docs/content/docs/architecture/runtime-audit.mdx @@ -0,0 +1,272 @@ +--- +title: Runtime Audit and Migration +description: 本地模拟器与 benchmark 的执行边界、故障证据、精简依据与验证记录。 +--- + +本次整理以当前工作区(包括既有未提交改动)为基线,保留本地 SDK、benchmark、 +MCP、自定义 agent 和故障扩展。下面区分代码检查、离线验证和真实环境验证, +不将模拟测试结果视为真实故障效果。 + +## 执行链路与职责 + +```mermaid +flowchart TD + B[Benchmark: 调度与报告] --> E[IncidentEngine] + S[本地模拟器: 租约与 reset/step] --> E + E --> P[ExecutorIncidentBackend.prepare] + P --> T[流量就绪] + T --> H[验证基线身份/时效或采集一个完整基线] + H --> I[注入或健康观察] + I --> O[固定窗口采集与分析] + O --> V[私有效果与完整性校验] + V --> D[公开观察与 DiagnosticSession] + D --> Q[MCP / 受限工具注册表] + D --> A[提交诊断与统一评分] + A --> C[关闭 incident] + C --> R[恢复、健康/配置/路由验证] + R --> W[发布已验证基线或隔离 runtime] +``` + +RuntimePool 仍依次部署设备、配置观测、启动 native client-agent、检查健康。 +Pingmesh 是观察路径;FaultInjector 是修改网络状态的路径。二者不相互替代。 + +模拟器不再维护第二套基线缓存,也不再用第二段采集窗口验证第一段基线。 +两种入口共用流量、基线、注入、观测、效果和恢复实现。基线复用保留时效、 +配置/实例/流量身份、恢复发布和重新查询晚到数据的限制。历史 `full_window` +模式仍单次消费;新 `state_checked` 模式采用有界复用与独立校准,详见 +[恢复策略及迁移](./state-checked-recovery)。 +发现未恢复的 active fault 时拒绝准备新案例,由清理路径处理残留。 + +租约池只在锁内操作记录与容量,部署和销毁在锁外执行。预留容量计入上限; +部署补偿失败及销毁失败的记录继续占用容量且不可出租。drain 等待在途部署, +不会遗漏刚完成的资源。incident 关闭还会等待已开始的工具调用结束,避免查询 +与恢复同时访问正在变化的设备。 + +## 公开证据与私有实现 + +| 信息 | 处理 | +|---|---| +| 接口 admin/oper、MTU、地址、计数器 | 保留;支持接口别名过滤 | +| FRR 配置、RIB、kernel FIB、ACL 规则和计数 | 保留,是诊断对象的真实状态 | +| netem/qdisc 参数及实现名称 | 不在接口任何格式中返回;只保留在私有效果审计 | +| 注入目标、参数、机制、恢复日志、评分答案、内部路径字段 | 从公开结构中递归移除 | +| 工具执行/采集错误 | 公开失败标志和通用错误,不返回内部异常文本 | +| 拓扑自定义 metadata | 仅保留 pod、rack、client_subnet、site、edge_index、pod_index 的标量值 | +| 语义化 episode ID、worker 环境变量及本地路径 | 不进入自动构建的诊断 context | +| 原始执行和恢复失败 | 留在操作者持有的 incident/运行报告;交互返回使用通用错误 | + +新增投影应用于 stdio MCP、会话后端和初始公开观察。它是结构化输出边界, +不是对同进程任意 Python 代码的安全沙箱。自定义本地 agent 是受信任代码; +不能依靠 SDK 对象封装阻止其读取宿主文件或反射私有对象。Codex 示例继续使用 +独立容器和会话 MCP。正常设备配置/日志文本仍保留其诊断含义,不做关键词盲删。 + +接口工具的 raw 输出移除的是 ip-link 头部 qdisc 字段,不删除 MTU、状态或错误计数。 +实时结果包含 `collected_at`;历史日志和接口指标使用 topology 身份及 episode 默认 +时间范围,并返回 `time_scope`。实时 fallback 有单独采集时间,不充当历史样本。 +周期故障可能在实时查询瞬间恢复,必须结合完整时间窗判断。 + +## 问题与修复清单 + +| 问题 | 修复及验证边界 | +|---|---| +| 工具通过 tc 参数或 ip-link 原始头部暴露注入实现 | 删除 include_tc;私有审计独立读取 qdisc;所有接口格式验证无实现标记 | +| interface 参数未真正过滤状态与地址 | 同时过滤 SONiC 表、Linux fallback 和地址;别名等价匹配;不存在的接口失败 | +| 清理抛错后再次访问未赋值 cleanup_result,掩盖根因 | 先保存失败结果,再清空基线并原样抛出;执行失败和清理失败分别记录 | +| 部署补偿失败或中断丢失资源所有权,可能错误释放容量 | 捕获中断并补偿;RuntimeProvisionError 分别携带原始/清理异常及 runtime;即使隔离元数据写入失败也保留资源,池禁止再次出租 | +| 慢部署/销毁占用租约条件锁 | 锁内预留与发布,锁外执行;同步事件测试验证续租、释放和容量约束 | +| 关闭 incident 与在途工具查询交错 | 关闭等待已开始的工具调用结束,锁内再次检查 ACTIVE | +| 模拟器独立基线签名与重复验证窗口 | 委托共同 backend;同一基线身份、单次消费、时效和恢复发布规则 | +| 历史指标/日志与当前案例窗口不一致 | 使用 episode 时间范围与 topology 过滤;实时 fallback 单独标注采集时间 | +| 接口指标 fallback 重复采集,工具 schema 反复构造 | 同一请求采集一次;缓存静态 TypeAdapter,不缓存跨注入边界的设备状态 | +| 无诊断结果被默认视为健康 | 缺失 verdict 默认 inconclusive;保留负样本原评分语义 | +| 有保存评分时仍重建 ground truth | 只有独立评分分支构造 ground truth;测试禁止复用路径访问拓扑或再次调用 evaluator | +| 服务采集异常和 ping 执行错误带出内部信息 | 按采集来源处理异常;保留 ping 丢包与本地 MTU 错误;公开状态不附加查询异常文本 | +| 删除源码后旧构建缓存仍将 HTTP 服务装入 wheel | 从干净副本执行 wheel 契约测试,检查模块与 console script 均不存在 | + +## 故障证据矩阵 + +下表覆盖 catalog v2 的全部 24 类以及健康样本。生效检查是案例有效性判定, +公开证据是 agent 可查询的依据。恢复还要经过共同的健康、配置及路由验证。 + +| 类型 | 前置条件与修改 | 生效/公开证据 | 恢复依据及注意事项 | +|---|---|---|---| +| link_down | 可读且原本正常的链路端点;关闭接口 | admin-down、邻接和探针变化 | 恢复两端拥有的状态及路由;不覆盖预存 down 状态 | +| link_flapping | 正常链路;周期关闭/恢复 | 验证过的周期阶段(私有)、接口与 BGP/Pingmesh 时序(公开) | 停止周期任务后恢复;线程未退出不能报成功 | +| interface_ip_misconfig | admin-up 且 SONiC/live 地址一致;替换 IP | 实际地址变化、邻接/连通变化 | 保存并恢复原地址;避免先删最后一个地址 | +| device_down | 节点正常运行;Containerlab stop | 节点停止、邻居与路径影响 | start、停车 namespace/链路状态和健康验证 | +| bgp_process_down | bgpd 正在运行;停止服务 | 节点仍可达、bgpd STOPPED、BGP 缺失 | 恢复服务和捕获的原配置 | +| packet_loss | 可拥有的默认 qdisc;netem loss | 私有规则回读,公开实测丢包增量 | 删除自身 qdisc 并回读;不覆盖外部 qdisc | +| packet_corruption | 可拥有的默认 qdisc;netem corrupt | 私有规则回读,当前公开证据主要是丢包 | 同上;没有独立 CRC/payload 损坏观测 | +| high_latency | 可拥有的默认 qdisc;netem delay | 相对基线的实测 RTT 增量 | 删除并验证 qdisc;区分注入 delay 与实际 RTT | +| mtu_mismatch | 可读取原 MTU;降低接口 MTU | 实际 MTU、小包/DF 大包差异 | 恢复原 MTU 并回读;区分本地 probe 错误 | +| blackhole_route | 目标前缀可配置;加入丢弃路由 | 实际 RIB/FIB 的 discard 与通信影响 | 删除拥有的路由并验证 | +| static_route_misconfig | 目标存在可构造的错误下一跳 | 配置、FIB、路径和可达性 | 移除拥有的静态路由;补偿失败保留残留 | +| routing_loop | 存在可形成返回路径的邻居 | 两端 FIB 循环与真实 TTL 耗尽/重复跳点 | 撤回静态路由;不能只凭注入命令认定成环 | +| bgp_as_mismatch | 邻居原本 Established;改 remote-as | 配置、邻居状态/错误 | 恢复原邻居选项 | +| bgp_auth_mismatch | 邻居原本 Established;改认证 | 两端配置、会话状态和日志 | 恢复原认证选项 | +| bgp_update_source_mismatch | 邻居 Established、选择的源接口不存在 | update-source 配置与实际接口不符 | 恢复原选项;旧案例保留旧默认 | +| bgp_neighbor_shutdown | 邻居 Established;设置 shutdown | 配置与邻居状态 | 恢复原 shutdown 状态 | +| bgp_max_prefix_misconfig | 原接收前缀至少两个;降低阈值 | 阈值、前缀数及明确的 prefix-limit 错误 | 恢复阈值并重新建立会话 | +| route_origination_misconfig | 本地产生目标前缀;撤 network 或拒绝起源策略 | RIB、通告、FIB 变化 | 恢复 network/原策略,移除拥有的策略对象 | +| route_filter_misconfig | 邻居和前缀前置条件满足;import/export 策略 | 两端通告、策略、FIB 的缺失或下一跳减少 | 恢复原策略绑定并刷新路由 | +| route_flapping | BGP 会话正常;周期切换前缀策略 | 反复前缀撤回/通告,且会话保持 Established | 停止周期任务并恢复策略;不用 session flap 代替 | +| ecmp_misconfig | 实际 FIB 多下一跳;限制路径/关闭 relax | 候选 BGP 路径仍在、实际 FIB 下一跳减少 | 恢复策略与下一跳;RTT/loss 可以正常 | +| acl_source_misconfig | 指定接口、方向和源范围 | ACL 匹配、命中计数、受影响/对照通信 | 按拥有的规则身份删除 SONiC/iptables 状态 | +| acl_destination_misconfig | 指定接口、方向和目的范围 | 同上,核对目的前缀 | 同上,不清空其他 ACL | +| acl_l4_port_misconfig | 指定 UDP 目的端口及接口/方向 | UDP 受影响、规则命中,ICMP 对照 | 同上;ICMP 正常不能证明 UDP 健康 | +| none(健康) | 健康基线与完整采样 | 健康观测,仍调用 agent | 不注入;只有 network_healthy 获得负样本得分 | + +corruption 与 loss 当前可能只产生相似的丢包症状。没有证明所有拓扑/路径下 +均可可靠区分;本次不改变分类或评分,也不制造 CRC 计数填补证据缺口。 +ECMP 案例检查转发冗余,不能用“Pingmesh 无异常”替代配置/路由健康。 + +## 精简与可达性依据 + +| 入口/组件 | 判定 | 处理 | +|---|---|---| +| pyproject CLI、SDK 懒加载、本地 SimulatorManager | 正式执行入口 | 保留并做打包/契约验证 | +| 独立 simulator_service / SimulatorService / HTTP 请求模型、事件日志和 tombstone | 用户明确移除的功能,不是误判为死代码 | 删除模块、console script、simulator extra 和专属测试 | +| authenticated session MCP 与公开 stdio MCP | 诊断 transport,仍被示例与 SDK 调用 | 保留 | +| 模拟器 baseline_signature、_ensure_baseline、重复流量准备与修复路径 | 由共享 backend 接替 | 删除,并将测试迁移至共享行为与两种入口一致性 | +| backend 的 setup_traffic=False / 外部 baseline_window 构造分支 | 原模拟器专用路径;移除调用者后仅测试引用 | 删除参数与分支,测试通过正式准备路径验证 | +| 接口 _get_device_interfaces 包装和重复格式分支 | 原 wrapper 负责 tc,职责消失 | 合并为一次采集与统一格式处理 | +| 两个接口指标 fallback 查询 helper | 同一请求各取一遍接口状态 | 改为纯列表选择函数,共享一次实时采集 | +| WorkerExecutionContext.as_env | 自动传入 context 的宿主路径通道;不再有正式调用者 | 移除;外部 stdio 配置由操作者显式提供 | +| FaultSpecRegistry、自定义 fault pack、动态 MCP 注册、SDK 导出 | 动态调用/扩展契约 | 保留,不以无直接 import 或低覆盖率删除 | +| Containerlab wrapper、SONiC startup、native client-agent、BGP helper、观测资源 | 子进程/打包资源路径 | 保留,并保留 wheel 资源测试 | +| 保存的 evaluation_result | 正式评分结果复用 | 保留;仅缺失时独立评估,缺失 verdict 默认为 inconclusive | + +既有用户改动和未跟踪文件不纳入删除候选。旧服务测试的删除与功能移除对应; +基线、流量失败、隔离、重复 close 等仍由迁移后的本地测试覆盖。 + +## 迁移说明 + +- 删除独立 `netopsbench-simulator` 命令和 `netopsbench[simulator]` extra。 + 改用 `bench.simulators.create()` / `prepare()`。诊断 HTTP MCP 不受此删除影响。 + 已安装环境需重新安装新版包。发布 wheel 应使用干净源码目录,不能沿用旧 + `build/lib`:setuptools 增量构建可能把已删除文件继续装入 wheel。 + wheel 契约测试现在从临时源码副本构建,并断言服务模块与命令都不存在。 +- `include_tc` 从直接 toolkit 和 MCP 签名删除。旧直接调用会得到 TypeError; + 删除该参数,使用正常接口证据。`interface` 现在真正过滤所有视图及地址。 +- 公共结果增加采集时间;不要用整个结果字典等于固定常量判断工具成功。 + `get_device_interfaces(format="both")` 的 `structured` 统一为包含 + `device` 与 `interfaces` 的对象;原先 Linux/client fallback 可能直接返回列表。 +- 自动生成的诊断 context 不再含 `worker_env` 和语义化 episode ID。 + 使用 `context.tools`,或由操作者显式配置外部 MCP;不要从模型输入获取宿主路径。 +- 自定义拓扑 metadata 只投影支持的标量字段;内部扩展数据仍可保存在 manifest。 +- 默认参数收敛为 loss 30%、corruption 20%、latency 120ms、MTU 1400。 + 直接 corruption 旧默认 5% 和 latency 旧默认 100ms 改变;需要旧值时显式传参。 +- 新生成案例记录 `metadata.generator.version=3` 与 seed,错误 IP/Loopback + 值按 seed 变化。注入前检查地址冲突与接口是否已存在;已有场景文件不改写。 +- 冻结 campaign 保留其源码快照、参数和评分。新工具边界与默认值应使用新运行记录。 + +## 性能与验收记录 + +新增私有阶段 `operations` 计数,记录平台命令入口的 subprocess/Docker 调用及 +Influx 查询;健康检查、路由采集和部署线程传播计数上下文。恢复次数与 ingestion +重试另计。租约池记录获取总耗时、锁获取耗时和条件等待耗时。计数不含外部 LLM、 +独立后台服务或绕过平台命令入口的第三方进程,不能当作整台主机的调用总数。 +工具查询还按工具名累计耗时、调用数、失败数和操作数。父阶段包含子步骤, +不能将父阶段与子步骤计数相加。 + +`scripts/validate_runtime_refactor.py` 提供无 LLM 的固定工具序列,每个故障后 +执行健康案例,失败立即停止并清理自己创建的 runtime。medium 使用 XS 实测 +容量样本进行预检;运行保留内存紧急取消机制。`audit.json` 包含完整私有证据、 +每次部署/案例耗时、Docker/Influx 调用数及清理状态。性能运行记录源码和脚本 +摘要,使用相同 seed 与完整观测窗口。脚本输出的 inconclusive 不是诊断准确率。 +计时范围是共享 ScenarioExecutor/DiagnosticSession 的确定性工具执行路径; +不包含外部 agent 容器、LLM 或 HTTP MCP transport 的启动开销。冷启动样本 +包含新 runtime 部署及首次案例,复用样本在同一 runtime 上重新执行相同类型; +性能模式的工具序列根据公开拓扑遍历全部交换机,不读取私有注入目标。 + +在同一主机上,以本次改动前的工作区源码快照对比,工具参数校验预热后每次 +执行 10,000 次,重复三次: + +| 指标 | 改动前 | 改动后 | +|---|---|---| +| registry 参数校验,三次秒数 | 0.50294 / 0.50057 / 0.51075 | 0.04222 / 0.04262 / 0.04212 | +| 中位数 | 0.50294s | 0.04222s | +| 相同接口指标 fallback 的实时接口采集次数 | 2 | 1 | +| 模拟器首次基线的完整采集窗口数 | 2 | 1 | + +约 11.9 倍的校验微基准改善来自缓存静态 TypeAdapter,不能外推为端到端加速。 +基线窗口数和重复采集次数由行为测试验证;未降低完整窗口时长或故障校验要求。 + +最终离线完整回归通过 1207 项(8 项 real 测试不在离线套件执行),耗时 +268.92 秒;另有 2 条第三方 websockets 弃用警告。中断清理等运行时聚焦测试 +87 项通过。全项目配置的 mypy 检查通过(84 个源文件),Ruff 与 +`git diff --check` 通过。原始离线日志保存在 `.netopsbench/refactor-verification/`。 + +真实环境已验证 Docker、镜像与固定 Containerlab 工具链。首次部署曾因 sudo +权限失败,取得操作者授权后,在专用新建 runtime 上完成 XS effects 验收: +健康、链路关闭、设备关闭、BGP 认证故障均有效、执行完成且恢复成功;最终 +runtime 已销毁。记录:`.netopsbench/refactor-after-xs-20261104/acceptance.json`。 +没有复用或改动其他正在运行的实验拓扑。 + +XS 固定工具调用验收也已通过:3 个故障分别跟随后续健康案例,共 7 例, +runtime 已销毁。记录:`.netopsbench/refactor-scripted-xs/audit.json`。 + +medium 固定工具验收已通过 17 例(8 个故障,各跟随健康案例,加初始健康), +包括 loss、corruption、latency、MTU、link_flapping、route_flapping、 +acl_destination_misconfig 与 ecmp_misconfig。各例 case_valid/success 为 true, +恢复成功,最终 runtime 已销毁。这里每类选择一个生成实例,不代表该类所有 +角色、方向与机制组合均已完成真实验收。记录: +`.netopsbench/refactor-scripted-medium/audit.json`。 + +真实中断验收通过:专用 XS 部署完成后主动抛出 KeyboardInterrupt,原始中断 +被保留,所属容器、管理网络及 runtime 目录均已清理。记录: +`.netopsbench/refactor-cancel-real/acceptance.json`。首次 sudo 失败留下的本任务 +隔离目录也已清理;最终核查没有本任务 audit 容器残留。 + +三次冷启动/复用性能对比已完成。前后各 30 个案例(含恢复后的健康检查)全部 +有效且执行成功;前后各 9 个 runtime 均已销毁。每种类型各有 3 个冷启动与 +3 个复用样本,冷启动包含部署和首次案例。两侧使用相同固定调用脚本。 +另检查重构后 1500 份真实公开工具输出,未发现 netem/qdisc、fault_type、 +effect_audit、recovery_journal 或本次内部路径标记;这项检查只针对公开输出, +私有 audit 本来就保留注入及恢复证据。 + +| 类型 / 模式 | 前三次秒数 | 后三次秒数 | 前 / 后中位数(秒) | +|---|---|---|---| +| 健康 冷启动 | 335.74 / 168.02 / 164.62 | 163.93 / 162.67 / 163.10 | 168.02 / 163.10 | +| 健康 复用 | 57.53 / 63.95 / 72.44 | 63.51 / 63.24 / 68.79 | 63.95 / 63.51 | +| loss 冷启动 | 195.78 / 201.50 / 196.60 | 208.67 / 209.01 / 196.53 | 196.60 / 208.67 | +| loss 复用 | 103.15 / 103.26 / 106.86 | 102.79 / 111.06 / 106.19 | 103.26 / 106.19 | +| ECMP 冷启动 | 202.91 / 203.45 / 203.55 | 202.64 / 203.48 / 205.88 | 203.45 / 203.48 | +| ECMP 复用 | 103.65 / 113.07 / 107.63 | 101.20 / 106.75 / 107.89 | 107.63 / 106.75 | + +| 类型 / 模式 | Docker 命令数:前三次 → 后三次 | Influx 查询数:前三次 → 后三次 | +|---|---|---| +| 健康 冷启动 | 256/301/302 → 305/300/303 | 29/15/15 → 28/15/15 | +| 健康 复用 | 138/138/138 → 138/138/138 | 11/6/6 → 10/5/6 | +| loss 冷启动 | 318/316/316 → 315/310/315 | 15/15/15 → 15/15/15 | +| loss 复用 | 152/152/152 → 152/152/152 | 6/6/6 → 6/6/6 | +| ECMP 冷启动 | 320/321/317 → 318/321/319 | 15/15/15 → 15/15/15 | +| ECMP 复用 | 156/156/156 → 156/156/156 | 6/6/6 → 6/6/6 | + +以 loss 复用样本为例,各阶段中位数如下;阶段可能包含子阶段,不能再次相加。 + +| 阶段 | 前 / 后(秒) | +|---|---| +| 基线采集(复用已验证窗口) | 0.00 / 0.00 | +| 注入 | 0.27 / 0.28 | +| 观察 | 30.00 / 30.00 | +| 观察查询 | 7.30 / 7.56 | +| 固定工具诊断 | 21.02 / 21.82 | +| 恢复与验证 | 44.75 / 45.62 | + +端到端没有一致加速:loss 冷启动中位数增加,ECMP 冷启动基本持平;复用案例 +的 Docker 命令数不变。窗口、采样率和校验没有缩减。剩余明显开销包括逐设备 +接口/ACL 查询、完整观察及恢复窗口和遥测晚到等待;这些数据是后续优化依据, +不将本次微基准收益外推为整轮收益。 + +完整私有记录:`.netopsbench/refactor-perf-before/audit.json`、 +`.netopsbench/refactor-perf-after/audit.json`;精简汇总: +`.netopsbench/refactor-performance-summary.json`。 +实测源码保存在 `.netopsbench/refactor-source-before.tar.gz` 与 +`.netopsbench/refactor-source-after-profiled.tar.gz`(不含固定工具链二进制)。 +源码摘要和相同的 driver SHA-256 随记录保存。实测完成后补充的 provision +中断清理修复不在性能执行链路中:测量脚本使用 create + 显式部署阶段。 + +计时限制:主机保留其他既有实验;首轮重构前采样部分时间与本次离线回归 +重叠。记录原始三次值及中位数,不据此声称受控实验中的因果加速;后续采样 +不再并行运行本次测试。冷启动指新建 runtime,镜像预先存在,不清空 Docker 缓存。 diff --git a/docs/content/docs/architecture/state-checked-recovery.mdx b/docs/content/docs/architecture/state-checked-recovery.mdx new file mode 100644 index 0000000..319e77d --- /dev/null +++ b/docs/content/docs/architecture/state-checked-recovery.mdx @@ -0,0 +1,247 @@ +--- +title: State-checked Recovery +description: 每例验证撤销与转发状态,独立校准全网健康基线。 +--- + +## 行为边界 + +新生成的 campaign 和 SDK 新建场景显式记录 `metadata.recovery_policy`。 +`state_checked` 每例验证修改撤销、容器、接口、BGP、FIB、流量与基础连通; +它不表示每例完成了全网 Pingmesh 数据面验证。故障观察窗口、采样率、诊断工具 +和评分不变。恢复策略 v3 只保留这一条执行流程;旧模式及其固定等待已移除。 +旧场景必须显式迁移后执行,历史报告仍可读取。 + +没有引入逐 case 的恢复计划、新探针、client-agent 协议或 Batfish。 + +```mermaid +flowchart TD + P[准备案例] --> B{健康基线有效且可复用?} + B -->|否| C[完整环境检查和健康窗口] + B -->|是| I[注入、观察、诊断] + C --> I + I --> U[已有回调撤销并回读] + U --> S[全设备状态收敛及最终复核] + S -->|正常通过| R[保留原基线时间和使用次数] + S -->|重试后通过 / 自定义兼容路径| C2[完整环境检查和健康窗口] + C2 --> R + U -->|失败| Q[清除基线资格并隔离] + S -->|未收敛 / 缺必要证据| Q + C2 -->|失败| Q + R --> N[下一例;结束时按环境去向校准或销毁] +``` + +## 配置及迁移 + +```python +from netopsbench.sdk import NetOpsBench, RecoveryPolicy + +bench = NetOpsBench(workspace=".") +case = bench.scenarios.create( + id="healthy", name="healthy", scale="medium", + episode={"episode_id": "diagnosis", "fault_type": "none", "duration_seconds": 30}, + metadata={"negative_sample": True}, + recovery_policy=RecoveryPolicy( + baseline_max_cases=10, + ), +) +``` + +新生成场景默认使用版本 3(10 次消费,无年龄上限)。不再提供 `--recovery-mode`。 +旧版本或没有恢复策略的场景会在部署前报错;显式迁移到新目录: + +```bash +netopsbench scenario migrate scenarios/generated/medium --out scenarios/migrated/medium-v3 +netopsbench scenario validate scenarios/migrated/medium-v3/CASE.yaml +``` + +迁移保留 testcase ID、故障参数及 experiment 配置,记录源文件和场景摘要, +写入新的 campaign 身份及 `migration.json`,不覆盖原文件或既有输出目录。 +冻结 campaign 不做原地升级。SDK `RecoveryPolicy` 保留名称,但不接受 `mode` 或 `baseline_max_age_seconds` 参数。 +生成 spec 的 `recovery_policy` 仅接受 `version: 3` 和 `baseline_max_cases`;未指定的新建配置使用默认值。 + +## 每例检查与失败处理 + +故障恢复回调仍是 `FaultSpec.recover_active_fault`。内置回调返回的私有 +`readback_verified` 标记只在实际回读通过时为真;没有相同保证的历史/自定义 +回调进入完整验证兼容路径,不声称取得同等修改回读保证。 + +| 资源 | 实际回读 | +|---|---| +| 链路 | 两端管理状态、客户端原路由;周期任务退出后再恢复 | +| IP | 原地址集合、错误地址消失及对应 SONiC CONFIG_DB | +| MTU | 实际接口 MTU | +| qdisc | 拥有的 netem 已消失;不可拥有的原规则在注入前拒绝 | +| ACL | 原 iptables 规则完整恢复,拥有的 CONFIG_DB 对象消失 | +| FRR | 注入前/恢复后的规范化 running-config 摘要一致 | +| 静态/丢弃路由 | 配置及实际路由回读,并与案例前 FIB 核对 | +| bgpd / 设备 | 进程或容器运行、原配置恢复、相关网络状态收敛 | + +命令返回零不能替代回读。失败项保留在活动故障表,不能由普通 ping 成功覆盖。 + +每例使用共享健康检查的状态部分:检查准确的容器身份;全部路由设备的接口、 +邻接身份和 FIB;客户端 Pingmesh 状态;背景流量及基础跨机架连通。 +首轮失败时只重采未收敛设备,之后必须完成两次全设备网络状态通过的采集, +间隔现有健康轮询周期(5 秒)。采集并发沿用现有限额。 + +全套遥测验收(包括发送 syslog 标记并等待入库)仅在完整校准运行。 +不再先固定等待 post_recovery_wait,再开始状态查询。 +恢复总 deadline 包含撤销、回读、收敛和异常校准,不为回退重新计时。 + +严格的重试策略意味着:即使最后恢复正常,只要状态检查曾出现错误或恢复发生 +重试,就升级完整校准。链路或 BGP 案例可能因此仍等待完整窗口;不保证所有案例 +都提速。明确的配置、FIB残留或任务未退出不能被完整 Pingmesh 覆盖。 + +## 基线和校准 + +每个 runtime 的原始健康窗口最多用于 10 个案例,不因经过 600 秒而失效;开始使用时计数, +诊断失败不退还次数。状态恢复成功只恢复复用资格,不延长窗口时间。 +只有新的、完整验证过的窗口才能刷新基线。 + +首次、次数用满、流量或环境身份变化时,在注入前校准。身份变化后不拿旧 +环境的窗口作新环境的比较基线。不缓存可能漏掉晚到记录的遥测查询结果。 + +平台拥有且确定立即销毁的 runtime 跳过末尾校准,记录 `runtime_will_be_destroyed`, +销毁失败仍标记清理失败。保留、外部或去向未知的 runtime 执行末尾校准; +紧邻结束的有效完整校准可以复用。校准失败将 +worker 隔离并使运行失败,案例原始评分保留。结果写入独立的 +`raw//final_calibration.json` 和 worker summary。 + +模拟器每次 prepare 都重新获取租约;新的使用方开始前清除跨租约复用资格并 +完整校准。案例关闭执行恢复,新模式不将未重新校准的环境直接证明为新租约健康。 + +## 报告及验证 + +私有 cleanup 包含策略、`validation_level`、完整验证原因、状态采集时间、轮询 +次数及基线交接结果。案例准备记录基线窗口、年龄和使用次数;校准分别记录 +环境检查、窗口等待和查询耗时及命令/查询计数。信息不进入 agent 上下文。 +同一案例发生多次校准时分别记录 `calibration`、`calibration_2` 等阶段,避免 +异常回退覆盖首次校准记录。恢复中的校准耗时已包含在 recovery 总耗时中, +统计总耗时时不要重复相加。 + +验收脚本 `scripts/validate_runtime_refactor.py` 支持: + +- `--shadow`:恢复通过后额外完整校准,影子耗时独立记录,不更新正式基线和校准状态。 +- `--all-mechanisms` / `--all-cases`:子机制或全部生成位置覆盖。 +- `--readback-negatives`:仅抑制撤销写操作,仍从真实设备读取状态,检查不能错误放行;随后解除抑制执行正常恢复。 +- `--tool-profile minimal`:只调用拓扑与 Pingmesh 汇总,排除模型耗时;两个版本必须使用相同 profile。 +- `--batch-repeats 3 --sequence-repeats 2`:在三个独立 runtime 上重复整批序列,包含首次、周期和末尾校准;不与逐类型 `--repeats` 混用。 +- `--compact-sequence`:性能运行使用健康样本和选定故障的连续序列;正确性验收仍独立执行影子检查。 + +计数范围为宿主 Python 发出的 Docker CLI 和 Influx 查询;不包括 Containerlab +内部子调用或容器内后台采集器的请求。两模式使用相同计数方式,部署和案例阶段 +分别统计。整批耗时以实际起止时间测量,包含周期和末尾校准。 + +真实验收和完整序列性能记录保存在 `.netopsbench/state-recovery-*`;它们是本地 +产物,不作为源码提交。 + +历史 v2 的删除依据与验收见 [Recovery v2 audit](./recovery-v2-audit)。 + +## v3 的兼容性与验证边界 + +v2 的 600 秒年龄限制已删除,agent 诊断超时与恢复 deadline 不变。 +v2(包括省略年龄字段的 v2)必须显式迁移,不能通过忽略旧字段改变原 campaign。 +迁移使用 v3 默认 10 次消费策略,保留故障参数与 testcase ID,生成新的身份; +原场景和历史报告无需原地修改。运行中的实验应继续使用冻结源码和配置。 + +校准后仍保留真实窗口起止时间、年龄和消费次数;每次查询仍读取该真实时间段, +状态检查不产生新的数据面窗口,也不刷新时间戳。长时间批次的基线可能跨越一小时以上, +因此 v3 不保证与 v2 相同的完整数据面证据新鲜度。若历史遥测因保留策略而不可用, +仍按原完整性校验处理,不能用空结果认定健康。 + +离线覆盖长时间复用、第 10/11 次、环境变化和恢复失败;v3 的真实影子窗口对照 +及端到端性能尚待独立验收。下面的 v1/v2 实测不能视作 v3 的实测结果。 + +## 历史验收:bf09430(2026-11-04) + +以下数据属于 v1 提交 bf09430,不能作为 v2 的验收结果。 + +### 离线验收 + +最终代码执行 `python -m pytest -q -m 'not real'`:**1272 通过,8 项 real 测试 +未纳入该次离线执行**,耗时 278.96 秒;包含干净 wheel 安装后的入口验证。 +另有 2 条既有 websockets 依赖弃用警告。Ruff、项目配置范围内的 Mypy +(85 个源文件)及 `git diff --check` 均通过。 + +新增回归覆盖五次消费与第六次校准、600 秒精确边界、环境变化与失败失效、 +邻接身份与二次状态变化、ACL/FRR 命令成功但残留、末尾校准失败保留评分并隔离、 +旧场景摘要兼容,以及并行查询和跨批次计数隔离。日志位于 +`.netopsbench/state-recovery-verification/`。 + +### 真实恢复验收(v1) + +以下为专用隔离环境、确定性工具调用的实测;正确性验收包含额外影子窗口, +不用于性能对比。medium 和 k=8 的正确性验收曾并行运行,性能运行另行串行执行。 + +| 环境 | 完成案例 | 覆盖 | 影子完整健康窗口 | +|---|---:|---|---:| +| XS | 7 | 健康、链路关闭、BGP 认证、设备关闭 | 7/7 通过 | +| medium | 28 | 24 类内置故障,包含路由发布与过滤的各个可生成子机制,26 个故障案例及 2 个健康样本 | 28/28 通过 | +| Fat-tree k=8 | 15 | ECMP 两种机制的 edge/agg 位置及跨 pod 路径;周期路由、ACL 的 edge/agg/core 位置;2 个健康样本 | 15/15 通过 | + +上述环境均已销毁。medium 的 25 次撤销残留测试全部拒绝放行,覆盖接口、 +qdisc、MTU、ACL、静态/丢弃路由、FRR、bgpd 和周期控制任务。设备关闭的正常 +恢复已实测;Containerlab 节点激活不经过该命令抑制钩子,**设备关闭的这项 +真实负向测试未执行**,不包含在 25 次中。 + +medium 的 bgpd、AS、认证、update-source、neighbor shutdown、maximum-prefix +六个案例发生收敛重试并升级完整校准,最终及影子检查均通过。不能因此宣称所有 +BGP 案例都能省去恢复窗口,也不能将 50 次影子通过解释为每例状态检查已经证明 +了全网数据面健康。 + +k=18 的本次容量预检未通过:当时可用内存约 142.84 GB,含余量的估算需求约 +145.72 GB;未强行部署,**k=18 正确性和性能均未实测**。预检记录位于 +`.netopsbench/state-recovery-verification/capacity.json`。 + +### 性能对照(v1) + +medium,1 个 worker,12 个路由设备、16 个 client、64 条背景流;使用现有镜像缓存。 +每批依次运行 `healthy → loss → ECMP → healthy → loss → ECMP`,观察窗口均为 +30 秒,使用相同 seed 和 `minimal` 工具脚本,不调用 LLM。两模式交替各跑三批, +每批创建独立 runtime,完成后销毁;36 个案例全部通过。六批源码和驱动指纹一致。 + +| 指标 | full_window | state_checked | +|---|---:|---:| +| 六例序列平均耗时,包含周期及末尾校准 | 469.8 秒 | 395.3 秒 | +| 完整 runtime 生命周期平均耗时,包含部署和销毁 | 537.2 秒 | 463.5 秒 | +| 每例恢复 P50 / P95 | 45.3 / 49.0 秒 | 7.0 / 7.3 秒 | +| 仅故障例恢复 P50 / P95 | 47.5 / 49.5 秒 | 7.0 / 7.4 秒 | +| 部署与预热平均耗时 | 57.0 秒 | 58.1 秒 | +| 首次健康基线准备/校准平均耗时 | 37.8 秒 | 42.5 秒 | +| 第六例前独立校准平均耗时 | — | 40.9 秒 | +| 独立末尾校准平均耗时 | — | 43.1 秒 | +| 额外健康窗口 / 批 | 5 | 3 | +| 序列 Docker CLI 调用 / 批 | 320 | 449 | +| 序列 Influx 查询 / 批,平均 | 102.7 | 67.3 | +| 异常回退 / 案例 | 不适用 | 0 / 18 | + +旧模式首次准备包含 readiness、窗口采集和查询;末例的完整恢复窗口已计入 +该例恢复耗时,无另加的末尾窗口。额外健康窗口不包含两例健康样本自身的诊断 +窗口。调用数包含序列及末尾校准,部署调用数在原始记录中单列;不包含销毁阶段。 +P50/P95 由各模式 18 次恢复测量计算,故障例为 12 次,P95 使用线性插值。 + +| 轮次 | 旧模式序列 / 全生命周期 | 新模式序列 / 全生命周期 | +|---|---:|---:| +| 1 | 468.6 / 535.5 秒 | 400.9 / 468.3 秒 | +| 2 | 471.8 / 539.1 秒 | 391.2 / 460.2 秒 | +| 3 | 469.1 / 537.1 秒 | 393.8 / 462.0 秒 | + +本序列耗时减少 **15.9%**,包含部署和销毁后减少 **13.7%**。Docker CLI 调用 +增加 **40.3%**,来自双轮全设备状态复核和独立校准;Influx 查询减少 **34.4%**。 +这验证了减少重复健康窗口的收益,不能解释成所有计算开销都下降。结果仅适用于 +本次 medium 短序列,不外推到 BGP 重试较多的序列、长时间 LLM 诊断或未实测的 k=18。 + +以下命令仅适用于独立检出的历史提交 bf09430: + +```bash +PYTHONPATH=. python scripts/validate_runtime_refactor.py \ + --scale medium --fault-types packet_loss ecmp_misconfig \ + --recovery-mode state_checked --compact-sequence --sequence-repeats 2 \ + --tool-profile minimal --capacity-sample /path/to/xs-capacity.json \ + --output /path/to/new-audit-directory +``` + +替换为 `full_window` 运行对照;每次使用新的输出目录,不启用 `--shadow` 或负向 +撤销钩子。汇总位于 `.netopsbench/state-recovery-verification/performance.json`, +各批原始记录位于 `.netopsbench/state-performance--<1..3>/audit.json`。 +共 9 个专用 runtime(3 个正确性验收、6 个性能对照)均已清理,未发现属于它们的 +残留容器或网络;校验记录位于 `.netopsbench/state-recovery-verification/verification.json`。 diff --git a/docs/content/docs/build-your-agent/custom-agents.mdx b/docs/content/docs/build-your-agent/custom-agents.mdx index 8efc332..e11e009 100644 --- a/docs/content/docs/build-your-agent/custom-agents.mdx +++ b/docs/content/docs/build-your-agent/custom-agents.mdx @@ -5,6 +5,12 @@ description: Implement the diagnosis contract that NetOpsBench evaluates. An agent is any Python object with a `diagnose(context)` method. NetOpsBench passes a `DiagnosticContext`; the agent returns a structured `DiagnosisResult`; the evaluator compares that result with scenario ground truth. +## Native Codex + +The bundled `examples.agents.CodexAgent` connects the native Codex CLI to this contract. Install `pip install -e '.[codex]'`, install the native CLI 0.159.2 package with its `codex-code-mode-host` helper, and run `codex login`. Then use `PYTHONPATH=. python examples/01_run_scenario.py --agent codex --scenario scenarios/generated/xs/generated_healthy_network_xs_001.yaml` or wrap `CodexAgent()` with `bench.agents.wrap()`. + +Each diagnosis runs in a fresh container with anonymous observations, episode-scoped MCP tools and Python/shell access. The container cannot access the repository, scenario answers, Docker socket or management network directly. Only private authentication persists between cases. Defaults are `gpt-6.1-sol`, effort `xhigh`, 600 seconds and 40 MCP calls; constructor options and recorded runtime artifacts make these settings explicit. See `examples/agents/codex_agent/README.md` for image building, isolation and acceptance commands. + ## Agent contract ```python @@ -44,12 +50,14 @@ with NetOpsBench(workspace=".") as bench: |---|---| | `scenario_id` | Scenario or testcase identifier. | | `topology` | Switches, clients, links, and scale-specific topology metadata. | -| `symptoms` | Episode observations, including Pingmesh summaries when available. | +| `symptoms` | Pingmesh observations with their window and data-quality metadata. | | `tools` | Optional runtime or MCP-backed tool access. | | `metadata` | Runtime metadata such as worker-specific environment values. | The reference LLM agent builds a compact prompt from topology size, symptom keys, episode data, Pingmesh windows, and high-signal anomalies. A custom agent may instead use rules, symbolic logic, retrieval, additional tool calls, or another model wrapper. +Initial symptoms do not include whole-network FIB differences or device-state summaries. Use diagnostic tools to investigate routing, BGP, interfaces, ACLs, services and logs. Private effect and recovery evidence is kept out of the agent context. This policy applies to new campaigns; archived and running frozen campaigns keep their original inputs and scores. + ## Output: `DiagnosisResult` | Field | Requirement | @@ -63,6 +71,8 @@ The reference LLM agent builds a compact prompt from topology size, symptom keys | `findings.evidence` | Concise evidence used to support the verdict. | | `confidence` | Float between 0 and 1. | | `reasoning` | Short explanation tied to observed evidence. | + +`success=False` is an agent execution failure, even if the fallback verdict is `inconclusive`. It does not count as a completed diagnosis. A successful `inconclusive` verdict remains a normal scored result. Acceptance records the failed case and continues after verified fault recovery. Budget exhaustion, timeout and invalid agent output do not stop the suite. Diagnosis mode also continues after an invalid effect audit when a complete recovery health window succeeds; that case stays invalid and unscored. These finished failures are reported separately and skipped on resume. Setup failures, missing recovery proof, effects-only invalid cases and cancellation still stop execution; failed recovery quarantines the lab. Ordinary SDK session ownership and teardown defaults are unchanged. | `metadata` | Optional provider, model, tool-call, token, or timing details. | Return structured fields rather than only natural language. Free-form explanations are useful for review, but scoring depends on verdict, fault type, and location fields. @@ -103,3 +113,5 @@ For interface-applicable faults, localization score is split between device and - Include device and interface when the evidence supports localization. - Prefer canonical fault names from the built-in fault catalog. - Return `success=False` and an `inconclusive` verdict when the agent runtime fails. + +The [diagnostic tool contract](/docs/build-your-agent/diagnostic-tools) describes the shared 16-entry surface and optional routing, interface and Pingmesh views. diff --git a/docs/content/docs/build-your-agent/diagnostic-tools.mdx b/docs/content/docs/build-your-agent/diagnostic-tools.mdx new file mode 100644 index 0000000..b6ba054 --- /dev/null +++ b/docs/content/docs/build-your-agent/diagnostic-tools.mdx @@ -0,0 +1,72 @@ +--- +title: Diagnostic Tools +description: The shared diagnostic surface for DeepAgent, native Codex and custom agents. +--- + +All agents use the same 16-entry registry, parameter validation, episode window, +budget and tracing. Native Codex receives it through authenticated per-case MCP +HTTP; public stdio MCP remains available. The registry exposes ordinary device +and telemetry observations. Pingmesh task/batch completeness is private runtime +validation; there is no `get_pingmesh_flows` tool. + +Existing required parameters and default views retain their meanings. The +following additions are optional: + +| Tool | Optional capability | +|---|---| +| `get_device_status(device)` | New entry: actual node running/accessibility, supported bgpd/zebra service states and collection time. Unavailable service data is reported explicitly, without an inferred fault label. | +| `get_route_table(device, view="kernel", prefix=...)` | Actual kernel IPv4 FIB, including multipath next hops. The default `view="frr"` remains the FRR route table. | +| `get_bgp_neighbor(device, peer, view="advertised_routes", prefix=...)` | Live advertised routes for one peer; optional exact-prefix filter. The default `view="detail"` retains session details. | +| `get_device_interfaces(device, interface=...)` | Interface state/counters and actual IPv4 addresses/masks, optionally filtered by interface (including aliases). Traffic-control injection configuration is not exposed. | +| `get_device_acl(device)` | SONiC table/rule match fields, port/stage attachment and iptables FORWARD counters, including input/output interfaces. | +| `query_bgp_events(event_type="prefix_count")` | Prefix-count changes from the existing BGP collector. Default session mode is unchanged; prefix mode does not apply the session-state filter. Collection gaps are explicit, and failed collection never becomes prefix count zero. | +| `get_pingmesh_summary(src_client=..., dst_client=...)` | Optional client filters over the existing aggregated output. | +| `traceroute(src, dst_ip, max_hops=...)` | Default 8, maximum 32 hops, bounded by the diagnostic session deadline. | + +A count decrease is a clue. Confirm the specific prefix through RIB, advertised +routes and kernel FIB. A missing container, a stopped bgpd and a down BGP peer +are separate observations; avoid treating collection failure as routing failure. + +Pingmesh query times retain this precedence: explicit `start_time`/`end_time`, +current toolkit episode window, context file, environment times, rolling +fallback. `get_pingmesh_hotspots` remains aggregated by leaf/edge pair. Filtering +summary clients does not change the hotspot granularity. + +Initial symptoms contain Pingmesh observations and their window/data-quality +metadata. Agents receive normal topology and configuration intent, then query +tools for device status, routing, BGP, interfaces, ACLs and logs. Whole-network +FIB/BGP snapshots and healthy/fault differences stay in private effect and +recovery validation; they are not supplied as initial localization clues. +ECMP can lose next hops while RTT/loss remain normal, so normal Pingmesh alone +does not establish routing redundancy or configuration health. + +This input policy applies to new runs. Frozen campaigns retain their source +snapshots, observations and scores; use a new campaign for this policy. + +Only anonymous case identifiers, normal topology/configuration intent and +public observations reach an agent. Injection targets, mechanisms, recovery +journals, private effect audits and grading answers stay outside prompts and +tool output. Agents return the existing diagnosis schema; mechanism is not a +new output field or scoring KPI. + +`include_tc` has been removed from MCP and direct toolkit calls; omit the +argument. Direct callers passing it receive Python `TypeError`. Raw interface +views omit the qdisc implementation field while preserving interface state, +MTU and counters. In `both` format, `structured` consistently contains a +`device` field and an `interfaces` list, including Linux fallbacks. +Netem loss/corruption/delay settings belong to private injection validation, not +measured packet loss, corruption counters or latency. + +Device snapshots carry `collected_at`. Logs and interface telemetry use the +current episode window by default and filter by topology identity; responses +include `time_scope`. A live fallback snapshot is explicitly separate from +historical telemetry. Periodic faults can be healthy at the instant of a live +query: inspect the full historical window before concluding network health. + +BGP tool parameters are enumerated in the MCP schema. For `get_bgp_neighbor`, +use `view="detail"` or `view="advertised_routes"`; `advertised-routes` and +`advertised` are accepted aliases for the latter. Received routes are not +supported. `prefix` applies only to advertised routes and matches exactly. +For `get_bgp_neighbors`, use `format="structured"`, `"raw"`, or `"both"`; +`"json"` aliases `"structured"`. Invalid view/format values return argument +guidance; collection failures remain redacted as `Observation unavailable`. diff --git a/docs/content/docs/build-your-agent/meta.json b/docs/content/docs/build-your-agent/meta.json index 00f1149..69fde25 100644 --- a/docs/content/docs/build-your-agent/meta.json +++ b/docs/content/docs/build-your-agent/meta.json @@ -1,4 +1,8 @@ { "title": "Agent Development", - "pages": ["custom-agents", "python-api-guide"] + "pages": [ + "custom-agents", + "python-api-guide", + "diagnostic-tools" + ] } diff --git a/docs/content/docs/extend-netopsbench/custom-faults.mdx b/docs/content/docs/extend-netopsbench/custom-faults.mdx index db0f391..7771ae4 100644 --- a/docs/content/docs/extend-netopsbench/custom-faults.mdx +++ b/docs/content/docs/extend-netopsbench/custom-faults.mdx @@ -9,20 +9,57 @@ Fault extension changes the benchmark fault surface. Most agent work should use Scenario YAML references faults by `fault_type`. -| Fault type | Category | Requires interface | Notes | -|---|---|:---:|---| -| `link_down` | Link | yes | Brings both physical endpoints of the selected link down. | -| `link_flapping` | Link | no | Repeatedly toggles both endpoints of a link. Parameters: `iterations`, `down_time`, `up_time`. | -| `mtu_mismatch` | Impairment | yes | Changes interface MTU to break path MTU. | -| `packet_loss` | Impairment | no | Adds tc-based loss on the target device. | -| `packet_corruption` | Impairment | no | Adds tc-based corruption. | -| `high_latency` | Impairment | no | Adds tc-based delay. Parameter: `latency_ms`. | -| `bgp_neighbor_misconfig` | Routing (BGP) | no | Misconfigures a BGP neighbor. | -| `static_route_misconfig` | Routing (Static) | no | Installs an incorrect static route. Alias: `static_route_misconfiguration`. | -| `blackhole_route` | Routing (Static) | no | Installs a route pointing to a null next-hop. Requires `target_prefix`. | -| `route_policy_misconfig` | Routing (Policy) | no | Misconfigures a prefix list or route-map. | -| `device_down` | System | no | Stops the target SONiC container, making its management, control, and data planes unavailable until recovery restarts it. | -| `acl_misconfig` | ACL | no | Adds an ACL that blocks expected traffic. Alias: `acl_misconfiguration`. | +The [benchmark methodology](/docs/run-benchmarks/methodology) lists all 24 +canonical labels, their 27 mechanisms, coverage units and corpus sizes. +`bgp_neighbor_misconfig`, `route_policy_misconfig` and `acl_misconfig` are +retired. Regenerate scenarios; no old-format converter is supplied. + +Interface faults include links, interface addressing, netem, MTU and all ACL +variants. Each applies to one explicit data interface. ACLs record interface, +direction, match fields and counters; L4 uses UDP destination port 33434 by +default and ICMP as a protocol control. Software packet corruption is not a +physical CRC fault. + +Merged publication, filtering and ECMP labels require an explicit mechanism +inside `episode.parameters`. BGP neighbor faults require `peer_ip`; prefix +filters require `peer_ip` or `peer_ips`; loops require `next_hop`. Injected +configuration belongs in `episode.parameters`, rather than scenario metadata. +Built-in handlers read injection values only from `parameters`, including MTU; +metadata does not supply fallback injection settings. +Loops and route flapping also require `target_interface` for their fabric +neighbor. A loop next hop must be a configured, established neighbor before +the temporary static route is applied. + +BGP update-source faults reference an absent source interface. A wrong source +IP alone can still permit a passive FRR session, so validity requires the actual +neighbor to leave Established while other configuration remains intact. + +```yaml +metadata: + fault_catalog_version: 2 +episode: + episode_id: diagnosis + fault_type: route_filter_misconfig + target_device: leaf3 + target_prefix: 192.168.2.0/30 + duration_seconds: 30 + parameters: + mechanism: import_filter + peer_ips: [10.1.3.1, 10.2.3.1, 10.3.3.1, 10.4.3.1] +``` + +Use neighbors from the generated manifest/configuration for the selected device. +A complete import withdrawal covers every valid source; a path reduction covers +only some sources. Independent policies preserve unrelated prefixes and the +original `RM-ALLOW` attachment. The wrong static next hop must be another client +on the root leaf/edge with IP forwarding disabled. Loop validity requires an +observed forwarding cycle or TTL exhaustion. + +Link and route flapping share a cancellable controller, with profile-configured phases +(default 10 seconds faulted and 10 seconds healthy), continuing until recovery. +They use the same 30/42/66-second scale window as all other benchmark cases. Netem refuses an existing nondefault qdisc it cannot safely +restore. Recovery restores owned state and compensates partial writes; failure +quarantines the runtime and preserves evidence. Common scenario fields: diff --git a/docs/content/docs/quickstart.mdx b/docs/content/docs/quickstart.mdx index 56d918a..073910a 100644 --- a/docs/content/docs/quickstart.mdx +++ b/docs/content/docs/quickstart.mdx @@ -15,7 +15,7 @@ NetOpsBench depends on Containerlab and Linux networking primitives such as netw - Python 3.12+ - Docker -- Containerlab +- Official Containerlab v0.77.0 (installed privately by the command below) - An API key for the selected LLM provider Install Docker: @@ -26,45 +26,147 @@ sudo usermod -aG docker $USER # re-login after this step docker run --rm hello-world ``` -Install Containerlab: +NetOpsBench installs a checksum-verified official Containerlab release after Python installation. The system `containerlab` command can remain installed for other labs; SDK-created runtimes use the repository-owned binary. + +If Docker reports a socket permission error after adding the Docker group, log out and back in, or start a new shell with `newgrp docker`. + +## Install ```bash -bash -c "$(curl -sL https://get.containerlab.dev)" -containerlab version +git clone https://github.com/NetX-lab/NetOpsBench.git +cd NetOpsBench +python -m venv .venv +source .venv/bin/activate +pip install -e ".[agent]" ``` -Enable non-interactive access for the privileged commands used by the benchmark scripts: +Prepare the runtime executable once: ```bash -echo "$USER ALL=(ALL) NOPASSWD: /usr/bin/docker, /usr/bin/containerlab, /usr/bin/rm" \ - | sudo tee /etc/sudoers.d/netopsbench -sudo chmod 440 /etc/sudoers.d/netopsbench -sudo visudo -cf /etc/sudoers.d/netopsbench +python -m netopsbench.platform.runtime.build_tools +docker build -f containers/client/Dockerfile -t netopsbench-client:pingmesh-v2 . ``` -Check the same shell session you will use for the run: +The installer verifies the official v0.77.0 release archive and executable SHA-256, +then checks the reported version. It installs only `containerlab` under the +package's `platform/runtime/_bin/`. It does not change `/usr/bin/containerlab` +or the Docker daemon. Linux amd64 and arm64 are supported. Offline installation +accepts `--archive /path/to/containerlab_0.77.0_linux_amd64.tar.gz`. +`--output` and `NETOPSBENCH_RUNTIME_TOOLS` select another private tools directory; +it must contain the same verified release and its installer manifest. Go and +local Containerlab patches are not required. + +### Privileged runtime operations + +Containerlab requires root for deployment, destruction and node stop/start. +The SDK invokes the private executable through `sudo -n`; host cleanup also +uses privileged commands. Configure administrator-reviewed permissions for the +trusted installation and its runtime directory before running unattended cases. +Docker socket access alone does not authorize Containerlab networking operations. +A root-run benchmark process may set `NETOPSBENCH_NO_SUDO=1` to omit nested sudo. + +Containerlab creates the Docker management bridge and uses Docker DNS. Node +faults use official `containerlab stop/start`, which park and restore data links; +raw Docker restart is not the benchmark's device recovery path. There is no +NetOpsBench management-network or DNS daemon, or Docker configuration change. + +The official v0.77.0 Docker runtime itself selects `nat-unprotected` on newer +Docker engines (see [upstream implementation](https://github.com/srl-labs/containerlab/blob/v0.77.0/runtime/docker/docker.go#L294-L305)). +Using upstream networking does not imply Docker’s default `nat` port filtering. +NetOpsBench does not override this upstream network option. + + +Runtime and campaign records include the actual Containerlab version and binary +hash, plus the SONiC startup script hash. A different or unrecorded backend +cannot resume a campaign: retain the historical artifacts and create a new one. +Capacity samples must carry the same backend identity; measurements from the +former custom backend cannot admit new deployments. + +Generated fabrics currently use BGP without BFD. A 30-second device-outage +observation can end before the negotiated BGP hold timer expires; it measures +that fault interval, not guaranteed post-convergence failover. Read the saved +FIB and neighbor evidence alongside Pingmesh loss. A redundant link or peer +fault may leave Pingmesh below its alert threshold while reducing paths. + +### Large-topology defaults + +The k12 profile selects 16 Containerlab workers and Pingmesh destination batches +of 32. All scales use official deployment scheduling and sequential SONiC service +startup. Full SONiC completion and runtime health gates remain enabled. Measure +resource consumption on this backend before admitting larger deployments; old +custom-backend capacity estimates do not establish K18 feasibility. + +Generate current assets with `netopsbench benchmark prepare --scales xlarge,fat-tree-k12,fat-tree-k18`. Healthy scenarios use the same baseline and diagnostic episode lifecycle as fault cases. Complete observation windows are 66 seconds for Xlarge and 42 seconds for K12/K18. Xlarge and K18 use two clients per rack with 50 PPS per client. K18 has 405 switches, 324 clients, and a `/22` management subnet. Pingmesh plans are generated once; client processes execute the fixed peer/port schedule. Coverage refers to topology candidate paths, not verified ECMP paths. + +This refactor requires topology/runtime schema v4, scale profiles v2 and client configuration v2. Recreate old runtimes and regenerate their topology/scenario assets; old formats are rejected. Client addresses now start at `192.168.1.0/24`, and Fat-tree ASNs are allocated consecutively by tier. The default local image is `netopsbench-client:pingmesh-v2`; `NETOPSBENCH_CLIENT_IMAGE` selects another image built from the current source. + +The acceptance entrypoint defaults to diagnosis mode with the DeepAgent +DeepSeek preset. Native Codex runs only when explicitly selected with +`--agents codex` or `--agents deepagent codex`. Use `--mode effects` +for configuration, observation and recovery validation without constructing +agents, requesting models or generating scores: ```bash -python3 --version -docker run --rm hello-world -containerlab version -sudo -n docker ps -sudo -n containerlab version -sudo -n rm --version +PYTHONPATH=. python scripts/validate_pingmesh_scales.py --mode effects --scales xs +PYTHONPATH=. python scripts/validate_pingmesh_scales.py --mode effects \ + --scales medium,large,fat-tree-k8,fat-tree-k12,xlarge,fat-tree-k18 ``` -If Docker still reports a socket permission error after `sudo usermod -aG docker $USER`, log out and back in, or start a new shell with `newgrp docker`. The `sudo -n` commands must not prompt for a password. +Each scale uses one lab and the existing suite loop. Capacity gates require a +20% memory margin; the 12 GiB emergency floor releases only campaign-owned +resources. A failed/interrupted case restores the fault and preserves the lab. +A failed recovery quarantines it. Successful requested cases, final health and +saved reports precede teardown. External runtimes remain caller-owned. -## Install +For a small real agent check, configure the DeepSeek preset and native Codex +login, then select the XS authentication fault: ```bash -git clone https://github.com/NetX-lab/NetOpsBench.git -cd NetOpsBench -python -m venv .venv -source .venv/bin/activate -pip install -e ".[agent]" +PYTHONPATH=. python scripts/validate_pingmesh_scales.py --scales xs \ + --agents deepagent codex --fault-types bgp_auth_mismatch \ + --output .netopsbench/auth-diagnosis-v2 ``` +The two agents run sequentially with restored health and fresh observation +windows. Diagnosis mode remains the default; running it over all formal scales +makes real model requests for the complete selected corpus. + +Acceptance artifacts include `acceptance.json`, generated cases/coverage +matrices, raw route and probe effect evidence, recovery checks, resource samples, +ingestion timing and independent agent traces. To resume, use the same output, +mode, requested case set and agent configuration with `--resume-runtime `. +Profile, catalog version, case IDs/content, plan, image and configuration must +match before model requests or resource changes. Completed valid cases skip +even with a zero score; incomplete/invalid attempts can run again. Quarantined +owned resources require explicit `--rebuild-runtime`; archived campaigns and +scores are never automatically migrated. +Capacity estimates are updated with the measured peaks from each completed scale. K18 requires a representative switch sample with at least 18 data ports and adequate available host memory. To continue K18 with an existing peak sample, run: + +```bash +PYTHONPATH=. python scripts/validate_pingmesh_scales.py \ + --mode effects --scales fat-tree-k18 \ + --capacity-sample /absolute/path/to/xlarge-effects/capacity-sample.json \ + --output .netopsbench/fault-catalog-v2/k18-effects +``` + +For an explicitly monitored experiment, `--allow-tight-capacity` waives the +20% memory margin. The report retains the failed margin check and the override; +the measured peak estimate plus 12 GiB of available headroom, disk capacity, and +representative switch samples are still required. + +Agent execution failures are distinct from valid `inconclusive` conclusions. +After verified recovery, acceptance records an agent failure and continues with +the next case. Finished agent failures are reported separately and skipped on +resume; successful `inconclusive` conclusions retain their real score. In diagnosis +mode, a failed effect audit also ends only that case when recovery verifies a +complete healthy window. It remains invalid and unscored, is skipped on resume, +and does not interrupt the remaining diagnoses. Effects-only acceptance retains +its stricter stop-on-invalid policy. A valid completed diagnosis whose subsequent recovery failed also +keeps its score and trace. Continuing requires the quarantined lab to be +explicitly rebuilt and checked healthy; the completed diagnosis is skipped. + +Shared InfluxDB and Grafana containers are reused without automatic recreation during provisioning. Apply shared-service configuration upgrades explicitly when no active runtimes depend on them. + ## Run one case Supported provider presets: @@ -80,7 +182,8 @@ Supported provider presets: ```bash netopsbench benchmark prepare --scales xs export OPENAI_API_KEY=... -PYTHONPATH=. python examples/01_run_scenario.py --vendor openai +PYTHONPATH=. python examples/01_run_scenario.py --vendor openai \ + --scenario scenarios/generated/xs/generated_link_down_xs_001.yaml ``` The run provisions an XS topology, starts observability, injects one generated fault, calls the reference agent, scores the returned diagnosis, and writes a `BenchmarkReport`. @@ -93,3 +196,5 @@ The run provisions an XS topology, starts observability, injects one generated f - Implement your own agent with [Custom Troubleshooting Agents](/docs/build-your-agent/custom-agents). - Run larger evaluations with [Running Benchmarks](/docs/run-benchmarks/run-scenario-vs-suite). - Use [Operations](/docs/debug-operate/observability) only when a runtime, Grafana dashboard, or cleanup path needs inspection. + +Acceptance resume requires the same selected scenario IDs and contents, profile, Pingmesh plan, client image and agent configuration. Valid zero-score diagnoses and verified recovered case failures are finished cases; interrupted attempts remain eligible for resume. A campaign that finishes with agent failures records `completed_with_agent_failures`; one with invalid effects records `completed_with_case_failures`. Both release their owned lab after final health validation. Setup, incomplete recovery validation, and effects-only invalid cases still stop acceptance. Quarantined owned labs require `--rebuild-runtime`; external labs are never rebuilt or released by acceptance. SIGINT/SIGTERM request cancellation, recovery and an atomic checkpoint. Memory monitoring starts before deployment and protects the existing 12 GiB available-memory floor. Health checks share one elapsed-time deadline across all probes and retries. diff --git a/docs/content/docs/run-benchmarks/interactive-simulator.mdx b/docs/content/docs/run-benchmarks/interactive-simulator.mdx index d47982a..03b84af 100644 --- a/docs/content/docs/run-benchmarks/interactive-simulator.mdx +++ b/docs/content/docs/run-benchmarks/interactive-simulator.mdx @@ -49,9 +49,9 @@ with NetOpsBench(workspace=".") as bench: incident.close() # fault recovery occurs once ``` -The optional localhost HTTP service accepts opaque case IDs and the same typed -tool and diagnosis actions. Install `netopsbench[simulator]` and run -`netopsbench-simulator --help` for its scenario-loading options. +The simulator is a local Python SDK. The standalone simulator HTTP service has +been removed. Per-case authenticated HTTP MCP for diagnostic agents remains +available and uses the same tool registry. `max_agent_seconds` is checked at action boundaries. It prevents a session from accepting additional tool or submit actions after its deadline; it does diff --git a/docs/content/docs/run-benchmarks/methodology.mdx b/docs/content/docs/run-benchmarks/methodology.mdx index e2e55cd..0241ac0 100644 --- a/docs/content/docs/run-benchmarks/methodology.mdx +++ b/docs/content/docs/run-benchmarks/methodology.mdx @@ -26,36 +26,80 @@ Pingmesh endpoint density. | Scale | Family | Fabric devices | Clients | |---|---|---:|---:| | XS | CLOS | 2 spine + 2 leaf | 2 | -| Small | CLOS | 2 spine + 4 leaf | 8 | | Medium | CLOS | 4 spine + 8 leaf | 16 | | Large | CLOS | 4 spine + 16 leaf | 64 | -| Xlarge | CLOS | 16 spine + 128 leaf | 128 | +| Xlarge | CLOS | 16 spine + 128 leaf | 256 | | Fat-tree K=8 | Fat-tree | 16 core + 32 aggregation + 32 edge | 128 | | Fat-tree K=12 | Fat-tree | 36 core + 72 aggregation + 72 edge | 144 | +| Fat-tree K=18 | Fat-tree | 81 core + 162 aggregation + 162 edge | 324 | -The benchmark covers twelve canonical fault types: +Fault catalog version 2 defines **24 scored fault types and 27 injection mechanisms**. +The scored category is independent of the private execution mechanism; agents +continue returning the existing `DiagnosisResult` fields. | Category | Fault types | |---|---| -| Link | `link_down`, `link_flapping` | -| Routing | `blackhole_route`, `static_route_misconfig`, `bgp_neighbor_misconfig`, `route_policy_misconfig` | +| Link and addressing | `link_down`, `link_flapping`, `interface_ip_misconfig` | +| Node and service | `device_down`, `bgp_process_down` | +| Forwarding | `blackhole_route`, `static_route_misconfig`, `routing_loop` | +| BGP neighbor | `bgp_as_mismatch`, `bgp_auth_mismatch`, `bgp_update_source_mismatch`, `bgp_neighbor_shutdown`, `bgp_max_prefix_misconfig` | +| Route publication and selection | `route_origination_misconfig`, `route_filter_misconfig`, `route_flapping`, `ecmp_misconfig` | | Impairment | `mtu_mismatch`, `packet_loss`, `packet_corruption`, `high_latency` | -| System | `device_down` | -| ACL | `acl_misconfig` | - -Each scale combines fault cases with healthy negative samples: - -| Scale | Fault cases | Healthy cases | Total | -|---|---:|---:|---:| -| XS | 12 | 2 | 14 | -| Small | 12 | 3 | 15 | -| Medium | 24 | 4 | 28 | -| Large | 48 | 4 | 52 | -| Xlarge | 66 | 4 | 70 | -| Fat-tree K=8 | 66 | 4 | 70 | -| Fat-tree K=12 | 66 | 4 | 70 | - -Scenarios are generated from the packaged canonical campaign spec. Running `netopsbench benchmark prepare --scales ` materializes YAML files under `scenarios/generated//`; `--spec` can select a custom campaign. +| ACL | `acl_source_misconfig`, `acl_destination_misconfig`, `acl_l4_port_misconfig` | + +Each necessary coverage unit gets one case. Units describe the type, mechanism, +role, interface position and necessary impact scope. Larger topologies spread +these units across devices and pods instead of multiplying repeated cases. + +| Scale | Purpose | Fault cases | Healthy cases | Total | +|---|---|---:|---:|---:| +| XS | validation | 3 | 1 | 4 | +| Medium | benchmark | 60 | 4 | 64 | +| Large | benchmark | 60 | 4 | 64 | +| Xlarge | benchmark | 60 | 4 | 64 | +| Fat-tree K=8 | benchmark | 104 | 4 | 108 | +| Fat-tree K=12 | benchmark | 104 | 4 | 108 | +| Fat-tree K=18 | benchmark | 104 | 4 | 108 | + +The six formal scales contain 516 cases. XS validates health, a fabric link, +a spine outage and BGP authentication; its results are excluded from formal +benchmark aggregates. `small` was removed without a conversion path. Historical +results and runtimes remain under their owners' control. + +New raw results keep diagnosis, scoring and observation fields in the primary +JSON. Large private baseline, fault and recovery route snapshots live in atomic +`evidence//` gzip JSON artifacts; their references record paths, +SHA-256 hashes and byte counts. Decode them with `json.load(gzip.open(path, "rt"))`. +Execution and scoring still use the complete live snapshots. Existing results +and diagnostic trajectories are never rewritten. + +Campaign checkpoints explicitly record whether a diagnosis completed. Resume +uses that state and validity evidence, including valid zero-score diagnoses; +it does not infer completion by reopening historical raw results. Effects cases +require successful recovery before they are considered completed. + +`netopsbench benchmark prepare` generates the six benchmark profiles. +Use `--scales xs` explicitly for validation. Omitted scale arguments in SDK +scenario creation, topology generation and public examples default to `medium`. +Custom profiles default to `purpose: benchmark`; `supported_scales()` still +includes XS. Generation writes scenario YAML and `coverage.json` with selected +roots, neighbors, prefixes and fixed-plan candidate/control witnesses. + +The merged types require `episode.parameters.mechanism`: + +| Type | Mechanisms | +|---|---| +| `route_origination_misconfig` | `network_statement_missing`, `origination_policy_deny` | +| `route_filter_misconfig` | `export_filter`, `import_filter` | +| `ecmp_misconfig` | `max_paths_limit`, `multipath_relax_disabled` | + +CLOS uses a shared spine ASN, so it does not generate the multipath-relax +mechanism. Fat-tree tests both mechanisms on edge and aggregation devices; +aggregation targets cross-pod prefixes. ECMP requires multiple actual healthy +FIB next hops and fewer, still nonzero next hops under fault. Healthy RTT and +loss are permitted. Uniform public route observations expose missing prefixes, +neighbor count changes and reduced FIB next hops independently of injection +parameters. Source ports do not prove which ECMP paths the probes traversed. ## Observation validity @@ -72,10 +116,102 @@ The canonical packet-loss campaign applies 30% loss on one selected egress member. On redundant fabrics, ECMP can dilute the endpoint-visible symptom; the benchmark reports only the evidence actually measured and does not lower detector thresholds to force an anomaly. Large profiles use a three-second -probe cycle so complete ECMP coverage is spread over 102 seconds (xlarge/K8) -or 114 seconds (K12) instead of being emitted in a host-scheduling burst. +probe interval. Their fixed offline schedules require 66-second complete windows +for Xlarge and 42 seconds for K8/K12/K18. Every rack pair participates; same-rack +clients form a complete directed mesh, while cross-rack tasks use deterministic +client matching. Xlarge and K18 split each rack-pair task between two clients. +The plan audits all directed links through candidate shortest-path DAGs, including +access links. This is topology coverage; source ports sample ECMP without proving +which kernel forwarding paths were selected. Runtime coverage checks the exact +planned peer/port-batch set and filters by `plan_id`. +Offline placement and private effect validation share the same candidate-path +DAG scope. Validation reuses already queried records for all fixed planned flows +within that configuration's scope, instead of relying on a small witness sample. +Records with any local send error cannot satisfy that coverage requirement; +network packet loss still counts as an executed probe. +All cases on a scale use one frozen experiment policy from the scale profile. +The observation window is the greater of configured `observation_seconds` and +the fixed plan's complete window: 30 seconds for XS/medium/large, 42 for +K8/K12/K18, and 66 for Xlarge. Healthy, ordinary and periodic cases share this +window; no fault-specific extension is applied. Early/steady observations are +analysis slices of one continuous capture, with no benchmark stabilization gap. + +| Scale | New baseline / case / recovery health window (s) | Recovery total budget (s) | +|---|---:|---:| +| XS | 30 | 120 | +| Medium | 30 | 120 | +| Large | 30 | 180 | +| Xlarge | 66 | 240 | +| Fat-tree K=8 | 42 | 240 | +| Fat-tree K=12 | 42 | 300 | +| Fat-tree K=18 | 42 | 600 | + +`netopsbench/models/scale_profiles.yaml` supplies the common policy and optional +per-profile `experiment` overrides. Its common `observation_seconds: 30` is a +minimum: the fixed plan raises it to 42 or 66 seconds where required. Changing +these settings changes the profile digest; regenerate scenarios and start a new +campaign. Explicit durations in custom SDK scenarios remain supported. + +A fresh baseline is captured once and validated using absolute health and full +coverage. Recovery captures the same scale window and can hand that verified +window to the next case; identity, age, recalibration and fresh-query rules still +apply. Recovery budgets are explicit profile settings, shared by commands, +background-controller shutdown, health probes, queries and retries. + +Periodic faults default to 10 seconds faulty / 10 seconds healthy. Within the +observation window, a case must prove fault → healthy → fault; route flapping +also requires actual withdrawal/readvertisement evidence and an established +session. Missing evidence invalidates the case instead of extending the window. +For access outages, only structurally correct, actually recorded local send +failures overlapping verified outage intervals may explain missing valid tasks. +They remain invalid probe samples and the original full audit stays incomplete. +Completely missing records, incorrect batches and errors during healthy periods +invalidate the case. No runtime peer, port or schedule changes are made. +Plan coverage and window ingestion readiness are checked separately. Existing +`probe_cycle` records before and after the interval bound the rounds that must +be present; the fixed plan supplies each round's expected targets, including +empty rounds. Boundary rounds are checked in full, while only records inside +the left-closed, right-open interval enter anomaly statistics. Late repeated +tasks and missing fields cannot pass merely because plan coverage is complete. +Queries and waits share the processing deadline without extending the window. +Each read includes the boundary context and all required metric fields. The +same returned rows prove ingestion readiness and supply the strictly sliced +statistical window, avoiding a separate progress query. Source shards remain +limited to 16 clients, with at most four concurrent HTTP requests per process. +Observation waiting uses a monotonic deadline; UTC query bounds retain their +fractional precision and fixed configured duration. + +Baseline handoff records component-level identity changes. An owned FRR startup +file rewrite is accepted only after running and saved configuration checks; +commands retain their order and nesting. The verified recovery window is bound +to its stable recovered identity, including any verified device restart. The +next case still checks identity, freshness and recalibration, then reads the +window again rather than using cached telemetry. +The 600-second recalibration period starts at the latest independently verified +new healthy window; republishing an older window cannot renew it. The window +must still be no more than 120 seconds old. A failed diagnosis or invalid fault +effect does not invalidate a separately verified recovery window. Publication +and rejection reasons are recorded without changing the preceding case result. + +Both bundled agents have a configured total diagnosis budget of 600 seconds, +including setup, reasoning and tools. DeepSeek requests retain their individual +120-second ceiling within the remaining total budget. Cancellation is followed +by separately measured resource cleanup and fault recovery. Effects mode skips +model diagnosis. Reports include per-case phase measurements and a +`phase-timings.csv` artifact; changed experiment settings require a new campaign. +The existing `recovery` phase also contains `steps` for fault restoration, +convergence, window waiting, query/ingestion, identity checks and handoff. Query +steps retain baseline/current ingestion timings and request-attempt counts +separately: concurrent read durations must not be summed as wall time. These +child measurements are also exported to `recovery-steps.csv`, leaving the +existing `phase-timings.csv` columns and parent-phase totals unchanged. + +ACL validity requires rule hits and increased ordinary or DF probe loss. DF loss +cannot establish ACL impact when local send errors or confirmed MTU drops explain +it. These private effect checks do not change detector thresholds or scores. Background traffic must start its complete topology-derived flow matrix before the baseline is captured. A partial matrix is an infrastructure-invalid case, rather than a degraded observation presented to the agent. +The profile's per-client PPS value is a hard ceiling. A smaller switch budget can reduce it; a larger switch budget cannot increase it. Xlarge and K18 cap background traffic at 50 PPS per client. The baseline is also invalid when coverage is incomplete, any path is unreachable, latency or network-MTU anomalies exist, or an unexplained local DF probe error occurs. A DF-only local send error is treated as a consequence of @@ -135,7 +271,7 @@ Some faults affect both ends of a link or path segment. For `link_down`, `link_f ## Optional semantic fault-type judge -Canonical string matching is the default. Set `NETOPSBENCH_FAULT_TYPE_JUDGE_ENABLED=1` to allow an LLM judge for non-exact but semantically meaningful fault type descriptions, such as mapping "BGP peer AS mismatch" to `bgp_neighbor_misconfig`. +Canonical string matching is the default. Set `NETOPSBENCH_FAULT_TYPE_JUDGE_ENABLED=1` to allow an LLM judge for non-exact but semantically meaningful fault type descriptions, such as mapping "BGP peer AS mismatch" to `bgp_as_mismatch`. The judge affects only fault-type classification. Verdict, device localization, interface localization, and efficiency metrics remain deterministic. Reports include `fault_type_judgment` when semantic matching is used. diff --git a/docs/content/docs/run-benchmarks/run-scenario-vs-suite.mdx b/docs/content/docs/run-benchmarks/run-scenario-vs-suite.mdx index 8896abc..ede6f07 100644 --- a/docs/content/docs/run-benchmarks/run-scenario-vs-suite.mdx +++ b/docs/content/docs/run-benchmarks/run-scenario-vs-suite.mdx @@ -17,14 +17,14 @@ NetOpsBench has one execution path with several entrypoints. Start with one scen Prepare scenario assets before these runs: ```bash -# prepare benchmark scenarios for all seven built-in topology scales +# prepare benchmark scenarios for the six formal benchmark scales netopsbench benchmark prepare ``` Use `--seed` when you need reproducible scenario generation, default seed is 42: ```bash -netopsbench benchmark prepare --scales xs,small --seed 42 +netopsbench benchmark prepare --scales medium,large --seed 42 ``` ## One scenario @@ -54,18 +54,32 @@ The script passes a list of scenarios and requests multiple workers: run = bench.sessions.run_suite( scenarios=scenarios, agent=agent, - scale="xs", + scale="medium", workers=3, ) ``` Use a small suite to check whether an agent generalizes beyond one selected case before paying the cost of a full generated corpus. +## Baseline handoff between cases + +Within one suite, each worker keeps its topology and traffic running. A case can hand its verified healthy window to the next case on that same worker. Healthy cases offer their observation window only after it passes the absolute health gate; fault cases offer the post-recovery validation window. Cleanup and the full worker health check must succeed before either can be reused. + +Recovery convergence, the validation window, snapshot queries and coverage retries share one deadline. The recovery budget comes from the profile's explicit `experiment.recovery_timeout_seconds`, independently of the observation window. If the remaining budget cannot cover a complete validation window, recovery remains unverified and the runtime is quarantined; a shortened window is never published as a healthy baseline. + +The next case always captures its own full observation window. A fresh baseline now uses one complete healthy capture and an absolute-health validation query. Reuse avoids that capture (42 seconds for K12), while observations are queried again. This changes baseline selection; performance comparisons should use the same handoff policy and case ordering. + +Handoff is rejected if the window ended more than 120 seconds ago, is too short, or the runtime containers, generated configuration, scale policy, traffic profile, or verified traffic plan have changed. A fresh capture and absolute-health validation are required after 600 seconds since the last fresh calibration. The worker owns one consumable candidate; a broken incident or failed cleanup clears it. This assumes exclusive ownership of the worker during the suite: do not edit live device configuration out of band while it runs. + +Only window timestamps are handed off. Telemetry is queried again, so late-arriving data remains visible. Baseline and observation queries overlap under a process-wide limit of four InfluxDB HTTP requests. Each raw case result records `baseline_preparation` (fresh/reused and reason) and `cleanup.baseline_handoff`. + +Use one `run_suite(...)` or `run_on_runtime_suite(...)` call for a batch. Separate `run_on_runtime_scenario(...)` calls create separate executors and do not share a baseline. No handoff survives the end of a suite. + ## Full scale run ```bash PYTHONPATH=. python examples/03_run_scale_benchmark.py \ - --scale xs \ + --scale medium \ --workers 3 \ --vendor ``` @@ -77,19 +91,21 @@ Scale choice changes both runtime cost and diagnosis difficulty: | Scale | Use | |---|---| | `xs` | Fastest feedback and provider validation. | -| `small` | More topology variety with moderate runtime cost. | -| `medium` | Broader fabric behavior and more generated scenarios. | +| `medium` | Default formal benchmark scale. | | `large` | Stress test for runtime stability, observability volume, and agent efficiency. | -| `xlarge` | 144-switch CLOS benchmark with 128 clients and 70 cases. | -| `fat-tree-k8` | 80-switch, three-tier Fat-tree with 128 clients and 70 cases. | -| `fat-tree-k12` | 180-switch, three-tier Fat-tree with 144 clients and 70 cases. | +| `xlarge` | 144-switch CLOS benchmark with 256 clients and 64 cases. | +| `fat-tree-k8` | 80-switch, three-tier Fat-tree with 128 clients and 108 cases. | +| `fat-tree-k12` | 180-switch, three-tier Fat-tree with 144 clients and 108 cases. | +| `fat-tree-k18` | 405-switch, three-tier Fat-tree with 324 clients and 108 cases. | + +By default, the scale example uses 3 workers for xs, 2 for medium/large, and 1 for xlarge/Fat-tree, matching the batch shell script. An explicit `--workers` overrides this selection. Worker count controls concurrency. Each worker provisions its own lab resources. If Docker, Containerlab, or provider rate limits become unstable, reduce `--workers`. For Xlarge and Fat-tree, begin with one worker and confirm host capacity, baseline health, provider connectivity, and exact teardown before increasing concurrency: ```bash -netopsbench benchmark prepare --scales xlarge,fat-tree-k8,fat-tree-k12 +netopsbench benchmark prepare --scales xlarge,fat-tree-k8,fat-tree-k12,fat-tree-k18 PYTHONPATH=. python examples/03_run_scale_benchmark.py \ --scale fat-tree-k12 --workers 1 --vendor deepseek ``` @@ -107,7 +123,7 @@ Preparing all three profiles does not deploy three labs. A lab is provisioned on ## Multi-scale batches ```bash -BENCH_VENDOR= BENCH_SCALES="xs small" bash scripts/run_all_benchmarks.sh +BENCH_VENDOR= BENCH_SCALES="medium large" bash scripts/run_all_benchmarks.sh ``` For long-running jobs: @@ -121,7 +137,7 @@ Useful environment overrides: | Variable | Meaning | |---|---| | `BENCH_VENDOR` | Provider passed to `examples/03_run_scale_benchmark.py`. | -| `BENCH_SCALES` | Space-separated scale list such as `xs small`. | +| `BENCH_SCALES` | Space-separated scale list such as `medium large`. | | `BENCH_WORKERS_` | Worker count override for one scale, for example `BENCH_WORKERS_LARGE=2`. | | `BENCH_CLEAN_RUNS=1` | Explicitly remove previous `.netopsbench/runs/` artifacts before the batch. By default, previous reports and traces are preserved. | diff --git a/examples/01_run_scenario.py b/examples/01_run_scenario.py index 54fe31d..cf1800c 100644 --- a/examples/01_run_scenario.py +++ b/examples/01_run_scenario.py @@ -23,7 +23,6 @@ resolve_repo_root, wait_and_print_run, ) -from examples.agents import MinimalDeepAgent from netopsbench.sdk import NetOpsBench @@ -32,14 +31,18 @@ def main( *, vendor: str = "minimax", bench_cls=NetOpsBench, - agent_cls=MinimalDeepAgent, + agent_cls=None, + backend: str = "deepagent", + scenario_path: Path | None = None, ) -> int: repo = resolve_repo_root(repo_root) scenario = require_scenarios( repo, - "scenarios/generated/xs/generated_link_down_xs_001.yaml", + str(scenario_path) + if scenario_path is not None + else "scenarios/generated/medium/generated_link_down_medium_001.yaml", prepare_hint=( - "Generate benchmark assets first with " "`netopsbench benchmark prepare --scales xs` from the repo root." + "Generate benchmark assets first with `netopsbench benchmark prepare --scales medium` from the repo root." ), )[0] @@ -48,7 +51,7 @@ def main( # ``with`` releases agent handles + manager resources on exit. with bench_cls(workspace=str(repo)) as bench: - raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor) + raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor, backend=backend) print_agent_banner("agent", vendor, raw_agent) try: run = bench.sessions.run_scenario(scenario=scenario, agent=agent) @@ -59,5 +62,11 @@ def main( if __name__ == "__main__": - args = build_arg_parser("Run one scenario").parse_args() - raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor)) + parser = build_arg_parser("Run one scenario") + parser.add_argument( + "--scenario", type=Path, default=None, help="Scenario YAML path, relative to the repository or absolute." + ) + args = parser.parse_args() + raise SystemExit( + main(repo_root=args.repo_root, vendor=args.vendor, backend=args.agent, scenario_path=args.scenario) + ) diff --git a/examples/02_run_suite.py b/examples/02_run_suite.py index 216930f..11438bc 100644 --- a/examples/02_run_suite.py +++ b/examples/02_run_suite.py @@ -21,7 +21,6 @@ resolve_repo_root, wait_and_print_run, ) -from examples.agents import MinimalDeepAgent from netopsbench.sdk import NetOpsBench @@ -30,23 +29,24 @@ def main( *, vendor: str = "minimax", bench_cls=NetOpsBench, - agent_cls=MinimalDeepAgent, + agent_cls=None, + backend: str = "deepagent", ) -> int: repo = resolve_repo_root(repo_root) scenarios = require_scenarios( repo, [ - "scenarios/generated/xs/generated_link_down_xs_001.yaml", - "scenarios/generated/xs/generated_packet_loss_xs_001.yaml", - "scenarios/generated/xs/generated_high_latency_xs_001.yaml", + "scenarios/generated/medium/generated_link_down_medium_001.yaml", + "scenarios/generated/medium/generated_packet_loss_medium_001.yaml", + "scenarios/generated/medium/generated_high_latency_medium_001.yaml", ], prepare_hint=( - "Generate benchmark assets first with " "`netopsbench benchmark prepare --scales xs` from the repo root." + "Generate benchmark assets first with `netopsbench benchmark prepare --scales medium` from the repo root." ), ) with bench_cls(workspace=str(repo)) as bench: - raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor) + raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor, backend=backend) print("02 — Run suite") print_agent_banner("agent", vendor, raw_agent) @@ -55,7 +55,7 @@ def main( run = bench.sessions.run_suite( scenarios=scenarios, agent=agent, - scale="xs", + scale="medium", workers=3, ) return wait_and_print_run(run, raise_on_failure=True) @@ -66,4 +66,4 @@ def main( if __name__ == "__main__": args = build_arg_parser("Run a suite of scenarios").parse_args() - raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor)) + raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor, backend=args.agent)) diff --git a/examples/03_run_scale_benchmark.py b/examples/03_run_scale_benchmark.py index e6179eb..b342eab 100644 --- a/examples/03_run_scale_benchmark.py +++ b/examples/03_run_scale_benchmark.py @@ -7,7 +7,7 @@ Usage:: PYTHONPATH=. python examples/03_run_scale_benchmark.py - PYTHONPATH=. python examples/03_run_scale_benchmark.py --scale small + PYTHONPATH=. python examples/03_run_scale_benchmark.py --scale medium PYTHONPATH=. python examples/03_run_scale_benchmark.py --vendor kimi PYTHONPATH=. python examples/03_run_scale_benchmark.py --vendor zhipu """ @@ -24,11 +24,19 @@ resolve_repo_root, wait_and_print_run, ) -from examples.agents import MinimalDeepAgent from netopsbench.sdk import NetOpsBench, supported_scales -DEFAULT_SCALE = "xs" +DEFAULT_SCALE = "medium" SCALE_CHOICES = list(supported_scales()) +DEFAULT_WORKERS = { + "xs": 3, + "medium": 2, + "large": 2, + "xlarge": 1, + "fat-tree-k8": 1, + "fat-tree-k12": 1, + "fat-tree-k18": 1, +} def main( @@ -36,15 +44,18 @@ def main( *, scale: str = DEFAULT_SCALE, vendor: str = "minimax", - workers: int = 3, + workers: int | None = None, bench_cls=NetOpsBench, - agent_cls=MinimalDeepAgent, + agent_cls=None, + backend: str = "deepagent", ) -> int: + if workers is None: + workers = DEFAULT_WORKERS.get(scale, 1) repo = resolve_repo_root(repo_root) scenarios = discover_generated_scenarios(repo, scale) with bench_cls(workspace=str(repo)) as bench: - raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor) + raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor, backend=backend) print(f"03 — Scale benchmark (scale={scale})") print_agent_banner("agent", vendor, raw_agent) @@ -77,8 +88,10 @@ def main( parser.add_argument( "--workers", type=int, - default=3, - help="Number of concurrent runtime worker labs to provision. Default: %(default)s.", + default=None, + help="Concurrent runtime labs. Default: xs=3, medium/large=2, xlarge/fat-tree=1.", ) args = parser.parse_args() - raise SystemExit(main(repo_root=args.repo_root, scale=args.scale, vendor=args.vendor, workers=args.workers)) + raise SystemExit( + main(repo_root=args.repo_root, scale=args.scale, vendor=args.vendor, workers=args.workers, backend=args.agent) + ) diff --git a/examples/04_custom_faults.py b/examples/04_custom_faults.py index 21e9faf..4ca7247 100644 --- a/examples/04_custom_faults.py +++ b/examples/04_custom_faults.py @@ -24,7 +24,6 @@ resolve_repo_root, wait_and_print_run, ) -from examples.agents import MinimalDeepAgent from examples.faults.custom_fault_pack import build_fault_pack from netopsbench.sdk import NetOpsBench @@ -34,7 +33,8 @@ def main( *, vendor: str = "minimax", bench_cls=NetOpsBench, - agent_cls=MinimalDeepAgent, + agent_cls=None, + backend: str = "deepagent", ) -> int: repo = resolve_repo_root(repo_root) scenario = require_scenarios( @@ -48,7 +48,7 @@ def main( print(" custom fault: demo_custom_latency") with bench_cls(workspace=str(repo)) as bench: bench.faults.register_pack(build_fault_pack()) - raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor) + raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor, backend=backend) print_agent_banner("agent", vendor, raw_agent) try: run = bench.sessions.run_scenario(scenario=scenario, agent=agent) @@ -60,4 +60,4 @@ def main( if __name__ == "__main__": args = build_arg_parser("Register and run a custom fault scenario").parse_args() - raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor)) + raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor, backend=args.agent)) diff --git a/examples/05_manual_runtime.py b/examples/05_manual_runtime.py index 5705ae5..33ba534 100644 --- a/examples/05_manual_runtime.py +++ b/examples/05_manual_runtime.py @@ -23,7 +23,6 @@ resolve_repo_root, wait_and_print_run, ) -from examples.agents import MinimalDeepAgent from netopsbench.sdk import NetOpsBench @@ -32,14 +31,15 @@ def main( *, vendor: str = "minimax", bench_cls=NetOpsBench, - agent_cls=MinimalDeepAgent, + agent_cls=None, + backend: str = "deepagent", ) -> int: repo = resolve_repo_root(repo_root) scenario = require_scenarios( repo, - "scenarios/generated/xs/generated_link_down_xs_001.yaml", + "scenarios/generated/medium/generated_link_down_medium_001.yaml", prepare_hint=( - "Generate benchmark assets first with " "`netopsbench benchmark prepare --scales xs` from the repo root." + "Generate benchmark assets first with `netopsbench benchmark prepare --scales medium` from the repo root." ), )[0] @@ -51,10 +51,10 @@ def main( print(f" scenario: {scenario.name}") print(f" runtime: {runtime_name}") with bench_cls(workspace=str(repo)) as bench: - raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor) + raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor, backend=backend) print_agent_banner("agent", vendor, raw_agent) try: - runtime = bench.runtimes.provision(scale="xs", workers=1, name=runtime_name) + runtime = bench.runtimes.provision(scale="medium", workers=1, name=runtime_name) run = bench.sessions.run_on_runtime_scenario( scenario=scenario, runtime=runtime, @@ -78,4 +78,4 @@ def main( if __name__ == "__main__": args = build_arg_parser("Provision a runtime manually").parse_args() - raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor)) + raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor, backend=args.agent)) diff --git a/examples/06_llm_fault_type_judge.py b/examples/06_llm_fault_type_judge.py index 7da312a..bad5c08 100644 --- a/examples/06_llm_fault_type_judge.py +++ b/examples/06_llm_fault_type_judge.py @@ -3,7 +3,7 @@ Same structure as ``01_run_scenario.py`` but enables the LLM judge so that free-form agent answers like ``"BGP peer AS mismatch"`` are semantically -matched to the canonical ``bgp_neighbor_misconfig`` taxonomy instead of +matched to the canonical ``bgp_as_mismatch`` taxonomy instead of failing a deterministic string compare. The judge is activated entirely via environment variables — no code change @@ -31,13 +31,12 @@ resolve_repo_root, wait_and_print_run, ) -from examples.agents import MinimalDeepAgent from netopsbench.sdk import NetOpsBench # BGP neighbor misconfig is the scenario where the LLM judge adds the most value: # agents often describe the fault as "BGP peer AS mismatch" or "BGP session down" -# which don't match the canonical "bgp_neighbor_misconfig" deterministically. -_SCENARIO_REL = "scenarios/generated/xs/generated_bgp_neighbor_misconfig_xs_001.yaml" +# which don't match the canonical "bgp_as_mismatch" deterministically. +_SCENARIO_REL = "scenarios/generated/medium/generated_bgp_as_mismatch_medium_001.yaml" def main( @@ -45,14 +44,15 @@ def main( *, vendor: str = "minimax", bench_cls=NetOpsBench, - agent_cls=MinimalDeepAgent, + agent_cls=None, + backend: str = "deepagent", ) -> int: repo = resolve_repo_root(repo_root) scenario = require_scenarios( repo, _SCENARIO_REL, prepare_hint=( - "Generate benchmark assets first with " "`netopsbench benchmark prepare --scales xs` from the repo root." + "Generate benchmark assets first with `netopsbench benchmark prepare --scales medium` from the repo root." ), )[0] @@ -64,7 +64,7 @@ def main( print(f" llm judge : {'enabled (model=' + judge_model + ')' if judge_enabled else 'disabled (deterministic)'}") with bench_cls(workspace=str(repo)) as bench: - raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor) + raw_agent, agent = build_wrapped_agent(bench, agent_cls, vendor=vendor, backend=backend) print_agent_banner("agent ", vendor, raw_agent) try: run = bench.sessions.run_scenario(scenario=scenario, agent=agent) @@ -76,4 +76,4 @@ def main( if __name__ == "__main__": args = build_arg_parser("Run a BGP scenario with optional LLM-as-judge fault type evaluation").parse_args() - raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor)) + raise SystemExit(main(repo_root=args.repo_root, vendor=args.vendor, backend=args.agent)) diff --git a/examples/README.md b/examples/README.md index a06b361..cf6b867 100644 --- a/examples/README.md +++ b/examples/README.md @@ -37,10 +37,10 @@ added the repository root to Python's import path. ## Quick start -First generate the XS benchmark assets from the repo root: +First generate the medium benchmark assets from the repo root: ```bash -netopsbench benchmark prepare --scales xs +netopsbench benchmark prepare --scales medium ``` ```python @@ -50,7 +50,7 @@ from netopsbench.sdk import NetOpsBench, RunFailedError with NetOpsBench(workspace=".") as bench: agent = bench.agents.wrap(MinimalDeepAgent()) run = bench.sessions.run_scenario( - scenario="scenarios/generated/xs/generated_link_down_xs_001.yaml", + scenario="scenarios/generated/medium/generated_link_down_medium_001.yaml", agent=agent, ) try: diff --git a/examples/_common.py b/examples/_common.py index 1bb8387..087e75a 100644 --- a/examples/_common.py +++ b/examples/_common.py @@ -32,7 +32,7 @@ def require_scenarios(repo: Path, relative_paths: str | list[str], *, prepare_hi if not missing: return scenarios - hint = prepare_hint or "Generate benchmark assets first with `netopsbench benchmark prepare --scales xs`." + hint = prepare_hint or "Generate benchmark assets first with `netopsbench benchmark prepare --scales medium`." if len(scenarios) == 1: raise FileNotFoundError(f"Scenario not found: {scenarios[0]}. {hint}") raise FileNotFoundError(f"Scenario files missing: {missing}. {hint}") @@ -55,13 +55,24 @@ def discover_generated_scenarios(repo: Path, scale: str) -> list[Path]: return scenarios -def build_wrapped_agent(bench: Any, agent_cls: Any, *, vendor: str | None = None) -> tuple[Any, Any]: +def agent_class(backend: str): + if backend == "codex": + from examples.agents import CodexAgent + + return CodexAgent + if backend == "deepagent": + from examples.agents import MinimalDeepAgent + + return MinimalDeepAgent + raise ValueError(f"Unknown agent backend: {backend}") + + +def build_wrapped_agent( + bench: Any, agent_cls: Any = None, *, vendor: str | None = None, backend: str = "deepagent" +) -> tuple[Any, Any]: """Construct an example agent and wrap it when the SDK manager is available.""" - try: - raw_agent = agent_cls(vendor=vendor) if vendor is not None else agent_cls() - except TypeError: - # Keep compatibility with tiny fake agents used by tests and docs. - raw_agent = agent_cls() + factory = agent_cls or agent_class(backend) + raw_agent = factory(vendor=vendor) if backend == "deepagent" and vendor is not None else factory() agents = getattr(bench, "agents", None) wrap = getattr(agents, "wrap", None) @@ -100,6 +111,12 @@ def build_arg_parser( ), ) if with_vendor: + parser.add_argument( + "--agent", + choices=["deepagent", "codex"], + default="deepagent", + help="Diagnostic runtime: bundled DeepAgent or native isolated Codex CLI.", + ) parser.add_argument( "--vendor", default=DEFAULT_VENDOR, @@ -124,4 +141,5 @@ def build_arg_parser( def print_agent_banner(label: str, vendor: str, raw_agent: Any) -> None: """Print the standard ``vendor / model`` banner used by every example.""" model = getattr(raw_agent, "model", "?") + vendor = "codex" if raw_agent.__class__.__name__ == "CodexAgent" else vendor print(f" {label}: vendor={vendor} model={model}") diff --git a/examples/agents/README.md b/examples/agents/README.md index 9bc4ab1..3ec4fca 100644 --- a/examples/agents/README.md +++ b/examples/agents/README.md @@ -5,11 +5,13 @@ This directory contains the official public agent examples for NetOpsBench. ## Recommended example - `minimal_deepagent/agent.py` — a runnable DeepAgent example with MCP tools and multiple provider presets +- `codex_agent/agent.py` — native `codex exec` with episode MCP tools and an isolated Python/shell container; see [setup and acceptance](codex_agent/README.md) ## File roles - `minimal_deepagent/agent.py` — self-contained agent with LLM + MCP wiring (DeepAgents, LangChain, provider presets) -- `minimal_deepagent/prompts.py` — system prompt and prompt-building helpers +- `diagnosis.py` — shared diagnosis schema, public observation prompt and result mapping +- `minimal_deepagent/prompts.py` — DeepAgent output framing - `minimal_deepagent/skills/` — example-local DeepAgents skills loaded via `FilesystemBackend` - `examples.agents.MinimalDeepAgent` re-exports the canonical agent class for stable imports @@ -19,7 +21,7 @@ On a fresh clone, generate the XS benchmark assets before using the example scenario path below: ```bash -netopsbench benchmark prepare --scales xs +netopsbench benchmark prepare --scales medium ``` If you are building against the public SDK API: @@ -35,7 +37,7 @@ from netopsbench.sdk import NetOpsBench with NetOpsBench(workspace=".") as bench: agent = bench.agents.wrap(MinimalDeepAgent(vendor="openai")) run = bench.sessions.run_scenario( - scenario="scenarios/generated/xs/generated_link_down_xs_001.yaml", + scenario="scenarios/generated/medium/generated_link_down_medium_001.yaml", agent=agent, ) report = run.wait(raise_on_failure=True) @@ -60,5 +62,6 @@ For `examples/01_run_scenario.py`, choose provider via CLI argument: - `PYTHONPATH=. python examples/01_run_scenario.py --vendor openai` - `PYTHONPATH=. python examples/01_run_scenario.py --vendor minimax` +- `PYTHONPATH=. python examples/01_run_scenario.py --agent codex --scenario scenarios/generated/medium/generated_healthy_network_medium_001.yaml` (install `.[codex]` and sign in with the pinned native CLI) These examples are references for application code, not required internal platform machinery. diff --git a/examples/agents/__init__.py b/examples/agents/__init__.py index 9ec5563..ad8624b 100644 --- a/examples/agents/__init__.py +++ b/examples/agents/__init__.py @@ -1,5 +1,13 @@ -"""Official public example agents for NetOpsBench.""" +"""Bundled diagnostic agents; backend dependencies load only when selected.""" -from .minimal_deepagent.agent import MinimalDeepAgent +__all__ = ["MinimalDeepAgent", "CodexAgent"] -__all__ = ["MinimalDeepAgent"] + +def __getattr__(name): + if name == "MinimalDeepAgent": + from .minimal_deepagent.agent import MinimalDeepAgent + return MinimalDeepAgent + if name == "CodexAgent": + from .codex_agent.agent import CodexAgent + return CodexAgent + raise AttributeError(name) diff --git a/examples/agents/codex_agent/Dockerfile b/examples/agents/codex_agent/Dockerfile new file mode 100644 index 0000000..bdfdb6b --- /dev/null +++ b/examples/agents/codex_agent/Dockerfile @@ -0,0 +1,10 @@ +FROM alpine:3.24.1 +RUN apk add --no-cache python3 ca-certificates iptables util-linux bash \ + && adduser -D -u 1000 diagnostic +COPY codex /usr/local/bin/codex +COPY codex-code-mode-host /usr/local/bin/codex-code-mode-host +COPY entrypoint.sh /usr/local/bin/diagnostic-entrypoint +RUN chmod 755 /usr/local/bin/diagnostic-entrypoint /usr/local/bin/codex /usr/local/bin/codex-code-mode-host +WORKDIR /workspace +ENV HOME=/home/diagnostic +ENTRYPOINT ["/usr/local/bin/diagnostic-entrypoint"] diff --git a/examples/agents/codex_agent/README.md b/examples/agents/codex_agent/README.md new file mode 100644 index 0000000..d69465a --- /dev/null +++ b/examples/agents/codex_agent/README.md @@ -0,0 +1,99 @@ +# Native Codex diagnostic agent + +`CodexAgent` runs the actual Codex CLI reasoning and tool loop. It implements +the same `diagnose(context) -> DiagnosisResult` contract as other benchmark +agents. It uses episode-scoped MCP tools and a separate shell container. + +From a Linux checkout with Docker and the normal NetOpsBench runtime prerequisites: + +```bash +pip install -e '.[codex]' +# Install the native Codex 0.159.2 standalone package, including +# codex-code-mode-host beside the codex executable, then sign in: +codex login +netopsbench benchmark prepare --scales medium +PYTHONPATH=. python examples/01_run_scenario.py --agent codex \ + --scenario scenarios/generated/medium/generated_healthy_network_medium_001.yaml +``` + +The first run builds `netopsbench-codex:0.159.2` from the installed native +executables. The adapter verifies both the CLI version and required helper. +Selecting Codex does not import DeepAgents or require a DeepSeek API key. + +```python +from examples.agents import CodexAgent +from netopsbench.sdk import NetOpsBench + +with NetOpsBench(workspace=".") as bench: + agent = bench.agents.wrap(CodexAgent()) + report = bench.sessions.run_scenario( + scenario="scenarios/generated/medium/generated_healthy_network_medium_001.yaml", + agent=agent, + ).wait(raise_on_failure=True) +``` + +Defaults are model `gpt-6.1-sol`, effort `xhigh`, explicit Standard service +(`service_tier="default"`, Fast and Ultrafast disabled), a 600-second diagnosis deadline, +40 MCP calls, 2 CPU, 2 GiB RAM and 512 MiB scratch space. Model, effort, CLI +version, image, deadline, MCP budget, auth store and trace directory are explicit +constructor options. DeepAgent retains its existing provider configuration and +graph budget; the reports record the different capabilities and budgets. + +Each case starts a fresh ephemeral CLI session and temporary CLI state directory. +Only refreshed `auth.json` persists in `.netopsbench/private/codex-auth/`; the +host login directory, configuration, skills and history are never mounted. +The private credential store is excluded from artifacts. Do not copy it into +reports or an image. + +The container receives anonymous public observations, Python and shell tools. +It has no repository, answers, other cases, Docker socket or host privileges. +A namespace firewall is installed before dropping all capabilities. Direct +network access is denied; only the authenticated episode MCP endpoint and an +OpenAI CONNECT relay are reachable. The relay permits `chatgpt.com`, +`api.openai.com` and `auth.openai.com` on port 443, rejects private destinations, +and honors the host HTTPS proxy. Web search, plugins, subagents and bundled +coding skills are disabled. Full-access CLI mode operates inside this container. + +MCP and shell actions feed the existing trace recorder; MCP events are counted +once. Redacted native JSONL and stderr are retained separately. Token usage comes +from native completion events. The CLI does not expose an exact model-request +count, so the adapter does not invent one. Nonzero exit, failed turns, timeout, +missing output and invalid JSON produce `success=False` and remain execution +failures rather than completed diagnoses. + +Acceptance defaults to DeepAgent with the DeepSeek preset. To explicitly run +both agents for real scale acceptance: + +```bash +PYTHONPATH=. python scripts/validate_pingmesh_scales.py \ + --scales fat-tree-k18 --agents deepagent codex --vendor deepseek \ + --output .netopsbench/acceptance-k18 +``` + +The runner preflights both providers and the pinned runtime tools, performs XS +healthy/link/device smoke cases, checks capacity, and runs both K18 campaigns +sequentially in one lab. It saves per-case checkpoints and separate reports. +XS smoke targets a redundant fabric link and a spine, keeping every client +able to send. Access-link outages can cause local send failures and therefore +fail the unchanged complete-observation gate; these attempts remain recorded. +On failure it recovers the injected fault and retains the lab. Failed recovery +or full health quarantines the runtime. Completed low-score diagnoses count as +completed; execution errors are retried on resume. + +```bash +PYTHONPATH=. python scripts/validate_pingmesh_scales.py \ + --scales fat-tree-k18 --agents deepagent codex --vendor deepseek \ + --output .netopsbench/acceptance-k18 --resume-runtime /absolute/runtime/path +``` + +Resume requires the recorded runtime path and unchanged plan, profile, client +image, cases and agent configuration. An already removed runtime can be rebuilt; +quarantined owned resources require explicit `--rebuild-runtime`. External +runtimes are retained even after success. The 12 GiB available-memory emergency +guard may release an owned runtime, with the reason saved in the receipt. + +See the official [non-interactive CLI](https://learn.chatgpt.com/docs/non-interactive-mode), +[MCP](https://learn.chatgpt.com/docs/extend/mcp?surface=cli) and +[container isolation](https://learn.chatgpt.com/docs/agent-approvals-security) documentation. + +Cancellation waits for in-flight container startup before teardown. Container and network removal are verified independently; cleanup failures return an agent execution failure and retain resource identifiers for a later cleanup attempt. Temporary per-case credentials are removed even if Docker cleanup fails. diff --git a/examples/agents/codex_agent/__init__.py b/examples/agents/codex_agent/__init__.py new file mode 100644 index 0000000..c1fd43f --- /dev/null +++ b/examples/agents/codex_agent/__init__.py @@ -0,0 +1 @@ +"""Native Codex CLI diagnostic adapter.""" diff --git a/examples/agents/codex_agent/agent.py b/examples/agents/codex_agent/agent.py new file mode 100644 index 0000000..2beaa69 --- /dev/null +++ b/examples/agents/codex_agent/agent.py @@ -0,0 +1,455 @@ +"""Adapt native `codex exec` to the existing public diagnostic-agent contract.""" + +import asyncio +import json +import re +import shutil +import tempfile +import time +import uuid +from dataclasses import replace +from pathlib import Path + +from examples.agents.diagnosis import SYSTEM_GUIDANCE, DiagnosisOutput, build_result, build_user_prompt +from netopsbench.models.profiles import default_experiment_profile +from netopsbench.platform.scenario.timing import agent_cleanup_timing +from netopsbench.platform.toolkit._core.control import current_tool_control, diagnosis_budget_scope +from netopsbench.platform.toolkit.mcp.registry import tool_schemas +from netopsbench.platform.toolkit.mcp.session_server import session_mcp +from netopsbench.platform.utils.control import finish_cleanup +from netopsbench.sdk.agents import DiagnosisResult + +from .proxy import openai_proxy +from .runtime import CLI_VERSION, DEFAULT_IMAGE, DiagnosticContainer, credentials, ensure_image, image_content_identity + + +def strict_output_schema(): + schema = DiagnosisOutput.model_json_schema() + + def strict(node): + if isinstance(node, dict): + if node.get("type") == "object": + node["additionalProperties"] = False + node["required"] = list(node.get("properties", {})) + node.pop("default", None) + for value in node.values(): + strict(value) + elif isinstance(node, list): + for value in node: + strict(value) + + strict(schema) + return schema + + +def redact(value, secrets): + text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=False) + for secret in secrets: + if secret: + text = text.replace(secret, "[REDACTED]") + text = re.sub(r"eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", "[REDACTED]", text) + text = re.sub(r"sk-[A-Za-z0-9_-]{20,}", "[REDACTED]", text) + return re.sub(r"(?i)Bearer\s+[A-Za-z0-9._~-]+", "Bearer [REDACTED]", text) + + +class CodexEvents: + def __init__(self, trace=None): + self.trace = trace + self.items = {} + self.usage = {} + self.final = None + self.error = None + self.completed = False + + def accept(self, event): + kind = event.get("type") + if kind == "turn.completed": + self.completed = True + usage = event.get("usage") or {} + self.usage = { + key: int(usage.get(key, 0) or 0) for key in ("input_tokens", "output_tokens", "cached_input_tokens") + } + self.usage["total_tokens"] = self.usage["input_tokens"] + self.usage["output_tokens"] + if kind in {"turn.failed", "error"}: + self.error = str(event.get("error") or event.get("message") or "Codex turn failed") + item = event.get("item") or {} + if item.get("id"): + self.items[item["id"]] = item + if kind == "item.completed" and item.get("type") == "agent_message": + self.final = item.get("text") + # MCP calls are traced by the gateway; only shell events are recorded here. + if item.get("type") == "command_execution" and self.trace: + run_id = f"codex-{item['id']}" + if kind == "item.started": + self.trace.record_tool_start(name="shell", args={"command": item.get("command")}, run_id=run_id) + elif kind == "item.completed": + self.trace.record_tool_end( + output={"output": item.get("aggregated_output"), "exit_code": item.get("exit_code")}, run_id=run_id + ) + + def result(self, exit_code): + if exit_code != 0 or self.error or not self.completed: + raise RuntimeError(self.error or f"Codex did not complete (exit={exit_code})") + if not self.final: + raise ValueError("Codex returned no structured diagnosis") + return DiagnosisOutput.model_validate_json(self.final).model_dump() + + def counts(self): + return { + "mcp_calls": sum(item.get("type") == "mcp_tool_call" for item in self.items.values()), + "shell_calls": sum(item.get("type") == "command_execution" for item in self.items.values()), + "failed_mcp_calls": sum( + item.get("type") == "mcp_tool_call" and item.get("status") == "failed" for item in self.items.values() + ), + } + + +class CodexAgent: + def __init__( + self, + *, + name="codex", + model="gpt-6.1-sol", + reasoning_effort="xhigh", + cli_version=CLI_VERSION, + image=DEFAULT_IMAGE, + timeout_seconds=None, + max_tool_calls=40, + auth_store=None, + artifacts_dir=None, + ): + self.name, self.model, self.reasoning_effort = name, model, reasoning_effort + self.service_tier = "default" + self.cli_version, self.image = cli_version, image + self.timeout_seconds = ( + default_experiment_profile().diagnosis_timeout_seconds if timeout_seconds is None else timeout_seconds + ) + self.max_tool_calls = max_tool_calls + self.auth_store = Path(auth_store or ".netopsbench/private/codex-auth").resolve() + self._refresh_from_host = auth_store is None + self.artifacts_dir = Path(artifacts_dir or ".netopsbench/codex-traces").resolve() + self._containers = set() + self._image_id = None + self._image_content_sha256 = None + + def preflight(self): + credentials(self.auth_store, refresh_from_host=self._refresh_from_host) + self._image_id = ensure_image(image=self.image, version=self.cli_version) + self._image_content_sha256 = image_content_identity(self._image_id) + return { + "cli_version": self.cli_version, + "image_id": self._image_id, + "image_content_sha256": self._image_content_sha256, + "model": self.model, + "reasoning_effort": self.reasoning_effort, + "service_tier": self.service_tier, + "timeout_seconds": self.timeout_seconds, + "max_mcp_calls": self.max_tool_calls, + } + + def cli_args(self, endpoint): + args = [ + "codex", + "--ask-for-approval", + "never", + "exec", + "--json", + "--ephemeral", + "--ignore-user-config", + "--ignore-rules", + "--skip-git-repo-check", + "--sandbox", + "danger-full-access", + "--cd", + "/workspace", + "--model", + self.model, + "--output-schema", + "/input/schema.json", + ] + config = { + "model_reasoning_effort": self.reasoning_effort, + "service_tier": self.service_tier, + "web_search": "disabled", + "developer_instructions": SYSTEM_GUIDANCE, + "mcp_servers.netopsbench.url": endpoint["url"], + "mcp_servers.netopsbench.bearer_token_env_var": "DIAGNOSTIC_MCP_TOKEN", + "mcp_servers.netopsbench.required": True, + "mcp_servers.netopsbench.enabled_tools": [tool["name"] for tool in tool_schemas()], + } + for feature in ( + "fast_mode", + "ultrafast_mode", + "apps", + "plugins", + "remote_plugin", + "multi_agent", + "browser_use", + "browser_use_external", + "computer_use", + "skill_search", + ): + config[f"features.{feature}"] = False + for key, value in config.items(): + args.extend(["-c", f"{key}={json.dumps(value)}"]) + skills = ["imagegen", "openai-docs", "review-agent", "skill-creator", "skill-installer"] + overrides = ",".join( + "{path=" + json.dumps(f"/home/diagnostic/.codex/skills/.system/{name}/SKILL.md") + ",enabled=false}" + for name in skills + ) + args.extend(["-c", f"skills.config=[{overrides}]"]) + return [*args, "-"] + + async def diagnose(self, context): + try: + async with diagnosis_budget_scope(self.timeout_seconds): + return await self._execute(context, build_user_prompt(context, fenced_output=False)) + except TimeoutError as exc: + return DiagnosisResult( + agent_name=self.name, + verdict="inconclusive", + success=False, + reasoning="Total diagnosis timeout exceeded", + metadata={ + **getattr(exc.__cause__, "agent_metadata", {}), + "error_type": "TimeoutError", + "agent_failure_stage": "diagnose", + "timeout_seconds": self.timeout_seconds, + }, + ) + + async def check_connection(self): + from types import SimpleNamespace + + from netopsbench.platform.toolkit._core.common import ToolResult + from netopsbench.sdk.agents import DiagnosticContext + + context = DiagnosticContext( + scenario_id="preflight", + topology={}, + symptoms={}, + tools=SimpleNamespace(get_topology=lambda **kwargs: ToolResult(True, {"preflight": "ok"})), + ) + result = await self._execute( + context, + ( + "This is a connectivity preflight, not a network diagnosis. Call get_topology once, " + "run python3 -c 'print(2+2)' in the shell, then return JSON with verdict network_healthy, " + "fault_type null, location {device:null,interface:null}, evidence [preflight ok], " + "confidence 1 and reasoning preflight complete. Do not call other tools." + ), + ) + if ( + not result.success + or result.verdict != "network_healthy" + or result.metadata.get("failed_mcp_calls") + or result.metadata.get("mcp_calls", 0) < 1 + or result.metadata.get("shell_calls", 0) < 1 + ): + raise RuntimeError(f"Codex connectivity preflight failed: {result.reasoning}") + return result.metadata + + async def _execute(self, context, prompt): + metadata = { + "runtime": "codex-cli+isolated-shell+mcp", + "provider": "codex", + "model": self.model, + "cli_version": self.cli_version, + "reasoning_effort": self.reasoning_effort, + "service_tier": self.service_tier, + "max_mcp_calls": self.max_tool_calls, + "timeout_seconds": self.timeout_seconds, + } + events = CodexEvents(context.trace) + container = DiagnosticContainer(self.image, self.auth_store) + self._containers.add(container) + directory = self.artifacts_dir / uuid.uuid4().hex + directory.mkdir(parents=True) + metadata["codex_events_path"] = str(directory / "events.jsonl") + metadata["codex_stderr_path"] = str(directory / "stderr.txt") + process = None + auth_temporary = None + open_task = None + secrets = [] + result = None + try: + if self._image_id is None: + await asyncio.to_thread(self.preflight) + metadata["image_id"] = self._image_id + metadata["image_content_sha256"] = self._image_content_sha256 + container.image = self._image_id + secrets = credentials(self.auth_store, refresh_from_host=self._refresh_from_host) + auth_temporary = tempfile.TemporaryDirectory(prefix="netopsbench-codex-auth-") + container.auth_store = Path(auth_temporary.name) + shutil.copyfile(self.auth_store / "auth.json", container.auth_store / "auth.json") + (container.auth_store / "auth.json").chmod(0o600) + open_task = asyncio.create_task(asyncio.to_thread(container.open)) + await asyncio.shield(open_task) + with tempfile.TemporaryDirectory(prefix="netopsbench-codex-input-") as temporary: + inputs = Path(temporary) + inputs.chmod(0o755) + (inputs / "schema.json").write_text(json.dumps(strict_output_schema())) + (inputs / "observation.json").write_text( + json.dumps( + { + "case_id": context.scenario_id, + "topology": context.topology, + "symptoms": context.symptoms, + }, + default=str, + ) + ) + with openai_proxy(container.gateway) as proxy_port: + async with session_mcp( + context, host=container.gateway, max_tool_calls=self.max_tool_calls + ) as endpoint: + secrets.append(endpoint["token"]) + command = container.command( + inputs, + mcp_port=endpoint["port"], + proxy_port=proxy_port, + token=endpoint["token"], + cli_args=self.cli_args(endpoint), + ) + control = current_tool_control() + if control is not None: + control.remaining() + process = await asyncio.create_subprocess_exec( + *command, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + limit=8 * 1024 * 1024, + ) + process.stdin.write(prompt.encode()) + await process.stdin.drain() + process.stdin.close() + + async def collect_stdout(): + with (directory / "events.jsonl").open("w") as output: + while line := await process.stdout.readline(): + cleaned = redact(line.decode(errors="replace"), secrets) + output.write(cleaned) + output.flush() + events.accept(json.loads(cleaned)) + + async def collect_stderr(): + with (directory / "stderr.txt").open("w") as output: + while line := await process.stderr.readline(): + output.write(redact(line.decode(errors="replace"), secrets)) + + cli_timeout = ( + control.remaining(self.timeout_seconds) if control is not None else self.timeout_seconds + ) + await asyncio.wait_for( + asyncio.gather(collect_stdout(), collect_stderr(), process.wait()), + timeout=cli_timeout, + ) + metadata.update(events.usage, **events.counts(), exit_code=process.returncode) + if metadata["mcp_calls"] > self.max_tool_calls: + raise RuntimeError("MCP tool-call budget exhausted") + output = events.result(process.returncode) + metadata["tool_calls"] = context.trace.tool_calls() if context.trace else [] + result = build_result(self.name, output, metadata=metadata) + except asyncio.CancelledError as exc: + metadata.update(events.usage, **events.counts(), agent_failure_stage="diagnose") + exc.agent_metadata = metadata + raise + except Exception as exc: + metadata.update( + events.usage, **events.counts(), error_type=type(exc).__name__, agent_failure_stage="diagnose" + ) + error = redact(str(exc), secrets) + stderr = directory / "stderr.txt" + if stderr.exists() and stderr.stat().st_size: + error += ": " + stderr.read_text()[-2000:] + result = DiagnosisResult( + agent_name=self.name, verdict="inconclusive", success=False, reasoning=error, metadata=metadata + ) + finally: + with agent_cleanup_timing(): + cleanup_started = time.monotonic() + cleanup_result, cancelled = await finish_cleanup( + self._cleanup(container, process, auth_temporary, open_task) + ) + errors = redact(cleanup_result, secrets) + metadata["agent_cleanup_seconds"] = time.monotonic() - cleanup_started + metadata["cleanup_errors"] = json.loads(errors) + if container in self._containers: + metadata["retained_resources"] = { + "container": getattr(container, "name", None), + "network": getattr(container, "network", None), + } + if metadata["cleanup_errors"] and result is not None: + result = replace( + result, success=False, reasoning=result.reasoning + "; diagnostic resource cleanup failed" + ) + if result is not None: + result.metadata.update(metadata) + (directory / "cleanup.json").write_text( + json.dumps( + { + "errors": metadata["cleanup_errors"], + "retained_resources": metadata.get("retained_resources", {}), + }, + indent=2, + ) + ) + if cancelled: + raise asyncio.CancelledError + return result + + async def _cleanup(self, container, process, auth_temporary, open_task): + errors = [] + if open_task is not None: + try: + await open_task + except Exception as exc: + errors.append(f"startup: {exc}") + if process is not None and process.returncode is None: + try: + process.terminate() + try: + await asyncio.wait_for(process.wait(), timeout=5) + except TimeoutError: + process.kill() + await process.wait() + except (OSError, ProcessLookupError) as exc: + errors.append(f"process: {exc}") + try: + await asyncio.to_thread(container.close) + except Exception as exc: + errors.append(str(exc)) + else: + self._containers.discard(container) + if auth_temporary is not None: + try: + refreshed = container.auth_store / "auth.json" + if refreshed.exists(): + from netopsbench.platform.utils.files import atomic_write_json + + auth = json.loads(refreshed.read_text()) + if not isinstance(auth, dict) or not (auth.get("tokens") or auth.get("OPENAI_API_KEY")): + raise ValueError("Invalid refreshed Codex authentication") + atomic_write_json(self.auth_store / "auth.json", auth) + (self.auth_store / "auth.json").chmod(0o600) + except (ValueError, OSError) as exc: + errors.append(f"credential refresh: {exc}") + finally: + try: + auth_temporary.cleanup() + except OSError as exc: + errors.append(f"temporary credentials: {exc}") + return errors + + async def aclose(self): + errors = [] + for container in list(self._containers): + try: + await asyncio.to_thread(container.close) + except Exception as exc: + errors.append(str(exc)) + else: + self._containers.discard(container) + if errors: + raise RuntimeError("; ".join(errors)) diff --git a/examples/agents/codex_agent/entrypoint.sh b/examples/agents/codex_agent/entrypoint.sh new file mode 100644 index 0000000..6f45f2e --- /dev/null +++ b/examples/agents/codex_agent/entrypoint.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +# Install the namespace policy before dropping every capability. The agent +# cannot alter this policy or reach another host/lab endpoint. +iptables -P OUTPUT DROP +iptables -A OUTPUT -o lo -j ACCEPT +iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT +iptables -A OUTPUT -p tcp -d "$DIAGNOSTIC_GATEWAY" --dport "$DIAGNOSTIC_MCP_PORT" -j ACCEPT +iptables -A OUTPUT -p tcp -d "$DIAGNOSTIC_GATEWAY" --dport "$DIAGNOSTIC_PROXY_PORT" -j ACCEPT +ip6tables -P OUTPUT DROP +chown "$DIAGNOSTIC_UID:$DIAGNOSTIC_GID" /workspace /tmp /home/diagnostic/.codex +exec setpriv --reuid="$DIAGNOSTIC_UID" --regid="$DIAGNOSTIC_GID" --clear-groups \ + --bounding-set=-all --inh-caps=-all --ambient-caps=-all --no-new-privs "$@" diff --git a/examples/agents/codex_agent/proxy.py b/examples/agents/codex_agent/proxy.py new file mode 100644 index 0000000..dcbb801 --- /dev/null +++ b/examples/agents/codex_agent/proxy.py @@ -0,0 +1,93 @@ +"""Small CONNECT relay: only explicitly allowed public OpenAI endpoints.""" + +import base64 +import http.client +import ipaddress +import os +import select +import socket +import socketserver +import threading +from contextlib import contextmanager +from urllib.parse import urlsplit + +ALLOWED_HOSTS = frozenset({"chatgpt.com", "api.openai.com", "auth.openai.com"}) + + +def validate_destination(authority): + host, port = authority.rsplit(":", 1) + if host not in ALLOWED_HOSTS or port != "443": + raise ValueError("Destination denied") + addresses = socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM) + if not addresses or any(not ipaddress.ip_address(row[4][0]).is_global for row in addresses): + raise ValueError("Non-public destination denied") + return host, addresses[0] + + +class ConnectHandler(socketserver.StreamRequestHandler): + def handle(self): + connection = None + try: + self.connection.settimeout(30) + request = self.rfile.readline(8192).decode("ascii").strip().split() + if len(request) != 3 or request[0] != "CONNECT": + raise ValueError("Only CONNECT is supported") + host, address = validate_destination(request[1]) + for _ in range(100): + if self.rfile.readline(8192) in (b"\r\n", b"\n", b""): + break + upstream = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") + if upstream: + parsed = urlsplit(upstream) + if parsed.scheme not in {"http", "https"}: + raise ValueError("Unsupported upstream proxy") + cls = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection + connection = cls(parsed.hostname, parsed.port, timeout=30) + headers = {} + if parsed.username: + credential = base64.b64encode(f"{parsed.username}:{parsed.password or ''}".encode()).decode() + headers["Proxy-Authorization"] = f"Basic {credential}" + connection.set_tunnel(host, 443, headers=headers) + connection.connect() + remote = connection.sock + else: + remote = socket.socket(address[0], address[1], address[2]) + remote.settimeout(30) + remote.connect(address[4]) + connection = remote + self.wfile.write(b"HTTP/1.1 200 Connection established\r\n\r\n") + self.wfile.flush() + while True: + readable, _, _ = select.select([self.connection, remote], [], [], 60) + if not readable: + break + for source in readable: + data = source.recv(65536) + if not data: + return + (remote if source is self.connection else self.connection).sendall(data) + except (ValueError, OSError, http.client.HTTPException): + try: + self.wfile.write(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n") + except OSError: + pass + finally: + if connection: + connection.close() + + +@contextmanager +def openai_proxy(host): + class Server(socketserver.ThreadingTCPServer): + daemon_threads = True + allow_reuse_address = True + + server = Server((host, 0), ConnectHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server.server_address[1] + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) diff --git a/examples/agents/codex_agent/runtime.py b/examples/agents/codex_agent/runtime.py new file mode 100644 index 0000000..0a6f185 --- /dev/null +++ b/examples/agents/codex_agent/runtime.py @@ -0,0 +1,204 @@ +"""Pinned diagnostic image and per-case, namespace-isolated container.""" + +import hashlib +import json +import os +import shutil +import subprocess +import tempfile +import uuid +from datetime import UTC, datetime +from pathlib import Path + +from netopsbench.platform.utils.files import atomic_write_json + +CLI_VERSION = "0.159.2" +DEFAULT_IMAGE = f"netopsbench-codex:{CLI_VERSION}" + + +def docker(*args): + return subprocess.check_output(["docker", *args], text=True, timeout=120).strip() + + +def ensure_image(*, image=DEFAULT_IMAGE, binary=None, version=CLI_VERSION): + try: + image_id = docker("image", "inspect", image, "--format", "{{.Id}}") + docker( + "run", + "--rm", + "--network", + "none", + "--entrypoint", + "test", + image, + "-x", + "/usr/local/bin/codex-code-mode-host", + ) + except subprocess.CalledProcessError: + binary = Path(binary or shutil.which("codex") or "").resolve() + if not binary.is_file(): + raise RuntimeError("Install the pinned Codex CLI before building the diagnostic image") from None + actual = subprocess.check_output([str(binary), "--version"], text=True).strip() + if actual != f"codex-cli {version}": + raise ValueError(f"Expected Codex {version}, found {actual}") from None + with tempfile.TemporaryDirectory(prefix="netopsbench-codex-build-") as directory: + source = Path(__file__).parent + for name in ("Dockerfile", "entrypoint.sh"): + shutil.copyfile(source / name, Path(directory) / name) + shutil.copyfile(binary, Path(directory) / "codex") + shutil.copyfile(binary.parent / "codex-code-mode-host", Path(directory) / "codex-code-mode-host") + subprocess.run(["docker", "build", "-t", image, directory], check=True, timeout=600) + image_id = docker("image", "inspect", image, "--format", "{{.Id}}") + actual = docker("run", "--rm", "--network", "none", "--entrypoint", "codex", image, "--version") + if actual != f"codex-cli {version}": + raise ValueError(f"Diagnostic image CLI mismatch: {actual}") + return image_id + + +def image_content_identity(image): + """Compare executable content across Docker image-store implementations.""" + inspected = json.loads(docker("image", "inspect", image))[0] + config = inspected.get("Config") or {} + execution = {key: config.get(key) for key in ("Env", "Entrypoint", "Cmd", "Volumes", "Healthcheck")} + execution.update({key: config.get(key) or "" for key in ("User", "WorkingDir", "StopSignal")}) + content = {key: inspected[key] for key in ("Architecture", "Os", "RootFS")} + content["Config"] = execution + return hashlib.sha256(json.dumps(content, sort_keys=True).encode()).hexdigest() + + +def credentials(store: Path, *, refresh_from_host: bool = False) -> list[str]: + """Seed only auth.json, never host configuration, skills or rollout history.""" + store.mkdir(parents=True, exist_ok=True, mode=0o700) + store.chmod(0o700) + target = store / "auth.json" + source = Path.home() / ".codex" / "auth.json" + if not target.exists(): + if not source.is_file(): + raise RuntimeError("Run `codex login` before Codex acceptance") + shutil.copyfile(source, target) + elif refresh_from_host and source.is_file() and source.resolve() != target.resolve(): + # Host login may have rotated the token since this dedicated store was seeded. + host_auth = json.loads(source.read_text()) + private_auth = json.loads(target.read_text()) + + def refreshed(auth): + value = auth.get("last_refresh") + return datetime.fromisoformat(value.replace("Z", "+00:00")) if value else datetime.min.replace(tzinfo=UTC) + + if refreshed(host_auth) > refreshed(private_auth): + atomic_write_json(target, host_auth) + target.chmod(0o600) + auth = json.loads(target.read_text()) + secrets = [] + + def collect(value): + if isinstance(value, dict): + for key, item in value.items(): + if isinstance(item, str) and any( + marker in key.lower() for marker in ("token", "key", "account", "email") + ): + secrets.append(item) + else: + collect(item) + + collect(auth) + return secrets + + +class DiagnosticContainer: + def __init__(self, image, auth_store): + self.image = image + self.auth_store = auth_store.resolve() + self.name = f"netopsbench-codex-{uuid.uuid4().hex[:12]}" + self.network = self.name + self.gateway = None + + def open(self): + docker("network", "create", "--internal", "--label", "netopsbench.role=diagnostic", self.network) + self.gateway = json.loads(docker("network", "inspect", self.network))[0]["IPAM"]["Config"][0]["Gateway"] + return self + + def command(self, inputs, *, mcp_port, proxy_port, token, cli_args): + return [ + "docker", + "run", + "--rm", + "-i", + "--name", + self.name, + "--label", + "netopsbench.role=diagnostic", + "--network", + self.network, + "--read-only", + "--cap-drop", + "ALL", + "--cap-add", + "NET_ADMIN", + "--cap-add", + "SETUID", + "--cap-add", + "SETGID", + "--cap-add", + "CHOWN", + "--cap-add", + "SETPCAP", + "--security-opt", + "no-new-privileges", + "--pids-limit", + "256", + "--cpus", + "2", + "--memory", + "2g", + "--tmpfs", + "/workspace:rw,nosuid,size=512m", + "--tmpfs", + "/tmp:rw,nosuid,size=64m", + "--mount", + f"type=bind,src={inputs},dst=/input,readonly", + "--mount", + f"type=bind,src={self.auth_store},dst=/home/diagnostic/.codex", + "-e", + f"DIAGNOSTIC_UID={os.getuid()}", + "-e", + f"DIAGNOSTIC_GID={os.getgid()}", + "-e", + f"DIAGNOSTIC_GATEWAY={self.gateway}", + "-e", + f"DIAGNOSTIC_MCP_PORT={mcp_port}", + "-e", + f"DIAGNOSTIC_PROXY_PORT={proxy_port}", + "-e", + f"DIAGNOSTIC_MCP_TOKEN={token}", + "-e", + f"HTTPS_PROXY=http://{self.gateway}:{proxy_port}", + "-e", + f"HTTP_PROXY=http://{self.gateway}:{proxy_port}", + "-e", + f"NO_PROXY={self.gateway}", + self.image, + *cli_args, + ] + + def close(self): + errors = [] + for kind, name, removal in ( + ("container", self.name, ["docker", "rm", "-f", self.name]), + ("network", self.network, ["docker", "network", "rm", self.network]), + ): + try: + removed = subprocess.run(removal, capture_output=True, text=True, timeout=60) + inspected = subprocess.run( + ["docker", "inspect", "--type", kind, name], capture_output=True, text=True, timeout=30 + ) + missing = inspected.returncode != 0 and any( + phrase in (inspected.stderr or "").lower() for phrase in ("no such", "not found") + ) + if not missing: + detail = (removed.stderr or inspected.stderr or "resource still exists").strip() + errors.append(f"{kind} {name}: {detail}") + except (OSError, subprocess.TimeoutExpired) as exc: + errors.append(f"{kind} {name}: {exc}") + if errors: + raise RuntimeError("Diagnostic cleanup failed: " + "; ".join(errors)) diff --git a/examples/agents/diagnosis.py b/examples/agents/diagnosis.py new file mode 100644 index 0000000..9765511 --- /dev/null +++ b/examples/agents/diagnosis.py @@ -0,0 +1,112 @@ +"""Pydantic output schema shared by all providers.""" + +import json +from typing import Any, Literal + +from pydantic import BaseModel, Field + +from netopsbench.platform.faults.specs import get_supported_scenario_faults +from netopsbench.sdk import build_canonical_observation +from netopsbench.sdk.agents import DiagnosisResult + + +class DiagnosisLocation(BaseModel): + device: str | None = None + interface: str | None = None + + +class DiagnosisOutput(BaseModel): + # The benchmark scorer requires an exact string match against one of these + # three values. Using Literal advertises the enum to the LLM through the + # tool's JSON schema and lets pydantic reject free-form synonyms like + # "fault", "fault_found", "fault_confirmed" that earlier runs produced. + verdict: Literal["fault_detected", "network_healthy", "inconclusive"] = Field( + description=( + "Final diagnosis verdict. Must be exactly one of: " + "'fault_detected' (a fault is present), " + "'network_healthy' (no fault), " + "'inconclusive' (insufficient evidence). " + "Do NOT invent other values such as 'fault', 'fault_found', or 'fault_confirmed'." + ) + ) + fault_type: str | None = Field( + default=None, description="Canonical scored category: " + ", ".join(get_supported_scenario_faults()) + ) + location: DiagnosisLocation = Field(default_factory=DiagnosisLocation) + evidence: list[str] = Field(default_factory=list) + confidence: float = Field(default=0.5, ge=0.0, le=1.0) + reasoning: str = "" + + +SYSTEM_GUIDANCE = ( + "You are a production network troubleshooting expert for DCN fabrics. " + "Use NetOpsBench MCP tools to diagnose live issues with evidence-first reasoning. " + "Do not assume hidden ground truth. " + "The DiagnosisOutput.verdict field is a strict enum — it MUST be exactly one of " + "'fault_detected', 'network_healthy', or 'inconclusive'. " + "Do NOT use synonyms such as 'fault', 'fault_found', 'fault_confirmed', or 'fault_resolved' — " + "any of those will be scored as wrong. " + "If evidence is insufficient, return verdict='inconclusive' with an empty location. " + "Use the initial Pingmesh symptoms and normal topology to guide investigation. " + "Query diagnostic tools for device state, routing, BGP, interfaces and ACL evidence. " + "Healthy latency/loss can coexist with missing routes or fewer FIB next hops. " + "Validate the route RIB, advertisements and kernel FIB, and distinguish the supported fault categories. " + "Be efficient: avoid redundant tool calls and do not repeat the same query. " + "You have a limited tool-call budget — focus on the most informative tools first. " +) + + +def build_user_prompt(context: Any, *, fenced_output: bool = True) -> str: + metadata = getattr(context, "metadata", {}) or {} + observation = metadata.get("canonical_observation") + if not isinstance(observation, dict): + observation = build_canonical_observation( + case_id=str(getattr(context, "scenario_id", "unknown")), + topology=dict(getattr(context, "topology", {}) or {}), + symptoms=dict(getattr(context, "symptoms", {}) or {}), + ) + prompt = ( + "Diagnose the current network state and return the final structured diagnosis.\n\n" + f"CANONICAL_OBSERVATION: {json.dumps(observation, ensure_ascii=False, sort_keys=True)}\n\n" + "Requirements:\n" + "1) Start with topology/Pingmesh-oriented MCP tools before concluding.\n" + "2) Gather evidence with tools instead of relying on the summary alone.\n" + "3) If a fault exists, identify fault_type and the most likely network-side location.\n" + "4) Keep reasoning concise and tied to tool evidence.\n" + "5) Device logs are valid evidence only inside the observation start_time/end_time. " + "Pass both timestamps to get_device_logs and ignore entries outside that window.\n" + "6) If you call an MCP tool, first explain in normal assistant text what evidence you need and why.\n" + "7) Do not reveal hidden chain-of-thought; keep investigation notes observable and evidence-oriented.\n" + ) + output = ( + "Return JSON matching DiagnosisOutput with verdict, fault_type, location, evidence, confidence, reasoning. " + ) + output += "Location must be an object with nullable device and interface. " + output += "Evidence must be a list of strings. " + if fenced_output: + output += "Include exactly one fenced JSON block." + else: + output += "Use the configured structured-output schema; do not include Markdown fences." + return ( + prompt + + output + + "\n\nDIAGNOSIS_OUTPUT_SCHEMA: " + + json.dumps(DiagnosisOutput.model_json_schema(), sort_keys=True) + ) + + +def build_result(name: str, structured: dict, *, metadata: dict) -> DiagnosisResult: + output = DiagnosisOutput.model_validate(structured) + return DiagnosisResult( + agent_name=name, + verdict=output.verdict, + success=True, + findings={ + "fault_type": output.fault_type, + "location": output.location.model_dump(), + "evidence": output.evidence, + }, + confidence=output.confidence, + reasoning=output.reasoning, + metadata=metadata, + ) diff --git a/examples/agents/minimal_deepagent/agent.py b/examples/agents/minimal_deepagent/agent.py index aa5121a..8d9074c 100644 --- a/examples/agents/minimal_deepagent/agent.py +++ b/examples/agents/minimal_deepagent/agent.py @@ -39,6 +39,10 @@ from deepagents.backends import FilesystemBackend from netopsbench.agents.base import DiagnosticContext +from netopsbench.models.profiles import default_experiment_profile +from netopsbench.platform.scenario.timing import agent_cleanup_timing +from netopsbench.platform.toolkit._core.control import diagnosis_budget_scope +from netopsbench.platform.toolkit.mcp.session_server import session_mcp from netopsbench.sdk.agents import DiagnosisResult from netopsbench.sdk.mcp import builtin_mcp_server_config @@ -89,6 +93,7 @@ def __init__( max_tool_calls: int = DEFAULT_MAX_TOOL_CALLS, system_prompt: str = DEFAULT_SYSTEM_PROMPT, mcp_server_config: dict[str, dict[str, Any]] | None = None, + diagnosis_timeout_seconds: int | None = None, ): provider = get_provider(vendor) # raises ValueError for unknown vendor @@ -104,8 +109,28 @@ def __init__( self.system_prompt = system_prompt self.api_key = api_key or os.environ.get(provider.PRESET["api_key_env"], "") self.mcp_server_config = mcp_server_config + self.diagnosis_timeout_seconds = ( + diagnosis_timeout_seconds + if diagnosis_timeout_seconds is not None + else default_experiment_profile().diagnosis_timeout_seconds + ) async def diagnose(self, context: DiagnosticContext) -> DiagnosisResult: + try: + async with diagnosis_budget_scope(self.diagnosis_timeout_seconds): + return await self._diagnose(context) + + except TimeoutError: + return _error_result( + self.name, + self.vendor, + self.model, + TimeoutError("Total diagnosis timeout exceeded"), + tool_calls=[], + token_counts={}, + ) + + async def _diagnose(self, context: DiagnosticContext) -> DiagnosisResult: if not self.api_key: raise ValueError( f"{self._provider.PRESET['api_key_env']} is required. " @@ -113,8 +138,7 @@ async def diagnose(self, context: DiagnosticContext) -> DiagnosisResult: ) repo_root = Path(__file__).resolve().parents[3] - worker_env = context.metadata.get("worker_env") if context.metadata else None - server_config = self.mcp_server_config or builtin_mcp_server_config(workspace=repo_root, env=worker_env) + server_config = self.mcp_server_config exit_stack = AsyncExitStack() trace_callback = _langchain_trace_callback(context) tool_calls: list[dict[str, Any]] = [] @@ -122,6 +146,17 @@ async def diagnose(self, context: DiagnosticContext) -> DiagnosisResult: try: await exit_stack.__aenter__() + if self.mcp_server_config is None and context.tools is not None: + endpoint = await exit_stack.enter_async_context(session_mcp(context, record_trace=False)) + server_config = { + "netopsbench": { + "transport": "streamable_http", + "url": endpoint["url"], + "headers": {"Authorization": f"Bearer {endpoint['token']}"}, + } + } + if server_config is None: + server_config = builtin_mcp_server_config(workspace=repo_root) mcp_tools = await _connect_mcp_tools(exit_stack, server_config) llm = self._provider.build_llm( @@ -172,7 +207,9 @@ async def diagnose(self, context: DiagnosticContext) -> DiagnosisResult: token_counts=token_counts, ) finally: - await exit_stack.aclose() + with agent_cleanup_timing(): + # MCP's AnyIO scopes must exit on the task that entered them. + await exit_stack.aclose() async def aclose(self) -> None: return None diff --git a/examples/agents/minimal_deepagent/prompts.py b/examples/agents/minimal_deepagent/prompts.py index 2529ffb..33a87fe 100644 --- a/examples/agents/minimal_deepagent/prompts.py +++ b/examples/agents/minimal_deepagent/prompts.py @@ -1,61 +1,7 @@ -"""Prompt helpers for the public DeepAgent example.""" +"""DeepAgent output framing over the shared diagnosis prompt.""" -from __future__ import annotations +from examples.agents.diagnosis import SYSTEM_GUIDANCE, build_user_prompt -import json -from typing import Any +DEFAULT_SYSTEM_PROMPT = SYSTEM_GUIDANCE + "Return one fenced JSON block matching DiagnosisOutput." -from netopsbench.sdk import build_canonical_observation - -DEFAULT_SYSTEM_PROMPT = ( - "You are a production network troubleshooting expert for DCN fabrics. " - "Use NetOpsBench MCP tools to diagnose live issues with evidence-first reasoning. " - "Do not assume hidden ground truth. " - "The DiagnosisOutput.verdict field is a strict enum — it MUST be exactly one of " - "'fault_detected', 'network_healthy', or 'inconclusive'. " - "Do NOT use synonyms such as 'fault', 'fault_found', 'fault_confirmed', or 'fault_resolved' — " - "any of those will be scored as wrong. " - "If evidence is insufficient, return verdict='inconclusive' with an empty location. " - "Prefer Pingmesh and topology tools first, then validate with interface, routing, and log evidence. " - "Be efficient: avoid redundant tool calls and do not repeat the same query. " - "You have a limited tool-call budget — focus on the most informative tools first. " - "When your investigation is complete, return a final answer containing one fenced JSON block that matches " - "the DiagnosisOutput schema." -) - - -def build_user_prompt(context: Any) -> str: - metadata = getattr(context, "metadata", {}) or {} - observation = metadata.get("canonical_observation") - if not isinstance(observation, dict): - observation = build_canonical_observation( - case_id=str(getattr(context, "scenario_id", "unknown")), - topology=dict(getattr(context, "topology", {}) or {}), - symptoms=dict(getattr(context, "symptoms", {}) or {}), - ) - return ( - "Diagnose the current network state and return the final structured diagnosis.\n\n" - f"CANONICAL_OBSERVATION: {json.dumps(observation, ensure_ascii=False, sort_keys=True)}\n\n" - "Requirements:\n" - "1) Start with topology/Pingmesh-oriented MCP tools before concluding.\n" - "2) Gather evidence with tools instead of relying on the summary alone.\n" - "3) If a fault exists, identify fault_type and the most likely network-side location.\n" - "4) Keep reasoning concise and tied to tool evidence.\n" - "5) Device logs are valid evidence only inside the observation start_time/end_time. " - "Pass both timestamps to get_device_logs and ignore entries outside that window.\n" - "6) If you call an MCP tool, first explain in normal assistant text what evidence you need and why.\n" - "7) Do not reveal hidden chain-of-thought; keep investigation notes observable and evidence-oriented.\n" - "8) When done, include exactly one fenced ```json block with fields: " - "verdict, fault_type, location, evidence, confidence, reasoning.\n" - "9) The JSON verdict MUST be exactly one of fault_detected, network_healthy, or inconclusive.\n" - "10) The JSON location MUST be an object, never a string: " - '{"device": "leaf1", "interface": "Ethernet8"}. ' - 'Use {"device": null, "interface": null} when location is unknown or not applicable.\n' - "11) Final JSON shape example:\n" - "```json\n" - '{"verdict":"fault_detected","fault_type":"link_down",' - '"location":{"device":"leaf1","interface":"Ethernet8"},' - '"evidence":["brief tool-backed fact"],"confidence":0.8,' - '"reasoning":"short evidence-based summary"}\n' - "```\n" - ) +__all__ = ["DEFAULT_SYSTEM_PROMPT", "build_user_prompt"] diff --git a/examples/agents/minimal_deepagent/providers/results.py b/examples/agents/minimal_deepagent/providers/results.py index 158d2a1..e1ce4d5 100644 --- a/examples/agents/minimal_deepagent/providers/results.py +++ b/examples/agents/minimal_deepagent/providers/results.py @@ -8,6 +8,7 @@ from pydantic import ValidationError +from examples.agents.diagnosis import build_result from netopsbench.sdk.agents import DiagnosisResult from ..schema import DiagnosisOutput @@ -200,37 +201,15 @@ def _build_diagnosis_result( token_counts: dict[str, int] | None = None, ) -> DiagnosisResult: """Build a successful ``DiagnosisResult`` from parsed structured output.""" - location = structured.get("location") or {} - evidence = structured.get("evidence") or [] - if not isinstance(evidence, list): - evidence = [str(evidence)] - - confidence = structured.get("confidence", 0.0) - try: - confidence = float(confidence) - except (TypeError, ValueError): - confidence = 0.0 - - return DiagnosisResult( - agent_name=agent_name, - verdict=structured.get("verdict", "inconclusive"), - success=True, - findings={ - "fault_type": structured.get("fault_type"), - "location": {"device": location.get("device"), "interface": location.get("interface")}, - "evidence": evidence, - }, - confidence=confidence, - reasoning=structured.get("reasoning", ""), + return build_result( + agent_name, + structured, metadata={ "provider": vendor, "model": model, "runtime": "deepagents+mcp", "tool_calls": tool_calls, - "input_tokens": int((token_counts or {}).get("input_tokens", 0) or 0), - "output_tokens": int((token_counts or {}).get("output_tokens", 0) or 0), - "total_tokens": int((token_counts or {}).get("total_tokens", 0) or 0), - "llm_call_count": int((token_counts or {}).get("llm_call_count", 0) or 0), + **dict(token_counts or {}), }, ) diff --git a/examples/agents/minimal_deepagent/schema.py b/examples/agents/minimal_deepagent/schema.py index 1962048..e4b37cc 100644 --- a/examples/agents/minimal_deepagent/schema.py +++ b/examples/agents/minimal_deepagent/schema.py @@ -1,33 +1,5 @@ -"""Pydantic output schema shared by all providers.""" +"""Shared bundled-agent output schema.""" -from __future__ import annotations +from examples.agents.diagnosis import DiagnosisLocation, DiagnosisOutput -from typing import Literal - -from pydantic import BaseModel, Field - - -class DiagnosisLocation(BaseModel): - device: str | None = None - interface: str | None = None - - -class DiagnosisOutput(BaseModel): - # The benchmark scorer requires an exact string match against one of these - # three values. Using Literal advertises the enum to the LLM through the - # tool's JSON schema and lets pydantic reject free-form synonyms like - # "fault", "fault_found", "fault_confirmed" that earlier runs produced. - verdict: Literal["fault_detected", "network_healthy", "inconclusive"] = Field( - description=( - "Final diagnosis verdict. Must be exactly one of: " - "'fault_detected' (a fault is present), " - "'network_healthy' (no fault), " - "'inconclusive' (insufficient evidence). " - "Do NOT invent other values such as 'fault', 'fault_found', or 'fault_confirmed'." - ) - ) - fault_type: str | None = None - location: DiagnosisLocation = Field(default_factory=DiagnosisLocation) - evidence: list[str] = Field(default_factory=list) - confidence: float = Field(default=0.5, ge=0.0, le=1.0) - reasoning: str = "" +__all__ = ["DiagnosisLocation", "DiagnosisOutput"] diff --git a/examples/agents/minimal_deepagent/skills/network-diagnosis/SKILL.md b/examples/agents/minimal_deepagent/skills/network-diagnosis/SKILL.md index bb5c145..a92d436 100644 --- a/examples/agents/minimal_deepagent/skills/network-diagnosis/SKILL.md +++ b/examples/agents/minimal_deepagent/skills/network-diagnosis/SKILL.md @@ -20,7 +20,7 @@ Use this skill for the public DeepAgent example when you need to diagnose a like - Do not assume client-facing prefixes should be `/24`. NetOpsBench commonly uses `/30` point-to-point access subnets; compare the configured prefix with topology and route evidence before calling it a misconfiguration. - - Report the canonical fault label `bgp_neighbor_misconfig`; do not substitute `bgp_down` or `link_flap`. + - Distinguish `bgp_as_mismatch`, `bgp_auth_mismatch`, `bgp_update_source_mismatch`, `bgp_neighbor_shutdown`, and `bgp_max_prefix_misconfig` using actual configuration and session evidence. - For an AS mismatch, set `location.device` to the device whose configured remote-AS disagrees with the peer's actual local AS. Do not report the correctly configured peer. - Separate a control-plane session event from confirmed data-plane impact. Historical events outside the episode window are not current faults. - `get_device_logs`: always pass the observation `start_time` and `end_time`; ignore log entries outside that episode window. diff --git a/native/client-agent/Cargo.lock b/native/client-agent/Cargo.lock index f5d7298..b358254 100644 --- a/native/client-agent/Cargo.lock +++ b/native/client-agent/Cargo.lock @@ -70,15 +70,6 @@ version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest", -] - [[package]] name = "block-buffer" version = "0.10.4" @@ -179,7 +170,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", - "subtle", ] [[package]] @@ -257,7 +247,6 @@ name = "netopsbench-client-agent" version = "0.2.0" dependencies = [ "anyhow", - "blake2", "clap", "libc", "nix", @@ -391,12 +380,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - [[package]] name = "syn" version = "2.0.119" diff --git a/native/client-agent/Cargo.toml b/native/client-agent/Cargo.toml index f0d1a34..652c7b1 100644 --- a/native/client-agent/Cargo.toml +++ b/native/client-agent/Cargo.toml @@ -8,7 +8,6 @@ publish = false [dependencies] anyhow = "=1.0.104" -blake2 = "=0.10.6" clap = { version = "=4.6.4", features = ["derive"] } libc = "=0.2.189" nix = { version = "=0.30.1", features = ["net", "socket", "time", "uio"] } diff --git a/native/client-agent/README.md b/native/client-agent/README.md index 97d2119..453ce0e 100644 --- a/native/client-agent/README.md +++ b/native/client-agent/README.md @@ -14,7 +14,7 @@ writes to the topology-local Telegraf listener. The traffic process owns the four planned background flows per client and exposes its control/status contract on the management network. -The supported v1 target is `x86_64-unknown-linux-musl`. The client image builds +The supported target is `x86_64-unknown-linux-musl`. The client image builds the binary with the repository-pinned Rust toolchain and `Cargo.lock`; it does not contain Python, iperf3, or a Rust toolchain at runtime. @@ -24,5 +24,23 @@ Local checks: cargo fmt --check cargo clippy --locked --all-targets -- -D warnings cargo test --locked -docker build -f containers/client/Dockerfile -t netopsbench-client:test . +docker build -f containers/client/Dockerfile -t netopsbench-client:pingmesh-v2 . +``` + +Configuration v2 references immutable per-client `pinglists/.json` files +and their SHA256 digests. The Python compiler selects all peers, ports, probe +orders and startup delays offline. Rust validates the files and repeats their +frames without generating or rotating peer lists. Every status response and +Pingmesh metric carries the current `plan_id`. Old configuration versions must +be regenerated with a matching rebuilt image. + +DF confirmation keeps the planned peer and source port and sends fifteen +additional probes when the initial reply is missing. Retry rounds are spaced +10 ms apart, and probe replies are drained throughout sending to avoid local +receive queues turning transient loss into an MTU symptom. + +Validate a client configuration without starting sockets: + +```bash +HOSTNAME=client1 netopsbench-client-agent validate-config --config /etc/netopsbench/client-agent.json ``` diff --git a/native/client-agent/src/config.rs b/native/client-agent/src/config.rs index ac76c25..726508c 100644 --- a/native/client-agent/src/config.rs +++ b/native/client-agent/src/config.rs @@ -1,11 +1,13 @@ +use std::collections::{HashMap, HashSet}; use std::fs; use std::net::Ipv4Addr; use std::path::Path; use anyhow::{Context, Result, bail}; use serde::Deserialize; +use sha2::{Digest, Sha256}; -pub const CONFIG_SCHEMA_VERSION: u32 = 1; +pub const CONFIG_SCHEMA_VERSION: u32 = 2; pub const CONTROL_PROTOCOL_VERSION: u32 = 1; pub const PINGMESH_CONTROL_PORT: u16 = 9910; pub const TRAFFIC_CONTROL_PORT: u16 = 9911; @@ -15,7 +17,8 @@ pub const TRAFFIC_CONTROL_PORT: u16 = 9911; pub struct ClientAgentConfig { pub schema_version: u32, pub topology_id: String, - pub pingmesh_policy: PingmeshPolicy, + pub pingmesh_plan: PlanSettings, + pub client_plan_sha256: HashMap, pub clients: Vec, } @@ -31,23 +34,50 @@ pub struct Client { #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] -pub struct PingmeshPolicy { - pub destination_batch_size: Option, - pub rtt_port_pool_size: usize, - pub rtt_ports_per_cycle: usize, - pub cycle_interval_seconds: f64, - pub destination_batch_count: usize, - pub port_batch_count: usize, - pub coverage_epoch_cycles: u64, +pub struct PlanSettings { + pub plan_id: String, + pub source_ports: Vec, + pub port_batches: Vec>, + pub destination_batch_size: usize, + pub cycle_interval_seconds: u64, + pub coverage_epoch_cycles: usize, pub coverage_epoch_seconds: u64, + pub complete_window_seconds: u64, pub df_payload_size: usize, } +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum ProbeKind { + Rtt, + Df, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProbeFrame { + pub destination_batch_index: usize, + pub port_batch_index: usize, + pub target_indices: Vec, + pub probes: Vec<(ProbeKind, usize, usize)>, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClientProbePlan { + pub schema_version: u32, + pub plan_id: String, + pub name: String, + pub targets: Vec, + pub startup_delay_ms: u64, + pub frames: Vec, +} + impl ClientAgentConfig { pub fn load(path: &Path) -> Result { let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?; - let config: Self = - serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))?; + let config: Self = serde_json::from_slice(&bytes) + .context("parse current client-agent config; regenerate old artifacts")?; config.validate()?; Ok(config) } @@ -61,45 +91,134 @@ impl ClientAgentConfig { .with_context(|| format!("HOSTNAME {hostname:?} is not present in client-agent config")) } + pub fn load_client_plan(&self, config_path: &Path, local: &Client) -> Result { + let path = config_path + .parent() + .context("config directory is required")? + .join("pinglists") + .join(format!("{}.json", local.name)); + let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?; + let digest = format!("{:x}", Sha256::digest(&bytes)); + if self.client_plan_sha256.get(&local.name) != Some(&digest) { + bail!("client plan digest mismatch; regenerate the topology"); + } + let plan: ClientProbePlan = serde_json::from_slice(&bytes).context("parse client plan")?; + plan.validate(self, local)?; + Ok(plan) + } + fn validate(&self) -> Result<()> { if self.schema_version != CONFIG_SCHEMA_VERSION { bail!( - "unsupported client-agent schema version {}; expected {}", - self.schema_version, + "unsupported client-agent schema; expected {}; regenerate the topology", CONFIG_SCHEMA_VERSION ); } - if self.clients.len() < 2 { - bail!("client-agent config requires at least two clients"); + let names: HashSet<_> = self.clients.iter().map(|client| &client.name).collect(); + let settings = &self.pingmesh_plan; + if self.clients.len() < 2 + || names.len() != self.clients.len() + || self + .clients + .iter() + .any(|client| client.name.contains('/') || client.name == "..") + || self.client_plan_sha256.keys().collect::>() != names + { + bail!("invalid client roster or client plan digests"); + } + if settings.plan_id.len() != 64 + || settings.source_ports.is_empty() + || settings.source_ports.contains(&33434) + || settings.source_ports.iter().collect::>().len() + != settings.source_ports.len() + || settings.cycle_interval_seconds == 0 + || settings.coverage_epoch_cycles == 0 + || settings.destination_batch_size == 0 + || settings.df_payload_size < 24 + || settings.df_payload_size > 65507 + || settings.port_batches.is_empty() + || settings.port_batches.iter().any(Vec::is_empty) + || settings.coverage_epoch_seconds + != settings.coverage_epoch_cycles as u64 * settings.cycle_interval_seconds + || settings.complete_window_seconds < settings.coverage_epoch_seconds + { + bail!("invalid compiled Pingmesh plan settings"); } - let destinations = self.clients.len() - 1; - let batch_size = self - .pingmesh_policy - .destination_batch_size - .unwrap_or(destinations) - .clamp(1, destinations); - let destination_batches = destinations.div_ceil(batch_size); - let ports = self.pingmesh_policy.rtt_port_pool_size; - let ports_per_cycle = self.pingmesh_policy.rtt_ports_per_cycle; - if ports == 0 || ports_per_cycle == 0 || ports_per_cycle > ports { - bail!("invalid Pingmesh source-port policy"); + let mut indices: Vec<_> = settings.port_batches.iter().flatten().copied().collect(); + indices.sort_unstable(); + if indices != (0..settings.source_ports.len()).collect::>() { + bail!("port batches must partition the source-port pool"); } - let port_batches = ports.div_ceil(ports_per_cycle); - if destination_batches != self.pingmesh_policy.destination_batch_count - || port_batches != self.pingmesh_policy.port_batch_count - || (destination_batches * port_batches) as u64 - != self.pingmesh_policy.coverage_epoch_cycles + Ok(()) + } +} + +impl ClientProbePlan { + fn validate(&self, config: &ClientAgentConfig, local: &Client) -> Result<()> { + let settings = &config.pingmesh_plan; + let names: HashSet<_> = config.clients.iter().map(|client| &client.name).collect(); + if self.schema_version != CONFIG_SCHEMA_VERSION + || self.plan_id != settings.plan_id + || self.name != local.name + || self.frames.len() != settings.coverage_epoch_cycles + || self.targets.is_empty() + || self.targets.iter().collect::>().len() != self.targets.len() + || self + .targets + .iter() + .any(|name| name == &local.name || !names.contains(name)) + || self.startup_delay_ms >= settings.cycle_interval_seconds * 1000 { - bail!("stale Pingmesh coverage policy; regenerate the topology"); + bail!("client plan does not match current configuration"); } - if self.pingmesh_policy.cycle_interval_seconds <= 0.0 { - bail!("Pingmesh cycle interval must be positive"); + let mut coverage = HashSet::new(); + for frame in &self.frames { + let batch = settings + .port_batches + .get(frame.port_batch_index) + .context("invalid frame port batch")?; + if frame.target_indices.len() > settings.destination_batch_size + || frame + .target_indices + .iter() + .any(|index| *index >= self.targets.len()) + || frame.target_indices.iter().collect::>().len() + != frame.target_indices.len() + { + bail!("invalid frame targets"); + } + let mut rtt = HashSet::new(); + let mut df = HashSet::new(); + for (kind, target, socket) in &frame.probes { + if *target >= frame.target_indices.len() || *socket >= batch.len() { + bail!("probe references an invalid target or socket"); + } + match kind { + ProbeKind::Rtt => { + if !rtt.insert((*target, *socket)) { + bail!("duplicate RTT task"); + } + } + ProbeKind::Df => { + if !df.insert(*target) { + bail!("duplicate DF task"); + } + } + } + } + if rtt.len() != frame.target_indices.len() * batch.len() + || df.len() != frame.target_indices.len() + { + bail!("frame is missing RTT or DF tasks"); + } + for target in &frame.target_indices { + if !coverage.insert((*target, frame.port_batch_index)) { + bail!("duplicate target/port batch"); + } + } } - let expected_epoch_seconds = (self.pingmesh_policy.coverage_epoch_cycles as f64 - * self.pingmesh_policy.cycle_interval_seconds) - .ceil() as u64; - if self.pingmesh_policy.coverage_epoch_seconds != expected_epoch_seconds { - bail!("stale Pingmesh coverage duration; regenerate the topology"); + if coverage.len() != self.targets.len() * settings.port_batches.len() { + bail!("client plan has incomplete target/port coverage"); } Ok(()) } @@ -107,35 +226,46 @@ impl ClientAgentConfig { #[cfg(test)] mod tests { + use super::*; + fn fixture() -> (ClientAgentConfig, ClientProbePlan) { + let config: ClientAgentConfig = serde_json::from_value(serde_json::json!({ + "schema_version": 2, "topology_id": "test", "clients": [ + {"name":"a","data_ip":"192.0.2.1","management_ip":"172.20.0.1","rack":"r1","leaf":"l1"}, + {"name":"b","data_ip":"192.0.2.2","management_ip":"172.20.0.2","rack":"r2","leaf":"l2"} + ], "client_plan_sha256":{"a":"digest", "b":"digest"}, + "pingmesh_plan": {"plan_id":"a".repeat(64), "source_ports":[33000,33001], "port_batches":[[0,1]], + "destination_batch_size":1, "cycle_interval_seconds":1, "coverage_epoch_cycles":1, + "coverage_epoch_seconds":1,"complete_window_seconds":6,"df_payload_size":1400} + })).unwrap(); + let plan: ClientProbePlan = serde_json::from_value(serde_json::json!({ + "schema_version":2,"plan_id":"a".repeat(64),"name":"a","targets":["b"],"startup_delay_ms":5, + "frames":[{"destination_batch_index":0,"port_batch_index":0,"target_indices":[0], + "probes":[["rtt",0,0],["rtt",0,1],["df",0,0]]}] + })).unwrap(); + (config, plan) + } + #[test] + fn current_plan_validates_and_rejects_missing_duplicate_or_wrong_tasks() { + let (config, plan) = fixture(); + config.validate().unwrap(); + plan.validate(&config, &config.clients[0]).unwrap(); + let mut missing = plan.clone(); + missing.frames[0].probes.pop(); + assert!(missing.validate(&config, &config.clients[0]).is_err()); + let mut duplicate = plan.clone(); + duplicate.frames[0].probes.push((ProbeKind::Rtt, 0, 0)); + assert!(duplicate.validate(&config, &config.clients[0]).is_err()); + let mut wrong = plan; + wrong.targets[0] = "unknown".into(); + assert!(wrong.validate(&config, &config.clients[0]).is_err()); + } #[test] - fn compact_config_is_linear_for_1024_clients() { - let clients: Vec<_> = (1..=1024) - .map(|index| { - serde_json::json!({ - "name": format!("client{index}"), - "data_ip": format!("10.{}.{}.{}", index / 65536, (index / 256) % 256, index % 256), - "management_ip": format!("172.20.{}.{}", (index / 254) % 256, index % 254 + 1), - "rack": format!("rack{}", index / 8), - "leaf": format!("leaf{}", index / 8) - }) - }) - .collect(); - let payload = serde_json::json!({ - "schema_version": 1, - "topology_id": "synthetic-1024", - "pingmesh_policy": { - "destination_batch_size": 16, - "rtt_port_pool_size": 16, - "rtt_ports_per_cycle": 4, - "cycle_interval_seconds": 1.0, - "destination_batch_count": 64, - "port_batch_count": 4, - "coverage_epoch_cycles": 256, - "coverage_epoch_seconds": 256, - "df_payload_size": 1400 - }, - "clients": clients - }); - assert!(serde_json::to_vec(&payload).unwrap().len() < 1_000_000); + fn stale_versions_and_mismatched_plan_ids_are_rejected() { + let (mut config, mut plan) = fixture(); + config.schema_version = 1; + assert!(config.validate().is_err()); + config.schema_version = 2; + plan.plan_id = "b".repeat(64); + assert!(plan.validate(&config, &config.clients[0]).is_err()); } } diff --git a/native/client-agent/src/control.rs b/native/client-agent/src/control.rs index 88e53a3..54c808c 100644 --- a/native/client-agent/src/control.rs +++ b/native/client-agent/src/control.rs @@ -18,6 +18,8 @@ const MAX_CONTROL_CONNECTIONS: usize = 32; #[derive(Clone, Debug, Default, Serialize)] pub struct AgentStatus { + pub config_schema_version: u32, + pub plan_id: String, pub ready: bool, pub enabled: bool, pub heartbeat_unix_ns: u64, diff --git a/native/client-agent/src/main.rs b/native/client-agent/src/main.rs index 02f4aad..a088e03 100644 --- a/native/client-agent/src/main.rs +++ b/native/client-agent/src/main.rs @@ -18,6 +18,10 @@ struct Cli { #[derive(Debug, Subcommand)] enum Command { + ValidateConfig { + #[arg(long)] + config: PathBuf, + }, Pingmesh { #[arg(long)] config: PathBuf, @@ -32,6 +36,13 @@ enum Command { async fn main() -> Result<()> { let cli = Cli::parse(); match cli.command { + Command::ValidateConfig { config } => { + let shared = config::ClientAgentConfig::load(&config)?; + let local = shared.local_client()?; + shared.load_client_plan(&config, &local)?; + println!("{} {}", shared.schema_version, shared.pingmesh_plan.plan_id); + Ok(()) + } Command::Pingmesh { config } => { logging::init("/var/log/netopsbench/pingmesh.log"); log_command_result(pingmesh::run(&config).await) diff --git a/native/client-agent/src/pingmesh.rs b/native/client-agent/src/pingmesh.rs index 76941be..33a124f 100644 --- a/native/client-agent/src/pingmesh.rs +++ b/native/client-agent/src/pingmesh.rs @@ -7,8 +7,6 @@ use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail}; -use blake2::Blake2sVar; -use blake2::digest::{Update, VariableOutput}; use nix::errno::Errno; use nix::sys::socket::{ControlMessageOwned, MsgFlags, SockaddrIn, recvmsg}; use nix::sys::time::TimeValLike; @@ -19,11 +17,10 @@ use tokio::net::TcpStream; use tokio::sync::{Mutex, mpsc}; use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep, sleep_until, timeout}; -use crate::config::{Client, ClientAgentConfig, PINGMESH_CONTROL_PORT}; +use crate::config::{Client, ClientAgentConfig, ClientProbePlan, PINGMESH_CONTROL_PORT, ProbeKind}; use crate::control::{self, AgentStatus, ResponseEnvelope}; const UDP_DESTINATION_PORT: u16 = 33434; -const RTT_SOURCE_PORT_BASE: u16 = 33000; const PROBE_MAGIC: u32 = 0x4e4f_4250; const PROBE_VERSION: u8 = 2; const HEADER_SIZE: usize = 24; @@ -48,12 +45,6 @@ struct Target { path_type: &'static str, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum ProbeKind { - Rtt, - Df, -} - #[derive(Clone, Copy, Debug)] struct Pending { kind: ProbeKind, @@ -108,15 +99,17 @@ struct IngestConfig { pub async fn run(path: &Path) -> Result<()> { let config = ClientAgentConfig::load(path)?; let local = config.local_client()?; + let plan = config.load_client_plan(path, &local)?; let status = Arc::new(Mutex::new(AgentStatus::default())); let responder = create_udp_socket(local.data_ip, UDP_DESTINATION_PORT, true, true) .context("create Pingmesh responder")?; - let probe_sockets = - create_probe_sockets(local.data_ip, config.pingmesh_policy.rtt_port_pool_size)?; + let probe_sockets = create_probe_sockets(local.data_ip, &config.pingmesh_plan.source_ports)?; let ingest = IngestConfig::from_environment()?; let (metrics_tx, metrics_rx) = mpsc::channel(METRICS_QUEUE_CAPACITY); { let mut current = status.lock().await; + current.plan_id = config.pingmesh_plan.plan_id.clone(); + current.config_schema_version = config.schema_version; current.ready = true; current.active_listeners = 1; current.expected_listeners = 1; @@ -145,6 +138,7 @@ pub async fn run(path: &Path) -> Result<()> { config, local, probe_sockets, + plan, metrics_tx, Arc::clone(&status), ); @@ -161,12 +155,9 @@ pub async fn run(path: &Path) -> Result<()> { } } -fn create_probe_sockets(data_ip: Ipv4Addr, count: usize) -> Result> { - let mut sockets = Vec::with_capacity(count); - for offset in 0..count { - let source_port = RTT_SOURCE_PORT_BASE - .checked_add(u16::try_from(offset).context("source-port pool is too large")?) - .context("source-port pool overflow")?; +fn create_probe_sockets(data_ip: Ipv4Addr, ports: &[u16]) -> Result> { + let mut sockets = Vec::with_capacity(ports.len()); + for &source_port in ports { let socket = create_udp_socket(data_ip, source_port, true, false) .with_context(|| format!("bind Pingmesh source port {source_port}"))?; set_df(socket.get_ref())?; @@ -276,26 +267,52 @@ async fn probe_loop( config: ClientAgentConfig, local: Client, sockets: Vec, + plan: ClientProbePlan, metrics_tx: mpsc::Sender, status: Arc>, ) -> Result<()> { - let targets = build_targets(&config, &local); - let policy = config.pingmesh_policy.clone(); - let destination_batch_size = policy - .destination_batch_size - .unwrap_or(targets.len()) - .clamp(1, targets.len()); - let destination_phase = config - .clients + let settings = &config.pingmesh_plan; + let targets = plan + .targets .iter() - .position(|client| client.name == local.name) - .unwrap_or(0); - let host_seed = stable_host_seed(&local.name); - let port_phase = host_seed as usize % policy.port_batch_count; - let startup_jitter = (host_seed % 10_000) as f64 / 10_000.0 * policy.cycle_interval_seconds; - sleep(Duration::from_secs_f64(startup_jitter)).await; - - let cycle_duration = Duration::from_secs_f64(policy.cycle_interval_seconds); + .map(|name| { + let client = config + .clients + .iter() + .find(|client| &client.name == name) + .expect("validated target") + .clone(); + let path_type = if client.rack == local.rack { + "same_rack" + } else { + "cross_rack" + }; + Target { client, path_type } + }) + .collect::>(); + let socket_batches = settings + .port_batches + .iter() + .map(|indices| { + indices + .iter() + .map(|&index| &sockets[index]) + .collect::>() + }) + .collect::>(); + let frames = plan + .frames + .iter() + .map(|frame| { + frame + .target_indices + .iter() + .map(|&index| targets[index].clone()) + .collect::>() + }) + .collect::>(); + sleep(Duration::from_millis(plan.startup_delay_ms)).await; + let cycle_duration = Duration::from_secs(settings.cycle_interval_seconds); let probe_duration = probe_work_duration(cycle_duration); let mut cadence = interval_at(Instant::now(), cycle_duration); cadence.set_missed_tick_behavior(MissedTickBehavior::Skip); @@ -305,38 +322,38 @@ async fn probe_loop( loop { cadence.tick().await; let cycle_started = Instant::now(); - let (destination_batch, port_batch) = probe_batch_indices( - cycle, - policy.destination_batch_count, - policy.port_batch_count, - port_phase, - ); - let active_targets = rotating_destination_batch( - &targets, - destination_batch_size, - destination_batch, - destination_phase, - ); - let port_start = port_batch * policy.rtt_ports_per_cycle; - let port_end = (port_start + policy.rtt_ports_per_cycle).min(sockets.len()); - let active_sockets = &sockets[port_start..port_end]; - let results = run_probe_cycle( - &active_targets, - active_sockets, - policy.df_payload_size, - probe_duration, - host_seed.wrapping_add(cycle.wrapping_mul(0x9e37_79b9_7f4a_7c15)), - &mut sequence, - ) - .await?; + let frame_index = cycle as usize % plan.frames.len(); + let frame = &plan.frames[frame_index]; + let active_targets = &frames[frame_index]; + let active_sockets = &socket_batches[frame.port_batch_index]; + let results = if active_targets.is_empty() { + Vec::new() + } else { + run_probe_cycle( + active_targets, + active_sockets, + settings.df_payload_size, + probe_duration, + &frame.probes, + &mut sequence, + ) + .await? + }; for (target, mut result) in active_targets.iter().zip(results) { result.probe_cycle = cycle; - result.destination_batch_index = destination_batch; - result.port_batch_index = port_batch; + result.destination_batch_index = frame.destination_batch_index; + result.port_batch_index = frame.port_batch_index; result.rtt_ports_total = sockets.len(); let timestamp = realtime_ns(); - for line in metric_lines(&config.topology_id, &local, target, &result, timestamp) { + for line in metric_lines( + &config.topology_id, + &settings.plan_id, + &local, + target, + &result, + timestamp, + ) { if metrics_tx.try_send(line).is_err() { let mut current = status.lock().await; current.ready = false; @@ -363,18 +380,17 @@ fn probe_work_duration(cycle_duration: Duration) -> Duration { async fn run_probe_cycle( targets: &[Target], - sockets: &[ProbeSocket], + sockets: &[&ProbeSocket], df_payload_size: usize, duration: Duration, - schedule_phase: u64, + send_queue: &[(ProbeKind, usize, usize)], sequence: &mut u64, ) -> Result> { let mut rtt_stats = vec![ProbeStats::default(); targets.len()]; let mut df_stats = vec![ProbeStats::default(); targets.len()]; + let mut receive_buffer = vec![0_u8; 65_535]; drain_sockets(sockets)?; let mut pending: HashMap = HashMap::new(); - let mut send_queue = build_probe_schedule(targets.len(), sockets.len()); - rotate_probe_schedule(&mut send_queue, schedule_phase); let started = Instant::now(); let deadline = started + duration; @@ -385,7 +401,7 @@ async fn run_probe_cycle( Duration::ZERO }; - for (index, (kind, target_index, socket_index)) in send_queue.into_iter().enumerate() { + for (index, (kind, target_index, socket_index)) in send_queue.iter().copied().enumerate() { sleep_until(started + spacing.mul_f64(index as f64)).await; send_probe( kind, @@ -399,14 +415,39 @@ async fn run_probe_cycle( &mut rtt_stats, &mut df_stats, )?; + drain_replies( + sockets, + &mut pending, + &mut rtt_stats, + &mut df_stats, + &mut receive_buffer, + )?; } - drain_replies(sockets, &mut pending, &mut rtt_stats, &mut df_stats)?; + drain_replies( + sockets, + &mut pending, + &mut rtt_stats, + &mut df_stats, + &mut receive_buffer, + )?; sleep(REPLY_DRAIN_INTERVAL).await; - drain_replies(sockets, &mut pending, &mut rtt_stats, &mut df_stats)?; + drain_replies( + sockets, + &mut pending, + &mut rtt_stats, + &mut df_stats, + &mut receive_buffer, + )?; let unanswered_df = unanswered_df_targets(&pending); - for (target_index, socket_index) in unanswered_df { - for _ in 0..DF_CONFIRMATION_PROBES { + // Keep all sixteen confirmations, but space retry rounds and receive + // between them. A burst of jumbo replies can otherwise fill the local + // receive queue and turn transient loss into a false network MTU signal. + for _ in 0..DF_CONFIRMATION_PROBES { + if unanswered_df.is_empty() { + break; + } + for &(target_index, socket_index) in &unanswered_df { send_probe( ProbeKind::Df, target_index, @@ -420,41 +461,45 @@ async fn run_probe_cycle( &mut df_stats, )?; } + sleep(REPLY_DRAIN_INTERVAL).await; + drain_replies( + sockets, + &mut pending, + &mut rtt_stats, + &mut df_stats, + &mut receive_buffer, + )?; } while Instant::now() < deadline && !pending.is_empty() { - drain_replies(sockets, &mut pending, &mut rtt_stats, &mut df_stats)?; + drain_replies( + sockets, + &mut pending, + &mut rtt_stats, + &mut df_stats, + &mut receive_buffer, + )?; sleep(REPLY_DRAIN_INTERVAL).await; } - drain_replies(sockets, &mut pending, &mut rtt_stats, &mut df_stats)?; + drain_replies( + sockets, + &mut pending, + &mut rtt_stats, + &mut df_stats, + &mut receive_buffer, + )?; Ok((0..targets.len()) .map(|index| build_result(&rtt_stats[index], &df_stats[index], sockets.len())) .collect()) } -fn build_probe_schedule( - target_count: usize, - socket_count: usize, -) -> Vec<(ProbeKind, usize, usize)> { - let mut schedule = Vec::new(); - for target_index in 0..target_count { - for socket_index in 0..socket_count { - schedule.push((ProbeKind::Rtt, target_index, socket_index)); - } - if socket_count > 0 { - schedule.push((ProbeKind::Df, target_index, target_index % socket_count)); - } - } - schedule -} - #[allow(clippy::too_many_arguments)] fn send_probe( kind: ProbeKind, target_index: usize, socket_index: usize, targets: &[Target], - sockets: &[ProbeSocket], + sockets: &[&ProbeSocket], df_payload_size: usize, sequence: &mut u64, pending: &mut HashMap, @@ -520,12 +565,6 @@ fn send_probe( Ok(()) } -fn rotate_probe_schedule(queue: &mut [T], phase: u64) { - if !queue.is_empty() { - queue.rotate_left((phase as usize) % queue.len()); - } -} - fn unanswered_df_targets(pending: &HashMap) -> Vec<(usize, usize)> { pending .values() @@ -534,7 +573,7 @@ fn unanswered_df_targets(pending: &HashMap) -> Vec<(usize, usize)> .collect() } -fn drain_sockets(sockets: &[ProbeSocket]) -> Result<()> { +fn drain_sockets(sockets: &[&ProbeSocket]) -> Result<()> { let mut buffer = vec![0_u8; 65_535]; for socket in sockets { loop { @@ -549,15 +588,15 @@ fn drain_sockets(sockets: &[ProbeSocket]) -> Result<()> { } fn drain_replies( - sockets: &[ProbeSocket], + sockets: &[&ProbeSocket], pending: &mut HashMap, rtt_stats: &mut [ProbeStats], df_stats: &mut [ProbeStats], + buffer: &mut [u8], ) -> Result<()> { - let mut buffer = vec![0_u8; 65_535]; for socket in sockets { loop { - let packet = match recv_timestamped(socket.socket.get_ref(), &mut buffer) { + let packet = match recv_timestamped(socket.socket.get_ref(), buffer) { Ok(packet) => packet, Err(error) if error.kind() == io::ErrorKind::WouldBlock => break, Err(error) => return Err(error).context("receive Pingmesh reply"), @@ -698,73 +737,6 @@ fn realtime_ns() -> u64 { .unwrap_or(u64::MAX) } -fn build_targets(config: &ClientAgentConfig, local: &Client) -> Vec { - let local_index = config - .clients - .iter() - .position(|client| client.name == local.name) - .expect("validated local client"); - (1..config.clients.len()) - .map(|offset| { - let client = config.clients[(local_index + offset) % config.clients.len()].clone(); - let path_type = if client.rack == local.rack { - "same_rack" - } else { - "cross_rack" - }; - Target { client, path_type } - }) - .collect() -} - -fn rotating_destination_batch( - targets: &[Target], - batch_size: usize, - batch_index: usize, - phase_offset: usize, -) -> Vec { - if targets.is_empty() { - return Vec::new(); - } - let size = batch_size.clamp(1, targets.len()); - let batch_count = targets.len().div_ceil(size); - let phase = phase_offset % targets.len(); - let ordered = targets[phase..] - .iter() - .chain(targets[..phase].iter()) - .cloned() - .collect::>(); - ordered - .into_iter() - .skip(batch_index % batch_count) - .step_by(batch_count) - .collect() -} - -fn probe_batch_indices( - cycle: u64, - destination_batch_count: usize, - port_batch_count: usize, - port_phase: usize, -) -> (usize, usize) { - let destination_count = destination_batch_count.max(1); - let port_count = port_batch_count.max(1); - let epoch_cycle = cycle as usize % (destination_count * port_count); - let destination_batch = epoch_cycle % destination_count; - let port_round = epoch_cycle / destination_count; - (destination_batch, (port_round + port_phase) % port_count) -} - -fn stable_host_seed(hostname: &str) -> u64 { - let mut hasher = Blake2sVar::new(8).expect("BLAKE2s supports an eight-byte digest"); - hasher.update(hostname.as_bytes()); - let mut digest = [0_u8; 8]; - hasher - .finalize_variable(&mut digest) - .expect("digest buffer has the configured size"); - u64::from_be_bytes(digest) -} - fn build_result(rtt: &ProbeStats, df: &ProbeStats, active_ports: usize) -> ProbeResult { let rtt_sent = valid_sent(rtt); let df_sent = valid_sent(df); @@ -822,13 +794,14 @@ fn percentile(values: &[f64], quantile: f64) -> f64 { fn metric_lines( topology_id: &str, + plan_id: &str, source: &Client, target: &Target, result: &ProbeResult, timestamp: u64, ) -> Vec { let tags = format!( - "src_ip={},dst_ip={},src_name={},dst_name={},src_leaf={},dst_leaf={},path_type={},topology_id={}", + "src_ip={},dst_ip={},src_name={},dst_name={},src_leaf={},dst_leaf={},path_type={},topology_id={},plan_id={}", escape_tag(&source.data_ip.to_string()), escape_tag(&target.client.data_ip.to_string()), escape_tag(&source.name), @@ -837,6 +810,7 @@ fn metric_lines( escape_tag(&target.client.leaf), target.path_type, escape_tag(topology_id), + escape_tag(plan_id), ); let fields = format!( "rtt_min={},rtt_avg={},rtt_max={},rtt_p90={},rtt_p99={},packets_sent={}i,packets_lost={}i,packet_loss={},rtt_ports_active={}i,rtt_ports_total={}i,probe_cycle={}i,destination_batch_index={}i,port_batch_index={}i,df_packets_sent={}i,df_packets_lost={}i,df_mtu_drops={}i,local_probe_errors={}i", @@ -1020,47 +994,6 @@ mod tests { assert_ne!(DF_DISCOVERY_MODE, libc::IP_PMTUDISC_DO); } - #[test] - fn probe_schedule_rotation_is_deterministic_and_source_specific() { - let original = vec![0, 1, 2, 3, 4]; - let mut first = original.clone(); - let mut repeated = original.clone(); - let mut other = original; - - rotate_probe_schedule(&mut first, 2); - rotate_probe_schedule(&mut repeated, 2); - rotate_probe_schedule(&mut other, 3); - - assert_eq!(first, repeated); - assert_ne!(first, other); - assert_eq!(first, vec![2, 3, 4, 0, 1]); - } - - #[test] - fn probe_schedule_starts_with_one_df_sample_per_path() { - let schedule = build_probe_schedule(2, 4); - - for target_index in 0..2 { - assert_eq!( - schedule - .iter() - .filter(|(kind, target, _socket)| { - *kind == ProbeKind::Df && *target == target_index - }) - .count(), - 1, - ); - } - assert_eq!(1 + DF_CONFIRMATION_PROBES, 16); - assert_eq!( - schedule - .iter() - .filter(|(kind, _target, _socket)| *kind == ProbeKind::Rtt) - .count(), - 8, - ); - } - #[test] fn confirmation_targets_only_unanswered_df_probes() { let pending = HashMap::from([ @@ -1088,6 +1021,76 @@ mod tests { assert!(unanswered_df_targets(&HashMap::new()).is_empty()); } + #[tokio::test] + async fn confirmation_recovers_initial_df_loss_without_flooding_reply_sockets() { + let results = run_df_confirmation_fixture(false).await; + assert!(results.iter().all(|result| result.packets_lost == 0)); + assert!(results.iter().all(|result| result.df_packets_sent == 16)); + assert!(results.iter().all(|result| result.df_packets_lost < 16)); + } + + #[tokio::test] + async fn confirmation_preserves_real_df_blackholes() { + let results = run_df_confirmation_fixture(true).await; + assert!(results.iter().all(|result| result.packets_lost == 0)); + assert!(results.iter().all(|result| result.df_packets_sent == 16)); + assert!(results.iter().all(|result| result.df_packets_lost == 16)); + } + + async fn run_df_confirmation_fixture(drop_all_df: bool) -> Vec { + let mut responders = Vec::new(); + let mut targets = Vec::new(); + for number in 1..=32_u8 { + let data_ip = Ipv4Addr::new(127, 0, if drop_all_df { 2 } else { 1 }, number); + let socket = tokio::net::UdpSocket::bind((data_ip, UDP_DESTINATION_PORT)) + .await + .unwrap(); + responders.push(tokio::spawn(async move { + let mut buffer = vec![0_u8; 65_535]; + let mut initial_df_dropped = false; + loop { + let (bytes, peer) = socket.recv_from(&mut buffer).await.unwrap(); + if bytes > RTT_PAYLOAD_BYTES && (drop_all_df || !initial_df_dropped) { + initial_df_dropped = true; + continue; + } + socket.send_to(&buffer[..bytes], peer).await.unwrap(); + } + })); + targets.push(Target { + client: Client { + name: format!("client{number}"), + data_ip, + management_ip: Ipv4Addr::LOCALHOST, + leaf: format!("leaf{number}"), + rack: format!("rack{number}"), + }, + path_type: "cross_rack", + }); + } + let owned_sockets = create_probe_sockets(Ipv4Addr::LOCALHOST, &[0; 4]).unwrap(); + let sockets = owned_sockets.iter().collect::>(); + let mut probes = Vec::new(); + for target in 0..targets.len() { + probes.extend((0..sockets.len()).map(|socket| (ProbeKind::Rtt, target, socket))); + probes.push((ProbeKind::Df, target, target % sockets.len())); + } + let results = run_probe_cycle( + &targets, + &sockets, + 9_000, + Duration::from_millis(650), + &probes, + &mut 0, + ) + .await + .unwrap(); + for responder in responders { + responder.abort(); + } + results + } + #[test] fn local_probe_errors_are_excluded_from_network_loss() { let rtt = ProbeStats { @@ -1157,52 +1160,6 @@ mod tests { assert_eq!(decode_header(&buffer), None); } - #[test] - fn host_seed_is_stable_for_the_same_client() { - assert_eq!(stable_host_seed("client-17"), 13_881_939_690_399_091_852); - } - - #[test] - fn destination_and_port_rotation_is_deterministic() { - let clients = (0..8) - .map(|index| Client { - name: format!("client{index}"), - data_ip: Ipv4Addr::new(192, 0, 2, index + 1), - management_ip: Ipv4Addr::new(172, 20, 0, index + 1), - rack: format!("rack{}", index / 2), - leaf: format!("leaf{}", index / 2), - }) - .collect::>(); - let targets = clients[1..] - .iter() - .cloned() - .map(|client| Target { - client, - path_type: "cross_rack", - }) - .collect::>(); - let batches = (0..3) - .map(|batch| { - rotating_destination_batch(&targets, 3, batch, 2) - .into_iter() - .map(|target| target.client.name) - .collect::>() - }) - .collect::>(); - - assert_eq!( - batches, - vec![ - vec!["client3", "client6", "client2"], - vec!["client4", "client7"], - vec!["client5", "client1"], - ] - ); - assert_eq!(probe_batch_indices(0, 3, 4, 2), (0, 2)); - assert_eq!(probe_batch_indices(3, 3, 4, 2), (0, 3)); - assert_eq!(probe_batch_indices(12, 3, 4, 2), (0, 2)); - } - #[test] fn probe_work_uses_the_topology_cycle_instead_of_a_fixed_cap() { assert_eq!( @@ -1272,7 +1229,7 @@ mod tests { } #[test] - fn line_protocol_snapshot_remains_compatible() { + fn line_protocol_includes_plan_identity() { let source = Client { name: "client1".into(), data_ip: "192.0.2.1".parse().unwrap(), @@ -1310,12 +1267,12 @@ mod tests { local_probe_errors: 0, }; - let lines = metric_lines("topology=1", &source, &target, &result, 123); + let lines = metric_lines("topology=1", "plan1", &source, &target, &result, 123); assert_eq!(lines.len(), 1); assert_eq!( lines[0], - "pingmesh,src_ip=192.0.2.1,dst_ip=192.0.2.2,src_name=client1,dst_name=client2,src_leaf=leaf1,dst_leaf=leaf2,path_type=cross_rack,topology_id=topology\\=1 rtt_min=1,rtt_avg=2,rtt_max=3,rtt_p90=2.5,rtt_p99=2.9,packets_sent=4i,packets_lost=1i,packet_loss=25,rtt_ports_active=4i,rtt_ports_total=16i,probe_cycle=7i,destination_batch_index=1i,port_batch_index=2i,df_packets_sent=1i,df_packets_lost=0i,df_mtu_drops=0i,local_probe_errors=0i 123" + "pingmesh,src_ip=192.0.2.1,dst_ip=192.0.2.2,src_name=client1,dst_name=client2,src_leaf=leaf1,dst_leaf=leaf2,path_type=cross_rack,topology_id=topology\\=1,plan_id=plan1 rtt_min=1,rtt_avg=2,rtt_max=3,rtt_p90=2.5,rtt_p99=2.9,packets_sent=4i,packets_lost=1i,packet_loss=25,rtt_ports_active=4i,rtt_ports_total=16i,probe_cycle=7i,destination_batch_index=1i,port_batch_index=2i,df_packets_sent=1i,df_packets_lost=0i,df_mtu_drops=0i,local_probe_errors=0i 123" ); } } diff --git a/netopsbench/cli/main.py b/netopsbench/cli/main.py index 3eecd88..790e9a5 100644 --- a/netopsbench/cli/main.py +++ b/netopsbench/cli/main.py @@ -10,6 +10,7 @@ from netopsbench.cli.trace import add_trace_subparser, cmd_trace from netopsbench.logging_utils import configure_logging +from netopsbench.models.profiles import ScaleRegistry from netopsbench.platform.scenario import generator as scenario_generator from netopsbench.platform.topology.generator import generate_topology from netopsbench.sdk import NetOpsBench @@ -50,6 +51,9 @@ def build_parser() -> argparse.ArgumentParser: scenario_list.add_argument("path", nargs="?", default="scenarios", help="Scenario file or directory") scenario_validate = scenario_sub.add_parser("validate", help="Validate one scenario YAML") scenario_validate.add_argument("file", help="Scenario YAML file") + scenario_migrate = scenario_sub.add_parser("migrate", help="Copy scenarios to recovery policy v3") + scenario_migrate.add_argument("source", type=Path) + scenario_migrate.add_argument("--out", type=Path, required=True) scenario_generate = scenario_sub.add_parser("generate", help="Generate scenario YAML for one scale") scenario_generate.add_argument("--scale", required=True, help="Topology scale") scenario_generate.add_argument("--spec", help="Scenario generation spec file (default: packaged campaign)") @@ -80,7 +84,7 @@ def build_parser() -> argparse.ArgumentParser: benchmark_prepare.add_argument( "--scales", default=None, - help="Comma-separated scale list (default: all resolved profiles)", + help="Comma-separated scale list (default: benchmark profiles; XS is explicit validation)", ) benchmark_prepare.add_argument("--spec", help="Scenario generation spec file (default: packaged campaign)") benchmark_prepare.add_argument("--seed", type=int, default=42, help="Random seed for reproducible generation") @@ -179,6 +183,7 @@ def _generate_scenarios( topology_dir: Path | None = None, out: Path | None = None, seed: int = 42, + scale_registry: ScaleRegistry | None = None, ) -> int: spec_path = Path(spec) topo_dir = Path(topology_dir) if topology_dir is not None else _default_topology_output_dir(workspace, scale) @@ -188,7 +193,7 @@ def _generate_scenarios( removed = scenario_generator.cleanup_existing_outputs(out_dir) if removed: print(f"removed existing scenarios: {removed}") - generated = scenario_generator.generate(loaded_spec, topology, out_dir, seed) + generated = scenario_generator.generate(loaded_spec, topology, out_dir, seed, scale_registry=scale_registry) print(f"generated scenarios: scale={scale}") print(f" spec: {spec_path}") print(f" topology_dir: {topo_dir}") @@ -226,6 +231,12 @@ def _cmd_scenario(bench: NetOpsBench, args: argparse.Namespace) -> int: for path in sorted(target.glob("*.y*ml")): print(path) return 0 + if args.scenario_action == "migrate": + from netopsbench.platform.scenario.migration import migrate_recovery + + output = migrate_recovery(bench.workspace / args.source, bench.workspace / args.out) + print(f"Migrated recovery campaign: {output}") + return 0 if args.scenario_action == "validate": raw_file = Path(args.file) scenario_file = raw_file if raw_file.is_absolute() else (bench.workspace / raw_file) @@ -241,7 +252,13 @@ def _cmd_scenario(bench: NetOpsBench, args: argparse.Namespace) -> int: topology_dir = Path(args.topology_dir) if args.topology_dir else None out = Path(args.out) if args.out else None return _generate_scenarios( - bench.workspace, scale=args.scale, spec=spec, topology_dir=topology_dir, out=out, seed=args.seed + bench.workspace, + scale=args.scale, + spec=spec, + topology_dir=topology_dir, + out=out, + seed=args.seed, + scale_registry=bench.scales.registry, ) raise AssertionError(f"unhandled scenario action: {args.scenario_action}") @@ -294,7 +311,8 @@ def _cmd_result(bench: NetOpsBench, args: argparse.Namespace) -> int: def _cmd_benchmark(bench: NetOpsBench, args: argparse.Namespace) -> int: if args.benchmark_action == "prepare": - scales = _parse_scales(args.scales, bench.scales.names()) + selected = args.scales or ",".join(p.name for p in bench.scales.registry.values() if p.purpose == "benchmark") + scales = _parse_scales(selected, bench.scales.registry.names()) spec = Path(args.spec) if args.spec else _default_scenario_spec() print("Preparing benchmark assets") print(f" workspace: {bench.workspace}") @@ -305,7 +323,13 @@ def _cmd_benchmark(bench: NetOpsBench, args: argparse.Namespace) -> int: scenario_dir = _default_scenario_output_dir(bench.workspace, scale) _generate_topology(bench, scale=scale, output_dir=topo_dir) _generate_scenarios( - bench.workspace, scale=scale, spec=spec, topology_dir=topo_dir, out=scenario_dir, seed=args.seed + bench.workspace, + scale=scale, + spec=spec, + topology_dir=topo_dir, + out=scenario_dir, + seed=args.seed, + scale_registry=bench.scales.registry, ) print("Benchmark assets ready") return 0 diff --git a/netopsbench/evaluator/fault_type_judge.py b/netopsbench/evaluator/fault_type_judge.py index 62b8dd5..5578c5a 100644 --- a/netopsbench/evaluator/fault_type_judge.py +++ b/netopsbench/evaluator/fault_type_judge.py @@ -31,18 +31,6 @@ "static_route_misconfiguration": "static_route_misconfig", "route_misconfig": "static_route_misconfig", "mtu_error": "mtu_mismatch", - "bgp_peer_misconfig": "bgp_neighbor_misconfig", - "bgp_peer_config_error": "bgp_neighbor_misconfig", - "bgp_session_misconfig": "bgp_neighbor_misconfig", - "bgp_neighbor_config_error": "bgp_neighbor_misconfig", - "route_policy_error": "route_policy_misconfig", - "route_policy_misconfiguration": "route_policy_misconfig", - "bgp_policy_misconfig": "route_policy_misconfig", - "route_origination_missing": "route_policy_misconfig", - "network_statement_missing": "route_policy_misconfig", - "prefix_filter_misconfig": "route_policy_misconfig", - "outbound_prefix_filter": "route_policy_misconfig", - "acl_misconfiguration": "acl_misconfig", } diff --git a/netopsbench/evaluator/scorer.py b/netopsbench/evaluator/scorer.py index ff4fd4a..67db555 100644 --- a/netopsbench/evaluator/scorer.py +++ b/netopsbench/evaluator/scorer.py @@ -37,6 +37,41 @@ class AgentOutput: # metadata["input_tokens"] -> int: prompt tokens consumed by the LLM # metadata["output_tokens"] -> int: completion tokens produced by the LLM + @classmethod + def from_diagnosis( + cls, + diagnosis, + *, + merge_location_fields=False, + metadata_evidence=True, + findings_tool_calls=True, + time_taken_seconds=None, + ) -> AgentOutput: + """Normalize shared fields while preserving each entrypoint's precedence.""" + findings, metadata = dict(diagnosis.findings or {}), dict(diagnosis.metadata or {}) + raw_location = findings.get("location") + location = raw_location if isinstance(raw_location, dict) else {} + if merge_location_fields: + location = {key: location.get(key) or findings.get(key) for key in ("device", "interface")} + location = {key: value for key, value in location.items() if value is not None} + elif not location: + location = {key: findings[key] for key in ("device", "interface") if findings.get(key) is not None} + return cls( + verdict=diagnosis.verdict, + fault_type=findings.get("fault_type") or metadata.get("fault_type"), + location=location, + evidence=list(findings.get("evidence") or (metadata.get("evidence") if metadata_evidence else None) or []), + confidence=float(diagnosis.confidence or 0.0), + reasoning=diagnosis.reasoning, + tool_calls=list( + metadata.get("tool_calls") or (findings.get("tool_calls") if findings_tool_calls else None) or [] + ), + time_taken_seconds=float( + (metadata.get("time_taken_seconds", 0.0) if time_taken_seconds is None else time_taken_seconds) or 0.0 + ), + metadata=metadata, + ) + def to_dict(self) -> dict: return asdict(self) diff --git a/netopsbench/models/pingmesh.py b/netopsbench/models/pingmesh.py new file mode 100644 index 0000000..ee4633d --- /dev/null +++ b/netopsbench/models/pingmesh.py @@ -0,0 +1,71 @@ +"""Persisted, offline-compiled Pingmesh schedules.""" + +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field + + +class _PlanModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class ProbeFrame(_PlanModel): + destination_batch_index: int = Field(ge=0) + port_batch_index: int = Field(ge=0) + target_indices: list[int] + # Kind, frame-local target index, batch-local socket index. + probes: list[tuple[Literal["rtt", "df"], int, int]] + + +class ClientProbePlan(_PlanModel): + name: str + targets: list[str] + startup_delay_ms: int = Field(ge=0) + frames: list[ProbeFrame] + + +class PlanSettings(_PlanModel): + plan_id: str + source_ports: list[int] + port_batches: list[list[int]] + destination_batch_size: int = Field(gt=0) + cycle_interval_seconds: int = Field(gt=0) + coverage_epoch_cycles: int = Field(gt=0) + coverage_epoch_seconds: int = Field(gt=0) + complete_window_seconds: int = Field(gt=0) + df_payload_size: int = Field(gt=0) + + +class LinkCoverage(_PlanModel): + source: str + destination: str + source_interface: str + destination_interface: str + witnesses: int = Field(ge=0) + + +class CandidateCoverage(_PlanModel): + basis: Literal["topology_candidate_paths"] = "topology_candidate_paths" + directed_links: list[LinkCoverage] + covered_switches: list[str] + minimum_witnesses: int = Field(ge=0) + + +class PingmeshPlan(_PlanModel): + schema_version: Literal["1"] = "1" + settings: PlanSettings + clients: list[ClientProbePlan] + coverage: CandidateCoverage + + @property + def directed_pair_count(self) -> int: + return sum(len(client.targets) for client in self.clients) + + def summary(self) -> dict: + return { + **self.settings.model_dump(mode="json"), + "directed_pair_count": self.directed_pair_count, + "coverage_basis": self.coverage.basis, + "candidate_directed_links": len(self.coverage.directed_links), + "minimum_link_witnesses": self.coverage.minimum_witnesses, + } diff --git a/netopsbench/models/profiles.py b/netopsbench/models/profiles.py index 18fbe3a..935605d 100644 --- a/netopsbench/models/profiles.py +++ b/netopsbench/models/profiles.py @@ -4,7 +4,7 @@ import hashlib import json -from functools import cached_property +from functools import cached_property, lru_cache from importlib.resources import files from pathlib import Path from typing import Annotated, Literal @@ -49,6 +49,7 @@ class ManagementProfile(BaseModel): class PingmeshProfile(BaseModel): + cross_rack_pairs: int | None = Field(default=None, gt=0) model_config = ConfigDict(extra="forbid", frozen=True) destination_batch_size: int | None = Field(default=None, gt=0) @@ -78,17 +79,40 @@ class RuntimeProfile(BaseModel): containerlab_max_workers: int | None = Field(default=None, gt=0) +class ExperimentProfile(BaseModel): + """One immutable experiment policy, independent of the injected fault.""" + + model_config = ConfigDict(extra="forbid", frozen=True) + + observation_seconds: int = Field(gt=0) + diagnosis_timeout_seconds: int = Field(gt=0) + recovery_timeout_seconds: int = Field(gt=0) + flapping_down_seconds: int = Field(gt=0) + flapping_up_seconds: int = Field(gt=0) + + def window_seconds(self, complete_window_seconds: int) -> int: + return max(self.observation_seconds, complete_window_seconds) + + +@lru_cache(maxsize=1) +def default_experiment_profile() -> ExperimentProfile: + payload = yaml.safe_load(files("netopsbench.models").joinpath("scale_profiles.yaml").read_text()) + return ExperimentProfile.model_validate(payload["experiment_defaults"]) + + class ScaleProfile(BaseModel): """Validated scale facts shared by topology and runtime subsystems.""" model_config = ConfigDict(extra="forbid", frozen=True) name: str = Field(min_length=1) + purpose: Literal["benchmark", "validation"] = "benchmark" topology: TopologyProfile management: ManagementProfile pingmesh: PingmeshProfile traffic: TrafficProfile runtime: RuntimeProfile + experiment: ExperimentProfile = Field(default_factory=default_experiment_profile) @property def family(self) -> Literal["clos", "fat-tree"]: @@ -196,9 +220,31 @@ def digest(self) -> str: class ScaleProfileDocument(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) - schema_version: Literal["1"] = "1" + schema_version: Literal["2"] = "2" override: bool = False profiles: list[ScaleProfile] + experiment_defaults: ExperimentProfile = Field(default_factory=default_experiment_profile) + + @model_validator(mode="before") + @classmethod + def resolve_experiment_defaults(cls, value): + if not isinstance(value, dict): + return value + payload = dict(value) + supplied = payload.get("experiment_defaults") or {} + if isinstance(supplied, ExperimentProfile): + supplied = supplied.model_dump() + defaults = {**default_experiment_profile().model_dump(), **supplied} + payload["experiment_defaults"] = defaults + payload["profiles"] = [ + ( + {**profile, "experiment": {**defaults, **profile.get("experiment", {})}} + if isinstance(profile, dict) + else profile + ) + for profile in payload.get("profiles", []) + ] + return payload class ScaleRegistry(BaseModel): @@ -301,6 +347,8 @@ def get_scale_profile(name: str, registry: ScaleRegistry | None = None) -> Scale __all__ = [ + "ExperimentProfile", + "default_experiment_profile", "ClosTopologyProfile", "FatTreeTopologyProfile", "ManagementProfile", diff --git a/netopsbench/models/recovery.py b/netopsbench/models/recovery.py new file mode 100644 index 0000000..2761f75 --- /dev/null +++ b/netopsbench/models/recovery.py @@ -0,0 +1,21 @@ +"""Versioned recovery policy stored in scenario metadata, never scale digests.""" + +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field + + +class RecoveryPolicy(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + version: Literal[3] = 3 + baseline_max_cases: int = Field(default=10, gt=0) + + @classmethod + def from_metadata(cls, metadata: dict) -> "RecoveryPolicy": + value = metadata.get("recovery_policy") + if not isinstance(value, dict) or value.get("version") != 3: + raise ValueError( + "Recovery policy v3 required; migrate with netopsbench scenario migrate SOURCE --out NEW_DIRECTORY" + ) + return cls.model_validate(value) diff --git a/netopsbench/models/runtime.py b/netopsbench/models/runtime.py index 05c283f..9fa0577 100644 --- a/netopsbench/models/runtime.py +++ b/netopsbench/models/runtime.py @@ -27,7 +27,7 @@ class RuntimeIdentity(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) - schema_version: Literal["3"] = "3" + schema_version: Literal["4"] = "4" runtime_id: str worker_id: str worker_index: int = Field(ge=1) diff --git a/netopsbench/models/scale_profiles.yaml b/netopsbench/models/scale_profiles.yaml index b4fae3c..0b4abe1 100644 --- a/netopsbench/models/scale_profiles.yaml +++ b/netopsbench/models/scale_profiles.yaml @@ -1,44 +1,169 @@ -schema_version: "1" +schema_version: '2' +experiment_defaults: + observation_seconds: 30 + diagnosis_timeout_seconds: 600 + recovery_timeout_seconds: 120 + flapping_down_seconds: 10 + flapping_up_seconds: 10 profiles: - - name: xs - topology: {family: clos, spines: 2, leafs: 2, clients_per_leaf: 1} - management: {prefix: 24, subnet_base: 100} - pingmesh: {destination_batch_size: null, rtt_port_pool_size: 16, rtt_ports_per_cycle: 8, cycle_interval_seconds: 1} - traffic: {max_pps_per_client: 250} - runtime: {deploy_timeout_seconds: 1800, worker_deploy_parallelism: 2, health_timeout_seconds: 60} - - name: small - topology: {family: clos, spines: 2, leafs: 4, clients_per_leaf: 2} - management: {prefix: 24, subnet_base: 120} - pingmesh: {destination_batch_size: null, rtt_port_pool_size: 16, rtt_ports_per_cycle: 8, cycle_interval_seconds: 1} - traffic: {max_pps_per_client: 250} - runtime: {deploy_timeout_seconds: 1800, worker_deploy_parallelism: 2, health_timeout_seconds: 60} - - name: medium - topology: {family: clos, spines: 4, leafs: 8, clients_per_leaf: 2} - management: {prefix: 24, subnet_base: 140} - pingmesh: {destination_batch_size: null, rtt_port_pool_size: 16, rtt_ports_per_cycle: 6, cycle_interval_seconds: 1} - traffic: {max_pps_per_client: 200} - runtime: {deploy_timeout_seconds: 1800, worker_deploy_parallelism: 2, health_timeout_seconds: 60} - - name: large - topology: {family: clos, spines: 4, leafs: 16, clients_per_leaf: 4} - management: {prefix: 24, subnet_base: 160} - pingmesh: {destination_batch_size: 16, rtt_port_pool_size: 16, rtt_ports_per_cycle: 4, cycle_interval_seconds: 3} - traffic: {max_pps_per_client: 100} - runtime: {deploy_timeout_seconds: 2700, worker_deploy_parallelism: 1, health_timeout_seconds: 180, containerlab_max_workers: 16} - - name: xlarge - topology: {family: clos, spines: 16, leafs: 128, clients_per_leaf: 1} - management: {prefix: 23, subnet_base: 180} - pingmesh: {destination_batch_size: 16, rtt_port_pool_size: 16, rtt_ports_per_cycle: 4, cycle_interval_seconds: 3} - traffic: {max_pps_per_client: 100} - runtime: {deploy_timeout_seconds: 3600, worker_deploy_parallelism: 1, health_timeout_seconds: 240, containerlab_max_workers: 16} - - name: fat-tree-k8 - topology: {family: fat-tree, k: 8, clients_per_edge: 4} - management: {prefix: 24, subnet_base: 200} - pingmesh: {destination_batch_size: 16, rtt_port_pool_size: 16, rtt_ports_per_cycle: 4, cycle_interval_seconds: 3} - traffic: {max_pps_per_client: 100} - runtime: {deploy_timeout_seconds: 3600, worker_deploy_parallelism: 1, health_timeout_seconds: 240, containerlab_max_workers: 1} - - name: fat-tree-k12 - topology: {family: fat-tree, k: 12, clients_per_edge: 2} - management: {prefix: 23, subnet_base: 220} - pingmesh: {destination_batch_size: 16, rtt_port_pool_size: 16, rtt_ports_per_cycle: 4, cycle_interval_seconds: 3} - traffic: {max_pps_per_client: 50} - runtime: {deploy_timeout_seconds: 5400, worker_deploy_parallelism: 1, health_timeout_seconds: 300, containerlab_max_workers: 1} +- name: xs + topology: + family: clos + spines: 2 + leafs: 2 + clients_per_leaf: 1 + management: + prefix: 24 + subnet_base: 100 + pingmesh: + destination_batch_size: null + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 8 + cycle_interval_seconds: 1 + traffic: + max_pps_per_client: 250 + runtime: + deploy_timeout_seconds: 1800 + worker_deploy_parallelism: 2 + health_timeout_seconds: 60 + purpose: validation +- name: medium + topology: + family: clos + spines: 4 + leafs: 8 + clients_per_leaf: 2 + management: + prefix: 24 + subnet_base: 140 + pingmesh: + destination_batch_size: null + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 6 + cycle_interval_seconds: 1 + traffic: + max_pps_per_client: 200 + runtime: + deploy_timeout_seconds: 1800 + worker_deploy_parallelism: 2 + health_timeout_seconds: 60 + purpose: benchmark +- name: large + experiment: + recovery_timeout_seconds: 180 + topology: + family: clos + spines: 4 + leafs: 16 + clients_per_leaf: 4 + management: + prefix: 24 + subnet_base: 160 + pingmesh: + destination_batch_size: 16 + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 4 + cycle_interval_seconds: 3 + traffic: + max_pps_per_client: 100 + runtime: + deploy_timeout_seconds: 2700 + worker_deploy_parallelism: 1 + health_timeout_seconds: 180 + containerlab_max_workers: 16 + purpose: benchmark +- name: xlarge + experiment: + recovery_timeout_seconds: 240 + topology: + family: clos + spines: 16 + leafs: 128 + clients_per_leaf: 2 + management: + prefix: 23 + subnet_base: 180 + pingmesh: + cross_rack_pairs: 1 + destination_batch_size: 16 + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 4 + cycle_interval_seconds: 3 + traffic: + max_pps_per_client: 50 + runtime: + deploy_timeout_seconds: 3600 + worker_deploy_parallelism: 1 + health_timeout_seconds: 240 + containerlab_max_workers: 16 + purpose: benchmark +- name: fat-tree-k8 + experiment: + recovery_timeout_seconds: 240 + topology: + family: fat-tree + k: 8 + clients_per_edge: 4 + management: + prefix: 24 + subnet_base: 200 + pingmesh: + destination_batch_size: 16 + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 4 + cycle_interval_seconds: 3 + traffic: + max_pps_per_client: 100 + runtime: + deploy_timeout_seconds: 3600 + worker_deploy_parallelism: 1 + health_timeout_seconds: 240 + containerlab_max_workers: 16 + purpose: benchmark +- name: fat-tree-k12 + experiment: + recovery_timeout_seconds: 300 + topology: + family: fat-tree + k: 12 + clients_per_edge: 2 + management: + prefix: 23 + subnet_base: 220 + pingmesh: + destination_batch_size: 32 + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 4 + cycle_interval_seconds: 3 + traffic: + max_pps_per_client: 50 + runtime: + deploy_timeout_seconds: 5400 + worker_deploy_parallelism: 1 + health_timeout_seconds: 300 + containerlab_max_workers: 16 + purpose: benchmark +- name: fat-tree-k18 + experiment: + recovery_timeout_seconds: 600 + topology: + family: fat-tree + k: 18 + clients_per_edge: 2 + management: + prefix: 22 + subnet_base: 224 + pingmesh: + cross_rack_pairs: 1 + destination_batch_size: 32 + rtt_port_pool_size: 16 + rtt_ports_per_cycle: 4 + cycle_interval_seconds: 3 + traffic: + max_pps_per_client: 50 + runtime: + deploy_timeout_seconds: 10800 + worker_deploy_parallelism: 1 + health_timeout_seconds: 600 + containerlab_max_workers: 16 + purpose: benchmark diff --git a/netopsbench/models/scenario.py b/netopsbench/models/scenario.py index 20dc4d7..9d73edf 100644 --- a/netopsbench/models/scenario.py +++ b/netopsbench/models/scenario.py @@ -40,7 +40,7 @@ class ScenarioSpec(BaseModel): scenario_id: str = Field(min_length=1) name: str = Field(min_length=1) description: str = "" - topology_scale: str = Field(default="xs", min_length=1) + topology_scale: str = Field(default="medium", min_length=1) traffic_profile: Literal["standard"] = "standard" episode: EpisodeSpec metadata: dict[str, Any] = Field(default_factory=dict) diff --git a/netopsbench/models/topology.py b/netopsbench/models/topology.py index ecfdfb7..fadd575 100644 --- a/netopsbench/models/topology.py +++ b/netopsbench/models/topology.py @@ -3,12 +3,13 @@ from __future__ import annotations from enum import StrEnum -from math import ceil from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, model_validator -SCHEMA_VERSION: Literal["3"] = "3" +from .pingmesh import PingmeshPlan + +SCHEMA_VERSION: Literal["4"] = "4" DEFAULT_LINK_MTU = 9232 DEFAULT_SONIC_PORT_MTU = 9100 @@ -62,34 +63,13 @@ class Collector(_PersistedModel): class PingmeshPolicy(_PersistedModel): + cross_rack_pairs: int | None = Field(default=None, ge=1) destination_batch_size: int | None = Field(default=None, ge=1) rtt_port_pool_size: int = Field(default=16, ge=1) rtt_ports_per_cycle: int = Field(default=4, ge=1) cycle_interval_seconds: int = Field(default=1, ge=1) df_payload_size: int = Field(default=DEFAULT_SONIC_PORT_MTU - 28, ge=1) - def destination_batch_count(self, client_count: int) -> int: - destinations = max(0, int(client_count) - 1) - batch_size = self.destination_batch_size or max(1, destinations) - return max(1, ceil(destinations / batch_size)) - - def port_batch_count(self) -> int: - return max(1, ceil(self.rtt_port_pool_size / self.rtt_ports_per_cycle)) - - def coverage_epoch_cycles(self, client_count: int) -> int: - return self.destination_batch_count(client_count) * self.port_batch_count() - - def coverage_epoch_seconds(self, client_count: int) -> int: - return self.coverage_epoch_cycles(client_count) * self.cycle_interval_seconds - - def coverage_grace_seconds(self) -> int: - """Return ingestion grace after one complete probe coverage epoch.""" - return max(5, 2 * self.cycle_interval_seconds) - - def complete_window_seconds(self, client_count: int) -> int: - """Return the shortest window that covers one epoch plus ingestion grace.""" - return self.coverage_epoch_seconds(client_count) + self.coverage_grace_seconds() - class TopologyDefaults(_PersistedModel): link_mtu: int = Field(default=DEFAULT_LINK_MTU, gt=0) @@ -122,16 +102,17 @@ class RoutingMetadata(_PersistedModel): edge_asn_range: str | None = None ecmp_hash_policy_by_role: dict[DeviceRole, Literal[0, 1]] ecmp: bool = True - bfd: bool = True + bfd: bool = False class TopologyManifest(_PersistedModel): """Versioned canonical topology, independent from runtime metadata formats.""" - schema_version: Literal["3"] = SCHEMA_VERSION + schema_version: Literal["4"] = SCHEMA_VERSION topology_id: str name: str scale: str + purpose: Literal["benchmark", "validation"] = "benchmark" family: Literal["clos", "fat-tree"] management: Management collector: Collector @@ -142,6 +123,13 @@ class TopologyManifest(_PersistedModel): routing: RoutingMetadata pingmesh: PingmeshPolicy = Field(default_factory=PingmeshPolicy) + pingmesh_plan: PingmeshPlan | None = None + + def require_pingmesh_plan(self) -> PingmeshPlan: + if self.pingmesh_plan is None: + raise ValueError("Missing compiled Pingmesh plan; regenerate topology.json") + return self.pingmesh_plan + @model_validator(mode="after") def _validate_topology_references(self) -> TopologyManifest: names = [device.name for device in self.devices] @@ -243,8 +231,7 @@ def to_agent_topology(self) -> dict[str, Any]: "link_mtu_scope": "containerlab/client link MTU", "sonic_port_mtu_scope": "SONiC front-panel interface MTU", "note": ( - "Do not compare link_mtu 9232 directly against healthy SONiC port MTU 9100 " - "when diagnosing faults." + "Do not compare link_mtu 9232 directly against healthy SONiC port MTU 9100 when diagnosing faults." ), }, "scale": self._agent_scale_facts(), @@ -260,13 +247,7 @@ def to_agent_topology(self) -> dict[str, Any]: ], "routing": self.routing.model_dump(mode="json", exclude_none=True), } - projected["pingmesh"] = { - **self.pingmesh.model_dump(mode="json"), - "destination_batch_count": self.pingmesh.destination_batch_count(self.facts.total_clients), - "port_batch_count": self.pingmesh.port_batch_count(), - "coverage_epoch_cycles": self.pingmesh.coverage_epoch_cycles(self.facts.total_clients), - "coverage_epoch_seconds": self.pingmesh.coverage_epoch_seconds(self.facts.total_clients), - } + projected["pingmesh"] = self.require_pingmesh_plan().summary() if self.family == "fat-tree": projected["fat_tree_k"] = self.facts.fat_tree_k return projected @@ -296,7 +277,14 @@ def _agent_scale_facts(self) -> dict[str, Any]: def _device_to_agent_entry(self, device: Device) -> dict[str, Any]: entry = device.model_dump(exclude={"role", "metadata"}, exclude_none=True, mode="json") - entry.update({key: value for key, value in device.metadata.items() if key not in Device.model_fields}) + entry.update( + { + key: value + for key, value in device.metadata.items() + if key in {"pod", "rack", "client_subnet", "site", "edge_index", "pod_index"} + and isinstance(value, (str, int)) + } + ) if device.role is DeviceRole.CLIENT and device.attached_switch: if self.family == "fat-tree": entry["edge"] = device.attached_switch diff --git a/netopsbench/platform/client_agent/config.py b/netopsbench/platform/client_agent/config.py index bcc9165..e8fc411 100644 --- a/netopsbench/platform/client_agent/config.py +++ b/netopsbench/platform/client_agent/config.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json from pathlib import Path @@ -9,17 +10,17 @@ from netopsbench.platform.utils.files import atomic_write_text CLIENT_AGENT_CONFIG_NAME = "client-agent.json" -CLIENT_AGENT_SCHEMA_VERSION = 1 +CLIENT_AGENT_SCHEMA_VERSION = 2 def build_client_agent_config(manifest: TopologyManifest) -> dict: - """Return an O(N) client description; each client derives its own probes.""" + """Return the shared roster and metadata for immutable per-client plans.""" clients = [] for client in manifest.clients(): if not client.data_ip or not client.mgmt_ip or not client.attached_switch: raise ValueError( - f"Client {client.name} requires data_ip, mgmt_ip, and attached_switch " "for the native client agent" + f"Client {client.name} requires data_ip, mgmt_ip, and attached_switch for the native client agent" ) rack = str(client.metadata.get("rack") or client.attached_switch) clients.append( @@ -32,25 +33,34 @@ def build_client_agent_config(manifest: TopologyManifest) -> dict: } ) - client_count = len(clients) - policy = { - **manifest.pingmesh.model_dump(mode="json"), - "destination_batch_count": manifest.pingmesh.destination_batch_count(client_count), - "port_batch_count": manifest.pingmesh.port_batch_count(), - "coverage_epoch_cycles": manifest.pingmesh.coverage_epoch_cycles(client_count), - "coverage_epoch_seconds": manifest.pingmesh.coverage_epoch_seconds(client_count), - } + plan = manifest.require_pingmesh_plan() return { "schema_version": CLIENT_AGENT_SCHEMA_VERSION, "topology_id": manifest.topology_id, - "pingmesh_policy": policy, + "pingmesh_plan": plan.settings.model_dump(mode="json"), + "client_plan_sha256": { + client.name: hashlib.sha256(_client_plan_bytes(manifest, client)).hexdigest() for client in plan.clients + }, "clients": clients, } +def _client_plan_bytes(manifest, client) -> bytes: + payload = { + "schema_version": CLIENT_AGENT_SCHEMA_VERSION, + "plan_id": manifest.require_pingmesh_plan().settings.plan_id, + **client.model_dump(mode="json"), + } + return (json.dumps(payload, separators=(",", ":")) + "\n").encode() + + def write_client_agent_config(manifest: TopologyManifest, output: str | Path) -> Path: path = Path(output) path.parent.mkdir(parents=True, exist_ok=True) + plans_dir = path.parent / "pinglists" + plans_dir.mkdir(parents=True, exist_ok=True) + for client in manifest.require_pingmesh_plan().clients: + atomic_write_text(plans_dir / f"{client.name}.json", _client_plan_bytes(manifest, client).decode()) atomic_write_text( path, json.dumps(build_client_agent_config(manifest), indent=2) + "\n", diff --git a/netopsbench/platform/client_agent/control.py b/netopsbench/platform/client_agent/control.py index 1ebcc93..103ee3b 100644 --- a/netopsbench/platform/client_agent/control.py +++ b/netopsbench/platform/client_agent/control.py @@ -4,6 +4,7 @@ import json import socket +import time from typing import Any from .contract import CONTROL_PROTOCOL_VERSION @@ -32,11 +33,20 @@ def request_agent( ).encode() + b"\n" ) + deadline = time.monotonic() + timeout + + def remaining(): + seconds = deadline - time.monotonic() + if seconds <= 0: + raise TimeoutError("native client-agent control deadline exceeded") + return seconds + with socket.create_connection((host, port), timeout=timeout) as connection: + connection.settimeout(remaining()) connection.sendall(request) - connection.settimeout(timeout) response = bytearray() while b"\n" not in response: + connection.settimeout(remaining()) chunk = connection.recv(min(4096, MAX_CONTROL_RESPONSE_BYTES + 1 - len(response))) if not chunk: break diff --git a/netopsbench/platform/client_agent/deploy.py b/netopsbench/platform/client_agent/deploy.py index ddce4db..4029970 100644 --- a/netopsbench/platform/client_agent/deploy.py +++ b/netopsbench/platform/client_agent/deploy.py @@ -2,6 +2,8 @@ from __future__ import annotations +import hashlib +import json import shlex import subprocess import time @@ -16,7 +18,7 @@ from netopsbench.platform.utils.files import atomic_write_text from netopsbench.platform.utils.proc import docker_prefix, safe_run -from .config import CLIENT_AGENT_CONFIG_NAME, write_client_agent_config +from .config import CLIENT_AGENT_CONFIG_NAME, build_client_agent_config from .contract import ( HEARTBEAT_MAX_AGE_SECONDS, PINGMESH_CONTROL_PORT, @@ -31,7 +33,6 @@ CLIENT_AGENT_BIND = "configs/client-agent:/etc/netopsbench:ro" CLIENT_AGENT_ENV_NAME = "client-agent.env" CLIENT_AGENT_ENV = f"/etc/netopsbench/{CLIENT_AGENT_ENV_NAME}" -PINGMESH_INGEST_URL = "http://telegraf:8186" DEFAULT_DEPLOY_PARALLELISM = 32 READINESS_TIMEOUT_SECONDS = 15.0 @@ -74,14 +75,13 @@ def _validate_bind(topology_dir: Path, lab_name: str) -> None: linux_kind = ((topology.get("topology") or {}).get("kinds") or {}).get("linux") or {} if CLIENT_AGENT_BIND not in (linux_kind.get("binds") or []): raise RuntimeError( - f"Native client-agent bind missing from {yaml_path}: expected {CLIENT_AGENT_BIND}. " - "Regenerate the topology." + f"Native client-agent bind missing from {yaml_path}: expected {CLIENT_AGENT_BIND}. Regenerate the topology." ) -def _write_agent_env(path: Path, *, token: str, org: str, bucket: str) -> None: +def _write_agent_env(path: Path, *, collector_ip: str, token: str, org: str, bucket: str) -> None: values = { - "NETOPSBENCH_INFLUXDB_URL": PINGMESH_INGEST_URL, + "NETOPSBENCH_INFLUXDB_URL": f"http://{collector_ip}:8186", "NETOPSBENCH_INFLUXDB_TOKEN": token, "NETOPSBENCH_INFLUXDB_ORG": org, "NETOPSBENCH_INFLUXDB_BUCKET": bucket, @@ -170,7 +170,7 @@ def _cleanup_started_clients(containers: list[str], parallelism: int) -> list[st return sorted(failures) -def _wait_until_ready(management_ip: str) -> None: +def _wait_until_ready(management_ip: str, plan_id: str) -> None: deadline = time.monotonic() + READINESS_TIMEOUT_SECONDS last_error = "status endpoint unavailable" while time.monotonic() < deadline: @@ -182,6 +182,8 @@ def _wait_until_ready(management_ip: str) -> None: heartbeat_age = time.time() - heartbeat_ns / 1_000_000_000 if ( pingmesh_status.get("ready") is True + and pingmesh_status.get("plan_id") == plan_id + and pingmesh_status.get("config_schema_version") == 2 and 0 <= heartbeat_age <= HEARTBEAT_MAX_AGE_SECONDS and traffic.get("ok") is True ): @@ -198,21 +200,23 @@ def _start_client( client_name: str, container: str, management_ip: str, + plan_id: str, ) -> tuple[str, bool, str]: command = ( "set -e; " f"test -x {CLIENT_AGENT_BINARY}; " f"test -r {CLIENT_AGENT_CONFIG}; " + f"{CLIENT_AGENT_BINARY} validate-config --config {CLIENT_AGENT_CONFIG}; " f"test -r {CLIENT_AGENT_ENV}; " f". {CLIENT_AGENT_ENV}; " "mkdir -p /run/netopsbench /var/log/netopsbench; " f"{_stop_processes_command(exit_with_status=False)} " '[ "$status" -eq 0 ]; ' f"nohup {CLIENT_AGENT_BINARY} pingmesh --config {CLIENT_AGENT_CONFIG} " - "> /dev/null 2>&1 > /var/log/netopsbench/pingmesh.log 2>&1 /run/netopsbench/pingmesh.pid; ' f"nohup {CLIENT_AGENT_BINARY} traffic --config {CLIENT_AGENT_CONFIG} " - "> /dev/null 2>&1 > /var/log/netopsbench/traffic.log 2>&1 /run/netopsbench/traffic.pid; ' "sleep 0.2; " 'kill -0 "$(cat /run/netopsbench/pingmesh.pid)"; ' @@ -223,7 +227,7 @@ def _start_client( detail = (result.stderr or result.stdout or "").strip() or f"exit status {result.returncode}" return client_name, False, detail try: - _wait_until_ready(management_ip) + _wait_until_ready(management_ip, plan_id) except RuntimeError as exc: return client_name, False, str(exc) return client_name, True, "" @@ -246,9 +250,16 @@ def deploy_client_agents( raise RuntimeError("Every native client-agent requires a management IP") _validate_bind(root, manifest.name) config_path = root / "configs" / "client-agent" / CLIENT_AGENT_CONFIG_NAME - write_client_agent_config(manifest, config_path) + expected = build_client_agent_config(manifest) + if not config_path.is_file() or json.loads(config_path.read_text()) != expected: + raise RuntimeError("Client-agent config is missing or stale; regenerate the topology") + for name, digest in expected["client_plan_sha256"].items(): + plan_path = config_path.parent / "pinglists" / f"{name}.json" + if not plan_path.is_file() or hashlib.sha256(plan_path.read_bytes()).hexdigest() != digest: + raise RuntimeError(f"Client plan {name} is missing or stale; regenerate the topology") _write_agent_env( config_path.parent / CLIENT_AGENT_ENV_NAME, + collector_ip=manifest.collector.ipv4, token=influxdb_token, org=influxdb_org, bucket=influxdb_bucket, @@ -271,6 +282,7 @@ def deploy_client_agents( client_name=client_name, container=container, management_ip=str(client.mgmt_ip), + plan_id=manifest.require_pingmesh_plan().settings.plan_id, ) futures[future] = client_name scheduled_containers.append(container) diff --git a/netopsbench/platform/faults/builtin/acl_specs.py b/netopsbench/platform/faults/builtin/acl_specs.py deleted file mode 100644 index c0bb6de..0000000 --- a/netopsbench/platform/faults/builtin/acl_specs.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Builtin ACL-fault specifications.""" - -from __future__ import annotations - -from ..models import FaultSpec -from .common import episode_param - - -def _inject_acl_misconfig_episode(injector, episode): - return injector.inject_acl_misconfig( - episode.target_device, - episode.target_prefix or episode_param(episode, "target_prefix"), - episode_param(episode, "interface") or getattr(episode, "target_interface", None), - episode_param(episode, "direction", "in"), - ) - - -def _recover_acl_misconfig_fault(injector, fault): - return injector.recover_acl_misconfig( - fault["device"], - fault["target_prefix"], - fault.get("interface"), - fault.get("direction", "in"), - fault.get("acl_name"), - ) - - -def build_acl_fault_specs() -> list[FaultSpec]: - return [ - FaultSpec( - name="acl_misconfig", - aliases=["acl_misconfiguration"], - inject_episode=_inject_acl_misconfig_episode, - recover_active_fault=_recover_acl_misconfig_fault, - ), - ] diff --git a/netopsbench/platform/faults/builtin/catalog_specs.py b/netopsbench/platform/faults/builtin/catalog_specs.py new file mode 100644 index 0000000..cb64568 --- /dev/null +++ b/netopsbench/platform/faults/builtin/catalog_specs.py @@ -0,0 +1,116 @@ +"""Registry adapters for the explicit configuration fault catalog.""" + +from __future__ import annotations + +import ipaddress +from functools import partial + +from ..catalog import FAULT_MECHANISMS +from ..models import FaultSpec + +CONFIGURATION_TYPES = { + "interface_ip_misconfig", + "bgp_process_down", + "routing_loop", + "bgp_as_mismatch", + "bgp_auth_mismatch", + "bgp_update_source_mismatch", + "bgp_neighbor_shutdown", + "bgp_max_prefix_misconfig", + "route_origination_misconfig", + "route_filter_misconfig", + "route_flapping", + "ecmp_misconfig", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", +} +INTERFACE_TYPES = { + "interface_ip_misconfig", + "routing_loop", + "route_flapping", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", +} +PREFIX_TYPES = { + "routing_loop", + "route_origination_misconfig", + "route_filter_misconfig", + "route_flapping", + "ecmp_misconfig", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", +} + + +def validate_parameters(fault_type, episode): + p = episode.parameters or {} + errors = [] + mechanisms = FAULT_MECHANISMS[fault_type] + if len(mechanisms) > 1 and p.get("mechanism") not in mechanisms: + errors.append(f"{fault_type} requires explicit parameters.mechanism in {mechanisms}") + if len(mechanisms) == 1 and "mechanism" in p and p["mechanism"] not in mechanisms: + errors.append(f"{fault_type} does not support mechanism {p['mechanism']!r}") + if "misconfig_kind" in p or "misconfig_kind" in (episode.metadata or {}): + errors.append("misconfig_kind is obsolete; regenerate the scenario") + required = [] + if fault_type.startswith("bgp_") and fault_type != "bgp_process_down": + required.append("peer_ip") + if fault_type == "routing_loop": + required.append("next_hop") + if fault_type in {"route_filter_misconfig", "route_flapping"}: + if not p.get("peer_ips") and not p.get("peer_ip"): + errors.append(f"{fault_type} requires parameters.peer_ip or peer_ips") + for name in required: + if not p.get(name): + errors.append(f"{fault_type} requires parameters.{name}") + for name in ("peer_ip", "next_hop"): + if p.get(name): + try: + ipaddress.IPv4Address(p[name]) + except ValueError: + errors.append(f"Invalid parameters.{name}") + if "peer_ips" in p: + peers = p["peer_ips"] + if not isinstance(peers, list) or not peers: + errors.append("parameters.peer_ips must be a nonempty address list") + else: + for peer in peers: + try: + ipaddress.IPv4Address(peer) + except (ValueError, TypeError): + errors.append("Invalid parameters.peer_ips address") + if fault_type.startswith("acl_") and p.get("direction", "in") not in ("in", "out"): + errors.append("ACL direction must be in or out") + if fault_type == "acl_l4_port_misconfig": + try: + port = int(p.get("destination_port", 33434)) + if not 1 <= port <= 65535: + raise ValueError + except (ValueError, TypeError): + errors.append("destination_port must be in 1..65535") + return errors + + +def inject(injector, episode): + return injector.inject_network_fault(episode) + + +def recover(injector, fault): + return injector.recover_network_fault(fault) + + +def build_catalog_fault_specs(): + return [ + FaultSpec( + name=name, + inject_episode=inject, + recover_active_fault=recover, + requires_interface=name in INTERFACE_TYPES, + requires_prefix=name in PREFIX_TYPES, + episode_validator=partial(validate_parameters, name), + ) + for name in sorted(CONFIGURATION_TYPES) + ] diff --git a/netopsbench/platform/faults/builtin/common.py b/netopsbench/platform/faults/builtin/common.py index be40348..1708916 100644 --- a/netopsbench/platform/faults/builtin/common.py +++ b/netopsbench/platform/faults/builtin/common.py @@ -6,13 +6,7 @@ def episode_param(episode: Any, key: str, default=None): - parameters = getattr(episode, "parameters", None) or {} - if isinstance(parameters, dict) and key in parameters: - return parameters.get(key, default) - metadata = getattr(episode, "metadata", None) or {} - if isinstance(metadata, dict): - return metadata.get(key, default) - return default + return episode.parameters.get(key, default) __all__ = ["episode_param"] diff --git a/netopsbench/platform/faults/builtin/impairment_specs.py b/netopsbench/platform/faults/builtin/impairment_specs.py index 8513d7b..bf7a409 100644 --- a/netopsbench/platform/faults/builtin/impairment_specs.py +++ b/netopsbench/platform/faults/builtin/impairment_specs.py @@ -2,6 +2,8 @@ from __future__ import annotations +from netopsbench.platform.faults.defaults import LATENCY_MS, MTU, PACKET_CORRUPTION_PCT, PACKET_LOSS_PCT + from ..models import FaultSpec from .common import episode_param @@ -10,7 +12,7 @@ def _inject_mtu_mismatch_episode(injector, episode): return injector.inject_mtu_mismatch( episode.target_device, episode.target_interface, - mtu=episode.mtu or 1400, + mtu=episode_param(episode, "mtu", MTU), ) @@ -22,7 +24,7 @@ def _inject_packet_corruption_episode(injector, episode): return injector.inject_packet_corruption( episode.target_device, episode.target_interface or "eth1", - corruption_pct=episode_param(episode, "corruption_pct", 20), + corruption_pct=episode_param(episode, "corruption_pct", PACKET_CORRUPTION_PCT), ) @@ -30,7 +32,7 @@ def _inject_packet_loss_episode(injector, episode): return injector.inject_packet_loss( episode.target_device, episode.target_interface or "eth1", - loss_pct=episode_param(episode, "loss_pct", 30), + loss_pct=episode_param(episode, "loss_pct", PACKET_LOSS_PCT), ) @@ -38,7 +40,7 @@ def _inject_high_latency_episode(injector, episode): return injector.inject_high_latency( episode.target_device, episode.target_interface or "eth1", - latency_ms=episode_param(episode, "latency_ms", 100), + latency_ms=episode_param(episode, "latency_ms", LATENCY_MS), ) diff --git a/netopsbench/platform/faults/builtin/link_specs.py b/netopsbench/platform/faults/builtin/link_specs.py index 9a4fbe6..00f0973 100644 --- a/netopsbench/platform/faults/builtin/link_specs.py +++ b/netopsbench/platform/faults/builtin/link_specs.py @@ -24,9 +24,8 @@ def _inject_link_flapping_episode(injector, episode): return injector.inject_link_flapping( device=episode.target_device, interface=episode.target_interface or "Ethernet0", - iterations=episode_param(episode, "iterations", 10), - down_time=episode_param(episode, "down_time", 2), - up_time=episode_param(episode, "up_time", 3), + down_time=episode_param(episode, "down_time", None), + up_time=episode_param(episode, "up_time", None), ) diff --git a/netopsbench/platform/faults/builtin/routing_specs.py b/netopsbench/platform/faults/builtin/routing_specs.py index 1b29f3d..2e64669 100644 --- a/netopsbench/platform/faults/builtin/routing_specs.py +++ b/netopsbench/platform/faults/builtin/routing_specs.py @@ -33,51 +33,6 @@ def _recover_static_route_misconfig_fault(injector, fault): ) -def _inject_bgp_neighbor_misconfig_episode(injector, episode): - return injector.inject_bgp_neighbor_misconfig( - episode.target_device, - peer_ip=episode_param(episode, "peer_ip"), - misconfig_kind=episode_param(episode, "misconfig_kind", "peer_as_mismatch"), - wrong_remote_as=episode_param(episode, "wrong_remote_as"), - password=episode_param(episode, "password"), - update_source=episode_param(episode, "update_source"), - ) - - -def _recover_bgp_neighbor_misconfig_fault(injector, fault): - return injector.recover_bgp_neighbor_misconfig( - fault["device"], - fault["peer_ip"], - fault.get("misconfig_kind", "peer_as_mismatch"), - original_remote_as=fault.get("original_remote_as"), - original_password=fault.get("original_password"), - original_update_source=fault.get("original_update_source"), - wrong_remote_as=fault.get("wrong_remote_as"), - bad_update_source=fault.get("bad_update_source"), - ) - - -def _inject_route_policy_misconfig_episode(injector, episode): - return injector.inject_route_policy_misconfig( - episode.target_device, - target_prefix=episode.target_prefix or episode_param(episode, "target_prefix"), - misconfig_kind=episode_param(episode, "misconfig_kind", "network_statement_missing"), - route_map=episode_param(episode, "route_map"), - ) - - -def _recover_route_policy_misconfig_fault(injector, fault): - return injector.recover_route_policy_misconfig( - fault["device"], - fault["target_prefix"], - fault.get("misconfig_kind", "network_statement_missing"), - route_map=fault.get("route_map"), - network_statement=fault.get("network_statement"), - prefix_list_name=fault.get("prefix_list_name"), - sequence=fault.get("sequence"), - ) - - def build_routing_fault_specs() -> list[FaultSpec]: return [ FaultSpec( @@ -91,14 +46,4 @@ def build_routing_fault_specs() -> list[FaultSpec]: inject_episode=_inject_static_route_misconfig_episode, recover_active_fault=_recover_static_route_misconfig_fault, ), - FaultSpec( - name="bgp_neighbor_misconfig", - inject_episode=_inject_bgp_neighbor_misconfig_episode, - recover_active_fault=_recover_bgp_neighbor_misconfig_fault, - ), - FaultSpec( - name="route_policy_misconfig", - inject_episode=_inject_route_policy_misconfig_episode, - recover_active_fault=_recover_route_policy_misconfig_fault, - ), ] diff --git a/netopsbench/platform/faults/catalog.py b/netopsbench/platform/faults/catalog.py new file mode 100644 index 0000000..ec45980 --- /dev/null +++ b/netopsbench/platform/faults/catalog.py @@ -0,0 +1,136 @@ +"""Versioned benchmark fault taxonomy and necessary coverage units. + +Mechanisms are execution details; they never extend the diagnosis contract. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +FAULT_CATALOG_VERSION = 2 + +# Each singleton uses the type itself as its injection mechanism. +FAULT_MECHANISMS = { + name: (name,) + for name in ( + "link_down", + "link_flapping", + "interface_ip_misconfig", + "device_down", + "bgp_process_down", + "packet_loss", + "packet_corruption", + "high_latency", + "mtu_mismatch", + "blackhole_route", + "static_route_misconfig", + "routing_loop", + "bgp_as_mismatch", + "bgp_auth_mismatch", + "bgp_update_source_mismatch", + "bgp_neighbor_shutdown", + "bgp_max_prefix_misconfig", + "route_flapping", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", + ) +} +FAULT_MECHANISMS.update( + { + "route_origination_misconfig": ("network_statement_missing", "origination_policy_deny"), + "route_filter_misconfig": ("export_filter", "import_filter"), + "ecmp_misconfig": ("max_paths_limit", "multipath_relax_disabled"), + } +) + + +@dataclass(frozen=True) +class CoverageUnit: + fault_type: str + role: str + position: str | None = None + mechanism: str | None = None + scope: str | None = None + + @property + def id(self) -> str: + return ":".join( + value for value in (self.fault_type, self.mechanism, self.role, self.position, self.scope) if value + ) + + +def coverage_units(family: str, *, validation: bool = False) -> tuple[CoverageUnit, ...]: + """Expand only necessary coverage, independent of the number of switches.""" + if validation: + return ( + CoverageUnit("link_down", "leaf", "leaf-spine"), + CoverageUnit("device_down", "spine"), + CoverageUnit("bgp_auth_mismatch", "leaf", "leaf-spine"), + ) + if family == "clos": + access, roles = "leaf", ("leaf", "spine") + positions = (("leaf", "leaf-client"), ("leaf", "leaf-spine"), ("spine", "spine-leaf")) + elif family == "fat-tree": + access, roles = "edge", ("edge", "agg", "core") + positions = ( + ("edge", "edge-client"), + ("edge", "edge-agg"), + ("agg", "agg-edge"), + ("agg", "agg-core"), + ("core", "core-agg"), + ) + else: + raise ValueError(f"Unsupported coverage family: {family}") + fabric = positions[1:] + units = [] + for fault in ( + "link_down", + "link_flapping", + "interface_ip_misconfig", + "packet_loss", + "packet_corruption", + "high_latency", + "mtu_mismatch", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", + ): + units.extend(CoverageUnit(fault, role, position) for role, position in positions) + for fault in ("device_down", "bgp_process_down"): + units.extend(CoverageUnit(fault, role) for role in roles) + units.extend(CoverageUnit("blackhole_route", access, scope=side) for side in ("source", "destination")) + units.extend(CoverageUnit("blackhole_route", role) for role in roles[1:]) + units.append(CoverageUnit("static_route_misconfig", access)) + for fault in ( + "routing_loop", + "bgp_as_mismatch", + "bgp_auth_mismatch", + "bgp_update_source_mismatch", + "bgp_neighbor_shutdown", + "bgp_max_prefix_misconfig", + "route_flapping", + ): + units.extend(CoverageUnit(fault, role, position) for role, position in fabric) + units.extend( + CoverageUnit("route_origination_misconfig", access, mechanism=mechanism) + for mechanism in FAULT_MECHANISMS["route_origination_misconfig"] + ) + units.extend(CoverageUnit("route_filter_misconfig", role, position, "export_filter") for role, position in fabric) + imports = ((access, "missing"), (access, "reduced"), (roles[-1], "missing")) + if family == "fat-tree": + imports += (("agg", "missing"), ("agg", "reduced_remote_pod")) + units.extend( + CoverageUnit("route_filter_misconfig", role, mechanism="import_filter", scope=scope) for role, scope in imports + ) + units.append(CoverageUnit("ecmp_misconfig", access, mechanism="max_paths_limit")) + if family == "fat-tree": + units.extend( + CoverageUnit("ecmp_misconfig", role, mechanism=mechanism, scope="remote_pod" if role == "agg" else None) + for role, mechanism in ( + ("edge", "multipath_relax_disabled"), + ("agg", "max_paths_limit"), + ("agg", "multipath_relax_disabled"), + ) + ) + return tuple(units) diff --git a/netopsbench/platform/faults/context.py b/netopsbench/platform/faults/context.py index 1309254..2f7997b 100644 --- a/netopsbench/platform/faults/context.py +++ b/netopsbench/platform/faults/context.py @@ -2,10 +2,11 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import Any +from netopsbench.models.profiles import ExperimentProfile, default_experiment_profile from netopsbench.models.topology import TopologyManifest from netopsbench.platform.topology.topology_utils import clab_container_name @@ -16,6 +17,7 @@ class FaultRuntimeContext: manifest: TopologyManifest topology_dir: Path + experiment: ExperimentProfile = field(default_factory=default_experiment_profile) @property def topology_file(self) -> Path: diff --git a/netopsbench/platform/faults/defaults.py b/netopsbench/platform/faults/defaults.py new file mode 100644 index 0000000..53cee2f --- /dev/null +++ b/netopsbench/platform/faults/defaults.py @@ -0,0 +1,13 @@ +"""Canonical defaults shared by fault adapters, handlers and generation.""" + +PACKET_LOSS_PCT = 30.0 +PACKET_CORRUPTION_PCT = 20.0 +LATENCY_MS = 120.0 +MTU = 1400 + +IMPAIRMENT_PARAMETERS = { + "packet_loss": {"loss_pct": PACKET_LOSS_PCT}, + "packet_corruption": {"corruption_pct": PACKET_CORRUPTION_PCT}, + "high_latency": {"latency_ms": LATENCY_MS}, + "mtu_mismatch": {"mtu": MTU}, +} diff --git a/netopsbench/platform/faults/handlers/acl.py b/netopsbench/platform/faults/handlers/acl.py deleted file mode 100644 index f3ce8db..0000000 --- a/netopsbench/platform/faults/handlers/acl.py +++ /dev/null @@ -1,346 +0,0 @@ -"""ACL misconfiguration fault handlers. - -Uses iptables for actual data-plane filtering (SONiC-VS forwards via Linux -kernel, so iptables rules are effective). A parallel SONiC CONFIG_DB -``ACL_TABLE`` / ``ACL_RULE`` entry is also written so that standard SONiC -diagnostic commands (``show acl table``, ``show acl rule``) reveal the -misconfiguration to the diagnosing agent — matching the real-device workflow. -""" - -from __future__ import annotations - -import re -from typing import TYPE_CHECKING, Any - -from netopsbench.logging_utils import get_logger - -logger = get_logger(__name__) - -if TYPE_CHECKING: - from ..context import FaultRuntimeContext - from ..services.command_runner import CommandRunner - from ..services.routing_runtime import RoutingRuntime - from ..services.sonic_runtime import SonicRuntime - from ..services.tracking import FaultTracker - -# iptables comment used to tag injected rules so we can selectively remove them. -_IPTABLES_TAG = "NETOPSBENCH_ACL" - -# Regex to validate prefix format (basic check) -_PREFIX_RE = re.compile(r"^\d{1,3}(\.\d{1,3}){3}/\d{1,2}$") - - -class AclHandler: - """Handles ACL misconfiguration fault injection and recovery. - - Injects both: - * **iptables DROP** rule on the SONiC container – this is the rule that - actually blocks forwarded traffic on the Linux data plane. - * **CONFIG_DB ACL_TABLE / ACL_RULE** – a SONiC-native breadcrumb visible - via ``show acl table`` and ``show acl rule`` so the agent can discover - the misconfiguration using standard SONiC diagnostic commands. - """ - - _ACL_NAME_PREFIX = "NETOPSBENCH_DENY" - - def __init__( - self, - cmd: CommandRunner, - sonic: SonicRuntime, - routing: RoutingRuntime, - tracker: FaultTracker, - ctx: FaultRuntimeContext, - ) -> None: - self._cmd = cmd - self._sonic = sonic - self._routing = routing - self._tracker = tracker - self._ctx = ctx - - # ------------------------------------------------------------------ - # helpers - # ------------------------------------------------------------------ - - def _acl_name(self, device: str, prefix: str) -> str: - safe = prefix.replace("/", "_").replace(".", "-") - return f"{self._ACL_NAME_PREFIX}_{device}_{safe}" - - @staticmethod - def _iptables_rule_args(target_prefix: str, acl_name: str) -> list[str]: - return [ - "FORWARD", - "-d", - target_prefix, - "-j", - "DROP", - "-m", - "comment", - "--comment", - f"{_IPTABLES_TAG}:{acl_name}", - ] - - def _acl_state_present(self, container: str, target_prefix: str, acl_name: str) -> bool: - rule = self._cmd.docker_exec( - container, - ["iptables", "-C", *self._iptables_rule_args(target_prefix, acl_name)], - ) - table = self._cmd.docker_exec( - container, - ["sonic-db-cli", "CONFIG_DB", "exists", f"ACL_TABLE|{acl_name}"], - ) - acl_rule = self._cmd.docker_exec( - container, - ["sonic-db-cli", "CONFIG_DB", "exists", f"ACL_RULE|{acl_name}|RULE_1"], - ) - return rule.returncode == 0 and (table.stdout or "").strip() == "1" and (acl_rule.stdout or "").strip() == "1" - - def _acl_state_absent(self, container: str, target_prefix: str, acl_name: str) -> bool: - rule = self._cmd.docker_exec( - container, - ["iptables", "-C", *self._iptables_rule_args(target_prefix, acl_name)], - ) - table = self._cmd.docker_exec( - container, - ["sonic-db-cli", "CONFIG_DB", "exists", f"ACL_TABLE|{acl_name}"], - ) - acl_rule = self._cmd.docker_exec( - container, - ["sonic-db-cli", "CONFIG_DB", "exists", f"ACL_RULE|{acl_name}|RULE_1"], - ) - return rule.returncode == 1 and (table.stdout or "").strip() == "0" and (acl_rule.stdout or "").strip() == "0" - - @staticmethod - def _validate_prefix(prefix: str) -> str: - if not _PREFIX_RE.match(prefix): - raise ValueError(f"Invalid prefix format: {prefix}") - return prefix - - # ------------------------------------------------------------------ - # inject - # ------------------------------------------------------------------ - - def inject_acl_misconfig( - self, - device: str, - target_prefix: str | None = None, - interface: str | None = None, - direction: str = "in", - ) -> dict[str, Any]: - """Inject an ACL that denies traffic matching *target_prefix*. - - 1. Adds an **iptables FORWARD DROP** rule in the SONiC container so - that forwarded packets to/from *target_prefix* are actually dropped - on the Linux data plane. - 2. Writes matching **CONFIG_DB ACL_TABLE / ACL_RULE** entries so that - ``show acl table`` and ``show acl rule`` reveal the misconfiguration - to the diagnosing agent. - """ - container = self._ctx.container_names.get(device) - if not container: - raise ValueError(f"Unknown device: {device}") - - # Resolve the prefix to deny - if not target_prefix: - network = self._routing.pick_advertised_network(device) - if network: - target_prefix = str(network["prefix"]) - else: - target_prefix = "10.0.0.0/8" - - self._validate_prefix(target_prefix) - - # Resolve interface (for vtysh breadcrumb; iptables rule is global FORWARD) - if not interface: - for link in self._ctx.manifest.links: - for endpoint in link.endpoints: - if endpoint.device == device: - interface = endpoint.interface - break - if interface: - break - # Fallback: query the device for the first Ethernet interface - if not interface: - try: - container_name = self._ctx.container_names.get(device) - if container_name: - result = self._cmd.docker_exec( - container_name, - [ - "vtysh", - "-c", - "show interface brief", - ], - ) - if result.returncode == 0: - for line in result.stdout.splitlines(): - parts = line.split() - if parts and parts[0].startswith("Ethernet"): - interface = parts[0] - break - except Exception: - logger.debug("failed to detect interface on %s for ACL binding", device, exc_info=True) - pass - if not interface: - raise RuntimeError(f"Unable to determine interface for ACL binding: device={device}") - - direction = direction.lower() - if direction not in ("in", "out"): - direction = "in" - - acl_name = self._acl_name(device, target_prefix) - - # --- 1. iptables: actually block forwarded traffic ---------------- - iptables_result = self._cmd.docker_exec( - container, - [ - "iptables", - "-I", - *self._iptables_rule_args(target_prefix, acl_name), - ], - ) - - # --- 2. CONFIG_DB breadcrumb: visible via 'show acl table/rule' --- - if iptables_result.returncode == 0: - stage = "ingress" if direction == "in" else "egress" - self._cmd.docker_exec( - container, - [ - "sonic-db-cli", - "CONFIG_DB", - "hset", - f"ACL_TABLE|{acl_name}", - "policy_desc", - f"netopsbench injected deny {target_prefix}", - "type", - "L3", - "stage", - stage, - "ports@", - interface, - ], - ) - self._cmd.docker_exec( - container, - [ - "sonic-db-cli", - "CONFIG_DB", - "hset", - f"ACL_RULE|{acl_name}|RULE_1", - "PRIORITY", - "999", - "PACKET_ACTION", - "DROP", - "DST_IP", - target_prefix, - ], - ) - - state_present = self._acl_state_present(container, target_prefix, acl_name) - fault_info: dict[str, Any] = { - "type": "acl_misconfig", - "device": device, - "target_prefix": target_prefix, - "interface": interface, - "direction": direction, - "acl_name": acl_name, - "success": state_present, - "error": ( - None - if state_present - else (iptables_result.stderr or iptables_result.stdout or "").strip() - or "ACL data-plane and CONFIG_DB state did not agree" - ), - } - - if state_present: - self._tracker.track(fault_info) - return fault_info - - rollback = self.recover_acl_misconfig( - device, - target_prefix, - interface=interface, - direction=direction, - acl_name=acl_name, - ) - if not rollback["recovered"]: - error = "; ".join( - filter( - None, - [ - str(fault_info.get("error") or ""), - str(rollback.get("error") or "ACL compensation failed"), - ], - ) - ) - fault_info["error"] = error - self._tracker.track_residual(fault_info, error) - return fault_info - - # ------------------------------------------------------------------ - # recover - # ------------------------------------------------------------------ - - def recover_acl_misconfig( - self, - device: str, - target_prefix: str, - interface: str | None = None, - direction: str = "in", - acl_name: str | None = None, - ) -> dict[str, Any]: - """Remove the previously injected ACL deny rule.""" - container = self._ctx.container_names.get(device) - if not container: - raise ValueError(f"Unknown device: {device}") - - acl_name = acl_name or self._acl_name(device, target_prefix) - direction = (direction or "in").lower() - - # --- 1. Remove iptables rule -------------------------------------- - iptables_result = self._cmd.docker_exec( - container, - [ - "iptables", - "-D", - *self._iptables_rule_args(target_prefix, acl_name), - ], - ) - - # --- 2. Remove CONFIG_DB breadcrumb -------------------------------- - self._cmd.docker_exec( - container, - [ - "sonic-db-cli", - "CONFIG_DB", - "del", - f"ACL_RULE|{acl_name}|RULE_1", - ], - ) - self._cmd.docker_exec( - container, - [ - "sonic-db-cli", - "CONFIG_DB", - "del", - f"ACL_TABLE|{acl_name}", - ], - ) - - recovered = self._acl_state_absent(container, target_prefix, acl_name) - if recovered: - self._tracker.remove_faults( - lambda fault: fault["type"] == "acl_misconfig" - and fault["device"] == device - and fault.get("target_prefix") == target_prefix - ) - - return { - "type": "acl_misconfig", - "device": device, - "target_prefix": target_prefix, - "interface": interface, - "acl_name": acl_name, - "recovered": recovered, - "error": None if recovered else iptables_result.stderr or "ACL state remained after recovery", - } diff --git a/netopsbench/platform/faults/handlers/impairment.py b/netopsbench/platform/faults/handlers/impairment.py index 4cb10b7..d6d5f04 100644 --- a/netopsbench/platform/faults/handlers/impairment.py +++ b/netopsbench/platform/faults/handlers/impairment.py @@ -6,6 +6,8 @@ import re from typing import TYPE_CHECKING, Any +from netopsbench.platform.faults.defaults import LATENCY_MS, MTU, PACKET_CORRUPTION_PCT, PACKET_LOSS_PCT + if TYPE_CHECKING: from ..context import FaultRuntimeContext from ..services.command_runner import CommandRunner @@ -52,6 +54,16 @@ def _qdisc_matches( and math.isclose(float(match.group(1)), float(expected_value), rel_tol=0.0, abs_tol=0.001) ) + def _require_default_qdisc(self, container: str, interface: str) -> None: + result = self._cmd.docker_exec(container, ["tc", "-j", "qdisc", "show", "dev", interface]) + import json + + if result.returncode: + raise RuntimeError("Cannot inspect existing qdisc") + rows = json.loads(result.stdout) + if any(row.get("kind") not in {"noqueue", "pfifo_fast", "mq"} for row in rows): + raise RuntimeError("Non-default qdisc exists; refusing to overwrite unowned state") + def _has_netem_qdisc(self, container: str, linux_if: str) -> bool | None: result = self._cmd.docker_exec(container, ["tc", "qdisc", "show", "dev", linux_if]) if result.returncode != 0: @@ -112,7 +124,7 @@ def _apply_mtu( effective_mtu = self._iface.get_interface_mtu(device, sonic_if) return result, effective_mtu - def inject_mtu_mismatch(self, device: str, interface: str, mtu: int = 1400) -> dict[str, Any]: + def inject_mtu_mismatch(self, device: str, interface: str, mtu: int = MTU) -> dict[str, Any]: container = self._ctx.container_names.get(device) if not container: raise ValueError(f"Unknown device: {device}") @@ -181,9 +193,9 @@ def recover_mtu_mismatch( recovered = result.returncode == 0 and effective_mtu == target_mtu if recovered: self._tracker.remove_faults( - lambda fault: fault["type"] == "mtu_mismatch" - and fault["device"] == device - and fault["interface"] == sonic_if + lambda fault: ( + fault["type"] == "mtu_mismatch" and fault["device"] == device and fault["interface"] == sonic_if + ) ) return { @@ -192,6 +204,7 @@ def recover_mtu_mismatch( "interface": sonic_if, "restored_mtu": target_mtu, "recovered": recovered, + "readback_verified": recovered, "error": ( None if recovered else result.stderr or f"effective MTU is {effective_mtu}, expected {target_mtu}" ), @@ -201,13 +214,14 @@ def inject_packet_corruption( self, device: str, interface: str = "Ethernet0", - corruption_pct: float = 20, + corruption_pct: float = PACKET_CORRUPTION_PCT, ) -> dict[str, Any]: container = self._ctx.container_names.get(device) if not container: raise ValueError(f"Unknown device: {device}") linux_if = self._iface.resolve_linux(interface) + self._require_default_qdisc(container, linux_if) result = self._cmd.docker_exec( container, ["tc", "qdisc", "replace", "dev", linux_if, "root", "netem", "corrupt", f"{corruption_pct}%"], @@ -228,13 +242,14 @@ def inject_packet_loss( self, device: str, interface: str = "Ethernet0", - loss_pct: float = 30, + loss_pct: float = PACKET_LOSS_PCT, ) -> dict[str, Any]: container = self._ctx.container_names.get(device) if not container: raise ValueError(f"Unknown device: {device}") linux_if = self._iface.resolve_linux(interface) + self._require_default_qdisc(container, linux_if) result = self._cmd.docker_exec( container, ["tc", "qdisc", "replace", "dev", linux_if, "root", "netem", "loss", f"{loss_pct}%"], @@ -255,13 +270,14 @@ def inject_high_latency( self, device: str, interface: str = "Ethernet0", - latency_ms: float = 100, + latency_ms: float = LATENCY_MS, ) -> dict[str, Any]: container = self._ctx.container_names.get(device) if not container: raise ValueError(f"Unknown device: {device}") linux_if = self._iface.resolve_linux(interface) + self._require_default_qdisc(container, linux_if) result = self._cmd.docker_exec( container, ["tc", "qdisc", "replace", "dev", linux_if, "root", "netem", "delay", f"{latency_ms}ms"], @@ -289,14 +305,17 @@ def recover_tc_rules(self, device: str, interface: str = "Ethernet0") -> dict[st if recovered: self._tracker.remove_faults( - lambda fault: fault["device"] == device - and fault.get("interface") == linux_if - and fault["type"] in ["packet_corruption", "packet_loss", "high_latency"] + lambda fault: ( + fault["device"] == device + and fault.get("interface") == linux_if + and fault["type"] in ["packet_corruption", "packet_loss", "high_latency"] + ) ) return { "device": device, "interface": linux_if, "recovered": recovered, + "readback_verified": recovered, "error": None if recovered else result.stderr or "netem qdisc remained installed", } diff --git a/netopsbench/platform/faults/handlers/link.py b/netopsbench/platform/faults/handlers/link.py index 2167e69..ec53943 100644 --- a/netopsbench/platform/faults/handlers/link.py +++ b/netopsbench/platform/faults/handlers/link.py @@ -3,11 +3,13 @@ from __future__ import annotations import json -import threading import time from typing import TYPE_CHECKING, Any from netopsbench.models.topology import DeviceRole +from netopsbench.platform.utils.control import current_operation_control + +from ..services.periodic import PeriodicController if TYPE_CHECKING: from ..context import FaultRuntimeContext @@ -48,11 +50,20 @@ def _set_link_admin_state( result = self._sonic.config_cmd(device, ["interface", action, sonic_if]) if result.returncode != 0: result = self._cmd.docker_exec(container, ["ip", "link", "set", linux_if, fallback_state]) - state = self._cmd.docker_exec(container, ["ip", "-o", "link", "show", "dev", linux_if]) - flags = "" - if state.returncode == 0 and "<" in (state.stdout or "") and ">" in (state.stdout or ""): - flags = (state.stdout or "").split("<", 1)[1].split(">", 1)[0] - state_matches = state.returncode == 0 and bool(flags) and (("UP" in flags.split(",")) is enabled) + # SONiC updates ConfigDB before the dataplane applies admin_status. + # Verify convergence without submitting reads after the shared budget. + deadline = time.monotonic() + 3 + state, state_matches = result, False + while (remaining := deadline - time.monotonic()) > 0: + state = self._cmd.docker_exec(container, ["ip", "-o", "link", "show", "dev", linux_if], timeout=remaining) + state_matches = time.monotonic() < deadline and self._admin_up(state) is enabled + if state_matches or result.returncode: + break + delay = min(0.1, deadline - time.monotonic()) + if delay <= 0: + break + control = current_operation_control() + control.sleep(delay) if control else time.sleep(delay) success = result.returncode == 0 and state_matches return { "success": success, @@ -64,6 +75,32 @@ def _set_link_admin_state( ), } + @staticmethod + def _admin_up(result) -> bool | None: + output = result.stdout or "" + if result.returncode or "<" not in output or ">" not in output: + return None + flags = output.split("<", 1)[1].split(">", 1)[0] + return "UP" in flags.split(",") if flags else None + + def _healthy_link_state(self, endpoints): + states = [ + { + "device": endpoint[0], + "interface": endpoint[2], + "admin_up": self._admin_up( + self._cmd.docker_exec(endpoint[1], ["ip", "-o", "link", "show", "dev", endpoint[3]]) + ), + } + for endpoint in endpoints + ] + healthy = all(row["admin_up"] is True for row in states) + return { + "original_state": states, + "success": healthy, + "error": None if healthy else "Both link endpoints must be readable and admin up before injection", + } + def _endpoint(self, device: str, interface: str) -> tuple[str, str, str, str]: container = self._ctx.container_names.get(device) if not container: @@ -236,6 +273,9 @@ def inject_link_down(self, device: str, interface: str) -> dict[str, Any]: Injection result with recovery info """ endpoints = self._link_endpoints(device, interface) + initial_state = self._healthy_link_state(endpoints) + if not initial_state["success"]: + return {"type": "link_down", "device": device, "interface": interface, **initial_state} route_snapshots = { f"{endpoint[0]}:{endpoint[3]}": self._snapshot_client_routes(endpoint) for endpoint in endpoints } @@ -257,6 +297,7 @@ def inject_link_down(self, device: str, interface: str) -> dict[str, Any]: "peer_interface": peer[2], "peer_linux_interface": peer[3], "route_snapshots": route_snapshots, + "original_state": initial_state["original_state"], "success": result["success"], "error": result["error"], } @@ -292,9 +333,9 @@ def recover_link_down( if result["success"]: self._tracker.remove_faults( - lambda fault: fault["type"] == "link_down" - and fault["device"] == device - and fault["interface"] == sonic_if + lambda fault: ( + fault["type"] == "link_down" and fault["device"] == device and fault["interface"] == sonic_if + ) ) return { @@ -302,6 +343,7 @@ def recover_link_down( "device": device, "interface": sonic_if, "recovered": result["success"], + "readback_verified": result["success"], "error": result["error"], } @@ -309,19 +351,23 @@ def inject_link_flapping( self, device: str = "spine1", interface: str = "Ethernet0", - iterations: int = 10, - down_time: int = 2, - up_time: int = 3, + down_time: int | None = None, + up_time: int | None = None, ) -> dict[str, Any]: """Inject link flapping using Python orchestration instead of a shell helper.""" + policy = self._ctx.experiment + down_time = policy.flapping_down_seconds if down_time is None else down_time + up_time = policy.flapping_up_seconds if up_time is None else up_time endpoints = self._link_endpoints(device, interface) + initial_state = self._healthy_link_state(endpoints) + if not initial_state["success"]: + return {"type": "link_flapping", "device": device, "interface": interface, **initial_state} route_snapshots = { f"{endpoint[0]}:{endpoint[3]}": self._snapshot_client_routes(endpoint) for endpoint in endpoints } target, peer = endpoints sonic_if = target[2] control_id = f"link-flap:{device}:{sonic_if}:{time.time_ns()}" - stop_event = threading.Event() initial = self._set_physical_link( endpoints, enabled=False, @@ -342,33 +388,18 @@ def inject_link_flapping( ) return fault_info - def _run_flap_loop() -> None: - for index in range(max(int(iterations), 1)): - if stop_event.wait(max(float(down_time), 0.0)): - break - self._set_physical_link( - endpoints, - enabled=True, - route_snapshots=route_snapshots, - ) - if stop_event.wait(max(float(up_time), 0.0)): - break - if index + 1 < max(int(iterations), 1): - self._set_physical_link( - endpoints, - enabled=False, - route_snapshots=route_snapshots, - ) - self._set_physical_link( - endpoints, - enabled=True, - route_snapshots=route_snapshots, - ) - self._tracker.stop_background(control_id, join_timeout=0) + def set_state(enabled): + state = self._set_physical_link(endpoints, enabled=enabled, route_snapshots=route_snapshots) + if not state["success"]: + raise RuntimeError(state["error"]) - thread = threading.Thread(target=_run_flap_loop, name=f"{control_id}-worker", daemon=True) - self._tracker.register_background_control(control_id, stop_event=stop_event, thread=thread) - thread.start() + controller = PeriodicController( + lambda: set_state(False), lambda: set_state(True), down_time=down_time, up_time=up_time + ) + self._tracker.register_background_control( + control_id, stop_event=controller.stop_event, thread=controller.thread, controller=controller + ) + controller.thread.start() fault_info = { "type": "link_flapping", @@ -379,11 +410,11 @@ def _run_flap_loop() -> None: "peer_interface": peer[2], "peer_linux_interface": peer[3], "route_snapshots": route_snapshots, - "iterations": iterations, "down_time": down_time, "up_time": up_time, "task_id": control_id, "orchestration": "python", + "original_state": initial_state["original_state"], "success": True, } @@ -401,7 +432,15 @@ def recover_link_flapping( route_snapshots: dict[str, list[dict[str, Any]]] | None = None, ) -> dict[str, Any]: """Stop link flapping and verify that both physical endpoints recover.""" - stopped = self._tracker.stop_background(task_id, join_timeout=5.0) if task_id else True + stopped = self._tracker.stop_background(task_id, join_timeout=65.0) if task_id else True + if not stopped: + return { + "type": "link_flapping", + "device": device, + "interface": interface, + "recovered": False, + "error": "Periodic controller still running", + } target, discovered_peer = self._link_endpoints(device, interface) peer = self._endpoint(peer_device, peer_interface) if peer_device and peer_interface else discovered_peer result = self._set_physical_link( @@ -412,9 +451,9 @@ def recover_link_flapping( recovered = stopped and result["success"] if recovered: self._tracker.remove_faults( - lambda fault: fault["type"] == "link_flapping" - and fault["device"] == device - and fault["interface"] == target[2] + lambda fault: ( + fault["type"] == "link_flapping" and fault["device"] == device and fault["interface"] == target[2] + ) ) error = result["error"] if not stopped: @@ -424,5 +463,6 @@ def recover_link_flapping( "device": device, "interface": target[2], "recovered": recovered, + "readback_verified": recovered, "error": error, } diff --git a/netopsbench/platform/faults/handlers/network.py b/netopsbench/platform/faults/handlers/network.py new file mode 100644 index 0000000..592c010 --- /dev/null +++ b/netopsbench/platform/faults/handlers/network.py @@ -0,0 +1,593 @@ +"""Scoped configuration faults with an undo journal and independent policies. + +All preconditions are read before mutation. Every attempted write is journaled +before execution, so partial CLI failures still participate in compensation. +""" + +from __future__ import annotations + +import ipaddress +import json +import re +import uuid +from pathlib import Path + +from ..services.periodic import PeriodicController + +_BGPD_RESTORE_SOURCE = (Path(__file__).parent.parent / "services" / "_bgpd_restore.py").read_text(encoding="utf-8") + + +class NetworkFaultHandler: + def __init__(self, cmd, sonic, iface, routing, tracker, ctx): + self.cmd, self.sonic, self.iface = cmd, sonic, iface + self.routing, self.tracker, self.ctx = routing, tracker, ctx + + def _run(self, device, kind, commands): + if kind == "frr": + result = self.sonic.vtysh(device, commands) + else: + result = self.cmd.docker_exec(self.ctx.container_names[device], commands) + service_status = commands[:2] == ["supervisorctl", "status"] and result.returncode == 3 + if (result.returncode and not service_status) or (kind == "frr" and re.search(r"(?m)^%", result.stdout or "")): + raise RuntimeError(result.stderr or result.stdout or f"{kind} command failed") + return result.stdout or "" + + def _json(self, device, commands): + return json.loads(self._run(device, "docker", commands)) + + def _frr_json(self, device, command): + return json.loads(self._run(device, "frr", [command])) + + @staticmethod + def _config(commands): + return ["configure terminal", *commands, "end", "write memory"] + + def _operation(self, kind, apply, restore): + return {"kind": kind, "apply": apply, "restore": restore} + + def _frr_operation(self, apply, restore): + return self._operation("frr", self._config(apply), self._config(restore)) + + def _neighbor(self, device, peer): + neighbor = self.routing.pick_bgp_neighbor(device, peer_ip=peer) + if not neighbor or not self.sonic.bgp_neighbor_state(device, peer): + raise RuntimeError(f"Target neighbor is not readable and established: {device}/{peer}") + return neighbor + + def _prefix_policy(self, device, prefix, peers, direction, *, network=None): + config = self._run(device, "frr", ["show running-config"]) + # Preserve other policy terms by cloning an existing attachment, placing + # the exact-prefix deny before them. Never modify the shared original. + token = "P" + uuid.uuid4().hex[:12].upper() + operations = [] + attachments = [(peer, None) for peer in peers] if network is None else [(None, network)] + snapshot = self.routing.get_bgp_config_snapshot(device) + asn = self.routing.get_device_asn(device) + for index, (peer, origin) in enumerate(attachments): + route_map = f"{token}{index}" + prefix_list = route_map + "L" + if origin is not None: + original = origin.get("route_map") + else: + neighbor = next(n for n in snapshot["neighbors"] if n["peer_ip"] == peer) + original = next((a["name"] for a in neighbor["route_maps"] if a["direction"] == direction), None) + cloned = [] + if original: + blocks = re.findall( + rf"(?m)^route-map {re.escape(original)} (?:permit|deny) \d+\n(?:(?: .*)?\n)*", config + "\n" + ) + if not blocks: + raise RuntimeError(f"Cannot snapshot attached policy {original}") + for block in blocks: + lines = block.rstrip().splitlines() + head = lines[0].split() + sequence = int(head[-1]) + if sequence <= 1: + raise RuntimeError("No safe sequence before the existing route-map") + cloned.extend([lines[0].replace(original, route_map, 1), *[line.strip() for line in lines[1:]]]) + else: + cloned = [f"route-map {route_map} permit 100"] + apply = [ + f"ip prefix-list {prefix_list} seq 5 permit {prefix}", + f"route-map {route_map} deny 1", + f"match ip address prefix-list {prefix_list}", + *cloned, + f"router bgp {asn}", + "address-family ipv4 unicast", + ] + restore = [f"router bgp {asn}", "address-family ipv4 unicast"] + if origin is not None: + statement = self.routing.format_network_statement(prefix, original) + apply += [f"no {statement}", f"network {prefix} route-map {route_map}"] + restore += [f"no network {prefix} route-map {route_map}", statement] + else: + apply += [f"neighbor {peer} route-map {route_map} {direction}"] + restore += [ + ( + f"neighbor {peer} route-map {original} {direction}" + if original + else f"no neighbor {peer} route-map {route_map} {direction}" + ) + ] + restore += ["exit-address-family", "exit", f"no route-map {route_map}", f"no ip prefix-list {prefix_list}"] + operation = self._frr_operation(apply, restore) + if peer is not None: + refresh = f"clear bgp ipv4 unicast {peer} soft {direction}" + operation["apply"].append(refresh) + operation["restore"].append(refresh) + operations.append(operation) + return operations + + def _prepare(self, episode): + device, fault, p = episode.target_device, episode.fault_type, dict(episode.parameters) + prefix = episode.target_prefix + container = self.ctx.container_names[device] + asn = self.routing.get_device_asn(device) + config = ( + self._run(device, "frr", ["show running-config"]) + if fault + not in { + "interface_ip_misconfig", + "bgp_process_down", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", + } + else "" + ) + evidence = {} + if fault.startswith("bgp_") and fault != "bgp_process_down": + peer = str(ipaddress.ip_address(p["peer_ip"])) + neighbor = self._neighbor(device, peer) + keyword, value = { + "bgp_as_mismatch": ("remote-as", str(int(neighbor["remote_as"]) + 1000)), + "bgp_auth_mismatch": ("password", uuid.uuid4().hex), + "bgp_update_source_mismatch": ("update-source", p.get("fault_update_source", "Loopback999")), + "bgp_neighbor_shutdown": ("shutdown", ""), + "bgp_max_prefix_misconfig": ("maximum-prefix", ""), + }[fault] + original = re.search(rf"(?m)^\s*neighbor {re.escape(peer)} {keyword}(?: (.*))?$", config) + if fault == "bgp_update_source_mismatch": + # FRR permits a passive connection despite an incorrect source + # IP. An absent source interface also makes incoming next-hop + # validation fail, while changing only this neighbor's option. + if not isinstance(value, str) or not re.fullmatch(r"Loopback[0-9]{1,4}", value): + raise ValueError("Invalid update-source interface") + links = self._json(device, ["ip", "-j", "link", "show"]) + if any(link["ifname"] == value for link in links): + raise RuntimeError("Reserved wrong update-source interface already exists") + evidence["fault_update_source"] = value + if fault == "bgp_max_prefix_misconfig": + detail = self._frr_json(device, f"show ip bgp neighbors {peer} json").get(peer, {}) + received = int( + detail.get("addressFamilyInfo", {}).get("ipv4Unicast", {}).get("acceptedPrefixCounter", 0) + ) + if received < 2: + raise RuntimeError("maximum-prefix requires at least two healthy received prefixes") + value = str(received - 1) + evidence["healthy_prefix_count"] = received + stem = f"neighbor {peer} {keyword}" + apply = [f"router bgp {asn}"] + restore = [f"router bgp {asn}"] + if keyword == "maximum-prefix": + apply += ["address-family ipv4 unicast"] + restore += ["address-family ipv4 unicast"] + apply.append(f"{stem} {value}".rstrip()) + restore.append(original.group(0).strip() if original else f"no {stem}") + operation = self._frr_operation(apply, restore) + if keyword == "maximum-prefix": + operation["apply"].append(f"clear bgp ipv4 unicast {peer} soft in") + operation["restore"].append(f"clear bgp ipv4 unicast {peer}") + return [operation], evidence + if fault == "bgp_process_down": + status = self._run(device, "docker", ["supervisorctl", "status", "bgpd"]) + if "RUNNING" not in status: + raise RuntimeError("bgpd must be running before injection") + config = self._run(device, "docker", ["vtysh", "-d", "bgpd", "-c", "show running-config"]) + _, marker, original = config.partition("Current configuration:\n") + if not marker or not re.search(r"(?m)^router bgp \d+", original): + raise RuntimeError("Cannot capture the running bgpd configuration before stopping it") + evidence.update(original_service=status.strip(), original_bgp_config=original) + return [ + self._operation( + "docker", + ["supervisorctl", "stop", "bgpd"], + ["python3", "-c", _BGPD_RESTORE_SOURCE, original], + ) + ], evidence + if fault == "interface_ip_misconfig": + interface = self.iface.resolve_sonic(episode.target_interface) + addresses = self._json(device, ["ip", "-j", "-4", "addr", "show", "dev", interface]) + original = [ + f"{a['local']}/{a['prefixlen']}" + for a in addresses[0].get("addr_info", []) + if a.get("scope") == "global" + ] + if len(original) != 1 or "UP" not in addresses[0].get("flags", []): + raise RuntimeError("Address fault requires one address on an admin-up data interface") + configured = self._run( + device, "docker", ["sonic-db-cli", "CONFIG_DB", "exists", f"INTERFACE|{interface}|{original[0]}"] + ) + if configured.strip() != "1": + raise RuntimeError("SONiC and live interface addresses disagree") + wrong = ipaddress.ip_interface(p.get("fault_address", "198.51.100.1/30")) + networks = [ipaddress.ip_network(self.ctx.manifest.management.ipv4_subnet)] + networks += [ipaddress.ip_network(c.data_ip + "/30", strict=False) for c in self.ctx.manifest.clients()] + for switch in self.ctx.manifest.switches(): + config_path = self.ctx.topology_dir / "configs" / "sonic" / switch.name / "config_db.json" + config_db = json.loads(config_path.read_text()) + networks += [ + ipaddress.ip_network(key.split("|", 1)[1], strict=False) + for key in config_db["INTERFACE"] + if "|" in key + ] + if wrong.ip not in ipaddress.ip_network("198.51.100.0/24") or any( + wrong.network.overlaps(net) for net in networks + ): + raise ValueError("Fault address must use the reserved, non-overlapping pool") + operations = [ + # Keep the routed interface present throughout replacement. + # The last-address removal path also shells out through sudo, + # which the pinned root-only SONiC image does not provide. + self._operation( + "docker", + ["config", "interface", "ip", "add", interface, str(wrong)], + ["config", "interface", "ip", "remove", interface, str(wrong)], + ), + self._operation( + "docker", + ["config", "interface", "ip", "remove", interface, original[0]], + ["config", "interface", "ip", "add", interface, original[0]], + ), + ] + evidence.update(original_address=original[0], fault_address=str(wrong)) + return operations, evidence + if fault in {"route_origination_misconfig", "route_filter_misconfig", "route_flapping"}: + mechanism = p.get("mechanism") + if fault == "route_origination_misconfig": + network = self.routing.pick_advertised_network(device, prefix) + if not network: + raise RuntimeError("Prefix is not originated on the root device") + if mechanism == "network_statement_missing": + statement = self.routing.format_network_statement(prefix, network.get("route_map")) + return [ + self._frr_operation( + [f"router bgp {asn}", "address-family ipv4 unicast", f"no {statement}"], + [f"router bgp {asn}", "address-family ipv4 unicast", statement], + ) + ], evidence + return self._prefix_policy(device, prefix, [], "out", network=network), evidence + peers = p.get("peer_ips", [p.get("peer_ip")]) + if not peers or any(not peer for peer in peers): + raise ValueError("Prefix filter requires explicit peers") + peers = [str(ipaddress.ip_address(peer)) for peer in peers] + for peer in peers: + self._neighbor(device, peer) + direction = "in" if mechanism == "import_filter" else "out" + return self._prefix_policy(device, prefix, peers, direction), evidence + if fault == "ecmp_misconfig": + routes = self._json(device, ["ip", "-j", "-4", "route", "show", "exact", prefix]) + hops = [hop for route in routes for hop in route.get("nexthops", [])] + if len(hops) < 2: + raise RuntimeError("ECMP requires multiple actual kernel FIB next hops") + evidence["healthy_fib"] = routes + rib = self._frr_json(device, f"show bgp ipv4 unicast {prefix} json") + evidence["healthy_bgp"] = rib + mechanism = p["mechanism"] + if mechanism == "multipath_relax_disabled": + gateways = {hop.get("gateway") for hop in hops if hop.get("gateway")} + as_paths = set() + for path in rib.get("paths", []): + if not path.get("valid") or not (path.get("multipath") or path.get("bestpath", {}).get("overall")): + continue + if not any( + hop.get("accessible") and hop.get("used") and hop.get("ip") in gateways + for hop in path.get("nexthops", []) + ): + continue + as_path = path.get("aspath", {}).get("string") + if isinstance(as_path, str) and as_path.strip(): + as_paths.add(tuple(as_path.split())) + if len(as_paths) < 2: + raise RuntimeError("multipath-relax requires distinct valid AS_PATHs") + if "bgp bestpath as-path multipath-relax" not in config: + raise RuntimeError("multipath-relax is already disabled") + return [ + self._frr_operation( + [f"router bgp {asn}", "no bgp bestpath as-path multipath-relax"], + [f"router bgp {asn}", "bgp bestpath as-path multipath-relax"], + ) + ], evidence + original = re.search(r"(?m)^\s*maximum-paths (\d+)\s*$", config) + apply = [f"router bgp {asn}", "address-family ipv4 unicast", "maximum-paths 1"] + restore = [ + f"router bgp {asn}", + "address-family ipv4 unicast", + original.group(0).strip() if original else "no maximum-paths 1", + ] + return [self._frr_operation(apply, restore)], evidence + if fault == "routing_loop": + nexthop = str(ipaddress.ip_address(p["next_hop"])) + self._neighbor(device, nexthop) + if any(line.strip().startswith(f"ip route {prefix} ") for line in config.splitlines()): + raise RuntimeError("Target static route already exists; refusing to overwrite it") + statement = f"ip route {prefix} {nexthop}" + return [self._frr_operation([statement], [f"no {statement}"])], evidence + if fault.startswith("acl_"): + interface = self.iface.resolve_sonic(episode.target_interface) + direction = p.get("direction", "in") + linux = self.iface.resolve_linux(interface) + # SONiC virtual dataplane interfaces use Ethernet names after startup. + live = self.cmd.docker_exec(container, ["ip", "link", "show", "dev", interface]) + if live.returncode == 0: + linux = interface + name = "P" + uuid.uuid4().hex[:12].upper() + match = { + "acl_source_misconfig": ["-s", p.get("source_prefix", prefix)], + "acl_destination_misconfig": ["-d", prefix], + "acl_l4_port_misconfig": ["-p", "udp", "--dport", str(p.get("destination_port", 33434))], + }[fault] + rule = [ + "FORWARD", + "-i" if direction == "in" else "-o", + linux, + *match, + "-m", + "comment", + "--comment", + name, + "-j", + "DROP", + ] + table = f"ACL_TABLE|{name}" + key = f"ACL_RULE|{name}|RULE1" + fields = {"PRIORITY": "999", "PACKET_ACTION": "DROP"} + if fault == "acl_source_misconfig": + fields["SRC_IP"] = match[1] + elif fault == "acl_destination_misconfig": + fields["DST_IP"] = prefix + else: + fields.update(IP_PROTOCOL="17", L4_DST_PORT=match[-1]) + operations = [ + self._operation( + "docker", + [ + "sonic-db-cli", + "CONFIG_DB", + "hset", + table, + "type", + "L3", + "ports@", + interface, + "stage", + "INGRESS" if direction == "in" else "EGRESS", + "policy_desc", + name, + ], + ["sonic-db-cli", "CONFIG_DB", "del", table], + ), + self._operation( + "docker", + ["sonic-db-cli", "CONFIG_DB", "hset", key, *[value for pair in fields.items() for value in pair]], + ["sonic-db-cli", "CONFIG_DB", "del", key], + ), + self._operation("docker", ["iptables", "-I", *rule], ["iptables", "-D", *rule]), + ] + evidence.update(acl_name=name, rule=rule, fields=fields, direction=direction, interface=interface) + return operations, evidence + raise ValueError(f"No scoped handler for {fault}") + + def _verify_written(self, episode, info): + device, fault = episode.target_device, episode.fault_type + if fault == "bgp_process_down": + if "STOPPED" not in self._run(device, "docker", ["supervisorctl", "status", "bgpd"]): + raise RuntimeError("Supervisor did not stop bgpd") + return + if fault == "interface_ip_misconfig": + interface = self.iface.resolve_sonic(episode.target_interface) + rows = self._json(device, ["ip", "-j", "-4", "addr", "show", "dev", interface]) + addresses = {f"{a['local']}/{a['prefixlen']}" for row in rows for a in row.get("addr_info", [])} + if info["evidence"]["fault_address"] not in addresses or info["evidence"]["original_address"] in addresses: + raise RuntimeError("Live address readback disagrees with the injected configuration") + if "UP" not in rows[0].get("flags", []): + raise RuntimeError("Address mutation changed admin state") + return + if fault.startswith("acl_"): + evidence = info["evidence"] + self._run(device, "docker", ["iptables", "-C", *evidence["rule"]]) + for key in (f"ACL_TABLE|{evidence['acl_name']}", f"ACL_RULE|{evidence['acl_name']}|RULE1"): + if self._run(device, "docker", ["sonic-db-cli", "CONFIG_DB", "exists", key]).strip() != "1": + raise RuntimeError("ACL ConfigDB readback is missing") + return + config = {" ".join(line.split()) for line in self._run(device, "frr", ["show running-config"]).splitlines()} + contexts = ("router bgp ", "address-family ", "match ", "set ") + for operation in info["journal"]: + for command in operation["apply"]: + if command in {"configure terminal", "end", "write memory"} or command.startswith( + (*contexts, "clear ") + ): + continue + normalized = " ".join(command.split()) + if command.startswith("no "): + if normalized[3:] in config: + raise RuntimeError(f"Configuration remained present: {normalized[3:]}") + elif normalized not in config: + raise RuntimeError(f"Configuration readback is missing: {normalized}") + + def inject(self, episode): + info = { + "fault_id": uuid.uuid4().hex, + "type": episode.fault_type, + "device": episode.target_device, + "interface": episode.target_interface, + "prefix": episode.target_prefix, + "mechanism": episode.parameters.get("mechanism", episode.fault_type), + "success": False, + "error": None, + "journal": [], + } + try: + operations, evidence = self._prepare(episode) + info["evidence"] = evidence + if any(operation["kind"] == "frr" for operation in operations): + from netopsbench.platform.scenario.baseline import normalized_frr + + evidence["original_frr_digest"] = normalized_frr( + self._run(info["device"], "frr", ["show running-config"]) + ) + if episode.fault_type.startswith("acl_"): + evidence["original_iptables"] = self._run(info["device"], "docker", ["iptables", "-S"]) + for key in (f"ACL_TABLE|{evidence['acl_name']}", f"ACL_RULE|{evidence['acl_name']}|RULE1"): + if self._run(info["device"], "docker", ["sonic-db-cli", "CONFIG_DB", "exists", key]).strip() != "0": + raise RuntimeError("Cannot own an existing ACL object") + for operation in operations: + info["journal"].append(operation) + self._run(info["device"], operation["kind"], operation["apply"]) + self._verify_written(episode, info) + if episode.fault_type == "route_flapping": + + def apply(): + for operation in operations: + self._run(info["device"], operation["kind"], operation["apply"]) + + def restore(): + for operation in reversed(operations): + self._run(info["device"], operation["kind"], operation["restore"]) + + controller = PeriodicController( + apply, + restore, + down_time=episode.parameters.get("down_time", self.ctx.experiment.flapping_down_seconds), + up_time=episode.parameters.get("up_time", self.ctx.experiment.flapping_up_seconds), + ) + # Already in the first fault phase; start the waiting loop only. + control_id = uuid.uuid4().hex + self.tracker.register_background_control( + control_id, stop_event=controller.stop_event, thread=controller.thread, controller=controller + ) + controller.thread.start() + info["control_id"] = control_id + info["success"] = True + self.tracker.track(info) + except Exception as exc: + info["error"] = str(exc) + recovery = self.recover(info) + if not recovery["recovered"]: + info["error"] += "; compensation: " + str(recovery["error"]) + self.tracker.track_residual(info, info["error"]) + return info + + def _verify_restored(self, fault): + """Read actual owned resources after undo; never infer success from exit code.""" + from netopsbench.platform.scenario.baseline import normalized_frr + + device, evidence = fault["device"], fault.get("evidence", {}) + if evidence.get("original_frr_digest"): + if normalized_frr(self._run(device, "frr", ["show running-config"])) != evidence["original_frr_digest"]: + raise RuntimeError("FRR configuration was not restored") + return True + if "original_bgp_config" in evidence: + if "RUNNING" not in self._run(device, "docker", ["supervisorctl", "status", "bgpd"]): + raise RuntimeError("bgpd is not running") + current = self._run(device, "docker", ["vtysh", "-d", "bgpd", "-c", "show running-config"]) + if normalized_frr(current) != normalized_frr(evidence["original_bgp_config"]): + raise RuntimeError("bgpd configuration was not restored") + return True + if "original_address" in evidence: + interface = self.iface.resolve_sonic(fault["interface"]) + rows = self._json(device, ["ip", "-j", "-4", "addr", "show", "dev", interface]) + actual = { + f"{a['local']}/{a['prefixlen']}" + for row in rows + for a in row.get("addr_info", []) + if a.get("scope") == "global" + } + if actual != {evidence["original_address"]}: + raise RuntimeError("Interface addresses were not restored") + for address, wanted in [(evidence["original_address"], "1"), (evidence["fault_address"], "0")]: + key = f"INTERFACE|{interface}|{address}" + if self._run(device, "docker", ["sonic-db-cli", "CONFIG_DB", "exists", key]).strip() != wanted: + raise RuntimeError("Interface CONFIG_DB was not restored") + return True + if "original_iptables" in evidence: + if self._run(device, "docker", ["iptables", "-S"]) != evidence["original_iptables"]: + raise RuntimeError("Actual ACL rules were not restored") + for key in (f"ACL_TABLE|{evidence['acl_name']}", f"ACL_RULE|{evidence['acl_name']}|RULE1"): + if self._run(device, "docker", ["sonic-db-cli", "CONFIG_DB", "exists", key]).strip() != "0": + raise RuntimeError("Owned ACL configuration remains") + return True + return False # Historical/custom records have no independently captured readback evidence. + + def recover(self, fault): + errors = [] + control = fault.get("control_id") + if control and not self.tracker.stop_background(control, join_timeout=65): + return {"type": fault["type"], "recovered": False, "error": "Periodic controller still running"} + for operation in reversed(fault.get("journal", [])): + try: + # iptables -C distinguishes an already absent owned rule from + # permission/tool failures; missing objects are idempotent. + commands = operation["restore"] + if operation["kind"] == "frr": + current = { + " ".join(line.split()) + for line in self._run(fault["device"], "frr", ["show running-config"]).splitlines() + } + + def present(statement, current=current): + parameter_stem = statement.startswith("neighbor ") and statement.split()[-1] in { + "password", + "remote-as", + "update-source", + "maximum-prefix", + } + if parameter_stem or statement.startswith(("route-map ", "ip prefix-list ")): + return any(line == statement or line.startswith(statement + " ") for line in current) + return statement in current + + commands = [ + command + for command in commands + if not command.startswith("no ") or present(" ".join(command[3:].split())) + ] + if commands[:4] == ["config", "interface", "ip", "remove"]: + interface, address = commands[4:] + live = self._json(fault["device"], ["ip", "-j", "-4", "addr", "show", "dev", interface]) + addresses = {f"{a['local']}/{a['prefixlen']}" for row in live for a in row.get("addr_info", [])} + key = f"INTERFACE|{interface}|{address}" + configured = self._run( + fault["device"], "docker", ["sonic-db-cli", "CONFIG_DB", "exists", key] + ).strip() + if configured == "0" and address not in addresses: + continue + if configured not in {"0", "1"}: + raise RuntimeError("Cannot read owned interface address state") + if commands[:2] == ["iptables", "-D"]: + check = self.cmd.docker_exec( + self.ctx.container_names[fault["device"]], ["iptables", "-C", *commands[2:]] + ) + if check.returncode == 1: + continue + if check.returncode: + raise RuntimeError(check.stderr or "ACL presence check failed") + self._run(fault["device"], operation["kind"], commands) + except Exception as exc: + errors.append(str(exc)) + verified = False + if not errors and fault.get("journal"): + try: + verified = self._verify_restored(fault) + except Exception as exc: + errors.append(str(exc)) + if not errors: + owner = fault.get("fault_id") + if owner: + self.tracker.remove_faults(lambda f: f.get("fault_id") == owner) + return { + "type": fault["type"], + "device": fault["device"], + "recovered": not errors, + "readback_verified": verified and not errors, + "error": "; ".join(errors) if errors else None, + } diff --git a/netopsbench/platform/faults/handlers/routing_bgp.py b/netopsbench/platform/faults/handlers/routing_bgp.py deleted file mode 100644 index 4625227..0000000 --- a/netopsbench/platform/faults/handlers/routing_bgp.py +++ /dev/null @@ -1,197 +0,0 @@ -"""BGP neighbor routing fault handlers.""" - -from __future__ import annotations - -import time -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from ..context import FaultRuntimeContext - from ..services.routing_runtime import RoutingRuntime - from ..services.sonic_runtime import SonicRuntime - from ..services.tracking import FaultTracker - - -class BgpHandler: - """Handles BGP neighbor misconfiguration fault injection and recovery.""" - - def __init__( - self, - sonic: SonicRuntime, - routing: RoutingRuntime, - tracker: FaultTracker, - ctx: FaultRuntimeContext, - ) -> None: - self._sonic = sonic - self._routing = routing - self._tracker = tracker - self._ctx = ctx - - def inject_bgp_neighbor_misconfig( - self, - device: str, - peer_ip: str | None = None, - misconfig_kind: str = "peer_as_mismatch", - wrong_remote_as: int | None = None, - password: str | None = None, - update_source: str | None = None, - ) -> dict[str, Any]: - """Inject a realistic BGP neighbor configuration error on one device.""" - container = self._ctx.container_names.get(device) - if not container: - raise ValueError(f"Unknown device: {device}") - - misconfig_kind = self._routing.normalize_bgp_neighbor_kind(misconfig_kind) - neighbor = self._routing.pick_bgp_neighbor(device, peer_ip=peer_ip) - if not neighbor: - raise RuntimeError( - f"Unable to determine target BGP neighbor from device config: device={device} peer_ip={peer_ip}" - ) - - peer_ip = str(neighbor["peer_ip"]) - local_as = neighbor.get("local_as") or self._routing.get_device_asn(device) - if local_as is None: - raise RuntimeError(f"Unable to determine local BGP ASN for target device: device={device}") - - commands = ["configure terminal", f"router bgp {local_as}"] - fault_info: dict[str, Any] = { - "type": "bgp_neighbor_misconfig", - "device": device, - "peer_ip": peer_ip, - "local_as": int(local_as), - "misconfig_kind": misconfig_kind, - "success": False, - "error": None, - } - - if misconfig_kind == "peer_as_mismatch": - original_remote_as = neighbor.get("remote_as") - if original_remote_as is None: - fault_info["error"] = "Unable to determine original remote-as for neighbor" - return fault_info - wrong_as = int(wrong_remote_as or (int(original_remote_as) + 1000)) - if wrong_as == int(original_remote_as): - wrong_as += 1000 - commands.append(f"neighbor {peer_ip} remote-as {wrong_as}") - fault_info["original_remote_as"] = int(original_remote_as) - fault_info["wrong_remote_as"] = wrong_as - elif misconfig_kind == "password_mismatch": - bad_password = str(password or f"netopsbench-{int(time.time())}") - commands.append(f"neighbor {peer_ip} password {bad_password}") - fault_info["original_password"] = neighbor.get("password") - fault_info["bad_password"] = bad_password - elif misconfig_kind == "update_source_mismatch": - bad_update_source = str(update_source or "Loopback0") - commands.append(f"neighbor {peer_ip} update-source {bad_update_source}") - fault_info["original_update_source"] = neighbor.get("update_source") - fault_info["bad_update_source"] = bad_update_source - else: - fault_info["error"] = f"Unsupported bgp_neighbor misconfig_kind: {misconfig_kind}" - return fault_info - - commands.extend(["end", "write memory"]) - result = self._sonic.vtysh(device, commands) - state_changed = False - if result.returncode == 0: - for _ in range(10): - if self._sonic.bgp_neighbor_state(device, peer_ip) is False: - state_changed = True - break - time.sleep(1) - fault_info["success"] = result.returncode == 0 and state_changed - fault_info["error"] = ( - None if fault_info["success"] else result.stderr or f"BGP neighbor {peer_ip} remained established" - ) - - if fault_info["success"]: - self._tracker.track(fault_info) - return fault_info - - rollback = self.recover_bgp_neighbor_misconfig( - device, - peer_ip, - misconfig_kind, - original_remote_as=fault_info.get("original_remote_as"), - original_password=fault_info.get("original_password"), - original_update_source=fault_info.get("original_update_source"), - wrong_remote_as=fault_info.get("wrong_remote_as"), - bad_update_source=fault_info.get("bad_update_source"), - ) - if not rollback.get("recovered"): - error = "; ".join( - filter( - None, - [ - str(fault_info.get("error") or ""), - str(rollback.get("error") or "BGP compensation failed"), - ], - ) - ) - fault_info["error"] = error - self._tracker.track_residual(fault_info, error) - return fault_info - - def recover_bgp_neighbor_misconfig( - self, - device: str, - peer_ip: str, - misconfig_kind: str, - original_remote_as: int | None = None, - original_password: str | None = None, - original_update_source: str | None = None, - wrong_remote_as: int | None = None, - bad_update_source: str | None = None, - ) -> dict[str, Any]: - """Recover one BGP neighbor configuration error.""" - container = self._ctx.container_names.get(device) - if not container: - raise ValueError(f"Unknown device: {device}") - - local_as = self._routing.get_device_asn(device) - if local_as is None: - raise ValueError(f"Unable to determine local BGP ASN for {device}") - - misconfig_kind = self._routing.normalize_bgp_neighbor_kind(misconfig_kind) - commands = ["configure terminal", f"router bgp {local_as}"] - if misconfig_kind == "peer_as_mismatch": - if original_remote_as is None: - raise ValueError("recover_bgp_neighbor_misconfig requires original_remote_as") - commands.append(f"neighbor {peer_ip} remote-as {int(original_remote_as)}") - elif misconfig_kind == "password_mismatch": - if original_password: - commands.append(f"neighbor {peer_ip} password {original_password}") - else: - commands.append(f"no neighbor {peer_ip} password") - elif misconfig_kind == "update_source_mismatch": - if original_update_source: - commands.append(f"neighbor {peer_ip} update-source {original_update_source}") - else: - commands.append(f"no neighbor {peer_ip} update-source {bad_update_source or 'Loopback0'}") - else: - raise ValueError(f"Unsupported bgp_neighbor misconfig_kind: {misconfig_kind}") - - commands.extend(["end", "write memory"]) - result = self._sonic.vtysh(device, commands) - established = False - if result.returncode == 0: - for _ in range(30): - if self._sonic.bgp_neighbor_state(device, peer_ip) is True: - established = True - break - time.sleep(1) - if established: - self._tracker.remove_faults( - lambda fault: fault["type"] == "bgp_neighbor_misconfig" - and fault["device"] == device - and fault.get("peer_ip") == peer_ip - ) - - return { - "type": "bgp_neighbor_misconfig", - "device": device, - "peer_ip": peer_ip, - "misconfig_kind": misconfig_kind, - "wrong_remote_as": wrong_remote_as, - "recovered": established, - "error": None if established else result.stderr or f"BGP neighbor {peer_ip} did not re-establish", - } diff --git a/netopsbench/platform/faults/handlers/routing_policy.py b/netopsbench/platform/faults/handlers/routing_policy.py deleted file mode 100644 index 99960f8..0000000 --- a/netopsbench/platform/faults/handlers/routing_policy.py +++ /dev/null @@ -1,259 +0,0 @@ -"""Route-policy and network origination fault handlers.""" - -from __future__ import annotations - -import time -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from ..context import FaultRuntimeContext - from ..services.routing_runtime import RoutingRuntime - from ..services.sonic_runtime import SonicRuntime - from ..services.tracking import FaultTracker - - -class RoutePolicyHandler: - """Handles route-policy / network-origination fault injection and recovery.""" - - def __init__( - self, - sonic: SonicRuntime, - routing: RoutingRuntime, - tracker: FaultTracker, - ctx: FaultRuntimeContext, - ) -> None: - self._sonic = sonic - self._routing = routing - self._tracker = tracker - self._ctx = ctx - - def _running_config(self, device: str) -> str | None: - result = self._sonic.vtysh(device, ["show running-config"]) - if result.returncode != 0: - return None - return result.stdout or "" - - def _bgp_prefix_present(self, device: str, prefix: str) -> bool | None: - result = self._sonic.vtysh(device, [f"show ip bgp {prefix}"]) - if result.returncode != 0: - return None - output = result.stdout or "" - lowered = output.lower() - if "network not in table" in lowered or "not found" in lowered: - return False - return prefix in output - - def _wait_for_bgp_prefix(self, device: str, prefix: str, *, present: bool) -> bool: - for attempt in range(10): - state = self._bgp_prefix_present(device, prefix) - if state is present: - return True - if attempt < 9: - time.sleep(1) - return False - - def _track_failed_compensation( - self, - fault_info: dict[str, Any], - rollback: dict[str, Any], - ) -> None: - if rollback.get("recovered") is True: - return - error = "; ".join( - filter( - None, - [ - str(fault_info.get("error") or ""), - str(rollback.get("error") or "route-policy compensation failed"), - ], - ) - ) - fault_info["error"] = error - self._tracker.track_residual(fault_info, error) - - def inject_route_policy_misconfig( - self, - device: str, - target_prefix: str | None = None, - misconfig_kind: str = "network_statement_missing", - route_map: str | None = None, - ) -> dict[str, Any]: - """Inject a route-policy/origination error using real FRR policy state.""" - container = self._ctx.container_names.get(device) - if not container: - raise ValueError(f"Unknown device: {device}") - - misconfig_kind = self._routing.normalize_route_policy_kind(misconfig_kind) - network = self._routing.pick_advertised_network(device, prefix=target_prefix) - if not network: - raise RuntimeError( - f"Unable to determine advertised network from device config: device={device} prefix={target_prefix}" - ) - - prefix = str(network["prefix"]) - local_as = network.get("local_as") or self._routing.get_device_asn(device) - if local_as is None: - raise RuntimeError(f"Unable to determine local BGP ASN for target device: device={device}") - - effective_route_map = route_map or network.get("route_map") - fault_info: dict[str, Any] = { - "type": "route_policy_misconfig", - "device": device, - "target_prefix": prefix, - "local_as": int(local_as), - "misconfig_kind": misconfig_kind, - "route_map": effective_route_map, - "success": False, - "error": None, - } - - if misconfig_kind == "network_statement_missing": - network_statement = self._routing.format_network_statement(prefix, effective_route_map) - commands = [ - "configure terminal", - f"router bgp {local_as}", - "address-family ipv4 unicast", - f"no {network_statement}", - "exit-address-family", - "end", - "write memory", - ] - fault_info["network_statement"] = network_statement - elif misconfig_kind == "route_map_deny_prefix": - route_map_name = effective_route_map or "RM-ALLOW" - prefix_list_name = self._routing.make_policy_artifact_name(device, prefix) - sequence = 5 - commands = [ - "configure terminal", - f"ip prefix-list {prefix_list_name} seq 5 permit {prefix}", - f"route-map {route_map_name} deny {sequence}", - f"match ip address prefix-list {prefix_list_name}", - "exit", - "end", - "write memory", - ] - fault_info["route_map"] = route_map_name - fault_info["prefix_list_name"] = prefix_list_name - fault_info["sequence"] = sequence - else: - fault_info["error"] = f"Unsupported route_policy misconfig_kind: {misconfig_kind}" - return fault_info - - result = self._sonic.vtysh(device, commands) - running = self._running_config(device) - if misconfig_kind == "network_statement_missing": - state_matches = ( - running is not None - and network_statement not in running - and self._wait_for_bgp_prefix(device, prefix, present=False) - ) - else: - state_matches = ( - running is not None - and f"route-map {fault_info['route_map']} deny {fault_info['sequence']}" in running - and f"ip prefix-list {fault_info['prefix_list_name']}" in running - and self._wait_for_bgp_prefix(device, prefix, present=True) - ) - fault_info["success"] = result.returncode == 0 and state_matches - fault_info["error"] = ( - None - if fault_info["success"] - else result.stderr or "route policy state did not match the injected configuration" - ) - - if fault_info["success"]: - self._tracker.track(fault_info) - return fault_info - - rollback = self.recover_route_policy_misconfig( - device, - prefix, - misconfig_kind, - route_map=fault_info.get("route_map"), - network_statement=fault_info.get("network_statement"), - prefix_list_name=fault_info.get("prefix_list_name"), - sequence=fault_info.get("sequence"), - ) - self._track_failed_compensation(fault_info, rollback) - return fault_info - - def recover_route_policy_misconfig( - self, - device: str, - target_prefix: str, - misconfig_kind: str, - route_map: str | None = None, - network_statement: str | None = None, - prefix_list_name: str | None = None, - sequence: int | None = None, - ) -> dict[str, Any]: - """Recover one route-policy/origination error.""" - container = self._ctx.container_names.get(device) - if not container: - raise ValueError(f"Unknown device: {device}") - - local_as = self._routing.get_device_asn(device) - if local_as is None: - raise ValueError(f"Unable to determine local BGP ASN for {device}") - - misconfig_kind = self._routing.normalize_route_policy_kind(misconfig_kind) - if misconfig_kind == "network_statement_missing": - statement = network_statement or self._routing.format_network_statement(target_prefix, route_map) - commands = [ - "configure terminal", - f"router bgp {local_as}", - "address-family ipv4 unicast", - statement, - "exit-address-family", - "end", - "write memory", - ] - elif misconfig_kind == "route_map_deny_prefix": - if not route_map: - raise ValueError("recover_route_policy_misconfig requires route_map") - if not prefix_list_name: - prefix_list_name = self._routing.make_policy_artifact_name(device, target_prefix) - commands = [ - "configure terminal", - f"no route-map {route_map} deny {int(sequence or 5)}", - f"no ip prefix-list {prefix_list_name}", - "end", - "write memory", - ] - else: - raise ValueError(f"Unsupported route_policy misconfig_kind: {misconfig_kind}") - - result = self._sonic.vtysh(device, commands) - running = self._running_config(device) - if misconfig_kind == "network_statement_missing": - recovered = ( - result.returncode == 0 - and running is not None - and statement in running - and self._wait_for_bgp_prefix(device, target_prefix, present=True) - ) - else: - recovered = ( - result.returncode == 0 - and running is not None - and ( - f"route-map {route_map} deny {int(sequence or 5)}" not in running - and f"ip prefix-list {prefix_list_name}" not in running - and self._wait_for_bgp_prefix(device, target_prefix, present=True) - ) - ) - if recovered: - self._tracker.remove_faults( - lambda fault: fault["type"] == "route_policy_misconfig" - and fault["device"] == device - and fault.get("target_prefix") == target_prefix - ) - - return { - "type": "route_policy_misconfig", - "device": device, - "target_prefix": target_prefix, - "misconfig_kind": misconfig_kind, - "recovered": recovered, - "error": None if recovered else result.stderr or "route policy recovery was not observed", - } diff --git a/netopsbench/platform/faults/handlers/routing_static.py b/netopsbench/platform/faults/handlers/routing_static.py index 469fb35..f7738a7 100644 --- a/netopsbench/platform/faults/handlers/routing_static.py +++ b/netopsbench/platform/faults/handlers/routing_static.py @@ -134,6 +134,8 @@ def inject_blackhole_route(self, device: str, target_prefix: str) -> dict[str, A if not container: raise ValueError(f"Unknown device: {device}") + if self._running_config_has_route(device, target_prefix) is not False: + raise RuntimeError("Cannot safely own an existing or unreadable static route") result = self._sonic.vtysh( device, [ @@ -189,9 +191,11 @@ def recover_blackhole_route(self, device: str, target_prefix: str) -> dict[str, ) if removed: self._tracker.remove_faults( - lambda fault: fault["type"] == "blackhole_route" - and fault["device"] == device - and fault["prefix"] == target_prefix + lambda fault: ( + fault["type"] == "blackhole_route" + and fault["device"] == device + and fault["prefix"] == target_prefix + ) ) return { @@ -199,6 +203,7 @@ def recover_blackhole_route(self, device: str, target_prefix: str) -> dict[str, "device": device, "prefix": target_prefix, "recovered": removed, + "readback_verified": removed, "error": None if removed else result.stderr or "blackhole route remained in running config", } @@ -225,6 +230,16 @@ def inject_static_route_misconfig( f"Unable to determine reachable wrong next-hop from topology metadata: device={device} target_ip={target_ip}" ) + local = next((c for c in self._ctx.clients_by_leaf.get(device, []) if c.get("data_ip") == wrong_nexthop), None) + if not local: + raise ValueError("Wrong next hop must be another directly attached client") + forwarding = self._sonic._cmd.docker_exec( + self._ctx.container_names[local["name"]], ["sysctl", "-n", "net.ipv4.ip_forward"] + ) + if forwarding.returncode or forwarding.stdout.strip() != "0": + raise RuntimeError("Wrong endpoint must have IP forwarding disabled") + if self._running_config_has_route(device, target_ip) is not False: + raise RuntimeError("Cannot safely own an existing or unreadable static route") result = self._sonic.vtysh( device, [ @@ -269,32 +284,12 @@ def recover_static_route_misconfig( if not container: raise ValueError(f"Unknown device: {device}") - command_sets = [] - if wrong_nexthop: - command_sets.append( - [ - "configure terminal", - f"no ip route {target_ip} {wrong_nexthop}", - "end", - "write memory", - ] - ) - command_sets.append( - [ - "configure terminal", - f"no ip route {target_ip}", - "end", - "write memory", - ] + if not wrong_nexthop: + raise ValueError("Recovery requires the owned next hop") + result = self._sonic.vtysh( + device, ["configure terminal", f"no ip route {target_ip} {wrong_nexthop}", "end", "write memory"] ) - result = None - for commands in command_sets: - result = self._sonic.vtysh(device, commands) - if result.returncode == 0: - break - assert result is not None - removed = ( result.returncode == 0 and self._running_config_has_route(device, target_ip) is False @@ -302,9 +297,11 @@ def recover_static_route_misconfig( ) if removed: self._tracker.remove_faults( - lambda fault: fault["type"] == "static_route_misconfig" - and fault["device"] == device - and fault["target_ip"] == target_ip + lambda fault: ( + fault["type"] == "static_route_misconfig" + and fault["device"] == device + and fault["target_ip"] == target_ip + ) ) return { @@ -313,5 +310,6 @@ def recover_static_route_misconfig( "target_ip": target_ip, "wrong_nexthop": wrong_nexthop, "recovered": removed, + "readback_verified": removed, "error": None if removed else result.stderr or "static route remained in running config", } diff --git a/netopsbench/platform/faults/handlers/system.py b/netopsbench/platform/faults/handlers/system.py index 3fad736..e516ed6 100644 --- a/netopsbench/platform/faults/handlers/system.py +++ b/netopsbench/platform/faults/handlers/system.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Any from netopsbench.platform.runtime.apply_configs import activate_device +from netopsbench.platform.runtime.toolchain import runtime_tools +from netopsbench.platform.utils.control import current_operation_control from netopsbench.platform.utils.proc import docker_prefix, sudo_prefix if TYPE_CHECKING: @@ -40,7 +42,7 @@ def __init__( def _containerlab_node_command(self, operation: str, device: str) -> list[str]: return [ *sudo_prefix(), - "containerlab", + str(runtime_tools() / "containerlab"), operation, "-t", str(self._ctx.topology_file), @@ -88,7 +90,8 @@ def _settled_stop_state(self, container: str) -> tuple[bool | None, bool | None] responsive_polls = 0 if time.monotonic() >= deadline: return state, parking - time.sleep(self._STOP_SETTLE_POLL_SECONDS) + control = current_operation_control() + control.sleep(self._STOP_SETTLE_POLL_SECONDS) if control else time.sleep(self._STOP_SETTLE_POLL_SECONDS) def _expected_dataplane_interface_count(self, device: str) -> int: return sum( @@ -182,6 +185,7 @@ def _start_and_wait(self, device: str, container: str) -> tuple[bool, str, bool] self._ctx.manifest.name, ecmp_hash_policy, readiness_max_tries=self._ACTIVATION_MAX_TRIES, + control=current_operation_control(), ) if not activated: return False, activation_error, True @@ -197,7 +201,8 @@ def _start_and_wait(self, device: str, container: str) -> tuple[bool, str, bool] last_error = (bgp_result.stderr or bgp_result.stdout or "").strip() or last_error elif running is None: last_error = "unable to read container running state" - time.sleep(5) + control = current_operation_control() + control.sleep(5) if control else time.sleep(5) return False, last_error or "device did not recover after containerlab node start", True def inject_device_down(self, device: str) -> dict[str, Any]: @@ -205,6 +210,15 @@ def inject_device_down(self, device: str) -> dict[str, Any]: if not container: raise ValueError(f"Unknown device: {device}") + original_running = self._cmd.container_is_running(container) + if original_running is not True: + return { + "type": "device_down", + "device": device, + "success": False, + "original_state": {"container_running": original_running}, + "error": "Device must be running before this fault can own its stop/start lifecycle", + } result = self._cmd.run_cmd( self._containerlab_node_command("stop", device), timeout=self._CONTAINERLAB_COMMAND_TIMEOUT_SECONDS, @@ -226,6 +240,7 @@ def inject_device_down(self, device: str) -> dict[str, Any]: "device": device, "container": container, "mode": "containerlab_node_stop", + "original_state": {"container_running": original_running}, "success": success, "parking_namespace": parking_namespace, "container_running": running_state, @@ -259,6 +274,7 @@ def recover_device_down(self, device: str) -> dict[str, Any]: "type": "device_down", "device": device, "recovered": ready, + "readback_verified": ready, "container_running": self._cmd.container_is_running(container), "sonic_ready": ready, "retryable": retryable, diff --git a/netopsbench/platform/faults/injector.py b/netopsbench/platform/faults/injector.py index 24d62fd..8cfe2a5 100644 --- a/netopsbench/platform/faults/injector.py +++ b/netopsbench/platform/faults/injector.py @@ -7,12 +7,12 @@ from pathlib import Path from typing import Any +from netopsbench.models.profiles import ExperimentProfile, default_experiment_profile from netopsbench.platform.faults.context import FaultRuntimeContext -from netopsbench.platform.faults.handlers.acl import AclHandler +from netopsbench.platform.faults.defaults import LATENCY_MS, MTU, PACKET_CORRUPTION_PCT, PACKET_LOSS_PCT from netopsbench.platform.faults.handlers.impairment import ImpairmentHandler from netopsbench.platform.faults.handlers.link import LinkHandler -from netopsbench.platform.faults.handlers.routing_bgp import BgpHandler -from netopsbench.platform.faults.handlers.routing_policy import RoutePolicyHandler +from netopsbench.platform.faults.handlers.network import NetworkFaultHandler from netopsbench.platform.faults.handlers.routing_static import StaticRouteHandler from netopsbench.platform.faults.handlers.system import SystemHandler from netopsbench.platform.faults.services.command_runner import CommandRunner @@ -40,6 +40,7 @@ def __init__( clab_dir: str | None = None, topology_metadata: dict[str, Any] | None = None, fault_registry: FaultSpecRegistry | None = None, + experiment: ExperimentProfile | None = None, ): self.fault_registry = fault_registry or create_fault_registry() resolved_clab_dir = Path(clab_dir or ".").resolve() @@ -53,7 +54,9 @@ def __init__( "Pass topology_metadata or a generated topology directory." ) manifest = load_topology_manifest(metadata_file) - self._ctx = FaultRuntimeContext(manifest=manifest, topology_dir=resolved_clab_dir) + self._ctx = FaultRuntimeContext( + manifest=manifest, topology_dir=resolved_clab_dir, experiment=experiment or default_experiment_profile() + ) # Build services (order matters — each layer depends on previous ones) self._cmd = CommandRunner() @@ -65,11 +68,11 @@ def __init__( # Build handlers self._link = LinkHandler(self._cmd, self._sonic, self._iface, self._tracker, self._ctx) self._impairment = ImpairmentHandler(self._cmd, self._sonic, self._iface, self._tracker, self._ctx) - self._bgp = BgpHandler(self._sonic, self._routing, self._tracker, self._ctx) self._static_route = StaticRouteHandler(self._sonic, self._tracker, self._ctx) - self._route_policy = RoutePolicyHandler(self._sonic, self._routing, self._tracker, self._ctx) + self._network = NetworkFaultHandler( + self._cmd, self._sonic, self._iface, self._routing, self._tracker, self._ctx + ) self._system = SystemHandler(self._cmd, self._sonic, self._tracker, self._ctx) - self._acl = AclHandler(self._cmd, self._sonic, self._routing, self._tracker, self._ctx) @property def container_names(self) -> dict[str, str]: @@ -108,35 +111,25 @@ def recover_link_flapping(self, device: str, interface: str, **kwargs) -> dict[s # ------------------------------------------------------------------ def inject_mtu_mismatch(self, device: str, interface: str, mtu: int | None = None) -> dict[str, Any]: - return self._impairment.inject_mtu_mismatch(device, interface, mtu=1400 if mtu is None else mtu) + return self._impairment.inject_mtu_mismatch(device, interface, mtu=MTU if mtu is None else mtu) def recover_mtu_mismatch(self, device: str, interface: str, original_mtu: int | None = None) -> dict[str, Any]: return self._impairment.recover_mtu_mismatch(device, interface, original_mtu=original_mtu) - def inject_packet_corruption(self, device: str, interface: str, corruption_pct: float = 5.0) -> dict[str, Any]: + def inject_packet_corruption( + self, device: str, interface: str, corruption_pct: float = PACKET_CORRUPTION_PCT + ) -> dict[str, Any]: return self._impairment.inject_packet_corruption(device, interface, corruption_pct=corruption_pct) - def inject_packet_loss(self, device: str, interface: str, loss_pct: float = 30.0) -> dict[str, Any]: + def inject_packet_loss(self, device: str, interface: str, loss_pct: float = PACKET_LOSS_PCT) -> dict[str, Any]: return self._impairment.inject_packet_loss(device, interface, loss_pct=loss_pct) - def inject_high_latency(self, device: str, interface: str, latency_ms: float = 100.0) -> dict[str, Any]: + def inject_high_latency(self, device: str, interface: str, latency_ms: float = LATENCY_MS) -> dict[str, Any]: return self._impairment.inject_high_latency(device, interface, latency_ms=latency_ms) def recover_tc_rules(self, device: str, interface: str) -> dict[str, Any]: return self._impairment.recover_tc_rules(device, interface) - # ------------------------------------------------------------------ - # BGP fault delegation - # ------------------------------------------------------------------ - - def inject_bgp_neighbor_misconfig(self, device: str, **kwargs) -> dict[str, Any]: - return self._bgp.inject_bgp_neighbor_misconfig(device, **kwargs) - - def recover_bgp_neighbor_misconfig( - self, device: str, peer_ip: str, misconfig_kind: str, **kwargs - ) -> dict[str, Any]: - return self._bgp.recover_bgp_neighbor_misconfig(device, peer_ip, misconfig_kind, **kwargs) - # ------------------------------------------------------------------ # Static route fault delegation # ------------------------------------------------------------------ @@ -159,40 +152,11 @@ def recover_static_route_misconfig( ) -> dict[str, Any]: return self._static_route.recover_static_route_misconfig(device, target_ip, wrong_nexthop=wrong_nexthop) - # ------------------------------------------------------------------ - # Route policy fault delegation - # ------------------------------------------------------------------ - - def inject_route_policy_misconfig(self, device: str, **kwargs) -> dict[str, Any]: - return self._route_policy.inject_route_policy_misconfig(device, **kwargs) + def inject_network_fault(self, episode) -> dict[str, Any]: + return self._network.inject(episode) - def recover_route_policy_misconfig( - self, device: str, target_prefix: str, misconfig_kind: str, **kwargs - ) -> dict[str, Any]: - return self._route_policy.recover_route_policy_misconfig(device, target_prefix, misconfig_kind, **kwargs) - - # ------------------------------------------------------------------ - # ACL fault delegation - # ------------------------------------------------------------------ - - def inject_acl_misconfig( - self, device: str, target_prefix: str | None = None, interface: str | None = None, direction: str = "in" - ) -> dict[str, Any]: - return self._acl.inject_acl_misconfig( - device, target_prefix=target_prefix, interface=interface, direction=direction - ) - - def recover_acl_misconfig( - self, - device: str, - target_prefix: str, - interface: str | None = None, - direction: str = "in", - acl_name: str | None = None, - ) -> dict[str, Any]: - return self._acl.recover_acl_misconfig( - device, target_prefix, interface=interface, direction=direction, acl_name=acl_name - ) + def recover_network_fault(self, fault) -> dict[str, Any]: + return self._network.recover(fault) # ------------------------------------------------------------------ # System fault delegation diff --git a/netopsbench/platform/faults/services/_bgpd_restore.py b/netopsbench/platform/faults/services/_bgpd_restore.py new file mode 100644 index 0000000..ce0d76e --- /dev/null +++ b/netopsbench/platform/faults/services/_bgpd_restore.py @@ -0,0 +1,35 @@ +"""Reload only the stopped daemon's captured configuration inside its node.""" + +import subprocess +import sys +import tempfile +import time +from pathlib import Path + + +def restore_bgpd(): + deadline = time.monotonic() + 25 + + def run(command): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("BGP configuration recovery deadline exceeded") + return subprocess.run(command, capture_output=True, text=True, timeout=remaining) + + status = run(["supervisorctl", "status", "bgpd"]) + if status.returncode not in (0, 3): + raise RuntimeError(status.stderr or "Cannot read bgpd service state") + if "RUNNING" not in status.stdout: + started = run(["supervisorctl", "start", "bgpd"]) + if started.returncode: + raise RuntimeError(started.stderr or started.stdout) + with tempfile.TemporaryDirectory(prefix="netopsbench-bgpd-") as directory: + path = Path(directory) / "bgpd.conf" + path.write_text(sys.argv[1]) + restored = run(["vtysh", "-d", "bgpd", "-f", str(path)]) + if restored.returncode or any(line.startswith("%") for line in restored.stdout.splitlines()): + raise RuntimeError(restored.stderr or restored.stdout or "Captured BGP configuration was not restored") + + +if __name__ == "__main__": + restore_bgpd() diff --git a/netopsbench/platform/faults/services/periodic.py b/netopsbench/platform/faults/services/periodic.py new file mode 100644 index 0000000..0b75a42 --- /dev/null +++ b/netopsbench/platform/faults/services/periodic.py @@ -0,0 +1,53 @@ +"""One cancellable controller for periodic link and prefix faults.""" + +from __future__ import annotations + +import threading +from collections.abc import Callable +from datetime import UTC, datetime + +from netopsbench.platform.utils.control import OperationCancelled, OperationControl, operation_scope + + +class PeriodicController: + def __init__(self, fault: Callable[[], None], healthy: Callable[[], None], *, down_time: float, up_time: float): + if min(down_time, up_time) <= 0: + raise ValueError("Periodic fault intervals must be positive") + self.stop_event = threading.Event() + self.error: str | None = None + self.history = [{"phase": "fault", "time": datetime.now(UTC).isoformat()}] + self._fault, self._healthy = fault, healthy + self._down, self._up = down_time, up_time + self.thread = threading.Thread(target=self._run, daemon=True, name="network-periodic-fault") + + def start(self) -> None: + # The first fault phase belongs to the injection transaction. + started_at = datetime.now(UTC).isoformat() + self._fault() + self.history[0] = {"phase": "fault", "started_at": started_at, "time": datetime.now(UTC).isoformat()} + self.thread.start() + + def _run(self) -> None: + try: + with operation_scope(OperationControl(cancel_event=self.stop_event)): + while not self.stop_event.wait(self._down): + started_at = datetime.now(UTC).isoformat() + self._healthy() + self.history.append( + {"phase": "healthy", "started_at": started_at, "time": datetime.now(UTC).isoformat()} + ) + if self.stop_event.wait(self._up): + break + started_at = datetime.now(UTC).isoformat() + self._fault() + self.history.append( + {"phase": "fault", "started_at": started_at, "time": datetime.now(UTC).isoformat()} + ) + self.history = self.history[-50:] + except OperationCancelled: + # Recovery cancels an in-flight controllable command before restoring + # the original state under its own remaining recovery budget. + pass + except Exception as exc: + self.error = f"{type(exc).__name__}: {exc}" + self.stop_event.set() diff --git a/netopsbench/platform/faults/services/routing_runtime.py b/netopsbench/platform/faults/services/routing_runtime.py index 8351a49..6559d70 100644 --- a/netopsbench/platform/faults/services/routing_runtime.py +++ b/netopsbench/platform/faults/services/routing_runtime.py @@ -2,9 +2,10 @@ from __future__ import annotations -import re from typing import TYPE_CHECKING, Any +from netopsbench.platform.utils.frr import parse_bgp_config + if TYPE_CHECKING: from ..context import FaultRuntimeContext from .sonic_runtime import SonicRuntime @@ -18,77 +19,9 @@ def __init__(self, sonic: SonicRuntime, ctx: FaultRuntimeContext) -> None: self._ctx = ctx def get_bgp_config_snapshot(self, device: str) -> dict[str, Any]: - local_as = None - neighbors: dict[str, dict[str, Any]] = {} - networks: list[dict[str, Any]] = [] - seen_networks = set() - result = self._sonic.vtysh(device, ["show running-config"]) - config_lines = (result.stdout or "").splitlines() if result.returncode == 0 else [] - for raw_line in config_lines: - line = raw_line.strip() - - match = re.match(r"^router bgp (\d+)$", line) - if match: - local_as = int(match.group(1)) - continue - - match = re.match(r"^neighbor (\S+) remote-as (\d+)$", line) - if match: - peer_ip, remote_as = match.groups() - peer = neighbors.setdefault( - peer_ip, - {"peer_ip": peer_ip, "remote_as": None, "password": None, "update_source": None, "route_maps": []}, - ) - peer["remote_as"] = int(remote_as) - continue - - match = re.match(r"^neighbor (\S+) password (\S+)$", line) - if match: - peer_ip, password = match.groups() - peer = neighbors.setdefault( - peer_ip, - {"peer_ip": peer_ip, "remote_as": None, "password": None, "update_source": None, "route_maps": []}, - ) - peer["password"] = password - continue - - match = re.match(r"^neighbor (\S+) update-source (\S+)$", line) - if match: - peer_ip, update_source = match.groups() - peer = neighbors.setdefault( - peer_ip, - {"peer_ip": peer_ip, "remote_as": None, "password": None, "update_source": None, "route_maps": []}, - ) - peer["update_source"] = update_source - continue - - match = re.match(r"^neighbor (\S+) route-map (\S+) (in|out)$", line) - if match: - peer_ip, route_map, direction = match.groups() - peer = neighbors.setdefault( - peer_ip, - {"peer_ip": peer_ip, "remote_as": None, "password": None, "update_source": None, "route_maps": []}, - ) - attachment = {"name": route_map, "direction": direction} - if attachment not in peer["route_maps"]: - peer["route_maps"].append(attachment) - continue - - match = re.match(r"^network (\S+)(?: route-map (\S+))?$", line) - if match: - prefix, route_map = match.groups() - identity = (prefix, route_map or "") - if identity in seen_networks: - continue - seen_networks.add(identity) - networks.append({"prefix": prefix, "route_map": route_map}) - - return { - "local_as": local_as, - "neighbors": sorted(neighbors.values(), key=lambda item: item["peer_ip"]), - "networks": sorted(networks, key=lambda item: item["prefix"]), - } + text = result.stdout if result.returncode == 0 else "" + return parse_bgp_config(text or "") def get_device_asn(self, device: str) -> int | None: for entry in self._ctx.manifest.routing_devices(): @@ -99,59 +32,13 @@ def get_device_asn(self, device: str) -> int | None: return int(snapshot["local_as"]) return None - @staticmethod - def normalize_bgp_neighbor_kind(misconfig_kind: str | None) -> str: - normalized = str(misconfig_kind or "peer_as_mismatch").strip().lower().replace("-", "_") - aliases = { - "peer_as": "peer_as_mismatch", - "remote_as_mismatch": "peer_as_mismatch", - "auth_mismatch": "password_mismatch", - "md5_mismatch": "password_mismatch", - "update_source": "update_source_mismatch", - } - return aliases.get(normalized, normalized) - - @staticmethod - def normalize_route_policy_kind(misconfig_kind: str | None) -> str: - normalized = str(misconfig_kind or "network_statement_missing").strip().lower().replace("-", "_") - aliases = { - "route_origination_missing": "network_statement_missing", - "outbound_prefix_filter": "route_map_deny_prefix", - "prefix_filter_misconfig": "route_map_deny_prefix", - } - return aliases.get(normalized, normalized) - - def pick_bgp_neighbor(self, device: str, peer_ip: str | None = None) -> dict[str, Any] | None: + def pick_bgp_neighbor(self, device: str, peer_ip: str) -> dict[str, Any] | None: snapshot = self.get_bgp_config_snapshot(device) - neighbors = list(snapshot.get("neighbors") or []) - if peer_ip: - for neighbor in neighbors: - if neighbor.get("peer_ip") == peer_ip: - return {"local_as": snapshot.get("local_as"), **neighbor} - return None - if not neighbors: - return None - selected = sorted(neighbors, key=lambda item: item.get("peer_ip", ""))[0] - return {"local_as": snapshot.get("local_as"), **selected} + return next((peer for peer in snapshot["neighbors"] if peer["peer_ip"] == peer_ip), None) - def pick_advertised_network(self, device: str, prefix: str | None = None) -> dict[str, Any] | None: + def pick_advertised_network(self, device: str, prefix: str) -> dict[str, Any] | None: snapshot = self.get_bgp_config_snapshot(device) - networks = list(snapshot.get("networks") or []) - if prefix: - for network in networks: - if network.get("prefix") == prefix: - return {"local_as": snapshot.get("local_as"), **network} - return None - if not networks: - return None - selected = sorted(networks, key=lambda item: item.get("prefix", ""))[0] - return {"local_as": snapshot.get("local_as"), **selected} - - @staticmethod - def make_policy_artifact_name(device: str, prefix: str) -> str: - raw = f"netopsbench_{device}_{prefix}" - token = re.sub(r"[^A-Za-z0-9]+", "_", raw).strip("_").upper() - return token[:60] or "NETOPSBENCH_ROUTE_POLICY" + return next((network for network in snapshot["networks"] if network["prefix"] == prefix), None) @staticmethod def format_network_statement(prefix: str, route_map: str | None = None) -> str: diff --git a/netopsbench/platform/faults/services/sonic_runtime.py b/netopsbench/platform/faults/services/sonic_runtime.py index 4c35204..4677d13 100644 --- a/netopsbench/platform/faults/services/sonic_runtime.py +++ b/netopsbench/platform/faults/services/sonic_runtime.py @@ -29,7 +29,20 @@ def vtysh(self, device: str, commands: list[str]) -> subprocess.CompletedProcess cmd = ["vtysh"] for command in commands: cmd.extend(["-c", command]) - return self._cmd.docker_exec(container, cmd) + result = self._cmd.docker_exec(container, cmd) + if result.returncode == 0 and "write memory" in commands: + # FRR rewrites its bind-mounted startup file as frr:frr 0640. + # Preserve the generated configuration's host-side readability + # so runtime baseline fingerprints can still inspect it. + readable = self._cmd.docker_exec(container, ["chmod", "a+r", "/etc/frr/frr.conf"]) + if readable.returncode != 0: + return subprocess.CompletedProcess( + result.args, + readable.returncode, + result.stdout, + readable.stderr or "Saved FRR configuration could not be made readable", + ) + return result def config_cmd(self, device: str, args: list[str]) -> subprocess.CompletedProcess: container = self._ctx.container_names.get(device) diff --git a/netopsbench/platform/faults/services/tracking.py b/netopsbench/platform/faults/services/tracking.py index bf3a2d4..eb8c606 100644 --- a/netopsbench/platform/faults/services/tracking.py +++ b/netopsbench/platform/faults/services/tracking.py @@ -7,6 +7,7 @@ from typing import Any from netopsbench.platform.faults.models import ActiveFault +from netopsbench.platform.utils.control import current_operation_control class FaultTracker: @@ -35,9 +36,15 @@ def track_residual(self, fault_info: dict, error: str) -> ActiveFault: ) return self.track(payload) - def register_background_control(self, control_id: str, *, stop_event: Any, thread: Any) -> None: + def register_background_control( + self, control_id: str, *, stop_event: Any, thread: Any, controller: Any = None + ) -> None: with self._lock: - self._background_fault_controls[control_id] = {"stop_event": stop_event, "thread": thread} + self._background_fault_controls[control_id] = { + "stop_event": stop_event, + "thread": thread, + "controller": controller, + } def stop_background(self, control_id: str, *, join_timeout: float = 1.0) -> bool: with self._lock: @@ -48,6 +55,12 @@ def stop_background(self, control_id: str, *, join_timeout: float = 1.0) -> bool thread = control.get("thread") if stop_event is not None: stop_event.set() + budget = current_operation_control() + if budget is not None: + try: + join_timeout = budget.remaining(join_timeout) + except TimeoutError: + return False if thread is not None and hasattr(thread, "join") and thread is not threading.current_thread(): thread.join(timeout=join_timeout) if bool(getattr(thread, "is_alive", lambda: False)()): diff --git a/netopsbench/platform/faults/specs.py b/netopsbench/platform/faults/specs.py index 964ae43..c5db12c 100644 --- a/netopsbench/platform/faults/specs.py +++ b/netopsbench/platform/faults/specs.py @@ -110,7 +110,7 @@ def _build_builtin_fault_specs() -> list[FaultSpec]: Imported lazily inside the function to avoid an import cycle: ``builtin/__init__`` may transitively import ``specs`` for shared types. """ - from .builtin.acl_specs import build_acl_fault_specs + from .builtin.catalog_specs import build_catalog_fault_specs from .builtin.impairment_specs import build_impairment_fault_specs from .builtin.link_specs import build_link_fault_specs from .builtin.routing_specs import build_routing_fault_specs @@ -121,7 +121,7 @@ def _build_builtin_fault_specs() -> list[FaultSpec]: build_routing_fault_specs, build_impairment_fault_specs, build_system_fault_specs, - build_acl_fault_specs, + build_catalog_fault_specs, ) aggregated: list[FaultSpec] = [] for build_specs in builders: diff --git a/netopsbench/platform/incident/context.py b/netopsbench/platform/incident/context.py index dc6b9b8..ec70b1e 100644 --- a/netopsbench/platform/incident/context.py +++ b/netopsbench/platform/incident/context.py @@ -6,13 +6,23 @@ import hashlib from typing import Any +from netopsbench.platform.toolkit.public import public_observation from netopsbench.platform.toolkit.toolkit import AgentToolkit _EPISODE_ALLOWED_KEYS = { - "episode_id", "duration_seconds", "stabilization_time", } +_OBSERVATION_ALLOWED_KEYS = { + "start_time", + "end_time", + "duration_seconds", + "pingmesh_metrics", + "anomalies_detected", + "coverage_status", + "data_source_status", + "observation_windows", +} _MAX_CANONICAL_ANOMALIES = 12 @@ -53,19 +63,19 @@ def extract_episode_pingmesh_query_window(episode_result: dict[str, Any]) -> dic return {"start_time": None, "end_time": None} -def _bounded_observations(observations: dict[str, Any]) -> dict[str, Any]: - """Return the complete public observation payload. +def _public_observations(observations: dict[str, Any]) -> dict[str, Any]: + """Expose Pingmesh symptoms and their window/data-quality metadata. - Model-specific prompt compaction belongs to the canonical observation - consumer. It must not silently alter ``DiagnosticContext.symptoms`` for - third-party benchmark agents. + Device-state snapshots and differences belong to private effect/recovery + validation. Agents obtain device evidence through diagnostic tools. + Keep the Pingmesh payload complete; only the canonical view compacts it. """ - return copy.deepcopy(observations) + return public_observation({key: value for key, value in observations.items() if key in _OBSERVATION_ALLOWED_KEYS}) def _compact_model_observations(observations: dict[str, Any]) -> dict[str, Any]: """Compact only the optional model-facing canonical view.""" - compacted = copy.deepcopy(observations) + compacted = _public_observations(observations) metrics = compacted.get("pingmesh_metrics") if not isinstance(metrics, dict): return compacted @@ -114,7 +124,7 @@ def build_public_symptoms(*, episode_result: dict[str, Any], pingmesh_query_wind ) return { "episode": safe_episode, - "observations": _bounded_observations(observations) if isinstance(observations, dict) else {}, + "observations": _public_observations(observations) if isinstance(observations, dict) else {}, "pingmesh_query_window": pingmesh_query_window if isinstance(pingmesh_query_window, dict) else {}, "observation_type": "scenario_episode", } diff --git a/netopsbench/platform/incident/engine.py b/netopsbench/platform/incident/engine.py index bb73507..ecdf2f3 100644 --- a/netopsbench/platform/incident/engine.py +++ b/netopsbench/platform/incident/engine.py @@ -191,6 +191,8 @@ def call_tool(self, action: ToolAction) -> dict[str, Any]: raise ValueError(f"Invalid tool action: {action.name}") self._refresh_lease() with self._tool_lock: + if self.state is not IncidentState.ACTIVE: + raise RuntimeError(f"Incident is not active: {self.state}") result = self.backend.call_tool(action) self._refresh_lease() return result @@ -254,7 +256,8 @@ def close(self) -> CleanupStatus: broken = self.state is IncidentState.BROKEN if not broken: self.state = IncidentState.CLOSING - self._finish_backend(broken=broken) + with self._tool_lock: + self._finish_backend(broken=broken) return self.cleanup_status def _finish_backend(self, *, broken: bool) -> None: @@ -325,19 +328,24 @@ def call_tool(self, action: ToolAction) -> SessionTransition: metrics=self._metrics(elapsed), ) try: - result = self.incident.call_tool(action) + from netopsbench.platform.toolkit._core.control import tool_deadline_scope + + with tool_deadline_scope(self.started_at + self.config.max_agent_seconds): + result = self.incident.call_tool(action) except Exception as exc: # noqa: BLE001 - ordinary query errors are recoverable failure = ExecutionFailure( domain=FailureDomain.TOOL_EXECUTION, phase="tool_execution", - message=str(exc), + message="Diagnostic query failed", error_type=type(exc).__name__, ) return SessionTransition( state=self.state, - observation=self._bounded_tool_observation({"tool": action.name, "success": False, "error": str(exc)}), + observation=self._bounded_tool_observation( + {"tool": action.name, "success": False, "error": "Diagnostic query failed"} + ), failure=failure, - error=str(exc), + error="Diagnostic query failed", metrics=self._metrics(elapsed), ) return SessionTransition( @@ -406,8 +414,10 @@ def terminate_failure( ) def _limit_transition(self, elapsed: float) -> SessionTransition | None: + timings = getattr(self, "phase_timings", None) + cleanup_seconds = timings.phases.get("agent_cleanup", {}).get("actual_seconds", 0) if timings else 0 message = None - if elapsed > self.config.max_agent_seconds: + if max(0.0, elapsed - cleanup_seconds) > self.config.max_agent_seconds: message = "max_agent_seconds exceeded" elif self.tool_calls >= self.config.max_tool_calls: message = "max_tool_calls exceeded" diff --git a/netopsbench/platform/observability/_routing_probe.py b/netopsbench/platform/observability/_routing_probe.py new file mode 100644 index 0000000..3b52a59 --- /dev/null +++ b/netopsbench/platform/observability/_routing_probe.py @@ -0,0 +1,56 @@ +"""Read-only routing checks inside one Docker exec; no NetOpsBench imports.""" + +import argparse +import json +import subprocess +import time +from pathlib import Path + + +def packet_counters(path=Path("/proc/net/snmp")): + """Read namespace-local counters; an unreadable counter is never zero.""" + try: + lines = path.read_text().splitlines() + values = {} + for header, row in zip(lines[::2], lines[1::2], strict=True): + names, counts = header.split(), row.split() + if names[0] == counts[0] == "Icmp:": + values = dict(zip(names[1:], map(int, counts[1:]), strict=True)) + return {"icmp_out_time_exceeded": values["OutTimeExcds"], "collected_at": time.time()} + except (OSError, ValueError, KeyError, IndexError) as error: + return {"error": type(error).__name__, "collected_at": time.time()} + + +def probe(run=subprocess.run, checks_to_run=None, budget_seconds=125): + deadline = time.monotonic() + budget_seconds + counters = packet_counters() + checks = {} + for name, command in ( + ("bgp", ["vtysh", "-c", "show ip bgp summary"]), + ("interfaces", ["bash", "-lc", "show interfaces status"]), + ("fib", ["ip", "-j", "-4", "route", "show"]), + ): + if checks_to_run is not None and name not in checks_to_run: + continue + remaining = deadline - time.monotonic() + if remaining <= 0: + checks[name] = {"returncode": -1, "stdout": "", "error": "deadline_exceeded"} + continue + try: + result = run(command, capture_output=True, text=True, check=False, timeout=min(60, remaining)) + checks[name] = {"returncode": result.returncode, "stdout": result.stdout or ""} + except (subprocess.TimeoutExpired, OSError) as error: + checks[name] = {"returncode": -1, "stdout": "", "error": type(error).__name__} + return {"version": 1, "checks": checks, "packet_counters": counters} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--routes-only", action="store_true") + parser.add_argument("--budget-seconds", type=float, default=125) + args = parser.parse_args() + print( + json.dumps( + probe(checks_to_run=("bgp", "fib") if args.routes_only else None, budget_seconds=args.budget_seconds) + ) + ) diff --git a/netopsbench/platform/observability/assets/grafana/dashboards/pingmesh.json b/netopsbench/platform/observability/assets/grafana/dashboards/pingmesh.json index 5105918..4d95569 100644 --- a/netopsbench/platform/observability/assets/grafana/dashboards/pingmesh.json +++ b/netopsbench/platform/observability/assets/grafana/dashboards/pingmesh.json @@ -75,7 +75,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p90\" or r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.path_type == \"${path_type}\" or \"${path_type}\" == \"all\")\n |> group(columns: [\"_field\", \"path_type\"])\n |> aggregateWindow(every: 15s, fn: mean, createEmpty: false)\n |> yield(name: \"result\")", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p90\" or r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.path_type == \"${path_type}\" or \"${path_type}\" == \"all\")\n |> group(columns: [\"_field\", \"path_type\"])\n |> aggregateWindow(every: 15s, fn: mean, createEmpty: false)\n |> yield(name: \"result\")", "refId": "A" } ], @@ -113,7 +113,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.path_type == \"cross_rack\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group(columns: [\"_time\"])\n |> mean(column: \"_value\")\n |> group()\n |> last()", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.path_type == \"cross_rack\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group(columns: [\"_time\"])\n |> mean(column: \"_value\")\n |> group()\n |> last()", "refId": "A" } ], @@ -151,7 +151,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.path_type == \"same_rack\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group(columns: [\"_time\"])\n |> mean(column: \"_value\")\n |> group()\n |> last()", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.path_type == \"same_rack\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group(columns: [\"_time\"])\n |> mean(column: \"_value\")\n |> group()\n |> last()", "refId": "A" } ], @@ -190,7 +190,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"packet_loss\")\n |> filter(fn: (r) => r.path_type == \"${path_type}\" or \"${path_type}\" == \"all\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group(columns: [\"_time\"])\n |> max(column: \"_value\")\n |> group()\n |> last()", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"packet_loss\")\n |> filter(fn: (r) => r.path_type == \"${path_type}\" or \"${path_type}\" == \"all\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> group(columns: [\"_time\"])\n |> max(column: \"_value\")\n |> group()\n |> last()", "refId": "A" } ], @@ -235,7 +235,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\" or r._field == \"packet_loss\")\n |> filter(fn: (r) => r.src_leaf == \"${src_leaf}\" or \"${src_leaf}\" == \"all\")\n |> filter(fn: (r) => r.dst_leaf == \"${dst_leaf}\" or \"${dst_leaf}\" == \"all\")\n |> group(columns: [\"src_leaf\", \"dst_leaf\", \"_field\"])\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> last()\n |> pivot(rowKey: [\"src_leaf\", \"dst_leaf\"], columnKey: [\"_field\"], valueColumn: \"_value\")", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\" or r._field == \"packet_loss\")\n |> filter(fn: (r) => r.src_leaf == \"${src_leaf}\" or \"${src_leaf}\" == \"all\")\n |> filter(fn: (r) => r.dst_leaf == \"${dst_leaf}\" or \"${dst_leaf}\" == \"all\")\n |> group(columns: [\"src_leaf\", \"dst_leaf\", \"_field\"])\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> last()\n |> pivot(rowKey: [\"src_leaf\", \"dst_leaf\"], columnKey: [\"_field\"], valueColumn: \"_value\")", "refId": "A" } ], @@ -273,7 +273,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\" or r._field == \"packet_loss\")\n |> group(columns: [\"src_leaf\", \"dst_leaf\", \"_field\"])\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> last()\n |> pivot(rowKey: [\"src_leaf\", \"dst_leaf\"], columnKey: [\"_field\"], valueColumn: \"_value\")\n |> sort(columns: [\"rtt_p99\"], desc: true)\n |> limit(n: 12)", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\" or r._field == \"packet_loss\")\n |> group(columns: [\"src_leaf\", \"dst_leaf\", \"_field\"])\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> last()\n |> pivot(rowKey: [\"src_leaf\", \"dst_leaf\"], columnKey: [\"_field\"], valueColumn: \"_value\")\n |> sort(columns: [\"rtt_p99\"], desc: true)\n |> limit(n: 12)", "refId": "A" } ], @@ -318,7 +318,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.src_leaf == \"${src_leaf}\" or \"${src_leaf}\" == \"all\")\n |> group(columns: [\"dst_leaf\"])\n |> aggregateWindow(every: 15s, fn: mean, createEmpty: false)", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.src_leaf == \"${src_leaf}\" or \"${src_leaf}\" == \"all\")\n |> group(columns: [\"dst_leaf\"])\n |> aggregateWindow(every: 15s, fn: mean, createEmpty: false)", "refId": "A" } ], @@ -380,7 +380,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_avg\" or r._field == \"rtt_p90\" or r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> yield(name: \"result\")", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_avg\" or r._field == \"rtt_p90\" or r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)\n |> yield(name: \"result\")", "refId": "A" } ], @@ -417,7 +417,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p90\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> last()\n |> mean()", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p90\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> last()\n |> mean()", "refId": "A" } ], @@ -454,7 +454,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> last()\n |> mean()", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_p99\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> last()\n |> mean()", "refId": "A" } ], @@ -493,7 +493,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"packet_loss\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> last()\n |> mean()", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"packet_loss\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> last()\n |> mean()", "refId": "A" } ], @@ -540,7 +540,7 @@ "targets": [ { "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_avg\" or r._field == \"rtt_p90\" or r._field == \"rtt_p99\" or r._field == \"packet_loss\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> filter(fn: (r) => r.path_type == \"${path_type}\" or \"${path_type}\" == \"all\")\n |> group(columns: [\"src_name\", \"dst_name\", \"src_leaf\", \"dst_leaf\", \"path_type\", \"_field\"])\n |> last()\n |> pivot(rowKey: [\"src_name\", \"dst_name\", \"src_leaf\", \"dst_leaf\", \"path_type\"], columnKey: [\"_field\"], valueColumn: \"_value\")\n |> sort(columns: [\"rtt_p99\"], desc: true)", + "query": "from(bucket: \"${bucket}\")\n |> range(start: v.timeRangeStart, stop: v.timeRangeStop)\n |> filter(fn: (r) => r._measurement == \"pingmesh\")\n |> filter(fn: (r) => r.plan_id == \"${plan_id}\")\n |> filter(fn: (r) => r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\")\n |> filter(fn: (r) => r._field == \"rtt_avg\" or r._field == \"rtt_p90\" or r._field == \"rtt_p99\" or r._field == \"packet_loss\")\n |> filter(fn: (r) => r.src_name == \"${src_host}\" or \"${src_host}\" == \"all\")\n |> filter(fn: (r) => r.dst_name == \"${dst_host}\" or \"${dst_host}\" == \"all\")\n |> filter(fn: (r) => r.path_type == \"${path_type}\" or \"${path_type}\" == \"all\")\n |> group(columns: [\"src_name\", \"dst_name\", \"src_leaf\", \"dst_leaf\", \"path_type\", \"_field\"])\n |> last()\n |> pivot(rowKey: [\"src_name\", \"dst_name\", \"src_leaf\", \"dst_leaf\", \"path_type\"], columnKey: [\"_field\"], valueColumn: \"_value\")\n |> sort(columns: [\"rtt_p99\"], desc: true)", "refId": "A" } ], @@ -593,6 +593,24 @@ "sort": 1, "type": "query" }, + { + "name": "plan_id", + "label": "Plan", + "type": "query", + "datasource": { + "type": "influxdb", + "uid": "InfluxDB_v2" + }, + "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"plan_id\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"plan_id\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "current": {}, + "includeAll": false, + "multi": false, + "options": [], + "refresh": 2, + "sort": 0, + "hide": 0 + }, { "current": { "selected": true, "text": "all", "value": "all" }, "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, @@ -615,7 +633,7 @@ { "current": { "selected": true, "text": "all", "value": "all" }, "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "hide": 0, "includeAll": true, "allValue": "all", @@ -623,7 +641,7 @@ "multi": false, "name": "src_leaf", "options": [], - "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "refresh": 2, "sort": 1, "type": "query" @@ -631,7 +649,7 @@ { "current": { "selected": true, "text": "all", "value": "all" }, "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "hide": 0, "includeAll": true, "allValue": "all", @@ -639,7 +657,7 @@ "multi": false, "name": "dst_leaf", "options": [], - "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_leaf\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "refresh": 2, "sort": 1, "type": "query" @@ -647,7 +665,7 @@ { "current": { "selected": true, "text": "all", "value": "all" }, "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "hide": 0, "includeAll": true, "allValue": "all", @@ -655,7 +673,7 @@ "multi": false, "name": "src_host", "options": [], - "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"src_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "refresh": 2, "sort": 1, "type": "query" @@ -663,7 +681,7 @@ { "current": { "selected": true, "text": "all", "value": "all" }, "datasource": { "type": "influxdb", "uid": "InfluxDB_v2" }, - "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "definition": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "hide": 0, "includeAll": true, "allValue": "all", @@ -671,7 +689,7 @@ "multi": false, "name": "dst_host", "options": [], - "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", + "query": "import \"influxdata/influxdb/schema\"\nschema.tagValues(\n bucket: \"${bucket}\",\n tag: \"dst_name\",\n predicate: (r) => r._measurement == \"pingmesh\" and r.plan_id == \"${plan_id}\" and (r.topology_id == \"${topology_id}\" or \"${topology_id}\" == \"all\"),\n start: -1h\n)", "refresh": 2, "sort": 1, "type": "query" diff --git a/netopsbench/platform/observability/bgp_collector.py b/netopsbench/platform/observability/bgp_collector.py index de0de87..2b2b8c2 100644 --- a/netopsbench/platform/observability/bgp_collector.py +++ b/netopsbench/platform/observability/bgp_collector.py @@ -197,6 +197,18 @@ def build_bgp_transition_line( return f"bgp_session_events,{','.join(tags)} {','.join(fields)} {timestamp_ns}" +def build_prefix_count_line(device, neighbor, previous, current, timestamp_ns, topology_id): + tags = [ + f"source={_escape_tag(device)}", + f"neighbor_address={_escape_tag(neighbor)}", + f"topology_id={_escape_tag(topology_id)}", + ] + return ( + f"bgp_prefix_events,{','.join(tags)} prefixes_before={int(previous['prefixes_received'])}i," + f"prefixes_after={int(current['prefixes_received'])}i {timestamp_ns}" + ) + + class BgpTransitionTracker: """Maintain one collector process' latest BGP states and emit transitions.""" @@ -240,6 +252,15 @@ def process( topology_id, ) ) + if ( + previous + and previous.get("prefixes_received") is not None + and current.get("prefixes_received") is not None + and previous["prefixes_received"] != current["prefixes_received"] + ): + lines.append( + build_prefix_count_line(device, neighbor, previous, current, timestamp_ns, topology_id) + ) self._previous[key] = current missing_keys = [key for key in self._previous if key[0] == device and key[1] not in current_rows] @@ -291,9 +312,9 @@ def _collect_device_bgp( if result.returncode != 0: error_type = "command_failed" else: - rows = parse_bgp_summary(result.stdout) - if result.stdout.strip() and "Neighbor" not in result.stdout and not rows: - error_type = "parser_failed" + rows = parse_bgp_summary(result.stdout, strict=True) + except ValueError: + error_type = "parser_failed" except subprocess.TimeoutExpired: error_type = "timeout" except Exception: diff --git a/netopsbench/platform/observability/bgp_parser.py b/netopsbench/platform/observability/bgp_parser.py index c5e8a94..d1297a7 100644 --- a/netopsbench/platform/observability/bgp_parser.py +++ b/netopsbench/platform/observability/bgp_parser.py @@ -21,7 +21,7 @@ def _coerce_value(value: Any) -> Any: return text -def parse_bgp_summary(text: str) -> list[dict[str, Any]]: +def parse_bgp_summary(text: str, *, strict: bool = False) -> list[dict[str, Any]]: """Return normalized neighbor rows from ``show ip bgp summary`` output.""" lines = [line.rstrip() for line in text.splitlines() if line.strip()] header_index = next( @@ -29,6 +29,8 @@ def parse_bgp_summary(text: str) -> list[dict[str, Any]]: None, ) if header_index is None: + if strict: + raise ValueError("BGP summary header is unavailable") return [] headers = lines[header_index].split() diff --git a/netopsbench/platform/observability/influxdb.py b/netopsbench/platform/observability/influxdb.py index 17d2afe..abe47ce 100644 --- a/netopsbench/platform/observability/influxdb.py +++ b/netopsbench/platform/observability/influxdb.py @@ -1,19 +1,27 @@ """Shared InfluxDB lifecycle and Flux query client.""" +import csv +import http.client import json +import socket +import threading import time import urllib.error import urllib.parse import urllib.request from dataclasses import dataclass +from io import StringIO from typing import Literal import requests from netopsbench.logging_utils import get_logger +from netopsbench.platform.utils.measurements import count_operation logger = get_logger(__name__) +_QUERY_SLOTS = threading.BoundedSemaphore(4) + DEFAULT_MANAGED_BUCKET_RETENTION_SECONDS = 7 * 24 * 60 * 60 @@ -24,35 +32,110 @@ class FluxQueryResult: error: str | None = None +def iter_annotated_csv_rows(csv_text: str): + """Parse Flux CSV while honoring the repeated headers emitted by multiple yields.""" + header: list[str] | None = None + for values in csv.reader(StringIO(csv_text)): + if not values or (values[0] and values[0].startswith("#")): + continue + if "result" in values and "table" in values: + header = values + continue + if header is None: + continue + padded = [*values, *([""] * max(0, len(header) - len(values)))] + yield dict(zip(header, padded[: len(header)], strict=False)) + + def query_flux( base_url: str, token: str, org: str, query: str, *, - timeout: int = 30, + timeout: float = 30, + deadline: float | None = None, ) -> FluxQueryResult: """Execute one Flux query without interpreting its domain-specific CSV.""" + count_operation("influx_queries") headers = { "Authorization": f"Token {token}", "Content-Type": "application/vnd.flux", "Accept": "application/csv", } + limit = time.monotonic() + timeout + if deadline is not None: + limit = min(limit, deadline) + remaining = limit - time.monotonic() + if remaining <= 0 or not _QUERY_SLOTS.acquire(timeout=max(0, remaining)): + return FluxQueryResult(status="error", error="InfluxDB query deadline exceeded while waiting for a slot") try: + remaining = limit - time.monotonic() + if remaining <= 0: + return FluxQueryResult(status="error", error="InfluxDB query deadline exceeded") + url = f"{base_url.rstrip('/')}/api/v2/query" + if deadline is not None: + return FluxQueryResult(status="ok", text=_query_before_deadline(url, org, query, headers, limit)) response = requests.post( f"{base_url.rstrip('/')}/api/v2/query", params={"org": org}, headers=headers, data=query, - timeout=timeout, + timeout=remaining, proxies={"http": "", "https": ""}, ) response.raise_for_status() - except requests.RequestException as exc: + except (requests.RequestException, OSError, http.client.HTTPException) as exc: + if time.monotonic() >= limit: + return FluxQueryResult(status="error", error="InfluxDB query deadline exceeded") return FluxQueryResult(status="error", error=f"{type(exc).__name__}: {exc}") + finally: + _QUERY_SLOTS.release() return FluxQueryResult(status="ok", text=response.text) +def _query_before_deadline(url: str, org: str, query: str, headers: dict, limit: float) -> str: + """Interrupt slow response headers or bodies at the shared elapsed-time limit.""" + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in {"http", "https"} or parsed.hostname is None: + raise OSError("Invalid InfluxDB query URL") + connection_type = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection + connection = connection_type(parsed.hostname, parsed.port, timeout=max(0.001, limit - time.monotonic())) + timer = None + try: + connection.connect() + transport = connection.sock + remaining = limit - time.monotonic() + if remaining <= 0: + raise TimeoutError("InfluxDB query deadline exceeded") + if transport is None: + raise OSError("InfluxDB connection did not create a socket") + + def interrupt(): + try: + transport.shutdown(socket.SHUT_RDWR) + except OSError: + pass # The completed request may already have closed its socket. + + timer = threading.Timer(remaining, interrupt) + timer.start() + transport.settimeout(remaining) + path = parsed.path + "?" + urllib.parse.urlencode({"org": org}) + connection.request("POST", path, body=query.encode("utf-8"), headers=headers) + response = connection.getresponse() + if response.status >= 400: + raise OSError(f"InfluxDB HTTP {response.status}: {response.reason}") + text = response.read().decode("utf-8") + if time.monotonic() >= limit: + raise TimeoutError("InfluxDB query deadline exceeded") + return text + finally: + if timer is not None: + timer.cancel() + timer.join() + connection.close() + + def _make_url_opener(url: str): hostname = (urllib.parse.urlparse(url).hostname or "").strip().lower() if hostname in {"localhost", "127.0.0.1", "::1"}: diff --git a/netopsbench/platform/observability/lifecycle.py b/netopsbench/platform/observability/lifecycle.py index 8f98eda..4c168b0 100644 --- a/netopsbench/platform/observability/lifecycle.py +++ b/netopsbench/platform/observability/lifecycle.py @@ -52,6 +52,7 @@ def ensure_observability_core() -> None: str(root / "docker-compose.yaml"), "up", "-d", + "--no-recreate", "influxdb", "grafana", ], diff --git a/netopsbench/platform/observability/routes.py b/netopsbench/platform/observability/routes.py new file mode 100644 index 0000000..3b3b6ce --- /dev/null +++ b/netopsbench/platform/observability/routes.py @@ -0,0 +1,128 @@ +"""Private, phase-scoped route snapshots for effect and recovery validation.""" + +from __future__ import annotations + +import json +import time +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context +from datetime import UTC, datetime +from pathlib import Path + +from netopsbench.platform.observability.bgp_parser import parse_bgp_summary +from netopsbench.platform.topology.topology_utils import clab_container_name +from netopsbench.platform.utils.control import OperationControl, current_operation_control +from netopsbench.platform.utils.proc import docker_prefix, safe_run + +_NETWORK_PROBE_SOURCE = Path(__file__).with_name("_routing_probe.py").read_text(encoding="utf-8") + + +def next_hops(route): + return route.get("nexthops") or ( + [{"gateway": route.get("gateway"), "dev": route.get("dev")}] if route.get("gateway") or route.get("dev") else [] + ) + + +def verify_route_recovery(baseline, recovery): + """Require complete observed BGP forwarding, using an existing node snapshot.""" + if baseline is None: + return [] + errors = [] + for device, before in baseline["nodes"].items(): + after = recovery.get("nodes", {}).get(device, {}) + if after.get("error") or "fib" not in after: + errors.append(f"{device}: missing recovery FIB") + continue + old = {r.get("dst"): r for r in before.get("fib", []) if r.get("protocol") == "bgp"} + current = {r.get("dst"): r for r in after["fib"]} + before_static = { + ( + r.get("dst"), + r.get("protocol"), + r.get("type", "unicast"), + tuple(sorted((h.get("gateway") or "", h.get("dev") or "") for h in next_hops(r))), + ) + for r in before.get("fib", []) + if r.get("protocol") == "static" or r.get("type") in {"blackhole", "unreachable", "prohibit"} + } + for route in after["fib"]: + if route.get("protocol") == "static" or route.get("type") in {"blackhole", "unreachable", "prohibit"}: + identity = ( + route.get("dst"), + route.get("protocol"), + route.get("type", "unicast"), + tuple(sorted((h.get("gateway") or "", h.get("dev") or "") for h in next_hops(route))), + ) + if identity not in before_static and route.get("dst") not in old: + errors.append(f"{device}/{route.get('dst')}: unexpected residual static/drop route") + for prefix, route in old.items(): + restored = current.get(prefix) + expected_hops = {(hop.get("gateway"), hop.get("dev")) for hop in next_hops(route)} + restored_hops = {(hop.get("gateway"), hop.get("dev")) for hop in next_hops(restored or {})} + if not restored or restored.get("protocol") != "bgp" or restored_hops != expected_hops: + errors.append(f"{device}/{prefix}: forwarding not restored") + return errors + + +def collect_routes(manifest, *, cancel_event=None, deadline=None): + inherited = current_operation_control() + if inherited is not None and inherited.deadline is not None: + deadline = min(deadline, inherited.deadline) if deadline is not None else inherited.deadline + control = OperationControl(cancel_event, deadline if deadline is not None else time.monotonic() + 60) + nodes = {} + + def probe(device): + control.remaining() + container = clab_container_name(manifest.name, device.name) + result = safe_run( + [ + *docker_prefix(), + "docker", + "exec", + container, + "python3", + "-c", + _NETWORK_PROBE_SOURCE, + "--routes-only", + "--budget-seconds", + str(control.remaining(60)), + ], + timeout=control.remaining(60), + control=control, + ) + if result.returncode: + return device.name, { + "error": result.stderr or "Node snapshot failed", + "collected_at": datetime.now(UTC).isoformat(), + } + payload = json.loads(result.stdout) + checks = payload["checks"] + fib = checks["fib"] + if fib["returncode"]: + return device.name, {"error": "FIB collection failed", "collected_at": datetime.now(UTC).isoformat()} + bgp_ok = checks["bgp"]["returncode"] == 0 + try: + bgp = parse_bgp_summary(checks["bgp"]["stdout"], strict=True) + except ValueError: + bgp, bgp_ok = [], False + return device.name, { + "packet_counters": payload.get("packet_counters", {"error": "Not collected"}), + "fib": json.loads(fib["stdout"]), + "bgp": bgp, + "bgp_collection_ok": bgp_ok, + "interfaces": checks.get("interfaces", {}).get("stdout", ""), + "collected_at": datetime.now(UTC).isoformat(), + } + + pool = ThreadPoolExecutor(max_workers=min(16, len(manifest.switches()))) + futures = [] + try: + for device in manifest.switches(): + control.remaining() + futures.append(pool.submit(copy_context().run, probe, device)) + for future in futures: + name, row = future.result(timeout=control.remaining()) + nodes[name] = row + finally: + pool.shutdown(wait=True, cancel_futures=True) + return {"nodes": nodes, "collected_at": datetime.now(UTC).isoformat()} diff --git a/netopsbench/platform/observability/validation.py b/netopsbench/platform/observability/validation.py index e11c599..0cd5f36 100644 --- a/netopsbench/platform/observability/validation.py +++ b/netopsbench/platform/observability/validation.py @@ -90,27 +90,33 @@ def check_observability( active_interfaces: Sequence[str] | None = None, min_active_coverage_ratio: float = 0.5, require_pingmesh: bool = True, + checks: set[str] | None = None, + plan_id: str = "", ) -> list[str]: """Run Pingmesh, interface, and syslog path checks.""" + selected = checks if checks is not None else {"pingmesh", "bgp", "interfaces", "syslog"} + if selected - {"pingmesh", "bgp", "interfaces", "syslog"}: + raise ValueError("Unknown observability check") errors: list[str] = [] active = [item for item in active_interfaces or [] if item] topology_filter = _topology_filter(topology_id) - if require_pingmesh: + if require_pingmesh and "pingmesh" in selected: pingmesh_query = ( f'from(bucket: "{bucket}")\n' f" |> range(start: -10m)\n" f' |> filter(fn: (r) => r._measurement == "pingmesh")\n' f"{topology_filter}" - f' |> filter(fn: (r) => r._field == "rtt_p99")\n' - f" |> last()\n" - f" |> group()\n" - f" |> limit(n: 1)\n" + + (f' |> filter(fn: (r) => r.plan_id == "{plan_id}")\n' if plan_id else "") + + ' |> filter(fn: (r) => r._field == "rtt_p99")\n' + " |> last()\n" + " |> group()\n" + " |> limit(n: 1)\n" ) if count_data_rows(query_runner(pingmesh_query)) <= 0: errors.append("no recent pingmesh samples found in InfluxDB") - if bgp_device: + if bgp_device and "bgp" in selected: bgp_query = ( f'from(bucket: "{bucket}")\n' f" |> range(start: -10m)\n" @@ -125,39 +131,40 @@ def check_observability( if count_data_rows(query_runner(bgp_query)) <= 0: errors.append(f"no recent bgp neighbor samples found for {bgp_device} in InfluxDB") - interface_identity_query = ( - f'from(bucket: "{bucket}")\n' - f" |> range(start: -10m)\n" - f' |> filter(fn: (r) => r._measurement == "interfaces")\n' - f"{topology_filter}" - f' |> filter(fn: (r) => r.source == "{obs_device}")\n' - f"{_interface_counter_field_filter()}" - f' |> group(columns: ["name", "path", "_field"])\n' - f" |> last()\n" - f' |> keep(columns: ["_time", "_field", "_value", "name", "path"])\n' - ) - interface_rows = query_runner(interface_identity_query) - if count_data_rows(interface_rows) <= 0: - errors.append(f"no recent interface samples found for {obs_device} in InfluxDB") - else: - observed_interfaces = extract_interface_names(interface_rows) - if active: - observed_active = [name for name in active if name in observed_interfaces] - coverage = len(observed_active) / len(active) - if not observed_active: - errors.append( - f"no recent interface samples found for active interfaces on {obs_device}; " - f"active={preview(active)} observed={preview(observed_interfaces)}" - ) - elif coverage < min_active_coverage_ratio: - missing_active = [name for name in active if name not in observed_interfaces] - errors.append( - f"active interface observability coverage too low on {obs_device}: " - f"{len(observed_active)}/{len(active)} observed; " - f"missing={preview(missing_active)} observed={preview(observed_interfaces)}" - ) - - if syslog_marker: + if "interfaces" in selected: + interface_identity_query = ( + f'from(bucket: "{bucket}")\n' + f" |> range(start: -10m)\n" + f' |> filter(fn: (r) => r._measurement == "interfaces")\n' + f"{topology_filter}" + f' |> filter(fn: (r) => r.source == "{obs_device}")\n' + f"{_interface_counter_field_filter()}" + f' |> group(columns: ["name", "path", "_field"])\n' + f" |> last()\n" + f' |> keep(columns: ["_time", "_field", "_value", "name", "path"])\n' + ) + interface_rows = query_runner(interface_identity_query) + if count_data_rows(interface_rows) <= 0: + errors.append(f"no recent interface samples found for {obs_device} in InfluxDB") + else: + observed_interfaces = extract_interface_names(interface_rows) + if active: + observed_active = [name for name in active if name in observed_interfaces] + coverage = len(observed_active) / len(active) + if not observed_active: + errors.append( + f"no recent interface samples found for active interfaces on {obs_device}; " + f"active={preview(active)} observed={preview(observed_interfaces)}" + ) + elif coverage < min_active_coverage_ratio: + missing_active = [name for name in active if name not in observed_interfaces] + errors.append( + f"active interface observability coverage too low on {obs_device}: " + f"{len(observed_active)}/{len(active)} observed; " + f"missing={preview(missing_active)} observed={preview(observed_interfaces)}" + ) + + if syslog_marker and "syslog" in selected: syslog_query = ( 'import "strings"\n' f'from(bucket: "{bucket}")\n' diff --git a/netopsbench/platform/pingmesh/_detector_analysis.py b/netopsbench/platform/pingmesh/_detector_analysis.py index e4bbe4b..1bbd29a 100644 --- a/netopsbench/platform/pingmesh/_detector_analysis.py +++ b/netopsbench/platform/pingmesh/_detector_analysis.py @@ -28,6 +28,29 @@ def _as_float(value, default: float = 0.0) -> float: return default +def probe_pair_evidence(baseline_rows: list[dict], current_rows: list[dict], pairs: list[dict]) -> list[dict]: + """Reuse queried snapshots for a bounded private effect audit, without extra reads.""" + selected = {(pair["src"], pair["dst"]) for pair in pairs} + evidence = {pair: {"src": pair[0], "dst": pair[1]} for pair in selected} + for phase, rows in (("baseline", baseline_rows), ("fault", current_rows)): + grouped: dict[tuple[str, str], list[dict]] = {pair: [] for pair in selected} + for row in rows: + key = row.get("src_name"), row.get("dst_name") + if key in grouped: + grouped[key].append(row) + for pair, points in grouped.items(): + rtts = [_as_float(row.get("rtt_avg")) for row in points if _as_float(row.get("rtt_avg")) > 0] + evidence[pair][phase] = { + "samples": len(points), + "rtt_median_ms": statistics.median(rtts) if rtts else None, + "rtt_max_ms": max((_as_float(row.get("rtt_max")) for row in points), default=None), + "local_probe_errors": sum(int(_as_float(row.get("local_probe_errors"))) for row in points), + "regular": _loss_stats(points), + "df": _loss_stats(points, prefix="df_"), + } + return [evidence[pair] for pair in sorted(evidence)] + + def _group_by_path(rows: list[dict]) -> dict[tuple[str, str], list[dict]]: paths: dict[tuple[str, str], list[dict]] = {} for row in rows: @@ -151,9 +174,10 @@ def _new_anomaly( sample_count=sample_count, ) - def _detect_latency_from_rows(self, baseline_rows: list[dict], current_rows: list[dict]) -> list: - baseline_paths = _group_by_path(baseline_rows) - current_paths = _group_by_path(current_rows) + def _detect_latency_from_rows(self, baseline_rows: list[dict], current_rows: list[dict], *, _paths=None) -> list: + baseline_paths, current_paths = ( + _paths if _paths is not None else (_group_by_path(baseline_rows), _group_by_path(current_rows)) + ) anomalies = [] for path_key, current_points in current_paths.items(): baseline_points = baseline_paths.get(path_key, []) @@ -181,9 +205,12 @@ def _detect_latency_from_rows(self, baseline_rows: list[dict], current_rows: lis ) return anomalies - def _detect_loss_from_rows(self, baseline_rows: list[dict], current_rows: list[dict]) -> tuple[list, int]: - baseline_paths = _group_by_path(baseline_rows) - current_paths = _group_by_path(current_rows) + def _detect_loss_from_rows( + self, baseline_rows: list[dict], current_rows: list[dict], *, _paths=None + ) -> tuple[list, int]: + baseline_paths, current_paths = ( + _paths if _paths is not None else (_group_by_path(baseline_rows), _group_by_path(current_rows)) + ) anomalies = [] insufficient_baseline = 0 for path_key, current_points in current_paths.items(): @@ -224,9 +251,12 @@ def _detect_loss_from_rows(self, baseline_rows: list[dict], current_rows: list[d ) return anomalies, insufficient_baseline - def _detect_df_from_rows(self, baseline_rows: list[dict], current_rows: list[dict]) -> list: - baseline_batches = _group_by_path_port_batch(baseline_rows) - current_batches = _group_by_path_port_batch(current_rows) + def _detect_df_from_rows(self, baseline_rows: list[dict], current_rows: list[dict], *, _batches=None) -> list: + baseline_batches, current_batches = ( + _batches + if _batches is not None + else (_group_by_path_port_batch(baseline_rows), _group_by_path_port_batch(current_rows)) + ) anomalies_by_path: dict[tuple[str, str], Any] = {} for batch_key, current_points in current_batches.items(): baseline_points = baseline_batches.get(batch_key, []) @@ -262,14 +292,19 @@ def _detect_df_from_rows(self, baseline_rows: list[dict], current_rows: list[dic return list(anomalies_by_path.values()) def analyze_snapshot_rows(self, baseline_rows: list[dict], current_rows: list[dict]) -> SnapshotAnalysis: - loss_anomalies, insufficient_baseline = self._detect_loss_from_rows(baseline_rows, current_rows) + # These indexes are local to this analysis: no stale cross-window data, + # and all detectors retain the same row ordering and sample population. + baseline_paths = _group_by_path(baseline_rows) + current_paths = _group_by_path(current_rows) + paths = (baseline_paths, current_paths) + baseline_batches = _group_by_path_port_batch(baseline_rows) + current_batches = _group_by_path_port_batch(current_rows) + loss_anomalies, insufficient_baseline = self._detect_loss_from_rows(baseline_rows, current_rows, _paths=paths) anomalies = [ - *self._detect_latency_from_rows(baseline_rows, current_rows), + *self._detect_latency_from_rows(baseline_rows, current_rows, _paths=paths), *loss_anomalies, - *self._detect_df_from_rows(baseline_rows, current_rows), + *self._detect_df_from_rows(baseline_rows, current_rows, _batches=(baseline_batches, current_batches)), ] - baseline_paths = _group_by_path(baseline_rows) - current_paths = _group_by_path(current_rows) absolute_unreachable_paths = 0 absolute_loss_paths = 0 absolute_mtu_paths: set[tuple[str, str]] = set() @@ -282,7 +317,7 @@ def analyze_snapshot_rows(self, baseline_rows: list[dict], current_rows: list[di elif regular["loss_pct"] >= self.loss_pct_threshold and regular["lost"] >= _MIN_PATH_LOST_PROBES: absolute_loss_paths += 1 - for batch_key, current_points in _group_by_path_port_batch(current_rows).items(): + for batch_key, current_points in current_batches.items(): regular = _loss_stats(current_points) df = _loss_stats(current_points, prefix="df_") if ( diff --git a/netopsbench/platform/pingmesh/_detector_coverage.py b/netopsbench/platform/pingmesh/_detector_coverage.py index cf2f747..2f750eb 100644 --- a/netopsbench/platform/pingmesh/_detector_coverage.py +++ b/netopsbench/platform/pingmesh/_detector_coverage.py @@ -1,123 +1,147 @@ -"""Coverage quality audit for bounded Pingmesh destination rotation.""" +"""Audit observations against the exact immutable offline probe plan.""" from __future__ import annotations from collections import Counter -from math import ceil class DetectorCoverageMixin: - """Audit schedule coverage without consulting fault targets.""" - - _pingmesh_clients: list[str] - _pingmesh_policy: dict + def _compile_coverage_expectations(self) -> None: + self._expected_combinations = set() + self._expected_frames = {} + self._expected_destinations = set() + for client in self._pingmesh_plan.clients: + for cycle, frame in enumerate(client.frames): + names = {client.targets[index] for index in frame.target_indices} + self._expected_frames[client.name, cycle] = ( + frame.destination_batch_index, + frame.port_batch_index, + names, + ) + self._expected_combinations.update((client.name, name, frame.port_batch_index) for name in names) + if names: + self._expected_destinations.add(frame.destination_batch_index) def summarize_coverage(self, rows: list[dict]) -> dict: - client_count = len(self._pingmesh_clients) - policy = self._pingmesh_policy - required_policy_fields = { - "destination_batch_size", - "rtt_port_pool_size", - "rtt_ports_per_cycle", - "coverage_epoch_cycles", - } - missing_policy_fields = sorted(required_policy_fields - set(policy)) - if missing_policy_fields: - return { - "status": "error", - "coverage_status": "error", - "error": "Pingmesh coverage policy is missing fields: " + ", ".join(missing_policy_fields), - } - destination_count = max(0, client_count - 1) - destination_batch_size = policy["destination_batch_size"] or max(1, destination_count) - port_pool_size = int(policy["rtt_port_pool_size"]) - ports_per_cycle = int(policy["rtt_ports_per_cycle"]) - expected_destination_batches = max(1, ceil(destination_count / destination_batch_size)) - expected_port_batches = max(1, ceil(port_pool_size / ports_per_cycle)) - expected_cycles = int(policy["coverage_epoch_cycles"]) - if expected_cycles != expected_destination_batches * expected_port_batches: - return { - "status": "error", - "coverage_status": "error", - "error": "Pingmesh coverage policy is missing or stale; regenerate the topology", - } - - cycle_rows = [row for row in rows if row.get("probe_cycle") is not None] - cycles = {int(row["probe_cycle"]) for row in cycle_rows} - destination_batches = { - int(row["destination_batch_index"]) for row in rows if row.get("destination_batch_index") is not None - } - port_batches = {int(row["port_batch_index"]) for row in rows if row.get("port_batch_index") is not None} - sources = {row.get("src_name") for row in cycle_rows if row.get("src_name")} - cycles_by_source: dict[str, set[int]] = {} - for row in cycle_rows: - source = row.get("src_name") - if source: - cycles_by_source.setdefault(source, set()).add(int(row["probe_cycle"])) - pair_counts = Counter( - (row.get("src_name"), row.get("dst_name")) - for row in cycle_rows - if row.get("src_name") and row.get("dst_name") - ) - pair_port_counts = Counter( - (row.get("src_name"), row.get("dst_name"), int(row["port_batch_index"])) - for row in cycle_rows - if row.get("src_name") and row.get("dst_name") and row.get("port_batch_index") is not None - ) - observed_cycle_span = max(cycles) - min(cycles) + 1 if cycles else 0 - source_cycle_spans = [ - max(source_cycles) - min(source_cycles) + 1 for source_cycles in cycles_by_source.values() if source_cycles - ] - min_source_cycle_span = min(source_cycle_spans, default=0) - missing_destination_batches = sorted(set(range(expected_destination_batches)) - destination_batches) - missing_port_batches = sorted(set(range(expected_port_batches)) - port_batches) - missing_sources = max(0, client_count - len(sources)) - regular_loss_by_socket_batch = _regular_loss_by_socket_batch(cycle_rows) - invalid_socket_rows = sum( - 1 - for row in cycle_rows + plan = self._pingmesh_plan + settings = plan.settings + expected = self._expected_combinations + valid = [] + invalid_rows = [] + invalid_tasks = set() + invalid_socket_rows = unexpected_rows = 0 + incomplete_record_rows = 0 + unexpected_records = [] + for row in rows: + if any( + row.get(key) in (None, "") + for key in ( + "plan_id", + "src_name", + "dst_name", + "probe_cycle", + "destination_batch_index", + "port_batch_index", + "rtt_ports_active", + "rtt_ports_total", + "local_probe_errors", + ) + ): + incomplete_record_rows += 1 + cycle = _field_int(row, "probe_cycle") + source, destination = row.get("src_name"), row.get("dst_name") + frame = ( + self._expected_frames.get((source, cycle % settings.coverage_epoch_cycles)) + if cycle is not None and cycle >= 0 + else None + ) + if ( + row.get("plan_id") != settings.plan_id + or frame is None + or _field_int(row, "destination_batch_index") != frame[0] + or _field_int(row, "port_batch_index") != frame[1] + or destination not in frame[2] + ): + unexpected_rows += 1 + if len(unexpected_records) < 20: + unexpected_records.append( + { + key: row.get(key) + for key in ( + "_time", + "src_name", + "dst_name", + "plan_id", + "probe_cycle", + "destination_batch_index", + "port_batch_index", + ) + } + ) + continue if not _has_valid_socket_batch( row, - port_pool_size=port_pool_size, - ports_per_cycle=ports_per_cycle, - port_batch_count=expected_port_batches, - regular_loss_by_socket_batch=regular_loss_by_socket_batch, - ) - ) - expected_pairs = client_count * destination_count - expected_pair_port_combinations = expected_pairs * expected_port_batches - complete = bool( - not missing_destination_batches - and not missing_port_batches - and missing_sources == 0 - and len(pair_counts) == expected_pairs - and len(pair_port_counts) == expected_pair_port_combinations - and invalid_socket_rows == 0 - ) - + source_ports=settings.source_ports, + port_batches=settings.port_batches, + ): + invalid_socket_rows += 1 + invalid_tasks.add((source, destination, frame[1])) + invalid_rows.append( + { + "src": source, + "dst": destination, + "port_batch_index": frame[1], + "probe_cycle": cycle, + "time": str(row.get("_time") or row.get("time") or ""), + "local_probe_errors": _field_int(row, "local_probe_errors"), + "socket_batch_valid": _has_expected_socket_batch( + row, source_ports=settings.source_ports, port_batches=settings.port_batches + ), + } + ) + continue + valid.append(row) + combinations = Counter((row["src_name"], row["dst_name"], int(row["port_batch_index"])) for row in valid) + pairs = Counter((row["src_name"], row["dst_name"]) for row in valid) + missing = expected - combinations.keys() + sources = {row["src_name"] for row in valid} + cycles_by_source = {} + for row in valid: + cycles_by_source.setdefault(row["src_name"], set()).add(int(row["probe_cycle"])) + cycles = {int(row["probe_cycle"]) for row in valid} + ports = {int(row["port_batch_index"]) for row in valid} + destinations = {int(row["destination_batch_index"]) for row in valid} + complete = not missing and not unexpected_rows and not invalid_socket_rows return { "status": "ok", + "plan_id": settings.plan_id, "coverage_status": "complete" if complete else "incomplete", - "expected_epoch_cycles": expected_cycles, - "observed_cycle_span": observed_cycle_span, - "min_source_cycle_span": min_source_cycle_span, - "source_clients_observed": len(sources), - "expected_source_clients": client_count, - "destination_pairs_observed": len(pair_counts), - "expected_destination_pairs": expected_pairs, - "pair_port_combinations_observed": len(pair_port_counts), - "expected_pair_port_combinations": expected_pair_port_combinations, - "missing_pair_port_combinations": max( - 0, - expected_pair_port_combinations - len(pair_port_counts), + "expected_epoch_cycles": settings.coverage_epoch_cycles, + "observed_cycle_span": max(cycles) - min(cycles) + 1 if cycles else 0, + "min_source_cycle_span": min( + (max(values) - min(values) + 1 for values in cycles_by_source.values()), default=0 ), - "min_samples_per_pair": min(pair_counts.values(), default=0), - "port_batches_observed": sorted(port_batches), - "destination_batches_observed": sorted(destination_batches), - "missing_port_batches": missing_port_batches, - "missing_destination_batches": missing_destination_batches, - "missing_source_clients": missing_sources, + "source_clients_observed": len(sources), + "expected_source_clients": len(plan.clients), + "destination_pairs_observed": len(pairs), + "expected_destination_pairs": plan.directed_pair_count, + "pair_port_combinations_observed": len(combinations), + "expected_pair_port_combinations": len(expected), + "missing_pair_port_combinations": len(missing), + "missing_tasks": sorted(missing), + "invalid_tasks": sorted(invalid_tasks), + "invalid_rows": invalid_rows, + "observable_pairs": sorted(pairs), + "min_samples_per_pair": min(pairs.values(), default=0), + "port_batches_observed": sorted(ports), + "destination_batches_observed": sorted(destinations), + "missing_port_batches": sorted(set(range(len(settings.port_batches))) - ports), + "missing_destination_batches": sorted(self._expected_destinations - destinations), + "missing_source_clients": len(plan.clients) - len(sources), "invalid_socket_rows": invalid_socket_rows, + "unexpected_rows": unexpected_rows, + "incomplete_record_rows": incomplete_record_rows, + "unexpected_records": unexpected_records, } @@ -128,28 +152,18 @@ def _field_int(row: dict, field: str) -> int | None: return None -def _has_valid_socket_batch( - row: dict, - *, - port_pool_size: int, - ports_per_cycle: int, - port_batch_count: int, - regular_loss_by_socket_batch: dict[tuple[str, str, int], int], -) -> bool: - port_batch_index = _field_int(row, "port_batch_index") - if port_batch_index is None or not 0 <= port_batch_index < port_batch_count: +def _has_valid_socket_batch(row, *, source_ports, port_batches) -> bool: + return _has_expected_socket_batch(row, source_ports=source_ports, port_batches=port_batches) and ( + _field_int(row, "local_probe_errors") == 0 + ) + + +def _has_expected_socket_batch(row, *, source_ports, port_batches) -> bool: + port_batch = _field_int(row, "port_batch_index") + if port_batch is None or not 0 <= port_batch < len(port_batches): return False - expected_active = min(ports_per_cycle, port_pool_size - port_batch_index * ports_per_cycle) - return ( - _field_int(row, "rtt_ports_total") == port_pool_size - and _field_int(row, "rtt_ports_active") == expected_active - and ( - _field_int(row, "local_probe_errors") == 0 - or is_explained_df_send_error( - row, - regular_loss_by_socket_batch=regular_loss_by_socket_batch, - ) - ) + return _field_int(row, "rtt_ports_total") == len(source_ports) and _field_int(row, "rtt_ports_active") == len( + port_batches[port_batch] ) diff --git a/netopsbench/platform/pingmesh/_detector_ingestion.py b/netopsbench/platform/pingmesh/_detector_ingestion.py new file mode 100644 index 0000000..4b07779 --- /dev/null +++ b/netopsbench/platform/pingmesh/_detector_ingestion.py @@ -0,0 +1,274 @@ +"""Close fixed observation intervals using existing ordered probe frames. + +Boundary rows are evidence only: they never enter the statistical window. +No successful packet delivery is required to prove that a row was ingested. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import time +from collections import defaultdict +from datetime import UTC, datetime, timedelta + +from netopsbench.platform.utils.control import OperationControl, current_operation_control +from netopsbench.platform.utils.measurements import count_operation + +from ._detector_query import _SNAPSHOT_FIELDS, SnapshotQueryResult + +_PROGRESS_FIELDS = ("probe_cycle", "destination_batch_index", "port_batch_index") +_PROGRESS_KEYS = (*_PROGRESS_FIELDS, "plan_id", "_time", "src_name", "dst_name") + + +def _time(value: str) -> datetime: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + if parsed.tzinfo is None: + raise ValueError("Pingmesh timestamps must include a timezone") + return parsed + + +def _iso(value: datetime) -> str: + return value.isoformat().replace("+00:00", "Z") + + +def _integer(row, key): + value = float(row[key]) + if not math.isfinite(value) or not value.is_integer() or value < 0: + raise ValueError(f"invalid {key}") + return int(value) + + +def _key(row): + return row["src_name"], _integer(row, "probe_cycle"), row["dst_name"], row["_time"] + + +class DetectorIngestionMixin: + def _ingestion_control(self, deadline): + inherited = current_operation_control() + limits = [value for value in (deadline, inherited.deadline if inherited else None) if value is not None] + return OperationControl( + inherited.cancel_event if inherited else None, + min(limits) if limits else time.monotonic() + 60, + ) + + def _boundary_padding_seconds(self): + longest = 0 + for client in self._pingmesh_plan.clients: + run = 0 + for frame in [*client.frames, *client.frames]: + run = run + 1 if not frame.target_indices else 0 + longest = max(longest, min(run, len(client.frames))) + return (longest + 2) * self._pingmesh_plan.settings.cycle_interval_seconds + + def _progress_frames(self, rows): + """Validate frame identities, retaining local failures as real records.""" + frames = defaultdict(dict) + for row in rows: + source, cycle, destination, timestamp = _key(row) + _time(timestamp) + expected = self._expected_frames.get((source, cycle % self._pingmesh_plan.settings.coverage_epoch_cycles)) + if ( + row.get("plan_id") != self.plan_id + or expected is None + or destination not in expected[2] + or _integer(row, "destination_batch_index") != expected[0] + or _integer(row, "port_batch_index") != expected[1] + ): + raise ValueError("unexpected frame identity, peer or port batch") + addresses = getattr(self, "_client_addresses", {}) + if any( + addresses.get(row.get(f"{side}_name")) not in (None, row.get(f"{side}_ip")) for side in ("src", "dst") + ): + raise ValueError("client address does not match the manifest") + previous = frames[source, cycle].get(destination) + if previous is not None and previous["_time"] != timestamp: + raise ValueError("repeated cycle/peer at a different timestamp; possible source restart") + frames[source, cycle][destination] = row + return frames + + def audit_ingestion(self, progress_rows, snapshot_rows, start_time, end_time): + """Prove all nonempty frames between two observed boundaries are present.""" + start, end = _time(start_time), _time(end_time) + pending = [] + expected_rows = set() + try: + complete_progress = [ + row for row in progress_rows if all(row.get(key) not in (None, "") for key in _PROGRESS_KEYS) + ] + if any( + not all(row.get(key) not in (None, "") for key in _PROGRESS_KEYS) and start <= _time(row["_time"]) < end + for row in progress_rows + ): + pending.append("progress: missing required fields") + frames = self._progress_frames(complete_progress) + by_source = defaultdict(list) + for (source, cycle), targets in frames.items(): + by_source[source].extend((_time(row["_time"]), cycle) for row in targets.values()) + for source in self._pingmesh_clients: + ordered = sorted(by_source[source]) + if any(after[1] < before[1] for before, after in zip(ordered, ordered[1:], strict=False)): + raise ValueError(f"{source}: cycle/time order conflict; possible source restart or clock reversal") + before = [cycle for stamp, cycle in ordered if stamp < start] + after = [cycle for stamp, cycle in ordered if stamp >= end] + if not before or not after: + pending.append(f"{source}: missing {'preceding' if not before else 'following'} boundary") + continue + left, right = max(before), min(after) + for cycle in range(left, right + 1): + expected = self._expected_frames[source, cycle % self._pingmesh_plan.settings.coverage_epoch_cycles] + targets = frames.get((source, cycle), {}) + if set(targets) != expected[2]: + pending.append(f"{source}/{cycle}: missing frame targets") + expected_rows.update(_key(row) for row in targets.values() if start <= _time(row["_time"]) < end) + actual = {} + for row in snapshot_rows: + # A missing field can be an incompletely flushed pivot row. + if any( + row.get(field) in (None, "") + for field in (*_SNAPSHOT_FIELDS, "plan_id", "_time", "src_name", "dst_name") + ): + pending.append("snapshot: missing required fields") + continue + if any(not math.isfinite(float(row[field])) for field in _SNAPSHOT_FIELDS): + raise ValueError("snapshot contains a non-finite metric") + key = _key(row) + if key in actual and actual[key] != row: + raise ValueError("conflicting duplicate snapshot record") + actual[key] = row + if set(actual) != expected_rows: + pending.append("snapshot and frame records do not match") + # Validate complete snapshot rows independently of progress-query arrival order. + self._progress_frames(list(actual.values())) + except (KeyError, TypeError, ValueError, OverflowError) as exc: + return {"status": "invalid", "error": str(exc)} + return { + "status": "pending" if pending else "ready", + "expected_records": len(expected_rows), + "observed_records": len(actual), + "reasons": pending[:20], + **( + { + "records_sha256": hashlib.sha256( + json.dumps( + [ + [*key, *[float(actual[key][field]) for field in _SNAPSHOT_FIELDS]] + for key in sorted(actual) + ], + separators=(",", ":"), + ).encode() + ).hexdigest() + } + if not pending + else {} + ), + } + + def _query_covered_snapshot(self, start_time, end_time, *, deadline=None): + control = self._ingestion_control(deadline) + started = time.monotonic() + start, end = _time(start_time), _time(end_time) + if end <= start: + raise ValueError("Pingmesh window must have positive duration") + padding = self._boundary_padding_seconds() + runtime_start = getattr(self, "runtime_start_time", None) + floor = ( + _time(runtime_start) + if runtime_start + else start - timedelta(seconds=self._pingmesh_plan.settings.coverage_epoch_seconds + padding) + ) + retries = 0 + coverage = {} + ingestion = {"status": "pending"} + query_seconds = 0.0 + wait_seconds = 0.0 + request_count = 0 + try: + while True: + control.remaining() + context_start = max(floor, start - timedelta(seconds=padding)) + context_end = min(datetime.now(UTC), end + timedelta(seconds=padding)) + tick = time.monotonic() + try: + context = self._query_snapshot(_iso(context_start), _iso(context_end), deadline=control.deadline) + request_count += context.request_count + finally: + query_seconds += time.monotonic() - tick + control.remaining() + if context.status != "ok": + raise RuntimeError(context.error or "snapshot query failed") + # One fresh read supplies both frame boundaries and metrics. + # Context outside [start, end) is never used in anomaly statistics. + snapshot = SnapshotQueryResult( + status="ok", + rows=self._slice_rows(context.rows, start_time, end_time), + request_count=context.request_count, + ) + coverage = self.summarize_coverage(snapshot.rows) + ingestion = self.audit_ingestion(context.rows, snapshot.rows, start_time, end_time) + control.remaining() + ingestion["elapsed_seconds"] = time.monotonic() - started + ingestion["query_seconds"] = query_seconds + ingestion["wait_seconds"] = wait_seconds + ingestion["query_requests"] = request_count + ingestion["verification_seconds"] = max( + 0.0, ingestion["elapsed_seconds"] - query_seconds - wait_seconds + ) + coverage.update(ingestion=ingestion, query_retries=retries) + if ingestion["status"] == "ready": + return snapshot, coverage + if ingestion["status"] == "invalid": + raise RuntimeError(ingestion["error"]) + if any("boundary" in reason for reason in ingestion["reasons"]): + padding = min(padding * 2, max(padding, (datetime.now(UTC) - floor).total_seconds() + 1)) + tick = time.monotonic() + try: + control.sleep(self._pingmesh_plan.settings.cycle_interval_seconds) + finally: + wait_seconds += time.monotonic() - tick + retries += 1 + count_operation("ingestion_retries") + except (TimeoutError, RuntimeError) as exc: + ingestion = { + **ingestion, + "status": "invalid" if ingestion["status"] == "invalid" else "not_ready", + "error": str(exc), + "elapsed_seconds": time.monotonic() - started, + "query_seconds": query_seconds, + "wait_seconds": wait_seconds, + "query_requests": request_count, + } + coverage.update(ingestion=ingestion, query_retries=retries) + return SnapshotQueryResult(status="error", rows=[], error=f"Window ingestion: {exc}"), coverage + + def wait_for_history(self, *, deadline): + """Establish preceding frames before the first fresh baseline starts.""" + control = self._ingestion_control(deadline) + padding = self._boundary_padding_seconds() + while True: + control.remaining() + now = datetime.now(UTC) + runtime_start = getattr(self, "runtime_start_time", None) + floor = _time(runtime_start) if runtime_start else now - timedelta(seconds=padding) + result = self._query_snapshot( + _iso(max(floor, now - timedelta(seconds=padding))), + _iso(now), + deadline=control.deadline, + fields=_PROGRESS_FIELDS, + ) + if result.status != "ok": + raise RuntimeError(result.error or "Pingmesh history query failed") + frames = self._progress_frames( + [row for row in result.rows if all(row.get(key) not in (None, "") for key in _PROGRESS_KEYS)] + ) + ready = { + source + for (source, cycle), targets in frames.items() + if set(targets) + == self._expected_frames[source, cycle % self._pingmesh_plan.settings.coverage_epoch_cycles][2] + } + if ready == set(self._pingmesh_clients): + return + padding = min(padding * 2, max(padding, (now - floor).total_seconds() + 1)) + control.sleep(self._pingmesh_plan.settings.cycle_interval_seconds) diff --git a/netopsbench/platform/pingmesh/_detector_query.py b/netopsbench/platform/pingmesh/_detector_query.py index 6993b22..4a9117f 100644 --- a/netopsbench/platform/pingmesh/_detector_query.py +++ b/netopsbench/platform/pingmesh/_detector_query.py @@ -2,12 +2,12 @@ from __future__ import annotations -import csv +import time from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context from dataclasses import dataclass -from io import StringIO -from netopsbench.platform.observability.influxdb import query_flux +from netopsbench.platform.observability.influxdb import iter_annotated_csv_rows, query_flux _SNAPSHOT_FIELDS = ( "rtt_min", @@ -35,6 +35,7 @@ class SnapshotQueryResult: status: str rows: list[dict] error: str | None = None + request_count: int = 0 class DetectorQueryMixin: @@ -52,11 +53,8 @@ def _safe_flux_string(value: str) -> str: @staticmethod def _parse_snapshot_csv(text: str) -> list[dict]: - data_lines = [line for line in text.splitlines() if line and not line.startswith("#")] - if not data_lines: - return [] rows = [] - for row in csv.DictReader(StringIO("\n".join(data_lines))): + for row in iter_annotated_csv_rows(text): if row.get("_time") in (None, "", "_time"): continue parsed = {key: value for key, value in row.items() if key and value not in (None, "")} @@ -75,11 +73,16 @@ def _query_snapshot_shard( start_time: str, end_time: str, source_names: list[str], + *, + deadline: float | None = None, + fields: tuple[str, ...] | None = None, ) -> SnapshotQueryResult: + if deadline is not None and time.monotonic() >= deadline: + return SnapshotQueryResult(status="error", rows=[], error="snapshot query deadline exceeded") bucket = self._safe_flux_string(self.bucket) start = self._safe_flux_string(start_time) end = self._safe_flux_string(end_time) - fields = " or ".join(f'r._field == "{field}"' for field in _SNAPSHOT_FIELDS) + field_filter = " or ".join(f'r._field == "{field}"' for field in (fields or _SNAPSHOT_FIELDS)) source_filter = "" if source_names: predicates = " or ".join(f'r.src_name == "{self._safe_flux_string(source)}"' for source in source_names) @@ -90,11 +93,11 @@ def _query_snapshot_shard( ' |> filter(fn: (r) => r._measurement == "pingmesh")\n' + self._topology_filter() + source_filter - + f" |> filter(fn: (r) => {fields})\n" + + f" |> filter(fn: (r) => {field_filter})\n" ' |> keep(columns: ["_time", "_field", "_value", "src_ip", "dst_ip", ' - '"src_name", "dst_name", "src_leaf", "dst_leaf", "path_type"])\n' + '"src_name", "dst_name", "src_leaf", "dst_leaf", "path_type", "plan_id"])\n' ' |> pivot(rowKey: ["_time", "src_ip", "dst_ip", "src_name", "dst_name", ' - '"src_leaf", "dst_leaf", "path_type"], columnKey: ["_field"], valueColumn: "_value")\n' + '"src_leaf", "dst_leaf", "path_type", "plan_id"], columnKey: ["_field"], valueColumn: "_value")\n' ) result = query_flux( self.influxdb_url, @@ -102,37 +105,46 @@ def _query_snapshot_shard( self.org, query, timeout=_SNAPSHOT_QUERY_TIMEOUT_SECONDS, + **({"deadline": deadline} if deadline is not None else {}), ) if result.status != "ok": - return SnapshotQueryResult(status="error", rows=[], error=result.error) - return SnapshotQueryResult(status="ok", rows=self._parse_snapshot_csv(result.text)) + return SnapshotQueryResult(status="error", rows=[], error=result.error, request_count=1) + return SnapshotQueryResult(status="ok", rows=self._parse_snapshot_csv(result.text), request_count=1) - def _query_snapshot(self, start_time: str, end_time: str) -> SnapshotQueryResult: + def _query_snapshot( + self, start_time: str, end_time: str, *, deadline: float | None = None, fields: tuple[str, ...] | None = None + ) -> SnapshotQueryResult: sources = list(dict.fromkeys(self._pingmesh_clients)) shards = [ sources[index : index + _SNAPSHOT_SOURCE_SHARD_SIZE] for index in range(0, len(sources), _SNAPSHOT_SOURCE_SHARD_SIZE) ] or [[]] + def query(shard): + return self._query_snapshot_shard( + start_time, + end_time, + shard, + **({"deadline": deadline} if deadline is not None else {}), + **({"fields": fields} if fields is not None else {}), + ) + if len(shards) == 1: - results = [self._query_snapshot_shard(start_time, end_time, shards[0])] + results = [query(shards[0])] else: workers = min(_SNAPSHOT_QUERY_WORKERS, len(shards)) with ThreadPoolExecutor(max_workers=workers) as executor: - results = list( - executor.map( - lambda shard: self._query_snapshot_shard(start_time, end_time, shard), - shards, - ) - ) + futures = [executor.submit(copy_context().run, query, shard) for shard in shards] + results = [future.result() for future in futures] + request_count = sum(result.request_count for result in results) failures = [(index, result) for index, result in enumerate(results, start=1) if result.status != "ok"] if failures: errors = [ f"snapshot shard {index}/{len(shards)} failed: {result.error or 'query_failed'}" for index, result in failures ] - return SnapshotQueryResult(status="error", rows=[], error="; ".join(errors)) + return SnapshotQueryResult(status="error", rows=[], error="; ".join(errors), request_count=request_count) rows = [row for result in results for row in result.rows] rows.sort( @@ -144,19 +156,12 @@ def _query_snapshot(self, start_time: str, end_time: str) -> SnapshotQueryResult str(row.get("dst_ip") or ""), ) ) - return SnapshotQueryResult(status="ok", rows=rows) + return SnapshotQueryResult(status="ok", rows=rows, request_count=request_count) def _topology_filter(self) -> str: - if not self.topology_id: - return "" - safe = str(self.topology_id).replace("\\", "\\\\").replace('"', '\\"') - return f' |> filter(fn: (r) => r.topology_id == "{safe}")\n' - - def _load_topology_metadata(self, metadata: dict) -> None: - devices = metadata.get("devices", {}) if isinstance(metadata, dict) else {} - clients = devices.get("clients", []) if isinstance(devices, dict) else [] - for client in clients: - name = client.get("name") - leaf = client.get("attached_switch") - if isinstance(name, str) and isinstance(leaf, str) and name and leaf: - self.client_to_leaf[name] = leaf + filters = {"topology_id": self.topology_id, "plan_id": self.plan_id} + return "".join( + f' |> filter(fn: (r) => r.{tag} == "{self._safe_flux_string(value)}")\n' + for tag, value in filters.items() + if value + ) diff --git a/netopsbench/platform/pingmesh/detector.py b/netopsbench/platform/pingmesh/detector.py index caa0fd2..c99e97b 100644 --- a/netopsbench/platform/pingmesh/detector.py +++ b/netopsbench/platform/pingmesh/detector.py @@ -2,7 +2,8 @@ from __future__ import annotations -import time +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context from dataclasses import asdict, dataclass, field from datetime import UTC, datetime @@ -11,6 +12,7 @@ from ._detector_analysis import DetectorAnalysisMixin from ._detector_coverage import DetectorCoverageMixin +from ._detector_ingestion import DetectorIngestionMixin from ._detector_query import DetectorQueryMixin @@ -35,7 +37,7 @@ class Anomaly: persistence: str | None = None -class AnomalyDetector(DetectorQueryMixin, DetectorCoverageMixin, DetectorAnalysisMixin): +class AnomalyDetector(DetectorIngestionMixin, DetectorQueryMixin, DetectorCoverageMixin, DetectorAnalysisMixin): """Detect anomalies in Pingmesh data using statistical methods.""" _anomaly_type = Anomaly @@ -50,24 +52,28 @@ def __init__( topology_id: str | None = None, loss_pct_threshold: float = 5.0, loss_pct_delta: float = 5.0, + runtime_start_time: str | None = None, ): + self.runtime_start_time = runtime_start_time self.influxdb_url = influxdb_url self.token = token self.org = org self.bucket = bucket - self.client_to_leaf: dict[str, str] = {} self.loss_pct_threshold = float(loss_pct_threshold) self.loss_pct_delta = float(loss_pct_delta) self._pingmesh_clients: list[str] = [] - self._pingmesh_policy: dict = {} if topology_metadata is None: raise ValueError("Canonical topology_metadata is required for Pingmesh anomaly detection") manifest = coerce_topology_manifest(topology_metadata) self.topology_id = topology_id or manifest.topology_id - projected_topology = manifest.to_agent_topology() + self.client_to_leaf = { + client.name: client.attached_switch for client in manifest.clients() if client.attached_switch + } self._pingmesh_clients = [device.name for device in manifest.clients()] - self._pingmesh_policy = dict(projected_topology["pingmesh"]) - self._load_topology_metadata(projected_topology) + self._client_addresses = {device.name: device.data_ip for device in manifest.clients()} + self._pingmesh_plan = manifest.require_pingmesh_plan() + self._compile_coverage_expectations() + self.plan_id = self._pingmesh_plan.settings.plan_id def _anomaly_to_dict(self, anomaly: Anomaly) -> dict: return asdict(anomaly) @@ -119,6 +125,7 @@ def _build_report( now_utc = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S") + "Z" return { "timestamp": now_utc, + "plan_id": self.plan_id, "windows": { "baseline": {"start": baseline_start, "end": baseline_end}, "current": {"start": current_start, "end": current_end}, @@ -126,6 +133,7 @@ def _build_report( "query_status": query_status, "coverage": coverage, "quality": quality, + "ingestion_status": coverage.get("ingestion", {}).get("status", "not_ready"), "summary": { "total_anomalies": len(anomalies), "latency_spikes": len(latency), @@ -195,39 +203,6 @@ def _merge_window_anomalies(self, analyses: list[tuple[str, list[Anomaly]]]) -> anomaly.persistence = "full_window" return sorted(full.values(), key=lambda item: (item.type, item.src_ip, item.dst_ip)) - def _query_covered_snapshot(self, start_time: str, end_time: str): - snapshot = self._query_snapshot(start_time, end_time) - if snapshot.status != "ok": - return snapshot, { - "status": "error", - "coverage_status": "error", - "error": snapshot.error or "query_failed", - } - coverage = self.summarize_coverage(snapshot.rows) - expected_seconds = int(coverage.get("expected_epoch_cycles", 0)) * int( - self._pingmesh_policy.get("cycle_interval_seconds", 1) - ) - actual_seconds = max( - 0.0, - ( - datetime.fromisoformat(end_time.replace("Z", "+00:00")) - - datetime.fromisoformat(start_time.replace("Z", "+00:00")) - ).total_seconds(), - ) - for _attempt in range(2): - if actual_seconds < expected_seconds or coverage.get("coverage_status") == "complete": - break - time.sleep(max(1, int(self._pingmesh_policy.get("cycle_interval_seconds", 1)))) - snapshot = self._query_snapshot(start_time, end_time) - if snapshot.status != "ok": - return snapshot, { - "status": "error", - "coverage_status": "error", - "error": snapshot.error or "query_failed", - } - coverage = self.summarize_coverage(snapshot.rows) - return snapshot, coverage - def generate_windowed_anomaly_report( self, *, @@ -237,9 +212,26 @@ def generate_windowed_anomaly_report( current_end: str, windows: list[dict], include_internal_health: bool = False, + evidence_pairs: list[dict] | None = None, + deadline: float | None = None, ) -> dict: - baseline, baseline_coverage = self._query_covered_snapshot(baseline_start, baseline_end) - current, current_coverage = self._query_covered_snapshot(current_start, current_end) + budget = {"deadline": deadline} if deadline is not None else {} + if (baseline_start, baseline_end) == (current_start, current_end): + # A newly captured healthy window needs one fresh read. Absolute + # health below is still checked; a zero relative delta is no proof. + baseline, baseline_coverage = self._query_covered_snapshot(baseline_start, baseline_end, **budget) + current, current_coverage = baseline, dict(baseline_coverage) + else: + # Both reads remain fresh; HTTP concurrency is process-wide bounded. + with ThreadPoolExecutor(max_workers=2) as executor: + baseline_future = executor.submit( + copy_context().run, self._query_covered_snapshot, baseline_start, baseline_end, **budget + ) + current_future = executor.submit( + copy_context().run, self._query_covered_snapshot, current_start, current_end, **budget + ) + baseline, baseline_coverage = baseline_future.result() + current, current_coverage = current_future.result() query_status = self._error_status(baseline, current) if not query_status["ok"]: return self._build_report( @@ -249,7 +241,7 @@ def generate_windowed_anomaly_report( current_start=current_start, current_end=current_end, query_status=query_status, - coverage={"status": "error", "coverage_status": "error", "error": query_status["error"]}, + coverage={**current_coverage, "status": "error", "error": query_status["error"]}, quality={}, ) @@ -258,7 +250,13 @@ def generate_windowed_anomaly_report( for window in windows: name = str(window.get("name") or "window") rows = self._slice_rows(current.rows, str(window["start_time"]), str(window["end_time"])) - window_analyses.append((name, self.analyze_snapshot_rows(baseline.rows, rows).anomalies)) + # A healthy steady window usually contains the entire snapshot. + # Check the actual slice, so invalid timestamps and boundary rows + # retain their filtering semantics even when the bounds match. + analysis = ( + full_analysis if len(rows) == len(current.rows) else self.analyze_snapshot_rows(baseline.rows, rows) + ) + window_analyses.append((name, analysis.anomalies)) anomalies = self._merge_window_anomalies(window_analyses) report = self._build_report( anomalies=anomalies, @@ -281,4 +279,8 @@ def generate_windowed_anomaly_report( if include_internal_health: report["_baseline_health"] = absolute_health report["_baseline_coverage"] = baseline_coverage + if evidence_pairs: + from ._detector_analysis import probe_pair_evidence + + report["_probe_evidence"] = probe_pair_evidence(baseline.rows, current.rows, evidence_pairs) return report diff --git a/netopsbench/platform/pingmesh/planner.py b/netopsbench/platform/pingmesh/planner.py new file mode 100644 index 0000000..c0bf16c --- /dev/null +++ b/netopsbench/platform/pingmesh/planner.py @@ -0,0 +1,176 @@ +"""The sole compiler for peer selection, probe schedules and candidate coverage.""" + +from __future__ import annotations + +import hashlib +import json +from collections import Counter, deque +from itertools import combinations, permutations + +from netopsbench.models.pingmesh import ( + CandidateCoverage, + ClientProbePlan, + LinkCoverage, + PingmeshPlan, + PlanSettings, + ProbeFrame, +) +from netopsbench.models.topology import TopologyManifest + + +def plan_fingerprint(manifest: TopologyManifest, plan: PingmeshPlan) -> str: + payload = plan.model_dump(mode="json") + payload["settings"]["plan_id"] = "" + encoded = json.dumps( + {"topology": manifest.model_dump(mode="json", exclude={"pingmesh_plan"}), "plan": payload}, + sort_keys=True, + separators=(",", ":"), + ).encode() + return hashlib.sha256(encoded).hexdigest() + + +def compile_pingmesh_plan(manifest: TopologyManifest) -> PingmeshPlan: + policy = manifest.pingmesh + clients = manifest.clients() + if len(clients) < 2: + raise ValueError("Pingmesh requires at least two clients") + racks: dict[str, list[str]] = {} + for client in clients: + racks.setdefault(str(client.attached_switch), []).append(client.name) + peers: dict[str, set[str]] = {client.name: set() for client in clients} + rack_pair_counts: Counter[tuple[str, str]] = Counter() + for names in racks.values(): + for source, destination in permutations(names, 2): + peers[source].add(destination) + indexed_racks = list(enumerate(racks.items())) + for (i, (left, a)), (j, (right, b)) in combinations(indexed_racks, 2): + count = policy.cross_rack_pairs or max(len(a), len(b)) + if count > max(len(a), len(b)): + raise ValueError("cross_rack_pairs exceeds the rack matching capacity") + for replica in range(count): + source = a[(i + j + replica) % len(a)] + destination = b[(i + j + replica) % len(b)] + peers[source].add(destination) + peers[destination].add(source) + rack_pair_counts[left, right] = count + rack_pair_counts[right, left] = count + if any(not targets for targets in peers.values()): + raise ValueError("Pingmesh plan leaves a client without probes") + + order = {client.name: index for index, client in enumerate(clients)} + batch_size = policy.destination_batch_size or max(map(len, peers.values())) + destination_batches = max((len(names) + batch_size - 1) // batch_size for names in peers.values()) + if policy.rtt_ports_per_cycle > policy.rtt_port_pool_size: + raise ValueError("rtt_ports_per_cycle exceeds the source-port pool") + source_ports = list(range(33000, 33000 + policy.rtt_port_pool_size)) + if source_ports[-1] > 65535 or 33434 in source_ports: + raise ValueError("Pingmesh source-port pool overflows or overlaps the responder") + port_batches = [ + list(range(start, min(start + policy.rtt_ports_per_cycle, len(source_ports)))) + for start in range(0, len(source_ports), policy.rtt_ports_per_cycle) + ] + epoch = destination_batches * len(port_batches) + interval = policy.cycle_interval_seconds + plans = [] + for client in clients: + targets = sorted(peers[client.name], key=order.__getitem__) + frames = [] + for port_batch, sockets in enumerate(port_batches): + for destination_batch in range(destination_batches): + active = list( + range(destination_batch * batch_size, min((destination_batch + 1) * batch_size, len(targets))) + ) + probes = [] + for target in range(len(active)): + probes.extend(("rtt", target, socket) for socket in range(len(sockets))) + probes.append(("df", target, target % len(sockets))) + frames.append( + ProbeFrame( + destination_batch_index=destination_batch, + port_batch_index=port_batch, + target_indices=active, + probes=probes, + ) + ) + jitter = int.from_bytes(hashlib.sha256(client.name.encode()).digest()[:8], "big") % (interval * 1000) + plans.append(ClientProbePlan(name=client.name, targets=targets, startup_delay_ms=jitter, frames=frames)) + plan = PingmeshPlan( + settings=PlanSettings( + plan_id="", + source_ports=source_ports, + port_batches=port_batches, + destination_batch_size=batch_size, + cycle_interval_seconds=interval, + coverage_epoch_cycles=epoch, + coverage_epoch_seconds=epoch * interval, + complete_window_seconds=epoch * interval + max(5, 2 * interval), + df_payload_size=policy.df_payload_size, + ), + clients=plans, + coverage=_candidate_coverage(manifest, racks, peers, rack_pair_counts), + ) + if set(plan.coverage.covered_switches) != {device.name for device in manifest.switches()}: + raise ValueError("Pingmesh plan leaves switches without candidate coverage") + if plan.coverage.minimum_witnesses < (2 if manifest.scale in {"xlarge", "fat-tree-k18"} else 1): + raise ValueError("Pingmesh plan has insufficient candidate link coverage") + plan.settings.plan_id = plan_fingerprint(manifest, plan) + return plan + + +def _candidate_coverage(manifest, racks, peers, rack_pair_counts) -> CandidateCoverage: + switches = {device.name for device in manifest.switches()} + graph: dict[str, list[str]] = {name: [] for name in switches} + for link in manifest.links: + a, b = (endpoint.device for endpoint in link.endpoints) + if a in switches and b in switches: + graph[a].append(b) + graph[b].append(a) + witnesses: Counter[tuple[str, str]] = Counter() + # Traverse shortest-path predecessor DAGs, never enumerate complete paths. + for source in racks: + distances = {source: 0} + queue = deque([source]) + while queue: + node = queue.popleft() + for neighbor in graph[node]: + if neighbor not in distances: + distances[neighbor] = distances[node] + 1 + queue.append(neighbor) + for destination in racks: + count = rack_pair_counts[source, destination] + if not count: + continue + if destination not in distances: + raise ValueError(f"Disconnected racks: {source}, {destination}") + pending = [destination] + visited = {destination} + while pending: + node = pending.pop() + for predecessor in graph[node]: + if distances.get(predecessor) == distances[node] - 1: + witnesses[predecessor, node] += count + if predecessor not in visited: + visited.add(predecessor) + pending.append(predecessor) + for client in manifest.clients(): + degree = len(peers[client.name]) + witnesses[client.name, client.attached_switch] = degree + witnesses[client.attached_switch, client.name] = degree + links = [] + for link in manifest.links: + for a, b in (link.endpoints, link.endpoints[::-1]): + links.append( + LinkCoverage( + source=a.device, + destination=b.device, + source_interface=a.interface, + destination_interface=b.interface, + witnesses=witnesses[a.device, b.device], + ) + ) + covered = {endpoint for link in links if link.witnesses for endpoint in (link.source, link.destination)} + return CandidateCoverage( + directed_links=links, + covered_switches=[device.name for device in manifest.switches() if device.name in covered], + minimum_witnesses=min((link.witnesses for link in links), default=0), + ) diff --git a/netopsbench/platform/runtime/_sonic_probe.py b/netopsbench/platform/runtime/_sonic_probe.py new file mode 100644 index 0000000..258ecd3 --- /dev/null +++ b/netopsbench/platform/runtime/_sonic_probe.py @@ -0,0 +1,58 @@ +"""Standalone, read-only SONiC probe executed inside one Docker exec. + +Keep this module standard-library-only: its source is sent to the container, +where NetOpsBench is not installed. Preserve the activation checks' ordering. +""" + +import json +import subprocess +import sys + + +def probe(services, expected_port_count=None, run=subprocess.run): + checks = {} + + def command(name, args): + try: + result = run(args, capture_output=True, text=True, check=False, timeout=15) + except (subprocess.TimeoutExpired, OSError) as error: + checks[name] = {"ok": False, "error": type(error).__name__} + return None + checks[name] = {"ok": result.returncode == 0} + return result + + def cfg(name): + result = command(name, ["sonic-cfggen", "-d", "-v", "DEVICE_METADATA.localhost.hostname"]) + return result is not None and result.returncode == 0 + + ready = False + if cfg("config_before"): + version = command("vtysh", ["vtysh", "-c", "show version"]) + if version is not None and version.returncode == 0: + status = command("services", ["supervisorctl", "status", *services]) + states = {} + if status is not None: + for line in (status.stdout or status.stderr or "").splitlines(): + fields = line.split() + if len(fields) >= 2: + states[fields[0]] = fields[1].upper() + checks["services"]["ok"] = all(states.get(service) == "RUNNING" for service in services) + if checks["services"]["ok"] and cfg("config_after"): + ready = True + if expected_port_count is not None: + ports = command("ports", ["redis-cli", "-n", "2", "--raw", "HLEN", "COUNTERS_PORT_NAME_MAP"]) + try: + ready = ( + ports is not None + and ports.returncode == 0 + and int(ports.stdout.strip()) >= expected_port_count + ) + except (ValueError, AttributeError): + ready = False + checks["ports"]["ok"] = ready + return {"version": 1, "ready": ready, "checks": checks} + + +if __name__ == "__main__": + request = json.loads(sys.argv[1]) + print(json.dumps(probe(request["services"], request.get("expected_port_count")))) diff --git a/netopsbench/platform/runtime/apply_configs.py b/netopsbench/platform/runtime/apply_configs.py index bfac366..911fe14 100644 --- a/netopsbench/platform/runtime/apply_configs.py +++ b/netopsbench/platform/runtime/apply_configs.py @@ -19,6 +19,7 @@ from netopsbench.models.topology import DeviceRole, TopologyManifest from netopsbench.platform.topology.config import SONIC_PORT_COUNTER_INTERVAL_MS from netopsbench.platform.topology.topology_utils import clab_container_name, load_topology_manifest +from netopsbench.platform.utils.control import OperationControl from netopsbench.platform.utils.proc import docker_prefix, safe_run _REQUIRED_SONIC_SERVICES = ("redis-server", "orchagent", "zebra") @@ -106,140 +107,62 @@ def _ecmp_hash_policies(manifest: TopologyManifest, devices: list[str]) -> dict[ return policies -def _configdb_ready(prefix: list[str], container: str) -> bool: - try: - configdb_ret = safe_run( - [ - *prefix, - "docker", - "exec", - container, - "sonic-cfggen", - "-d", - "-v", - "DEVICE_METADATA.localhost.hostname", - ], - capture_output=True, - text=True, - check=False, - timeout=15, - ) - except subprocess.TimeoutExpired: - return False - return configdb_ret.returncode == 0 - - -def _startup_status(prefix: list[str], container: str) -> str | None: - try: - ret = safe_run( - [*prefix, "docker", "exec", container, "supervisorctl", "status", "start.sh"], - capture_output=True, - text=True, - check=False, - timeout=10, - ) - except subprocess.TimeoutExpired: - return None - parts = str(ret.stdout or ret.stderr or "").split() - return parts[1].upper() if len(parts) >= 2 else None - - -def _required_services_ready(prefix: list[str], container: str) -> bool: - try: - ret = safe_run( - [*prefix, "docker", "exec", container, "supervisorctl", "status", *_REQUIRED_SONIC_SERVICES], - capture_output=True, - text=True, - check=False, - timeout=15, - ) - except subprocess.TimeoutExpired: - return False - output = str(ret.stdout or ret.stderr or "") - states: dict[str, str] = {} - for line in output.splitlines(): - parts = line.split() - if len(parts) >= 2: - states[parts[0]] = parts[1].upper() - return all(states.get(service) == "RUNNING" for service in _REQUIRED_SONIC_SERVICES) - - -def _countersdb_ready(prefix: list[str], container: str, expected_port_count: int) -> bool: +def _sonic_readiness_snapshot( + prefix: list[str], container: str, expected_port_count: int | None, *, control: OperationControl | None = None +) -> bool: + """Run the existing ordered checks using a single container process.""" + source = Path(__file__).with_name("_sonic_probe.py").read_text(encoding="utf-8") + request = json.dumps({"services": _REQUIRED_SONIC_SERVICES, "expected_port_count": expected_port_count}) try: ret = safe_run( - [ - *prefix, - "docker", - "exec", - container, - "redis-cli", - "-n", - "2", - "--raw", - "HLEN", - "COUNTERS_PORT_NAME_MAP", - ], + [*prefix, "docker", "exec", container, "python3", "-c", source, request], capture_output=True, text=True, check=False, - timeout=15, + timeout=80, + control=control, ) - except subprocess.TimeoutExpired: + if ret.returncode != 0: + return False + snapshot = json.loads(ret.stdout or "") + except (subprocess.TimeoutExpired, OSError, ValueError): return False - if ret.returncode != 0: - return False - try: - return int(str(ret.stdout).strip()) >= expected_port_count - except ValueError: + if not isinstance(snapshot, dict) or snapshot.get("version") != 1 or snapshot.get("ready") is not True: return False + checks = snapshot.get("checks") + required = ["config_before", "vtysh", "services", "config_after"] + if expected_port_count is not None: + required.append("ports") + return isinstance(checks, dict) and all( + isinstance(checks.get(name), dict) and checks[name].get("ok") is True for name in required + ) def _wait_for_sonic( - device: str, container: str, max_tries: int | None = None, delay: int = 5, expected_port_count: int | None = None, + control: OperationControl | None = None, ) -> bool: """Block until SONiC control-plane and ConfigDB commands are responsive.""" max_tries = max_tries or SONIC_READINESS_MAX_TRIES prefix = docker_prefix() for _ in range(max_tries): - _startup_status(prefix, container) - configdb_ready = _configdb_ready(prefix, container) - if not configdb_ready: - time.sleep(delay) - continue - - try: - vtysh_ret = safe_run( - [*prefix, "docker", "exec", container, "vtysh", "-c", "show version"], - capture_output=True, - text=True, - check=False, - timeout=15, - ) - except subprocess.TimeoutExpired: - time.sleep(delay) - continue - - if vtysh_ret.returncode != 0: - time.sleep(delay) - continue - - if not _required_services_ready(prefix, container): - time.sleep(delay) - continue - - if _configdb_ready(prefix, container) and ( - expected_port_count is None or _countersdb_ready(prefix, container, expected_port_count) - ): + if control is not None: + control.remaining() + if _sonic_readiness_snapshot(prefix, container, expected_port_count, control=control): return True - time.sleep(delay) + if control is not None: + control.sleep(delay) + else: + time.sleep(delay) return False -def _activate_preseed_device(prefix: list[str], container: str, ecmp_hash_policy: int) -> bool: +def _activate_preseed_device( + prefix: list[str], container: str, ecmp_hash_policy: int, *, control: OperationControl | None = None +) -> bool: command = ( "set -e; " f"sysctl -w net.ipv4.fib_multipath_hash_policy={ecmp_hash_policy} >/dev/null; " @@ -267,11 +190,14 @@ def _activate_preseed_device(prefix: list[str], container: str, ecmp_hash_policy text=True, check=False, timeout=30, + control=control, ) return ret.returncode == 0 -def _kernel_interface_addresses(prefix: list[str], container: str) -> dict[str, set[str]] | None: +def _kernel_interface_addresses( + prefix: list[str], container: str, *, control: OperationControl | None = None +) -> dict[str, set[str]] | None: try: ret = safe_run( [*prefix, "docker", "exec", container, "ip", "-j", "address", "show"], @@ -279,6 +205,7 @@ def _kernel_interface_addresses(prefix: list[str], container: str) -> dict[str, text=True, check=False, timeout=15, + control=control, ) except subprocess.TimeoutExpired: return None @@ -308,12 +235,14 @@ def _kernel_interface_addresses(prefix: list[str], container: str) -> dict[str, return observed -def _reconcile_preseed_interfaces(prefix: list[str], container: str, config_file: str) -> list[str]: +def _reconcile_preseed_interfaces( + prefix: list[str], container: str, config_file: str, *, control: OperationControl | None = None +) -> list[str]: """Repair rare SONiC-VS startup drift between ConfigDB and kernel state.""" expected = _expected_interface_addresses(config_file) if not expected: return [] - observed = _kernel_interface_addresses(prefix, container) + observed = _kernel_interface_addresses(prefix, container, control=control) if observed is None: return ["unable to inspect kernel interface addresses"] @@ -335,6 +264,7 @@ def _reconcile_preseed_interfaces(prefix: list[str], container: str, config_file text=True, check=False, timeout=15, + control=control, ) except subprocess.TimeoutExpired: return [f"{interface}|{address}: command timed out"] @@ -342,7 +272,7 @@ def _reconcile_preseed_interfaces(prefix: list[str], container: str, config_file detail = (ret.stderr or ret.stdout or "").strip() return [f"{interface}|{address}: {detail or f'exit status {ret.returncode}'}"] - observed = _kernel_interface_addresses(prefix, container) + observed = _kernel_interface_addresses(prefix, container, control=control) if observed is None: return ["unable to verify kernel interface addresses"] return sorted( @@ -360,8 +290,11 @@ def _apply_single_device( ecmp_hash_policy: int, *, readiness_max_tries: int | None = None, + control: OperationControl | None = None, ) -> tuple[str, bool, str, float, float, float]: """Activate one preseeded device after Containerlab has started it.""" + if control is not None: + control.remaining() started_at = time.monotonic() container = clab_container_name(lab_name, device) prefix = docker_prefix() @@ -394,10 +327,10 @@ def _apply_single_device( readiness_started = time.monotonic() if not _wait_for_sonic( - device, container, max_tries=readiness_max_tries, expected_port_count=expected_port_count, + control=control, ): readiness_elapsed = time.monotonic() - readiness_started return ( @@ -411,8 +344,8 @@ def _apply_single_device( readiness_elapsed = time.monotonic() - readiness_started activation_started = time.monotonic() - if _activate_preseed_device(prefix, container, ecmp_hash_policy): - unreconciled = _reconcile_preseed_interfaces(prefix, container, preseed_config) + if _activate_preseed_device(prefix, container, ecmp_hash_policy, control=control): + unreconciled = _reconcile_preseed_interfaces(prefix, container, preseed_config, control=control) activation_elapsed = time.monotonic() - activation_started if not unreconciled: return ( @@ -449,6 +382,7 @@ def activate_device( ecmp_hash_policy: int, *, readiness_max_tries: int | None = None, + control: OperationControl | None = None, ) -> tuple[bool, str]: """Activate one SONiC device using the canonical post-deploy path.""" _, success, message, *_ = _apply_single_device( @@ -457,6 +391,7 @@ def activate_device( lab_name, ecmp_hash_policy, readiness_max_tries=readiness_max_tries, + control=control, ) return success, message @@ -465,6 +400,8 @@ def apply_configs( topology_dir: str, max_parallel: int = 32, lab_name: str | None = None, + *, + control: OperationControl | None = None, ) -> ApplyResult: """Activate all preseeded SONiC devices in *topology_dir*.""" manifest = load_topology_manifest(topology_dir) @@ -498,6 +435,7 @@ def apply_configs( topology_dir, lab_name, ecmp_hash_policies[device], + control=control, ): device for device in devices } @@ -546,6 +484,7 @@ def apply_configs( capture_output=True, check=False, timeout=30, + control=control, ) print(f" checked {candidates[0]}") diff --git a/netopsbench/platform/runtime/assets/CONTAINERLAB-LICENSE b/netopsbench/platform/runtime/assets/CONTAINERLAB-LICENSE new file mode 100644 index 0000000..1c1c55c --- /dev/null +++ b/netopsbench/platform/runtime/assets/CONTAINERLAB-LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2021 Nokia. All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/netopsbench/platform/runtime/assets/README.md b/netopsbench/platform/runtime/assets/README.md new file mode 100644 index 0000000..b935139 --- /dev/null +++ b/netopsbench/platform/runtime/assets/README.md @@ -0,0 +1,31 @@ +# Official Containerlab runtime + +`containerlab.lock.json` pins the official **v0.77.0** Linux amd64 and arm64 +release archives and the SHA-256 of each extracted executable. Archive hashes +come from the upstream release assets. `CONTAINERLAB-LICENSE` retains its license. + +Prepare with `python -m netopsbench.platform.runtime.build_tools`. Use `--archive` +for an offline release package and `--output` for a private destination. Runtime +selection uses `NETOPSBENCH_RUNTIME_TOOLS` or the package's ignored `_bin/` +directory. The installer publishes its manifest last. The resolver verifies +that manifest, the actual executable hash and the reported version before use. +There is no system binary fallback, Go fork, or patch application. + +Upstream deployment, Docker bridge/DNS, and node stop/start own networking. +NetOpsBench retains its existing SONiC configuration/bootstrap wrapper with +sequential service starts, optional missing-service handling, readable config +files and full readiness checks. It does not install a management daemon or +modify Docker configuration. Runtime and campaign identity records the actual +binary version/hash and startup script hash; historical custom-backend campaigns +and capacity samples must remain archived rather than being resumed. + +The baseline version includes the upstream parking-node implementation without +the older veth peer-index ownership heuristic. Verify stop/start and complete +routing/Pingmesh recovery on an independent lab when updating this release. +New upstream blockers require a reproduction and minimal correction evidence; +performance forks are not an automatic fallback. + +The official v0.77.0 Docker runtime itself selects `nat-unprotected` on newer +Docker engines (see [upstream implementation](https://github.com/srl-labs/containerlab/blob/v0.77.0/runtime/docker/docker.go#L294-L305)). +Using upstream networking does not imply Docker’s default `nat` port filtering. +NetOpsBench does not override this upstream network option. diff --git a/netopsbench/platform/runtime/assets/containerlab.lock.json b/netopsbench/platform/runtime/assets/containerlab.lock.json new file mode 100644 index 0000000..cbda229 --- /dev/null +++ b/netopsbench/platform/runtime/assets/containerlab.lock.json @@ -0,0 +1,16 @@ +{ + "provider": "upstream", + "version": "0.77.0", + "releases": { + "amd64": { + "archive_url": "https://github.com/srl-labs/containerlab/releases/download/v0.77.0/containerlab_0.77.0_linux_amd64.tar.gz", + "archive_sha256": "072a9ead3da57594fe138d4d0174b9b1c50ecb12252f49a5558c56040dbace07", + "binary_sha256": "bb9508eb2f107f7d45142dffb8a21ecbad49187b3ff140c5c69a2013c78d6587" + }, + "arm64": { + "archive_url": "https://github.com/srl-labs/containerlab/releases/download/v0.77.0/containerlab_0.77.0_linux_arm64.tar.gz", + "archive_sha256": "3aaaa1cb9faffcadbc8e553ac968081a2b4208e3b2d012c441944c6cd63a579a", + "binary_sha256": "34d1c3e2cdc27f199bb92246517ab8ffd7cce8de8bd491a2847c0206e03841ab" + } + } +} diff --git a/netopsbench/platform/runtime/build_tools.py b/netopsbench/platform/runtime/build_tools.py new file mode 100644 index 0000000..788d8b6 --- /dev/null +++ b/netopsbench/platform/runtime/build_tools.py @@ -0,0 +1,62 @@ +"""Install a verified official Containerlab release in a private tools directory.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import tarfile +import tempfile +import urllib.request +from pathlib import Path + +from .toolchain import DEFAULT_TOOLS, binary_version, release_spec + + +def install_release(archive: Path, output: Path) -> None: + spec = release_spec() + if hashlib.sha256(archive.read_bytes()).hexdigest() != spec["archive_sha256"]: + raise RuntimeError("Official Containerlab archive checksum mismatch") + # Extract only the executable, never paths or symlinks supplied by an archive. + with tarfile.open(archive) as tar: + member = tar.getmember("containerlab") + if not member.isfile(): + raise RuntimeError("Official archive has no regular Containerlab executable") + stream = tar.extractfile(member) + if stream is None: + raise RuntimeError("Official archive has no readable Containerlab executable") + with stream: + data = stream.read() + if hashlib.sha256(data).hexdigest() != spec["binary_sha256"]: + raise RuntimeError("Official Containerlab executable checksum mismatch") + output.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix=".containerlab-", dir=output) as temp: + binary = Path(temp) / "containerlab" + binary.write_bytes(data) + binary.chmod(0o755) + if binary_version(binary) != spec["version"]: + raise RuntimeError("Official Containerlab version mismatch") + manifest = Path(temp) / "manifest.json" + manifest.write_text(json.dumps(spec, indent=2) + "\n") + # Publish identity last; partial installs cannot pass runtime validation. + (output / "manifest.json").unlink(missing_ok=True) + binary.replace(output / "containerlab") + manifest.replace(output / "manifest.json") + + +def _main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", type=Path, help="Use a previously downloaded official release archive") + parser.add_argument("--output", type=Path, default=DEFAULT_TOOLS) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="netopsbench-release-") as temp: + archive = args.archive or Path(temp) / "containerlab.tar.gz" + if args.archive is None: + with urllib.request.urlopen(release_spec()["archive_url"], timeout=120) as response: + archive.write_bytes(response.read()) + install_release(archive, args.output.resolve()) + print(f"Installed official Containerlab {release_spec()['version']} in {args.output.resolve()}") + + +if __name__ == "__main__": + _main() diff --git a/netopsbench/platform/runtime/deployment.py b/netopsbench/platform/runtime/deployment.py index d37b677..a934df1 100644 --- a/netopsbench/platform/runtime/deployment.py +++ b/netopsbench/platform/runtime/deployment.py @@ -8,6 +8,7 @@ import os import shlex import signal +import subprocess import tempfile import time from contextlib import contextmanager @@ -17,9 +18,11 @@ from netopsbench.models.profiles import ScaleProfile, ScaleRegistry, get_scale_profile from netopsbench.models.runtime import RuntimeIdentity from netopsbench.platform.runtime.apply_configs import apply_configs +from netopsbench.platform.runtime.toolchain import containerlab_command from netopsbench.platform.topology.config import SONIC_PID1_COMMAND from netopsbench.platform.topology.generator import generate_topology from netopsbench.platform.topology.topology_utils import clab_container_name, load_topology_manifest +from netopsbench.platform.utils.control import OperationControl from netopsbench.platform.utils.proc import docker_prefix, safe_run, sudo_prefix APPLY_CONFIG_PARALLELISM = 32 @@ -111,21 +114,39 @@ def allocate_management_subnets(scale: str, worker_count: int, registry: ScaleRe @contextmanager -def runtime_deploy_lock(): +def runtime_deploy_lock(control: OperationControl | None = None): """Serialize host-side network allocation and Containerlab creation.""" with RUNTIME_DEPLOY_LOCK_PATH.open("a+", encoding="utf-8") as lock_file: - fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) + if control is None: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX) + else: + while True: + control.remaining() + try: + fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + control.sleep(0.2) try: yield finally: fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN) -def deploy_worker_lab(worker: RuntimeIdentity, scale: str, registry: ScaleRegistry | None = None) -> None: +def deploy_worker_lab( + worker: RuntimeIdentity, + scale: str, + registry: ScaleRegistry | None = None, + *, + control: OperationControl | None = None, +) -> None: """Generate, deploy, and activate one worker without observability side effects.""" + if control is not None: + control.remaining() topology_dir = Path(worker.topology_dir) + backend = containerlab_command() # Validate the official executable before resource changes. topology_dir.mkdir(parents=True, exist_ok=True) - stale_paths = [topology_dir / "configs", *topology_dir.glob("clab-*")] + stale_paths = [path for path in [topology_dir / "configs", *topology_dir.glob("clab-*")] if path.exists()] if stale_paths: safe_run( [*sudo_prefix(), "rm", "-rf", *(str(path) for path in stale_paths)], @@ -145,17 +166,26 @@ def deploy_worker_lab(worker: RuntimeIdentity, scale: str, registry: ScaleRegist if not topology_file.is_file(): raise FileNotFoundError(f"Generated Containerlab topology not found: {topology_file}") - command = [*sudo_prefix(), "containerlab", "deploy", "-t", str(topology_file), "--reconfigure"] + command = [*sudo_prefix(), *backend, "deploy", "-t", str(topology_file), "--reconfigure"] profile = get_scale_profile(scale, registry) if profile.containerlab_max_workers is not None: command.extend(["--max-workers", str(profile.containerlab_max_workers)]) - deploy_result = safe_run(command, cwd=topology_dir, check=False, timeout=profile.deploy_timeout_seconds) + deploy_result = safe_run( + command, cwd=topology_dir, check=False, timeout=profile.deploy_timeout_seconds, control=control + ) if deploy_result.returncode != 0: details = (deploy_result.stderr or deploy_result.stdout or "no diagnostic output").strip() raise RuntimeError(f"Containerlab deploy failed ({deploy_result.returncode}): {details[-4000:]}") + if control is not None: + control.remaining() _verify_sonic_pid1_contract(worker) - result = apply_configs(str(topology_dir), APPLY_CONFIG_PARALLELISM, worker.lab_name) + result = apply_configs( + str(topology_dir), + APPLY_CONFIG_PARALLELISM, + worker.lab_name, + **({"control": control} if control is not None else {}), + ) if result.failed: raise RuntimeError(f"SONiC activation failed for: {', '.join(result.failed)}") @@ -254,25 +284,27 @@ def teardown_worker_lab(worker: RuntimeIdentity, registry: ScaleRegistry | None topology_file = topology_dir / f"{worker.lab_name}.clab.yaml" profile = _teardown_profile(topology_dir / "topology.json", registry) + backend = containerlab_command() command = ( - [*sudo_prefix(), "containerlab", "destroy", "-t", str(topology_file), "--cleanup"] + [*sudo_prefix(), *backend, "destroy", "-t", str(topology_file), "--cleanup"] if topology_file.is_file() - else [*sudo_prefix(), "containerlab", "destroy", "--name", worker.lab_name, "--cleanup"] + else [*sudo_prefix(), *backend, "destroy", "--name", worker.lab_name, "--cleanup"] ) if profile is not None and profile.containerlab_max_workers is not None: command.extend(["--max-workers", str(profile.containerlab_max_workers)]) teardown_timeout = profile.deploy_timeout_seconds if profile is not None else 600 - destroy = safe_run( - command, - cwd=topology_dir, - check=False, - timeout=teardown_timeout, - ) + try: + destroy = safe_run(command, cwd=topology_dir, check=False, timeout=teardown_timeout) + except subprocess.TimeoutExpired: + destroy = subprocess.CompletedProcess(command, 124, "", "Containerlab destroy timed out") names = _lab_container_names(docker, worker.lab_name) if names: safe_run([*docker, "docker", "rm", "-f", *names], check=False, timeout=300) _wait_for_lab_removal(docker, worker.lab_name) + if destroy.returncode != 0: + # Finish upstream namespace/hosts cleanup after removing stuck owned containers. + destroy = safe_run(command, cwd=topology_dir, check=False, timeout=teardown_timeout) network_remove = safe_run( [*docker, "docker", "network", "rm", worker.mgmt_network], check=False, @@ -286,7 +318,7 @@ def teardown_worker_lab(worker: RuntimeIdentity, registry: ScaleRegistry | None if _network_exists(docker, worker.mgmt_network): details = (network_remove.stderr or network_remove.stdout or "management network remained").strip() errors.append(f"{worker.mgmt_network}: {details}") - if destroy.returncode != 0 and errors: + if destroy.returncode != 0: details = (destroy.stderr or destroy.stdout or "").strip() errors.append(f"containerlab destroy failed ({destroy.returncode}): {details[-2000:]}") if errors: diff --git a/netopsbench/platform/runtime/health.py b/netopsbench/platform/runtime/health.py index 1a2557a..98382ce 100644 --- a/netopsbench/platform/runtime/health.py +++ b/netopsbench/platform/runtime/health.py @@ -11,12 +11,15 @@ from __future__ import annotations +import json import os import re import subprocess import time from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context from math import ceil +from pathlib import Path from netopsbench.config import config from netopsbench.logging_utils import get_logger @@ -30,35 +33,89 @@ from netopsbench.platform.client_agent.control import request_agent from netopsbench.platform.topology.topology_utils import ( clab_container_name, - coerce_topology_manifest, load_topology_manifest, ) +from netopsbench.platform.utils.control import OperationControl from netopsbench.platform.utils.proc import docker_prefix, safe_run logger = get_logger(__name__) HEALTH_POLL_INTERVAL_SECONDS = 5 ACTIVE_INTERFACE_COVERAGE_MIN_RATIO = 0.5 +_NETWORK_PROBE_SOURCE = (Path(__file__).parent.parent / "observability" / "_routing_probe.py").read_text( + encoding="utf-8" +) -def _docker_exec(container: str, *cmd: str, check: bool = False, capture: bool = True) -> subprocess.CompletedProcess: +def _docker_exec( + container: str, + *cmd: str, + check: bool = False, + capture: bool = True, + timeout: float = 60, + control: OperationControl | None = None, +) -> subprocess.CompletedProcess: prefix = docker_prefix() return safe_run( [*prefix, "docker", "exec", container, *cmd], check=check, capture_output=capture, text=True, - timeout=60, + timeout=timeout, + control=control, ) -def _running_container_count(lab_name: str) -> int: +def _routing_state( + container: str, control: OperationControl | None = None, route_snapshot: dict | None = None +) -> tuple[str, str]: + budget = control.remaining(125) if control is not None else 125 + result = _docker_exec( + container, + "python3", + "-c", + _NETWORK_PROBE_SOURCE, + "--budget-seconds", + str(budget), + timeout=budget, + control=control, + ) + if result.returncode != 0: + return "", "" + try: + payload = json.loads(result.stdout) + if payload["version"] != 1: + return "", "" + checks = payload["checks"] + if route_snapshot is not None: + fib = checks.get("fib", {}) + route_snapshot.update( + packet_counters=payload.get("packet_counters", {"error": "Not collected"}), + fib=json.loads(fib["stdout"]) if fib.get("returncode") == 0 else [], + bgp_collection_ok=checks.get("bgp", {}).get("returncode") == 0, + collected_at=time.time(), + ) + if fib.get("returncode") != 0: + route_snapshot["error"] = "FIB collection failed" + outputs = [] + for name in ("bgp", "interfaces"): + check = checks[name] + if check["returncode"] != 0 or not isinstance(check["stdout"], str): + return "", "" + outputs.append(check["stdout"]) + return outputs[0], outputs[1] + except (KeyError, TypeError, ValueError): + return "", "" + + +def _running_container_count(lab_name: str, control: OperationControl | None = None) -> int: result = safe_run( [*docker_prefix(), "docker", "ps", "--filter", f"label=containerlab={lab_name}", "--format", "{{.Names}}"], capture_output=True, text=True, check=False, timeout=30, + control=control, ) return len([line for line in result.stdout.strip().splitlines() if line]) @@ -99,51 +156,16 @@ def _parse_active_interfaces(show_interfaces_output: str) -> set[str]: return active -def _expected_active_interface_count(topo: TopologyManifest | dict, device: str) -> int: - manifest = coerce_topology_manifest(topo) - target = manifest.device(device) - if target is None: - return 0 - clients = manifest.clients() - fat_tree_k = int(manifest.facts.fat_tree_k or 0) - - if fat_tree_k: - half = fat_tree_k // 2 - if target.role is DeviceRole.CORE: - return fat_tree_k - if target.role is DeviceRole.AGG: - return fat_tree_k - if target.role is DeviceRole.EDGE: - attached_clients = [client for client in clients if client.attached_switch == device] - clients_per_edge = len(attached_clients) or int(manifest.facts.clients_per_attached_switch) - return half + clients_per_edge - - if target.role is DeviceRole.SPINE: - return int(manifest.facts.num_leafs or len(manifest.devices_by_role(DeviceRole.LEAF))) - if target.role is DeviceRole.LEAF: - num_spines = int(manifest.facts.num_spines or len(manifest.devices_by_role(DeviceRole.SPINE))) - attached_clients = [client for client in clients if client.attached_switch == device] - clients_per_leaf = len(attached_clients) or int(manifest.facts.clients_per_attached_switch) - return num_spines + clients_per_leaf - return 0 - - -def _expected_bgp_neighbor_count(topo: TopologyManifest | dict, device: str) -> int: - manifest = coerce_topology_manifest(topo) - target = manifest.device(device) - if target is None: - return 0 - fat_tree_k = int(manifest.facts.fat_tree_k or 0) - if fat_tree_k: - if target.role in {DeviceRole.CORE, DeviceRole.AGG}: - return fat_tree_k - if target.role is DeviceRole.EDGE: - return fat_tree_k // 2 - if target.role is DeviceRole.SPINE: - return len(manifest.devices_by_role(DeviceRole.LEAF)) - if target.role is DeviceRole.LEAF: - return len(manifest.devices_by_role(DeviceRole.SPINE)) - return 0 +def expected_network_counts(topo: TopologyManifest) -> dict[str, dict[str, int]]: + """Compile interface and BGP expectations once from the current manifest.""" + routed = {item.name for item in topo.routing_devices()} + counts = {item.name: {"active_interfaces": 0, "bgp_neighbors": 0} for item in topo.devices} + for link in topo.links: + routing_link = all(endpoint.device in routed for endpoint in link.endpoints) + for endpoint in link.endpoints: + counts[endpoint.device]["active_interfaces"] += 1 + counts[endpoint.device]["bgp_neighbors"] += int(routing_link) + return counts def _convergence_targets(topo: TopologyManifest, *, all_routing_devices: bool) -> list[Device]: @@ -174,6 +196,79 @@ def check_worker_health( scale_registry: ScaleRegistry | None = None, require_client_agent: bool = True, all_routing_devices: bool = False, + *, + deadline: float | None = None, + cancel_event=None, + route_snapshot: dict | None = None, + expected_routes: dict | None = None, + state_only: bool = False, + recovery_audit: dict | None = None, +) -> list[str]: + """Check health within one elapsed-time budget, including all retries.""" + started = time.monotonic() + topo = _load_topology_metadata(str(worker.topology_dir)) + limit = started + get_scale_profile(topo.scale, scale_registry).health_timeout_seconds + control = OperationControl(cancel_event, min(limit, deadline) if deadline is not None else limit) + try: + control.remaining() + return _check_worker_health( + worker, + influxdb_url, + influxdb_token, + influxdb_org, + health_retries, + health_delay, + scale_registry, + require_client_agent, + all_routing_devices, + topology=topo, + control=control, + route_snapshot=route_snapshot, + expected_routes=expected_routes, + state_only=state_only, + recovery_audit=recovery_audit, + ) + except (TimeoutError, subprocess.TimeoutExpired): + return ["Worker health check deadline exceeded"] + + +def _parallel_check(function, items, workers, control): + """Queued probes must not start after cancellation or deadline expiry.""" + + def probe(item): + control.remaining() + result = function(item) + control.remaining() + return result + + executor = ThreadPoolExecutor(max_workers=min(workers, max(1, len(items)))) + futures = [] + try: + for item in items: + control.remaining() + futures.append(executor.submit(copy_context().run, probe, item)) + return [future.result(timeout=control.remaining()) for future in futures] + finally: + executor.shutdown(wait=True, cancel_futures=True) + + +def _check_worker_health( + worker: RuntimeIdentity, + influxdb_url: str | None = None, + influxdb_token: str | None = None, + influxdb_org: str | None = None, + health_retries: int | None = None, + health_delay: int | None = None, + scale_registry: ScaleRegistry | None = None, + require_client_agent: bool = True, + all_routing_devices: bool = False, + *, + topology: TopologyManifest, + control: OperationControl, + route_snapshot: dict | None = None, + expected_routes: dict | None = None, + state_only: bool = False, + recovery_audit: dict | None = None, ) -> list[str]: """Run all health checks and return a list of error messages (empty = healthy). @@ -186,7 +281,7 @@ def check_worker_health( """ errors: list[str] = [] topology_dir = str(worker.topology_dir) - topo = _load_topology_metadata(topology_dir) + topo = topology projected_topo = topo.to_agent_topology() lab_name = worker.lab_name if topo.name != worker.lab_name or topo.topology_id != worker.topology_id: @@ -226,6 +321,7 @@ def check_worker_health( text=True, check=False, timeout=30, + control=control, ) if telegraf_container not in ret.stdout.strip().splitlines(): errors.append(f"worker telegraf container is not running: {telegraf_container}") @@ -235,54 +331,143 @@ def check_worker_health( # [2/5] Container count logger.info("[2/5] Checking container count...") expected_nodes = len(switches) + len(clients) - running_nodes = _running_container_count(lab_name) + running_nodes = _running_container_count(lab_name, control=control) if running_nodes < expected_nodes: errors.append( - f"running node count mismatch for {lab_name}: " f"got {running_nodes} expected at least {expected_nodes}" + f"running node count mismatch for {lab_name}: got {running_nodes} expected at least {expected_nodes}" ) return errors + if state_only: + names = [clab_container_name(lab_name, d.name) for d in topo.devices] + inspected = safe_run( + [ + *docker_prefix(), + "docker", + "inspect", + "--format", + "{{.Name}} {{.State.Running}} {{.State.OOMKilled}}", + *names, + ], + capture_output=True, + text=True, + check=False, + timeout=30, + control=control, + ) + actual = {tuple(line.lstrip("/").split()) for line in inspected.stdout.splitlines()} + if inspected.returncode or actual != {(name, "true", "false") for name in names}: + return ["Runtime container identities or running state do not match"] + bgp_device = routed[0].name if routed else "spine1" convergence_targets = _convergence_targets(topo, all_routing_devices=all_routing_devices) + obs_device = edge_switches[0].name if edge_switches else (routed[0].name if routed else bgp_device) + syslog_marker = f"NETOPSBENCH_HEALTH_{lab_name}_{time.time_ns()}" + # Allow collector ingestion to overlap all-device convergence checks. + if collector_ip and not state_only: + _docker_exec( + clab_container_name(lab_name, bgp_device), + "bash", + "-lc", + f"logger -n '{collector_ip}' -P 514 -d '{syslog_marker}'", + control=control, + ) + network_interfaces: dict[str, set[str]] = {} + expected_counts = expected_network_counts(topo) logger.info( "[3/5] Checking BGP and interface convergence on %s routing devices...", len(convergence_targets), ) + route_errors = {} + def network_state(device) -> tuple[str, int, int, int, int]: container = clab_container_name(lab_name, device.name) - bgp = _docker_exec(container, "vtysh", "-c", "show ip bgp summary") - interfaces = _docker_exec(container, "bash", "-lc", "show interfaces status") + if route_snapshot is None: + bgp, interfaces = _routing_state(container, control=control) + else: + node_snapshot: dict = {} + bgp, interfaces = _routing_state(container, control=control, route_snapshot=node_snapshot) + from netopsbench.platform.observability.bgp_parser import parse_bgp_summary + + node_snapshot.update(bgp=parse_bgp_summary(bgp), interfaces=interfaces) + route_snapshot.setdefault("nodes", {})[device.name] = node_snapshot + if expected_routes is not None: + from netopsbench.platform.observability.routes import verify_route_recovery + + route_errors[device.name] = verify_route_recovery( + {"nodes": {device.name: expected_routes["nodes"].get(device.name, {})}}, + {"nodes": {device.name: node_snapshot}}, + ) + if state_only: + from netopsbench.platform.observability.bgp_parser import parse_bgp_summary + from netopsbench.platform.utils.interface_names import to_sonic_interface + + expected = (expected_routes or {}).get("nodes", {}).get(device.name) + issues = route_errors.setdefault(device.name, []) + if expected is None or expected.get("bgp_collection_ok") is not True: + issues.append("Missing pre-injection BGP evidence") + else: + wanted = { + (row["neighbor"], row["asn"]) + for row in expected.get("bgp", []) + if row.get("state") == "Established" + } + present = { + (row["neighbor"], row["asn"]) for row in parse_bgp_summary(bgp) if row.get("state") == "Established" + } + if wanted != present: + issues.append("BGP neighbor identities not restored") + required_interfaces = { + to_sonic_interface(e.interface) + for link in topo.links + for e in link.endpoints + if e.device == device.name + } + if not required_interfaces.issubset(_parse_active_interfaces(interfaces)): + issues.append("Expected interface identities not active") + network_interfaces[device.name] = _parse_active_interfaces(interfaces) return ( device.name, - _parse_bgp_established(bgp.stdout or ""), - _expected_bgp_neighbor_count(topo, device.name), - len(_parse_active_interfaces(interfaces.stdout or "")), - _expected_active_interface_count(topo, device.name), + _parse_bgp_established(bgp), + expected_counts[device.name]["bgp_neighbors"], + len(network_interfaces[device.name]), + expected_counts[device.name]["active_interfaces"], ) pending: dict[str, tuple[int, int, int, int]] = {} pending_devices = list(convergence_targets) + stable_passes = 0 for attempt in range(retries): - with ThreadPoolExecutor(max_workers=min(16, max(1, len(pending_devices)))) as network_executor: - network_states = list(network_executor.map(network_state, pending_devices)) + network_states = _parallel_check(network_state, pending_devices, 16, control) pending = { device: (established, expected_bgp, active, expected_active) for device, established, expected_bgp, active, expected_active in network_states - if established < expected_bgp or active < expected_active + if established < expected_bgp or active < expected_active or route_errors.get(device) } + if recovery_audit is not None: + recovery_audit["network_rounds"] = recovery_audit.get("network_rounds", 0) + 1 + recovery_audit["had_errors"] = recovery_audit.get("had_errors", False) or bool(pending) if not pending: - break - pending_devices = [device for device in pending_devices if device.name in pending] + stable_passes = stable_passes + 1 if len(pending_devices) == len(convergence_targets) else 0 + if not state_only or stable_passes == 2: + break + pending_devices = list(convergence_targets) + else: + stable_passes = 0 + pending_devices = [device for device in pending_devices if device.name in pending] if attempt + 1 < retries: - time.sleep(delay) + control.sleep(delay) + if state_only and stable_passes < 2 and not pending: + return ["Insufficient stable network observations"] if pending: details = ", ".join( f"{device}(bgp={state[0]}/{state[1]},if={state[2]}/{state[3]})" for device, state in sorted(pending.items())[:12] ) errors.append(f"network not converged on {len(pending)} routing devices: {details}") + errors.extend(error for name in pending for error in route_errors.get(name, [])) return errors # [4/5] Client connectivity + native Pingmesh process @@ -307,11 +492,13 @@ def network_state(device) -> tuple[str, int, int, int, int]: src_container = clab_container_name(lab_name, src_name) connectivity_ok = False for _ in range(retries): - ret = _docker_exec(src_container, "ping", "-c", "1", "-W", "2", dst_ip) + ret = _docker_exec(src_container, "ping", "-c", "1", "-W", "2", dst_ip, control=control) if ret.returncode == 0: connectivity_ok = True break - time.sleep(delay) + if recovery_audit is not None: + recovery_audit["had_errors"] = True + control.sleep(delay) if not connectivity_ok: errors.append(f"client connectivity failed from {src_container} to {dst_ip}") return errors @@ -325,7 +512,7 @@ def agent_state(client: dict) -> tuple[str, bool]: if not management_ip: return name, False try: - response = request_agent(management_ip, PINGMESH_CONTROL_PORT, "status") + response = request_agent(management_ip, PINGMESH_CONTROL_PORT, "status", timeout=control.remaining(2)) except (OSError, RuntimeError, ValueError): response = {} status = response.get("status") or {} @@ -334,72 +521,90 @@ def agent_state(client: dict) -> tuple[str, bool]: return name, bool( response.get("ok") is True and status.get("ready") is True + and status.get("plan_id") == topo.require_pingmesh_plan().settings.plan_id + and status.get("config_schema_version") == 2 and 0 <= heartbeat_age <= HEARTBEAT_MAX_AGE_SECONDS ) pending_agents = list(agent_targets) failed_agents: list[str] = [] for attempt in range(retries): - with ThreadPoolExecutor(max_workers=min(32, max(1, len(pending_agents)))) as agent_executor: - agent_states = list(agent_executor.map(agent_state, pending_agents)) + agent_states = _parallel_check(agent_state, pending_agents, 32, control) failed_agents = [name for name, ready in agent_states if not ready] if not failed_agents: break + if recovery_audit is not None: + recovery_audit["had_errors"] = True failed_set = set(failed_agents) pending_agents = [client for client in pending_agents if str(client.get("name", "")).strip() in failed_set] if attempt + 1 < retries: - time.sleep(delay) + control.sleep(delay) if failed_agents: preview = ", ".join(sorted(failed_agents)[:12]) errors.append(f"Native Pingmesh process is not ready on {len(failed_agents)} clients: {preview}") return errors + if state_only: + if recovery_audit is not None: + recovery_audit["collected_at"] = time.time() + return errors + # [5/5] InfluxDB observability path logger.info("[5/5] Checking InfluxDB observability path...") - obs_device = edge_switches[0].name if edge_switches else (routed[0].name if routed else bgp_device) - obs_container = clab_container_name(lab_name, obs_device) - - # Get active interfaces - ret = _docker_exec(obs_container, "bash", "-lc", "show interfaces status") - observed_active_interfaces = sorted(_parse_active_interfaces(ret.stdout or "")) - - # Send syslog marker - syslog_marker = f"NETOPSBENCH_HEALTH_{lab_name}_{int(time.time())}" - if collector_ip: - _docker_exec( - clab_container_name(lab_name, bgp_device), - "bash", - "-lc", - f"logger -n '{collector_ip}' -P 514 -d '{syslog_marker}'", + if obs_device in network_interfaces: + observed_active_interfaces = sorted(network_interfaces[obs_device]) + else: + ret = _docker_exec( + clab_container_name(lab_name, obs_device), "bash", "-lc", "show interfaces status", control=control ) + observed_active_interfaces = sorted(_parse_active_interfaces(ret.stdout or "")) # Delegate to the observability validation module from netopsbench.platform.observability.influxdb import query_flux from netopsbench.platform.observability.validation import check_observability def query_runner(query: str) -> str: - result = query_flux(influxdb_url, influxdb_token, influxdb_org, query, timeout=20) + result = query_flux( + influxdb_url, influxdb_token, influxdb_org, query, timeout=control.remaining(20), deadline=control.deadline + ) if result.status != "ok": raise RuntimeError(result.error or "InfluxDB query failed") return result.text + pending_checks = {"interfaces", "syslog"} + if require_client_agent: + pending_checks.add("pingmesh") + if bgp_device: + pending_checks.add("bgp") + + def observe(check: str) -> tuple[str, list[str]]: + try: + result = check_observability( + query_runner, + bucket=worker.bucket, + obs_device=obs_device, + bgp_device=bgp_device, + topology_id=worker.topology_id, + plan_id=topo.require_pingmesh_plan().settings.plan_id, + syslog_marker=syslog_marker, + active_interfaces=observed_active_interfaces, + min_active_coverage_ratio=ACTIVE_INTERFACE_COVERAGE_MIN_RATIO, + require_pingmesh=require_client_agent, + checks={check}, + ) + except RuntimeError as exc: + result = [str(exc)] + return check, result + obs_errors: list[str] = [] for attempt in range(retries): - obs_errors = check_observability( - query_runner, - bucket=worker.bucket, - obs_device=obs_device, - bgp_device=bgp_device, - topology_id=worker.topology_id, - syslog_marker=syslog_marker, - active_interfaces=observed_active_interfaces, - min_active_coverage_ratio=ACTIVE_INTERFACE_COVERAGE_MIN_RATIO, - require_pingmesh=require_client_agent, - ) - if not obs_errors: + results = _parallel_check(observe, sorted(pending_checks), 4, control) + obs_errors = [error for _check, check_errors in results for error in check_errors] + pending_checks = {check for check, check_errors in results if check_errors} + if not pending_checks: break if attempt + 1 < retries: - time.sleep(delay) + control.sleep(delay) errors.extend(obs_errors) if not errors: diff --git a/netopsbench/platform/runtime/lifecycle.py b/netopsbench/platform/runtime/lifecycle.py index 506cb5d..f1d9a0d 100644 --- a/netopsbench/platform/runtime/lifecycle.py +++ b/netopsbench/platform/runtime/lifecycle.py @@ -5,6 +5,7 @@ import logging from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor, as_completed +from contextvars import copy_context from datetime import UTC, datetime from pathlib import Path from time import monotonic @@ -26,6 +27,8 @@ teardown_worker_lab, ) from netopsbench.platform.runtime.health import check_worker_health +from netopsbench.platform.utils.control import OperationControl +from netopsbench.platform.utils.measurements import measurement_scope logger = logging.getLogger(__name__) @@ -87,12 +90,16 @@ def deploy_workers( scale: str, runtime_root: Path | None = None, scale_registry: ScaleRegistry | None = None, + *, + control: OperationControl | None = None, ) -> None: if not workers: return job_count = _parallel_job_count(scale, len(workers), scale_registry) def deploy(worker: RuntimeIdentity) -> None: + if control is not None: + control.remaining() logger.info( "[Worker Deploy %s/%s] %s subnet=%s", worker.worker_index, @@ -101,7 +108,7 @@ def deploy(worker: RuntimeIdentity) -> None: worker.mgmt_subnet, ) _append_worker_log_header(_worker_deploy_log_path(worker, runtime_root), f"worker deploy {worker.lab_name}") - deploy_worker_lab(worker, scale, scale_registry) + deploy_worker_lab(worker, scale, scale_registry, **({"control": control} if control is not None else {})) if job_count == 1: for worker in workers: @@ -110,7 +117,7 @@ def deploy(worker: RuntimeIdentity) -> None: failures: list[tuple[RuntimeIdentity, Exception]] = [] with ThreadPoolExecutor(max_workers=job_count) as executor: - future_map = {executor.submit(deploy, worker): worker for worker in workers} + future_map = {executor.submit(copy_context().run, deploy, worker): worker for worker in workers} for future in as_completed(future_map): try: future.result() @@ -126,11 +133,12 @@ def deploy(worker: RuntimeIdentity) -> None: raise error -def ensure_worker_client_agent(worker: RuntimeIdentity) -> None: +def ensure_worker_client_agent(worker: RuntimeIdentity, *, control: OperationControl | None = None) -> None: preflight_errors = check_worker_health( worker, require_client_agent=False, all_routing_devices=True, + cancel_event=control.cancel_event if control else None, ) if preflight_errors: raise RuntimeError("Network must converge before starting native client agents: " + "; ".join(preflight_errors)) @@ -146,10 +154,17 @@ def validate_worker_health( worker: RuntimeIdentity, runtime_root: Path | None = None, scale_registry: ScaleRegistry | None = None, + *, + control: OperationControl | None = None, ) -> None: log_path = _worker_deploy_log_path(worker, runtime_root) _append_worker_log_header(log_path, "worker health validation") - errors = check_worker_health(worker, scale_registry=scale_registry) + errors = check_worker_health( + worker, + scale_registry=scale_registry, + all_routing_devices=True, + cancel_event=control.cancel_event if control else None, + ) if errors: message = "; ".join(errors) with open(log_path, "a", encoding="utf-8") as log_file: @@ -203,6 +218,7 @@ class RuntimeLifecycle: def __init__(self, scale_registry: ScaleRegistry | None = None): self.scale_registry = scale_registry or default_scale_registry() + self.control: OperationControl | None = None def run(self, stage: str, runtime: RuntimePoolLike) -> LifecycleStageResult: operations = { @@ -219,8 +235,13 @@ def run(self, stage: str, runtime: RuntimePoolLike) -> LifecycleStageResult: started_at = datetime.now(UTC) started_tick = monotonic() + counts: dict[str, int] = {} try: - details = operation(runtime) or {} + if self.control is not None: + self.control.remaining() + with measurement_scope(counts): + details = operation(runtime) or {} + details["operations"] = counts except Exception as exc: ended_at = datetime.now(UTC) result = LifecycleStageResult( @@ -230,6 +251,7 @@ def run(self, stage: str, runtime: RuntimePoolLike) -> LifecycleStageResult: ended_at=ended_at, duration_seconds=monotonic() - started_tick, error=f"{type(exc).__name__}: {exc}", + details={"operations": counts}, ) raise RuntimeLifecycleError(result) from exc @@ -243,7 +265,7 @@ def run(self, stage: str, runtime: RuntimePoolLike) -> LifecycleStageResult: ) def _deploy(self, runtime: RuntimePoolLike) -> dict[str, Any]: - with runtime_deploy_lock(): + with runtime_deploy_lock(self.control): subnets = allocate_management_subnets(runtime.scale, runtime.size, self.scale_registry) runtime.workers = [ worker.model_copy(update={"mgmt_subnet": subnets[index]}) @@ -252,11 +274,16 @@ def _deploy(self, runtime: RuntimePoolLike) -> dict[str, Any]: for worker in runtime.workers: assert_worker_slot_available(worker) runtime.metadata["deployment_started"] = True - deploy_workers(runtime.workers, runtime.scale, runtime.root_dir, self.scale_registry) + deploy_workers( + runtime.workers, + runtime.scale, + runtime.root_dir, + self.scale_registry, + **({"control": self.control} if self.control is not None else {}), + ) return {"workers": runtime.size} - @staticmethod - def _ensure_observability(runtime: RuntimePoolLike) -> dict[str, Any]: + def _ensure_observability(self, runtime: RuntimePoolLike) -> dict[str, Any]: registry = ManagedBucketRegistry(runtime.telemetry_ownership_file) created: list[str] = [] @@ -266,22 +293,33 @@ def record_created(bucket: str) -> None: runtime._provision_created_buckets.append(bucket) for worker in runtime.workers: + if self.control is not None: + self.control.remaining() ensure_worker_observability( worker, on_bucket_created=record_created, ) return {"workers": runtime.size, "created_buckets": created} - @staticmethod - def _ensure_pingmesh(runtime: RuntimePoolLike) -> dict[str, Any]: + def _ensure_pingmesh(self, runtime: RuntimePoolLike) -> dict[str, Any]: for worker in runtime.workers: - ensure_worker_client_agent(worker) + ensure_worker_client_agent(worker, **({"control": self.control} if self.control is not None else {})) return {"workers": runtime.size} def _warm(self, runtime: RuntimePoolLike) -> dict[str, Any]: for worker in runtime.workers: - validate_worker_health(worker, runtime.root_dir, self.scale_registry) - return {"workers": runtime.size, "health": "ready"} + validate_worker_health( + worker, + runtime.root_dir, + self.scale_registry, + **({"control": self.control} if self.control is not None else {}), + ) + return { + "workers": runtime.size, + "health": "ready", + "all_routing_devices": True, + "checked_at": datetime.now(UTC).isoformat(), + } def _teardown(self, runtime: RuntimePoolLike) -> dict[str, Any]: teardown_workers(runtime.workers, self.scale_registry) diff --git a/netopsbench/platform/runtime/manager.py b/netopsbench/platform/runtime/manager.py index b8f91f1..e58765e 100644 --- a/netopsbench/platform/runtime/manager.py +++ b/netopsbench/platform/runtime/manager.py @@ -8,6 +8,7 @@ import uuid from dataclasses import dataclass, field from pathlib import Path +from threading import RLock from pydantic import ValidationError @@ -24,6 +25,8 @@ RuntimeLifecycleError, teardown_workers, ) +from netopsbench.platform.runtime.toolchain import runtime_backend_identity +from netopsbench.platform.utils.control import OperationControl from netopsbench.platform.utils.files import atomic_write_json from netopsbench.platform.utils.proc import safe_run @@ -47,6 +50,8 @@ class RuntimePool: scale_registry: ScaleRegistry = field(default_factory=default_scale_registry, repr=False) telemetry_ownership_file: Path = field(repr=False, default=Path(".netopsbench/telemetry-buckets.json")) _provision_created_buckets: list[str] = field(default_factory=list, repr=False) + operation_control: OperationControl | None = field(default=None, repr=False) + _metadata_lock: RLock = field(default_factory=RLock, repr=False, compare=False) @property def size(self) -> int: @@ -56,7 +61,7 @@ def describe(self) -> dict[str, object]: """Return the canonical serializable runtime description.""" profile = self.scale_registry.get(self.scale) return { - "schema_version": "3", + "schema_version": "4", "id": self.id, "name": self.name, "scale": self.scale, @@ -74,11 +79,28 @@ def _write_metadata(self) -> None: atomic_write_json(self.root_dir / "runtime.json", self.describe()) def _run_stage(self, stage: str, next_state: str) -> RuntimePool: + if stage != "teardown" and self.operation_control is not None: + self.operation_control.remaining() + if stage != "teardown": + identity = runtime_backend_identity() + previous_backend = self.metadata.get("runtime_backend") + if ( + previous_backend is None + and self.state == "created" + and not self.stage_results + and not self.metadata.get("deployment_started") + ): + self.metadata["runtime_backend"] = identity + self._write_metadata() # Durable even if deployment is interrupted. + elif previous_backend != identity: + raise ValueError("Runtime backend changed or is unrecorded; archive it and create a new runtime") previous = self.stage_results.get(stage) if previous is not None and previous.status == "completed": return self try: - result = RuntimeLifecycle(scale_registry=self.scale_registry).run(stage, self) + lifecycle = RuntimeLifecycle(scale_registry=self.scale_registry) + lifecycle.control = None if stage == "teardown" else self.operation_control + result = lifecycle.run(stage, self) except RuntimeLifecycleError as exc: self.stage_results[stage] = exc.result self._write_metadata() @@ -88,6 +110,20 @@ def _run_stage(self, stage: str, next_state: str) -> RuntimePool: self._write_metadata() return self + def mark_quarantined(self, reason: str, workers: list[str] | None = None) -> None: + """Persist recovery failure immediately and accumulate affected workers.""" + with self._metadata_lock: + changes = {"quarantined": True, "quarantine_reason": reason} + if workers is not None: + previous = self.metadata.get("quarantined_workers") + known = {str(worker) for worker in previous} if isinstance(previous, list) else set() + changes["quarantined_workers"] = sorted(known | set(workers)) + if self.state == "quarantined" and all(self.metadata.get(k) == v for k, v in changes.items()): + return + self.metadata.update(changes) + self.state = "quarantined" + self._write_metadata() + def deploy(self) -> RuntimePool: return self._run_stage("deploy", "deployed") @@ -103,58 +139,59 @@ def warm(self) -> RuntimePool: def status(self) -> dict[str, object]: return {"id": self.id, "name": self.name, "scale": self.scale, "state": self.state} + def _record_cleanup_failure(self, error: BaseException, provision_error: BaseException | None = None) -> None: + self.state = "cleanup_failed" + self.metadata.update( + quarantined=True, + cleanup_error=f"{type(error).__name__}: {error}", + cleanup_pending_buckets=list(self._provision_created_buckets), + ) + if provision_error is not None: + self.metadata["provision_error"] = f"{type(provision_error).__name__}: {provision_error}" + try: + self._write_metadata() + except BaseException as metadata_error: + self.metadata["quarantine_persistence_error"] = f"{type(metadata_error).__name__}: {metadata_error}" + logger.warning("Unable to persist runtime cleanup failure", exc_info=True) + + def _remove_root(self) -> None: + shutil.rmtree(self.root_dir, ignore_errors=True) + if self.root_dir.exists(): + try: + safe_run( + ["sudo", "-n", "rm", "-rf", str(self.root_dir)], + check=False, + capture_output=True, + text=True, + timeout=120, + ) + except Exception: + logger.warning("sudo rm of runtime root failed during cleanup", exc_info=True) + if self.root_dir.exists(): + raise RuntimeError(f"runtime directory remained after cleanup: {self.root_dir}") + def teardown(self) -> RuntimePool: if self.state == "torn_down": return self - # ``create()`` only reserves metadata; it has no physical lab to - # teardown. A failed deploy does have a stage result and must still - # attempt precise cleanup of any partially-created resources. - if self.state != "created" or "deploy" in self.stage_results: - try: + try: + # A reservation owns no lab. Interrupted deployment still does, + # even when it has not written a lifecycle stage result yet. + if self.state != "created" or "deploy" in self.stage_results or self.metadata.get("deployment_started"): + pending = self.metadata.get("cleanup_pending_buckets") + self._provision_created_buckets = ( + [str(bucket) for bucket in pending] + if self.state == "cleanup_failed" and isinstance(pending, list) + else ManagedBucketRegistry(self.telemetry_ownership_file).active_for_runtime(self.id) + ) RuntimeLifecycle(scale_registry=self.scale_registry).run("teardown", self) - except RuntimeLifecycleError as exc: - self.stage_results["teardown"] = exc.result - self.state = "cleanup_failed" - self.metadata["quarantined"] = True - self.metadata["cleanup_error"] = exc.result.error or str(exc) - self.metadata["cleanup_pending_buckets"] = ManagedBucketRegistry( - self.telemetry_ownership_file - ).active_for_runtime(self.id) - self._write_metadata() - raise - registry = ManagedBucketRegistry(self.telemetry_ownership_file) - pending = self.metadata.get("cleanup_pending_buckets") - if self.state == "cleanup_failed" and isinstance(pending, list): - self._provision_created_buckets = [str(bucket) for bucket in pending] - else: - self._provision_created_buckets = registry.active_for_runtime(self.id) - try: self._delete_provision_created_buckets() - except Exception as exc: - self.state = "cleanup_failed" - self.metadata["quarantined"] = True - self.metadata["cleanup_error"] = f"{type(exc).__name__}: {exc}" - self.metadata["cleanup_pending_buckets"] = list(self._provision_created_buckets) - self._write_metadata() - raise - self.metadata.pop("cleanup_pending_buckets", None) - - if self.root_dir.exists(): - shutil.rmtree(self.root_dir, ignore_errors=True) - if self.root_dir.exists(): - safe_run( - ["sudo", "-n", "rm", "-rf", str(self.root_dir)], - check=False, - capture_output=True, - text=True, - timeout=120, - ) - if self.root_dir.exists(): - self.state = "cleanup_failed" - self.metadata["quarantined"] = True - self.metadata["cleanup_error"] = f"runtime directory remained after teardown: {self.root_dir}" - self._write_metadata() - raise RuntimeError(str(self.metadata["cleanup_error"])) + self.metadata.pop("cleanup_pending_buckets", None) + self._remove_root() + except BaseException as exc: + if isinstance(exc, RuntimeLifecycleError): + self.stage_results["teardown"] = exc.result + self._record_cleanup_failure(exc) + raise self.state = "torn_down" return self @@ -175,6 +212,16 @@ def _delete_provision_created_buckets(self) -> None: raise RuntimeError("Managed bucket cleanup failed: " + "; ".join(errors)) +class RuntimeProvisionError(RuntimeError): + """Provisioning left owned resources that still require cleanup.""" + + def __init__(self, runtime: RuntimePool, message: str): + self.runtime = runtime + self.provision_error: BaseException | None = None + self.cleanup_error: BaseException | None = None + super().__init__(message) + + class RuntimeManager: def __init__(self, workspace: str = ".", scale_registry: ScaleRegistry | None = None): self.workspace = Path(workspace).expanduser().resolve() @@ -228,75 +275,40 @@ def _build_runtime( runtime._write_metadata() return runtime + @staticmethod + def _failed_provision( + runtime: RuntimePool, provision_error: BaseException, cleanup_error: BaseException + ) -> RuntimeProvisionError: + """Retain ownership even when persisting the quarantine also fails.""" + runtime._record_cleanup_failure(cleanup_error, provision_error) + error = RuntimeProvisionError( + runtime, + f"Runtime provisioning failed ({runtime.metadata['provision_error']}) " + f"and cleanup failed ({runtime.metadata['cleanup_error']})", + ) + error.provision_error = provision_error + error.cleanup_error = cleanup_error + return error + def provision( self, *, scale: str, workers: int = 1, name: str | None = None, root_dir: Path | None = None ) -> RuntimePool: runtime = self._build_runtime(scale=scale, workers=workers, name=name, root_dir=root_dir) try: runtime.deploy().ensure_observability().ensure_pingmesh().warm() - except Exception as provision_error: + runtime.metadata["provisioning_mode"] = "worker_pool" + runtime.state = "warm" + runtime._write_metadata() + except BaseException as provision_error: logger.warning("Worker deployment failed; tearing down partial state", exc_info=True) try: if runtime.metadata.get("deployment_started"): teardown_workers(runtime.workers, self.scale_registry) - except Exception as cleanup_error: - logger.warning("Best-effort teardown_workers failed during cleanup", exc_info=True) - runtime.state = "cleanup_failed" - runtime.metadata["quarantined"] = True - runtime.metadata["cleanup_error"] = f"{type(cleanup_error).__name__}: {cleanup_error}" - runtime.metadata["cleanup_pending_buckets"] = list(runtime._provision_created_buckets) - runtime._write_metadata() - raise RuntimeError( - f"Runtime provisioning failed ({type(provision_error).__name__}: " - f"{provision_error}) and cleanup failed " - f"({type(cleanup_error).__name__}: {cleanup_error})" - ) from cleanup_error - - try: runtime._delete_provision_created_buckets() - except Exception as cleanup_error: - logger.warning("Managed bucket cleanup failed during provisioning compensation", exc_info=True) - runtime.state = "cleanup_failed" - runtime.metadata["quarantined"] = True - runtime.metadata["cleanup_error"] = f"{type(cleanup_error).__name__}: {cleanup_error}" - runtime.metadata["cleanup_pending_buckets"] = list(runtime._provision_created_buckets) - runtime._write_metadata() - raise RuntimeError( - f"Runtime provisioning failed ({type(provision_error).__name__}: " - f"{provision_error}) and cleanup failed " - f"({type(cleanup_error).__name__}: {cleanup_error})" - ) from cleanup_error - # Use sudo rm to handle root-owned files left by containerlab. - try: - safe_run( - ["sudo", "-n", "rm", "-rf", str(runtime.root_dir)], - check=False, - capture_output=True, - timeout=120, - ) - except Exception: - logger.warning("sudo rm of runtime root failed during cleanup", exc_info=True) - if runtime.root_dir.exists(): - shutil.rmtree(runtime.root_dir, ignore_errors=True) - if runtime.root_dir.exists(): - residual_cleanup_error = RuntimeError( - f"runtime directory remained after provisioning cleanup: {runtime.root_dir}" - ) - runtime.state = "cleanup_failed" - runtime.metadata["quarantined"] = True - runtime.metadata["cleanup_error"] = str(residual_cleanup_error) - try: - runtime._write_metadata() - except Exception: - logger.warning("Unable to persist provisioning cleanup failure", exc_info=True) - raise RuntimeError( - f"Runtime provisioning failed ({type(provision_error).__name__}: " - f"{provision_error}) and cleanup failed ({residual_cleanup_error})" - ) from residual_cleanup_error + runtime._remove_root() + except BaseException as cleanup_error: + raise self._failed_provision(runtime, provision_error, cleanup_error) from cleanup_error raise - runtime.metadata["provisioning_mode"] = "worker_pool" - runtime.state = "warm" - runtime._write_metadata() return runtime def create(self, *, scale: str, workers: int = 1, name: str | None = None) -> RuntimePool: @@ -311,7 +323,7 @@ def attach(self, root_dir: Path) -> RuntimePool: raise except (OSError, json.JSONDecodeError) as exc: raise RuntimeMetadataError(f"Unable to read runtime metadata {metadata_path}: {exc}") from exc - if payload.get("schema_version") != "3": + if payload.get("schema_version") != "4": raise RuntimeMetadataError( "Unsupported runtime.json schema; recreate the runtime with the current RuntimeManager" ) @@ -342,7 +354,7 @@ def attach(self, root_dir: Path) -> RuntimePool: } except (KeyError, TypeError, ValidationError, ValueError) as exc: raise RuntimeMetadataError( - f"Invalid schema-v3 runtime metadata in {metadata_path}; recreate the runtime: {exc}" + f"Invalid schema-v4 runtime metadata in {metadata_path}; recreate the runtime: {exc}" ) from exc return RuntimePool( id=str(payload["id"]), diff --git a/netopsbench/platform/runtime/resources.py b/netopsbench/platform/runtime/resources.py new file mode 100644 index 0000000..511e8f8 --- /dev/null +++ b/netopsbench/platform/runtime/resources.py @@ -0,0 +1,305 @@ +"""Measured lab capacity and resource monitoring, independent of acceptance policy.""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +import threading +from collections import Counter +from datetime import UTC, datetime +from pathlib import Path + +from netopsbench.models.profiles import get_scale_profile +from netopsbench.platform.runtime.toolchain import runtime_backend_identity +from netopsbench.platform.topology.topology_utils import load_topology_manifest +from netopsbench.platform.utils.control import OperationControl +from netopsbench.platform.utils.proc import safe_run + +GIB = 1024**3 +EMERGENCY_MEMORY_BYTES = 12 * GIB + + +def available_memory_bytes() -> int: + return next( + int(line.split()[1]) * 1024 + for line in Path("/proc/meminfo").read_text().splitlines() + if line.startswith("MemAvailable:") + ) + + +class ResourceMonitor: + """Monitor memory before allocation; attach Docker sampling once a lab exists.""" + + def __init__(self, result, cancel, emergency, lock): + self.result, self.cancel, self.emergency, self.lock = result, cancel, emergency, lock + self.target = None + self.stop = threading.Event() + self.thread = threading.Thread(target=self._run, daemon=True) + + def watch(self, entry, lab_name, manifest): + with self.lock: + self.target = (entry, lab_name, manifest) + + def start(self): + self._memory_sample() + self.thread.start() + + def close(self): + self.stop.set() + if self.thread.ident is not None: + self.thread.join() + + def _memory_sample(self): + available = available_memory_bytes() + with self.lock: + self.result.setdefault("memory_samples", []).append( + { + "time": datetime.now(UTC).isoformat(), + "available_bytes": available, + } + ) + if available < EMERGENCY_MEMORY_BYTES: + self.result["resource_emergency"] = "MemAvailable below 12 GiB" + self.emergency.set() + self.cancel.set() + + def _run(self): + # Docker stats may block; keep emergency monitoring on its own thread. + sampler = threading.Thread(target=self._sample, daemon=True) + sampler.start() + try: + while not self.stop.is_set(): + self._memory_sample() + self.stop.wait(1) + except Exception as exc: + with self.lock: + self.result["memory_monitor_error"] = str(exc) + self.cancel.set() + finally: + sampler.join() + + def _sample(self): + while not self.stop.is_set(): + with self.lock: + target = self.target + if target is not None and target[0] is not None: + entry, lab_name, manifest = target + try: + if isinstance(manifest, Path): + if not (manifest / "topology.json").exists(): + self.stop.wait(1) + continue + manifest = load_topology_manifest(manifest) + sample = resource_snapshot(lab_name, manifest, control=OperationControl(self.stop)) + with self.lock: + if self.target is target: + entry["resource_samples"].append(sample) + except Exception as exc: + with self.lock: + if not self.stop.is_set(): + entry["monitor_error"] = str(exc) + self.stop.wait(15) + + +def memory_bytes(value: str) -> int: + match = re.fullmatch(r"([\d.]+)([A-Za-z]+)", value.strip()) + if match is None: + raise ValueError(f"Invalid Docker memory quantity: {value}") + number, unit = match.groups() + powers = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": GIB, "TiB": 1024**4} + return int(float(number) * powers[unit]) + + +def resource_snapshot(lab_name: str, manifest, *, control: OperationControl | None = None) -> dict: + def output(command, **kwargs): + return safe_run(command, check=True, control=control, **kwargs).stdout + + ports = Counter(endpoint.device for link in manifest.links for endpoint in link.endpoints) + names = output( + ["docker", "ps", "--filter", f"label=containerlab={lab_name}", "--format", "{{.Names}}"], + text=True, + ).split() + services = output(["docker", "ps", "--format", "{{.Names}}"], text=True).split() + services = [name for name in services if name in {"influxdb", "grafana", f"telegraf-{lab_name}"}] + diagnostics = output( + ["docker", "ps", "--filter", "label=netopsbench.role=diagnostic", "--format", "{{.Names}}"], text=True + ).split() + names.extend(services) + names.extend(diagnostics) + rows = ( + output( + ["docker", "stats", "--no-stream", "--format", "{{json .}}", *names], + text=True, + timeout=60, + ) + if names + else "" + ) + sizes = ( + output( + ["docker", "inspect", "--size", "--format", "{{.Name}} {{.SizeRw}}", *names], + text=True, + timeout=60, + ) + if names + else "" + ) + writable_bytes = {name.lstrip("/"): int(size) for name, size in map(str.split, sizes.splitlines())} + return { + "runtime_backend": runtime_backend_identity(), + "time": datetime.now(UTC).isoformat(), + "nodes": [ + dict( + name=row["Name"], + role=( + "diagnostic" + if row["Name"] in diagnostics + else ( + "observability" + if row["Name"] in services + else "client" if "-client" in row["Name"] else "switch" + ) + ), + data_ports=ports.get(row["Name"].removeprefix(f"clab-{lab_name}-"), 0), + memory_bytes=memory_bytes(row["MemUsage"].split("/")[0]), + writable_bytes=writable_bytes[row["Name"]], + ) + for row in map(json.loads, rows.splitlines()) + ], + } + + +def storage_snapshot() -> dict: + """Measure shared observability data separately from container writable layers.""" + return { + "time": datetime.now(UTC).isoformat(), + "influxdb_data_bytes": int( + subprocess.check_output( + ["docker", "exec", "influxdb", "du", "-sb", "/var/lib/influxdb2"], text=True, timeout=60 + ).split()[0] + ), + "grafana_data_bytes": int( + subprocess.check_output( + ["docker", "exec", "grafana", "du", "-sb", "/var/lib/grafana"], text=True, timeout=60 + ).split()[0] + ), + } + + +def peak_sample(samples: list[dict]) -> dict: + identities = [sample.get("runtime_backend") for sample in samples] + if not identities or identities[0] is None or any(identity != identities[0] for identity in identities): + raise ValueError("Capacity samples must belong to the same recorded runtime backend") + nodes: dict[str, dict] = {} + for sample in samples: + for row in sample["nodes"]: + peak = nodes.setdefault(row["name"], dict(row)) + for key in ("memory_bytes", "writable_bytes"): + peak[key] = max(peak[key], row[key]) + return {"nodes": list(nodes.values()), "runtime_backend": identities[0]} + + +def capacity_check( + sample: dict, scale: str, docker_root: Path, existing_runtime: bool = False, diagnostics: bool = True +) -> dict: + if sample.get("runtime_backend") != runtime_backend_identity(): + raise ValueError("Capacity sample uses a different or unrecorded backend; measure the current runtime first") + profile = get_scale_profile(scale) + switches = [ + row for row in sample["nodes"] if row.get("role", "switch") == "switch" and "-client" not in row["name"] + ] + clients = [row["memory_bytes"] for row in sample["nodes"] if "-client" in row["name"]] + if not switches or not clients: + raise RuntimeError("Capacity check requires a converged switch/client sample") + available = next( + int(line.split()[1]) * 1024 + for line in Path("/proc/meminfo").read_text().splitlines() + if line.startswith("MemAvailable:") + ) + if profile.family == "clos": + assert profile.num_leafs is not None and profile.num_spines is not None + required_ports: Counter[int] = Counter() + required_ports[int(profile.num_leafs)] += int(profile.num_spines) + required_ports[int(profile.num_spines) + profile.clients_per_attached_switch] += int(profile.num_leafs) + else: + assert profile.fat_tree_k is not None and profile.num_cores is not None and profile.num_aggs is not None + assert profile.num_edges is not None + k = int(profile.fat_tree_k) + required_ports = Counter() + required_ports[k] += int(profile.num_cores) + int(profile.num_aggs) + required_ports[k // 2 + profile.clients_per_attached_switch] += int(profile.num_edges) + costs = [] + for ports, count in sorted(required_ports.items()): + classes = sorted({row.get("data_ports", 0) for row in switches}) + representative = next((value for value in classes if value >= ports), classes[-1]) + rows = [row for row in switches if row.get("data_ports", 0) == representative] + costs.append( + { + "required_ports": ports, + "switches": count, + "sample_ports": representative, + "sample_memory_bytes": max(row["memory_bytes"] for row in rows), + "sample_writable_bytes": max(row["writable_bytes"] for row in rows), + "extrapolated": representative < ports, + } + ) + diagnostic_reserve = int(2.25 * GIB) if diagnostics else 0 + # Match port capacity before applying the maximum measured node cost and margin. + estimated = int( + 1.2 + * ( + sum(row["sample_memory_bytes"] * row["switches"] for row in costs) + + max(clients) * profile.total_clients + + 8 * GIB + + diagnostic_reserve + ) + ) + disk_free = shutil.disk_usage(docker_root).free + client_disk = max(row["writable_bytes"] for row in sample["nodes"] if "-client" in row["name"]) + estimated_disk = int( + 1.2 + * ( + sum(row["sample_writable_bytes"] * row["switches"] for row in costs) + + client_disk * profile.total_clients + + 20 * GIB + ) + ) + full_memory, full_disk = estimated, estimated_disk + if existing_runtime: + # MemAvailable already excludes the retained lab's allocation. Resume + # needs headroom for diagnosis/services, not a second copy of the lab. + estimated = int(1.2 * (8 * GIB + diagnostic_reserve)) + estimated_disk = 20 * GIB + result = { + "available_memory_bytes": available, + "estimated_memory_bytes": estimated, + "docker_disk_free_bytes": disk_free, + "estimated_disk_bytes": estimated_disk, + "memory_margin": 1.2, + "diagnostic_memory_reserve_bytes": diagnostic_reserve, + "mode": "retained_runtime" if existing_runtime else "new_deployment", + "full_runtime_estimated_memory_bytes": full_memory, + "full_runtime_estimated_disk_bytes": full_disk, + "switch_costs": costs, + "status": ( + "passed" + if estimated <= available + and disk_free >= estimated_disk + and not (not existing_runtime and scale == "fat-tree-k18" and any(row["extrapolated"] for row in costs)) + else "blocked" + ), + } + return result + + +def require_capacity(capacity, allow): + if capacity["status"] == "passed": + return + if not allow or ( + capacity["available_memory_bytes"] < capacity["estimated_memory_bytes"] / 1.2 + EMERGENCY_MEMORY_BYTES + or capacity["docker_disk_free_bytes"] < capacity["estimated_disk_bytes"] + or any(cost["extrapolated"] for cost in capacity["switch_costs"]) + ): + raise RuntimeError(f"Capacity check failed: {capacity}") diff --git a/netopsbench/platform/runtime/toolchain.py b/netopsbench/platform/runtime/toolchain.py new file mode 100644 index 0000000..0fa81a0 --- /dev/null +++ b/netopsbench/platform/runtime/toolchain.py @@ -0,0 +1,71 @@ +"""Resolve a checksum-verified official Containerlab release, without global fallback.""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +from pathlib import Path + +ASSETS = Path(__file__).with_name("assets") +DEFAULT_TOOLS = Path(__file__).with_name("_bin") + + +def release_spec() -> dict: + lock = json.loads((ASSETS / "containerlab.lock.json").read_text()) + architecture = {"x86_64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine()) + if platform.system() != "Linux" or architecture not in lock["releases"]: + raise RuntimeError("The pinned runtime supports Linux amd64 and arm64 only") + return { + "provider": lock["provider"], + "version": lock["version"], + "architecture": architecture, + **lock["releases"][architecture], + } + + +def binary_version(binary: Path) -> str: + result = subprocess.run([str(binary), "version", "--json"], capture_output=True, text=True, check=True, timeout=10) + version = json.loads(result.stdout)["version"] + if not isinstance(version, str): + raise ValueError("Invalid Containerlab version response") + return version + + +def runtime_tools() -> Path: + root = Path(os.environ.get("NETOPSBENCH_RUNTIME_TOOLS", str(DEFAULT_TOOLS))).expanduser().resolve() + hint = "Prepare the official runtime: python -m netopsbench.platform.runtime.build_tools" + try: + spec = release_spec() + manifest = json.loads((root / "manifest.json").read_text()) + if manifest != spec: + raise ValueError("Runtime tools do not match the locked official release") + binary = root / "containerlab" + if not binary.is_file() or not os.access(binary, os.X_OK): + raise ValueError("Missing executable: containerlab") + if hashlib.sha256(binary.read_bytes()).hexdigest() != spec["binary_sha256"]: + raise ValueError("Containerlab executable checksum mismatch") + if binary_version(binary) != spec["version"]: + raise ValueError("Containerlab executable version mismatch") + except (OSError, ValueError, KeyError, subprocess.SubprocessError) as exc: + raise RuntimeError(f"{hint}. {exc}") from exc + return root + + +def containerlab_command() -> list[str]: + return [str(runtime_tools() / "containerlab")] + + +def runtime_backend_identity() -> dict[str, str]: + """Freeze the actual executable and SONiC startup behavior in runtime/campaign identity.""" + root = runtime_tools() + from netopsbench.platform.topology.config import SONIC_START_WRAPPER_SOURCE + + return { + "provider": "upstream", + "containerlab_version": binary_version(root / "containerlab"), + "containerlab_sha256": hashlib.sha256((root / "containerlab").read_bytes()).hexdigest(), + "sonic_start_sha256": hashlib.sha256(SONIC_START_WRAPPER_SOURCE.read_bytes()).hexdigest(), + } diff --git a/netopsbench/platform/scenario/artifacts.py b/netopsbench/platform/scenario/artifacts.py new file mode 100644 index 0000000..01d77f0 --- /dev/null +++ b/netopsbench/platform/scenario/artifacts.py @@ -0,0 +1,45 @@ +"""Persist large private route evidence separately from the public result fields.""" + +from __future__ import annotations + +import gzip +import hashlib +import json +from pathlib import Path + +from netopsbench.platform.utils.files import atomic_write_bytes, atomic_write_json + + +def persist_result(path: Path, result: dict) -> None: + """Keep results in JSON and losslessly compress the private phase snapshots.""" + evidence_dir = path.parent / "evidence" / path.stem + + def snapshot_reference(name, snapshot): + raw = json.dumps(snapshot, separators=(",", ":"), default=str, ensure_ascii=False).encode() + compressed = gzip.compress(raw, compresslevel=3, mtime=0) + artifact = evidence_dir / f"{name}.json.gz" + atomic_write_bytes(artifact, compressed) + return { + "path": str(artifact.resolve()), + "encoding": "gzip+json", + "sha256": hashlib.sha256(compressed).hexdigest(), + "collected_at": snapshot.get("collected_at"), + "uncompressed_bytes": len(raw), + "compressed_bytes": len(compressed), + } + + # Shallow-copy only the serialized branches: execution, scoring and the + # checkpoint callbacks must still receive the original live observations. + payload = dict(result) + episode = result.get("episode") or {} + if episode.get("route_evidence"): + payload["episode"] = { + **episode, + "route_evidence": { + phase: snapshot_reference(phase, snapshot) for phase, snapshot in episode["route_evidence"].items() + }, + } + cleanup = result.get("cleanup") or {} + if cleanup.get("route_recovery"): + payload["cleanup"] = {**cleanup, "route_recovery": snapshot_reference("recovery", cleanup["route_recovery"])} + atomic_write_json(path, payload, default=str) diff --git a/netopsbench/platform/scenario/baseline.py b/netopsbench/platform/scenario/baseline.py new file mode 100644 index 0000000..f0ef497 --- /dev/null +++ b/netopsbench/platform/scenario/baseline.py @@ -0,0 +1,230 @@ +"""Bounded reusable handoff of a worker's verified healthy window. + +This stores window identity, never telemetry rows. Each consumer queries InfluxDB +again so late arrivals remain visible. Ownership ends with the suite's executor. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path + +from netopsbench.platform.utils.proc import docker_prefix, safe_run + + +@dataclass(frozen=True) +class RuntimeScope: + identity: dict + configs: dict[str, str] + containers: dict[str, list[str]] + + @property + def digest(self): + return hashlib.sha256(json.dumps(self.__dict__, sort_keys=True).encode()).hexdigest() + + +def scope_changes(before, after): + if before == after: + return [] + if not isinstance(before, RuntimeScope) or not isinstance(after, RuntimeScope): + return ["scope_unavailable_or_changed"] + changes = [ + f"identity:{key}" + for key in before.identity.keys() | after.identity.keys() + if before.identity.get(key) != after.identity.get(key) + ] + for group in ("configs", "containers"): + old, new = getattr(before, group), getattr(after, group) + changes.extend(f"{group}:{key}" for key in old.keys() | new.keys() if old.get(key) != new.get(key)) + return sorted(changes) + + +def normalized_frr(text): + """Discard FRR display headers/comments, preserving command order and nesting.""" + if "Current configuration:\n" in text: + text = text.split("Current configuration:\n", 1)[1] + lines = [line.rstrip() for line in text.splitlines()] + lines = [ + line + for line in lines + if line.strip() and not line.lstrip().startswith("!") and line.strip() != "Building configuration..." + ] + if lines and lines[-1].strip() == "end": + lines.pop() + if not any(line.startswith("router bgp ") for line in lines): + raise ValueError("FRR configuration is missing the BGP router") + return hashlib.sha256("\n".join(lines).encode()).hexdigest() + + +def frr_snapshot(runner, device): + container = runner.injector.container_names[device] + result = safe_run( + [*docker_prefix(), "docker", "exec", container, "vtysh", "-c", "show running-config"], check=True, timeout=30 + ) + path = Path(runner.topology_dir) / "configs" / "frr" / f"{device}.conf" + saved = path.read_bytes() + return { + "device": device, + "running": normalized_frr(result.stdout), + "saved": normalized_frr(saved.decode()), + "saved_bytes": hashlib.sha256(saved).hexdigest(), + } + + +def restored_scope_errors(before, after, scenario, config_proof): + """Permit only an owned, verified FRR rewrite and the requested device restart.""" + changes = scope_changes(before, after) + allowed = set() + device = scenario.episode.target_device + if config_proof and config_proof.get("restored"): + allowed.add(f"configs:configs/frr/{device}.conf") + if scenario.episode.fault_type == "device_down" and isinstance(after, RuntimeScope): + allowed.update( + f"containers:{name}" + for name in after.containers + if name.endswith(f"-{device}") + and isinstance(before, RuntimeScope) + and name in before.containers + and before.containers[name][1] == after.containers[name][1] + ) + return [change for change in changes if change not in allowed] + + +@dataclass +class BaselineHandoff: + window: dict | None = None + scope: RuntimeScope | None = None + source: str | None = None + epoch: float | None = None + last_changes: list[str] | None = None + last_reason: str = "no_verified_window" + last_verified_end: datetime | None = None + uses: int = 0 + max_cases: int = 10 + ready: bool = False + + def clear(self, reason: str = "no_verified_window") -> None: + self.window = self.scope = self.source = self.epoch = None + self.last_reason = reason + self.uses = 0 + self.ready = False + + def take(self, scope: RuntimeScope | None, minimum_seconds: int) -> tuple[dict | None, str]: + window, previous_scope = self.window, self.scope + self.last_changes = scope_changes(previous_scope, scope) + if window is None: + return None, self.last_reason + if not self.ready: + return None, "previous_case_not_verified" + elif self.uses >= self.max_cases: + return None, "case_limit" + self.ready = False # Failure/interruption cannot silently reuse this window. + self.last_reason = "window_already_consumed" + if not scope: + return None, "scope_unavailable" + if scope != previous_scope: + return None, "scope_changed" + if self.epoch is None: + return None, "recalibration_due" + reason = window_error(window, minimum_seconds) + if reason: + return None, reason + self.uses += 1 + return dict(window), "verified_previous_case" + + def publish( + self, window: dict, scope: RuntimeScope | None, source: str, minimum_seconds: int, *, verified: bool = False + ) -> bool: + reason = "scope_unavailable" if not scope else window_error(window, minimum_seconds) + if reason: + self.window = None + self.last_reason = reason + return False + end = datetime.fromisoformat(window["end_time"].replace("Z", "+00:00")) + if verified and (self.last_verified_end is None or end > self.last_verified_end): + # A new, independently verified full window is itself calibration. + # Republishing a prior window cannot extend the calibration epoch. + self.epoch = time.monotonic() + self.last_verified_end = end + self.uses = 0 + if self.epoch is None: + self.window = None + self.last_reason = "calibration_missing" + return False + self.window, self.scope, self.source = dict(window), scope, source + self.ready = True + self.last_reason = "verified_window_published" if verified else "window_published" + return True + + +def window_error(window: dict, minimum_seconds: int) -> str | None: + try: + start = datetime.fromisoformat(window["start_time"].replace("Z", "+00:00")) + end = datetime.fromisoformat(window["end_time"].replace("Z", "+00:00")) + if start.tzinfo is None or end.tzinfo is None: + return "invalid_window" + if (end - start).total_seconds() < minimum_seconds or int(window["duration_seconds"]) < minimum_seconds: + return "short_window" + age = (datetime.now(UTC) - end).total_seconds() + if age < 0: + return "future_window" + except (KeyError, TypeError, ValueError, OverflowError): + return "invalid_window" + return None + + +def runtime_scope(runner, scenario) -> RuntimeScope | None: + """Require unchanged runtime instances, generated configs and traffic plans.""" + worker = runner.runtime_worker + controller = runner.traffic_controller + if worker is None or controller is None or not controller.generation or not controller.plan_digests: + return None + root = Path(runner.topology_dir) + paths = [root / "topology.json", *sorted((root / "configs").rglob("*"))] + configs = {} + for path in paths: + if path.is_file(): + configs[str(path.relative_to(root))] = hashlib.sha256(path.read_bytes()).hexdigest() + manifest = runner.topology_metadata + names = sorted(f"clab-{worker.lab_name}-{device['name']}" for device in manifest["devices"]) + inspected = safe_run( + [ + *docker_prefix(), + "docker", + "inspect", + "--format", + "{{.Id}} {{.Image}} {{.State.StartedAt}} {{.State.Pid}} {{.State.Running}} {{.State.OOMKilled}}", + *names, + ], + check=True, + timeout=30, + ) + rows = [line.split() for line in inspected.stdout.splitlines() if line.strip()] + if len(rows) != len(names) or any(len(row) != 6 or row[4:] != ["true", "false"] for row in rows): + return None + containers = dict(zip(names, rows, strict=True)) + client_names = {device["name"] for device in manifest["devices"] if device["role"] == "client"} + starts = [ + row[2] for name, row in containers.items() if name.removeprefix(f"clab-{worker.lab_name}-") in client_names + ] + if starts: + runner._pingmesh_runtime_start = min(starts) + return RuntimeScope( + identity={ + "runtime": worker.runtime_id, + "worker": worker.worker_id, + "topology": runner.topology_id, + "pingmesh_plan_id": runner.topology_metadata["pingmesh_plan"]["settings"]["plan_id"], + "bucket": runner.influxdb_bucket, + "scale": runner.scale_registry.get(scenario.scale).digest, + "traffic_profile": scenario.traffic_profile, + "generation": controller.generation, + "plans": dict(controller.plan_digests), + }, + configs=configs, + containers=containers, + ) diff --git a/netopsbench/platform/scenario/candidates.py b/netopsbench/platform/scenario/candidates.py new file mode 100644 index 0000000..176a9dd --- /dev/null +++ b/netopsbench/platform/scenario/candidates.py @@ -0,0 +1,86 @@ +"""Shared candidate-path scope for offline placement and private effect audits.""" + +from collections import defaultdict, deque + +from netopsbench.models.topology import DeviceRole +from netopsbench.platform.utils.interface_names import to_sonic_interface + + +class CandidatePaths: + """Cache shortest-path DAG membership without enumerating complete paths.""" + + def __init__(self, manifest): + self.devices = {device.name: device for device in manifest.devices} + self.clients = {device.name: device for device in manifest.clients()} + self.adj, self.ports, self.distances = defaultdict(list), {}, {} + for link in manifest.links: + a, b = link.endpoints + if self.devices[a.device].role != DeviceRole.CLIENT and self.devices[b.device].role != DeviceRole.CLIENT: + self.adj[a.device].append(b.device) + self.adj[b.device].append(a.device) + self.ports[a.device, b.device] = to_sonic_interface(a.interface) + self.ports[b.device, a.device] = to_sonic_interface(b.interface) + self.pairs = [ + (client.name, dst) for client in manifest.require_pingmesh_plan().clients for dst in client.targets + ] + + def distance(self, root): + if root not in self.distances: + distances, queue = {root: 0}, deque([root]) + while queue: + node = queue.popleft() + for neighbor in self.adj[node]: + if neighbor not in distances: + distances[neighbor] = distances[node] + 1 + queue.append(neighbor) + self.distances[root] = distances + return self.distances[root] + + def contains(self, src, dst, root, peer=None): + source, target = self.clients[src].attached_switch, self.clients[dst].attached_switch + ds, dt = self.distance(source), self.distance(target) + if peer in self.clients: + return dst == peer and root == target + if peer: + return ds[root] + 1 + dt[peer] == ds[target] + return ds[root] + dt[root] == ds[target] + + def affected_pairs(self, fault, root, peer, anchor, *, reverse=False): + """Include all immutable planned pairs within this configuration's scope.""" + found = [anchor] + for src, dst in self.pairs: + if {"src": src, "dst": dst} == anchor: + continue + if fault == "acl_source_misconfig": + if src != anchor["src"] and dst != anchor["src"]: + continue + elif fault not in { + "acl_l4_port_misconfig", + "packet_loss", + "packet_corruption", + "high_latency", + "mtu_mismatch", + }: + if dst != anchor["dst"] and src != anchor["dst"]: + continue + forward, backward = self.contains(src, dst, root, peer), self.contains(dst, src, root, peer) + if fault == "acl_source_misconfig": + eligible = src == anchor["src"] and forward or dst == anchor["src"] and backward + elif fault == "acl_l4_port_misconfig": + eligible = forward + elif fault in {"packet_loss", "packet_corruption", "high_latency", "mtu_mismatch"}: + eligible = forward or backward + elif fault == "routing_loop": + eligible = ( + dst == anchor["dst"] + and self.contains(src, dst, root) + or src == anchor["dst"] + and self.contains(dst, src, root) + ) + else: + member = self.contains(src, dst, peer, root) if reverse else forward + returning = self.contains(dst, src, peer, root) if reverse else backward + eligible = dst == anchor["dst"] and member or src == anchor["dst"] and returning + if eligible: + found.append({"src": src, "dst": dst}) + return found diff --git a/netopsbench/platform/scenario/effects.py b/netopsbench/platform/scenario/effects.py new file mode 100644 index 0000000..d01f9fd --- /dev/null +++ b/netopsbench/platform/scenario/effects.py @@ -0,0 +1,506 @@ +"""Private, mechanism-specific validity checks over actual observations. + +This module is never used to construct agent prompts or tool results. Public +route changes are computed separately without access to episode parameters. +""" + +from __future__ import annotations + +import ipaddress +import json +import re +import time +from datetime import UTC, datetime, timedelta + +from netopsbench.models.profiles import get_scale_profile +from netopsbench.platform.faults.defaults import LATENCY_MS +from netopsbench.platform.incident.context import extract_episode_pingmesh_query_window +from netopsbench.platform.observability.routes import next_hops +from netopsbench.platform.toolkit.toolkit import AgentToolkit +from netopsbench.platform.utils.control import OperationControl, current_operation_control +from netopsbench.platform.utils.proc import docker_prefix, safe_run + + +def _route(snapshot, device, prefix): + network = ipaddress.ip_network(prefix, strict=False) + return next( + ( + route + for route in snapshot["nodes"].get(device, {}).get("fib", []) + if route.get("dst") not in {None, "default"} and ipaddress.ip_network(route["dst"], strict=False) == network + ), + None, + ) + + +def _count(snapshot, device, prefix): + route = _route(snapshot, device, prefix) + return len(next_hops(route)) if route and route.get("type", "unicast") == "unicast" else 0 + + +def _measured_loss(rows, probe="regular"): + return any( + (row.get("fault", {}).get(probe) or {}).get("lost", 0) >= 3 + and (row.get("fault", {}).get(probe) or {}).get("loss_pct", 0) + > (row.get("baseline", {}).get(probe) or {}).get("loss_pct", 0) + for row in rows + ) + + +def _periodic_client_outages(phases, clients, end_time): + """Bound access outages by verified down/up transactions, including transitions.""" + end = datetime.fromisoformat(end_time.replace("Z", "+00:00")) + outages = [] + for index, phase in enumerate(phases): + if phase["phase"] != "fault": + continue + start = datetime.fromisoformat(phase.get("started_at", phase["time"]).replace("Z", "+00:00")) + stop = end + if index + 1 < len(phases): + stop = min(stop, datetime.fromisoformat(phases[index + 1]["time"].replace("Z", "+00:00"))) + if start < stop: + outages.extend( + {"client": client, "start": start.isoformat(), "end": stop.isoformat()} for client in clients + ) + return outages + + +def _observed_periodic_phases(history, start_time, end_time): + start = datetime.fromisoformat(start_time.replace("Z", "+00:00")) + end = datetime.fromisoformat(end_time.replace("Z", "+00:00")) + previous, observed = [], [] + for phase in history: + verified_at = datetime.fromisoformat(phase["time"].replace("Z", "+00:00")) + if verified_at <= start: + previous = [phase] + elif verified_at <= end: + observed.append(phase) + return previous + observed + + +def _outage_explains_local_error(row, outages, cycle_seconds): + if row.get("socket_batch_valid") is not True or not (row.get("local_probe_errors") or 0) > 0: + return False + try: + end = datetime.fromisoformat(row["time"].replace("Z", "+00:00")) + start = end - timedelta(seconds=cycle_seconds) + # Native metrics are timestamped after the fixed probe cycle. A cycle + # can straddle a verified link transition; limit that overlap to one + # plan interval rather than excusing the client's whole episode. + return any( + row["src"] == outage["client"] + and start < datetime.fromisoformat(outage["end"]) + and end > datetime.fromisoformat(outage["start"]) + for outage in outages + ) + except (KeyError, TypeError, ValueError): + return False + + +def _ttl_loop_evidence(executor, episode, baseline, current): + root, prefix = episode.target_device, episode.target_prefix + evidence = {"forwarding_cycle": False, "ttl_expirations": {}} + if not prefix or not episode.target_interface: + return evidence + endpoints = executor.injector._link._link_endpoints(root, episode.target_interface) + peer = endpoints[1][0] + root_route = _route(current, root, prefix) + target = ipaddress.ip_network(prefix).network_address + candidates = [] + for route in current["nodes"].get(peer, {}).get("fib", []): + dst = route.get("dst") or "default" + network = ipaddress.ip_network("0.0.0.0/0" if dst == "default" else dst, strict=False) + if target in network: + candidates.append((network.prefixlen, route)) + peer_route = max(candidates, key=lambda item: item[0], default=(0, None))[1] + local = next( + ( + r.get("prefsrc") + for r in baseline["nodes"].get(root, {}).get("fib", []) + if r.get("protocol") == "kernel" and r.get("dev") == endpoints[0][2] + ), + None, + ) + evidence["forwarding_cycle"] = bool( + local + and root_route + and peer_route + and episode.parameters.get("next_hop") in {h.get("gateway") for h in next_hops(root_route)} + and local in {h.get("gateway") for h in next_hops(peer_route)} + ) + for device in (root, peer): + before = baseline["nodes"].get(device, {}).get("packet_counters", {}) + after = current["nodes"].get(device, {}).get("packet_counters", {}) + key = "icmp_out_time_exceeded" + if key in before and key in after and after[key] > before[key]: + evidence["ttl_expirations"][device] = {"before": before[key], "after": after[key]} + return evidence + + +def validate_effect(executor, episode, episode_result, baseline, current): + fault, root, prefix = episode.fault_type, episode.target_device, episode.target_prefix + p = episode.parameters + mechanism = p.get("mechanism", fault) + errors, evidence = [], {"collected_at": datetime.now(UTC).isoformat(), "mechanism": mechanism} + node_errors = {name: row["error"] for name, row in current["nodes"].items() if row.get("error")} + if node_errors and not (fault == "device_down" and set(node_errors) == {root}): + errors.append(f"Unexpected route collection failures: {node_errors}") + bgp_errors = {name for name, row in current["nodes"].items() if row.get("bgp_collection_ok") is False} + if bgp_errors and not (fault in {"device_down", "bgp_process_down"} and bgp_errors == {root}): + errors.append(f"Unexpected BGP table collection failures: {sorted(bgp_errors)}") + toolkit = AgentToolkit(topology_metadata=executor.current_manifest().model_dump(mode="json")) + toolkit.influxdb_bucket = executor.influxdb_bucket + toolkit.topology_id = executor.topology_id + injection = episode_result.get("injection", {}) + quality = episode_result.get("observations", {}).get("pingmesh_metrics", {}).get("quality", {}) + probes = episode_result.get("observations", {}).pop("_probe_evidence", []) + evidence["probes"] = probes + validation_only = executor.current_manifest().purpose == "validation" + evidence["control_role"] = "comparison" if validation_only else "unaffected" + by_pair = {(row["src"], row["dst"]): row for row in probes} + affected_pairs = executor._case_affected_pairs + affected_rows = [by_pair.get((pair["src"], pair["dst"]), {}) for pair in affected_pairs] + for pair in affected_pairs + p.get("control_candidates", []): + row = by_pair.get((pair["src"], pair["dst"]), {}) + if not row.get("baseline", {}).get("samples"): + errors.append(f"Planned witness lacks healthy probe evidence: {pair}") + status = toolkit.get_device_status(root) if root else None + if status: + evidence["device_status"] = status.to_dict() + if fault == "none": + return {"valid": not errors, "errors": errors, "evidence": evidence, "unobservable_clients": []} + if status is None or not status.success: + errors.append("Actual node status unavailable") + elif fault == "device_down": + if status.data["running"]: + errors.append("Root container remains running") + elif not status.data["running"] or not status.data["accessible"]: + errors.append("Root is unexpectedly unavailable") + if fault.startswith("bgp_") and fault != "bgp_process_down": + neighbor = toolkit.get_bgp_neighbor(root, p["peer_ip"]) + evidence["neighbor"] = neighbor.to_dict() + if not neighbor.success or str(neighbor.data.get("state", "")).lower() == "established": + errors.append("Target BGP session did not leave Established") + elif fault == "bgp_max_prefix_misconfig": + reasons = {key: neighbor.data.get(key) for key in ("last_reset", "last_error", "notifications")} + evidence["maximum_prefix_reason"] = reasons + if not re.search( + r"(?:maximum|exceed|limit).*prefix|prefix.*(?:exceed|limit)|max-prefix", json.dumps(reasons), re.I + ): + errors.append("BGP maximum-prefix trigger was not observed") + if fault == "bgp_process_down": + if not status or not status.success or status.data.get("services", {}).get("bgpd") != "STOPPED": + errors.append("bgpd was not stopped under Supervisor") + if fault in {"route_origination_misconfig", "route_filter_misconfig", "ecmp_misconfig"}: + changed = [ + device for device in baseline["nodes"] if _count(current, device, prefix) < _count(baseline, device, prefix) + ] + evidence["changed_forwarding_devices"] = changed + if not changed: + errors.append("No actual FIB effect for target prefix") + if fault == "ecmp_misconfig" or mechanism == "import_filter": + before, after = _count(baseline, root, prefix), _count(current, root, prefix) + evidence.update(next_hops_before=before, next_hops_after=after) + reduced = fault == "ecmp_misconfig" or p.get("impact_scope", "") in {"reduced", "reduced_remote_pod"} + if reduced and not 0 < after < before: + errors.append("Expected nonzero forwarding with fewer next hops") + if not reduced and after != 0: + errors.append("Expected complete target prefix withdrawal") + if fault == "ecmp_misconfig": + rib = toolkit.get_bgp_rib(root, prefix) + sessions = toolkit.get_bgp_neighbors(root) + evidence.update(candidate_bgp_routes=rib.to_dict(), sessions=sessions.to_dict()) + if ( + not rib.success + or not sessions.success + or any(n.get("state") != "Established" for n in sessions.data.get("neighbors", [])) + ): + errors.append("ECMP route/session evidence is incomplete") + if fault == "routing_loop": + witnesses = affected_pairs + ttl = _ttl_loop_evidence(executor, episode, baseline, current) + evidence["ttl_exhaustion"] = ttl + traces, cyclic = [], bool(ttl["forwarding_cycle"] and ttl["ttl_expirations"]) + control = current_operation_control() or OperationControl( + getattr(executor, "_cancel_event", None), + time.monotonic() + get_scale_profile(executor.current_manifest().scale).health_timeout_seconds, + ) + for pair in witnesses[:8]: + if cyclic: + break + dst = executor.current_manifest().device(pair["dst"]).data_ip + container = toolkit._resolve_container(pair["src"]) + # ICMP does not bind the UDP sockets already owned by Pingmesh. + # This proves an actual cycle, without claiming ECMP calibration. + output = safe_run( + [ + *docker_prefix(), + "docker", + "exec", + container, + "traceroute", + "-n", + "-I", + "-q", + "1", + "-w", + "0.2", + "-m", + "32", + dst, + ], + timeout=control.remaining(15), + control=control, + ) + hops = [ + re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", line)[0] + for line in output.stdout.splitlines()[1:] + if re.findall(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", line) + ] + traces.append( + { + "src": pair["src"], + "dst": pair["dst"], + "protocol": "icmp", + "output": output.stdout, + "returncode": output.returncode, + } + ) + cyclic = len(hops) >= 4 and len(set(hops)) < len(hops) + if cyclic: + break + evidence["traces"] = traces + if not cyclic: + errors.append("No actual forwarding cycle or TTL exhaustion was proved") + unobservable, access_clients, bounded_outages = [], [], [] + if fault == "device_down" and status and status.success and not status.data["running"]: + unobservable = [c.name for c in executor.current_manifest().clients() if c.attached_switch == root] + if fault in { + "link_down", + "interface_ip_misconfig", + "link_flapping", + "packet_loss", + "packet_corruption", + "high_latency", + "mtu_mismatch", + }: + interface = executor.injector._iface.resolve_sonic(episode.target_interface) + details = toolkit.get_device_interfaces(root, interface=interface) + evidence["interface"] = details.to_dict() + if not details.success: + errors.append("Actual interface configuration unavailable") + if fault in {"packet_loss", "packet_corruption", "high_latency"}: + # Injection state belongs to the private effect audit, never to + # AgentToolkit or the model-facing diagnostic registry. + linux_interface = executor.injector._iface.resolve_linux(interface) + try: + qdisc = executor.injector._cmd.docker_exec( + executor.injector.container_names[root], + ["tc", "-s", "-j", "qdisc", "show", "dev", linux_interface], + ) + if qdisc.returncode: + raise RuntimeError(qdisc.stderr or "qdisc collection failed") + evidence["qdisc"] = {"linux_interface": linux_interface, "rows": json.loads(qdisc.stdout)} + except Exception as exc: + errors.append(f"Private qdisc collection failed: {exc}") + if fault == "interface_ip_misconfig" and details.success: + addresses = details.data.get("addresses", {}).get(interface, []) + if injection.get("evidence", {}).get("fault_address") not in addresses: + errors.append("Actual interface address did not change") + if fault == "link_down" and details.success: + rows = details.data.get("interfaces", []) + selected = next((row for row in rows if row.get("name") == interface), {}) + if str(selected.get("admin", selected.get("state", ""))).lower() not in {"down", "disabled"}: + errors.append("Link admin-down state unavailable") + if fault in {"link_down", "interface_ip_misconfig", "link_flapping"} and not errors: + for link in executor.current_manifest().links: + ends = link.endpoints + for endpoint, peer in (ends, tuple(reversed(ends))): + if ( + endpoint.device == root + and executor.injector._iface.resolve_sonic(endpoint.interface) == interface + ): + node = executor.current_manifest().device(peer.device) + if node.role.value == "client": + access_clients.append(node.name) + if fault != "link_flapping": + unobservable.extend(access_clients) + if fault in {"packet_loss", "packet_corruption", "high_latency", "mtu_mismatch"}: + if fault == "high_latency": + observed = any( + (row.get("fault", {}).get("rtt_max_ms") or 0) - (row.get("baseline", {}).get("rtt_max_ms") or 0) + >= float(p.get("latency_ms", LATENCY_MS)) / 2 + for row in affected_rows + ) + else: + probe = "df" if fault == "mtu_mismatch" else "regular" + observed = _measured_loss(affected_rows, probe) + if not observed: + errors.append("Configured impairment had no measured effect on planned witnesses") + if fault in {"route_flapping", "link_flapping"}: + identifier = injection.get("control_id", injection.get("task_id")) + controller = executor.injector._tracker._background_fault_controls.get(identifier, {}).get("controller") + scope = episode_result["observations"] + history = list(controller.history) if controller else [] + phases = _observed_periodic_phases(history, scope["start_time"], scope["end_time"]) if controller else [] + transitions = [p["phase"] for p in phases] + repeated = any(transitions[i : i + 3] == ["fault", "healthy", "fault"] for i in range(len(transitions) - 2)) + if controller is None or controller.error or not repeated: + errors.append("Periodic fault did not complete multiple verified phases") + if controller: + evidence["phases"] = phases + evidence["controller_error"] = controller.error + if controller.error: + errors.append(f"Periodic controller failed: {controller.error}") + if fault == "link_flapping" and not controller.error and repeated: + bounded_outages = _periodic_client_outages( + history, access_clients, episode_result["observations"]["end_time"] + ) + if fault == "route_flapping": + scope = extract_episode_pingmesh_query_window(episode_result) + interface = executor.injector._iface.resolve_sonic(episode.target_interface) + addresses = toolkit.get_device_interfaces(root, interface=interface) + local_addresses = addresses.data.get("addresses", {}).get(interface, []) if addresses.success else [] + peer_address = local_addresses[0].split("/")[0] if local_addresses else None + peer_devices = { + endpoint.device + for link in executor.current_manifest().links + if any( + end.device == root and executor.injector._iface.resolve_sonic(end.interface) == interface + for end in link.endpoints + ) + for endpoint in link.endpoints + if endpoint.device != root + } + events = toolkit.query_bgp_events( + **scope, + device=next(iter(sorted(peer_devices)), None), + peer=peer_address, + event_type="prefix_count", + state="all", + limit=500, + ) + evidence["prefix_events"] = events.to_dict() + rows = events.data.get("events", []) if events.success else [] + rows = [row for row in rows if row.get("device") in peer_devices and row.get("peer") == peer_address] + changes = [ + row["prefixes_after"] - row["prefixes_before"] + for row in rows + if row.get("prefixes_before") is not None and row.get("prefixes_after") is not None + ] + if ( + not events.success + or events.data.get("status") != "ok" + or not (any(n < 0 for n in changes) and any(n > 0 for n in changes)) + ): + errors.append("Repeated actual route withdrawals and advertisements were not observed") + session = toolkit.get_bgp_neighbor(root, p["peer_ip"]) + evidence["flapping_session"] = session.to_dict() + if not session.success or session.data.get("state") != "Established": + errors.append("Route flapping did not preserve the BGP session") + if fault.startswith("acl_"): + receipt = injection.get("evidence", {}) + rule = receipt.get("rule", []) + counter = executor.injector._cmd.docker_exec( + executor.injector.container_names[root], ["iptables", "-L", "FORWARD", "-n", "-v", "-x"] + ) + evidence["counters"] = counter.stdout + line = next((line for line in counter.stdout.splitlines() if receipt.get("acl_name", "!") in line), "") + hit = line.split()[0] if line else "" + if counter.returncode or not hit.isdigit() or int(hit) <= 0: + errors.append("Owned ACL rule has no verified hits") + if not rule or ("-i" not in rule and "-o" not in rule): + errors.append("ACL interface/direction was not applied") + if fault == "acl_l4_port_misconfig": + pair = p.get("affected_candidates", [{}])[0] + if pair.get("src"): + icmp = toolkit.ping_test(pair["src"], executor.current_manifest().device(pair["dst"]).data_ip, count=3) + evidence["icmp_control"] = icmp.to_dict() + if not icmp.success or icmp.data.get("return_code"): + errors.append("ICMP control is not reachable") + # The immutable ECMP tuples can send regular and DF probes over + # different members. DF loss proves ACL impact only when no local + # send error or MTU-drop confirmation explains it. + network_df_rows = [ + row + for row in affected_rows + if not row.get("fault", {}).get("local_probe_errors") + and not row.get("fault", {}).get("df", {}).get("mtu_drops") + ] + evidence["matched_probe_loss_kinds"] = [ + kind for kind, rows in (("regular", affected_rows), ("df", network_df_rows)) if _measured_loss(rows, kind) + ] + if not evidence["matched_probe_loss_kinds"]: + errors.append("ACL rule produced no observed probe loss") + if fault in {"blackhole_route", "static_route_misconfig"} and not _measured_loss(affected_rows): + errors.append("Static route had no observed effect") + evidence["pingmesh_quality"] = quality + observable = set(unobservable) + anomalies = episode_result.get("observations", {}).get("pingmesh_metrics", {}).get("anomalies", []) + for pair in p.get("control_candidates", []): + if pair["src"] in observable or pair["dst"] in observable: + continue + row = by_pair.get((pair["src"], pair["dst"]), {}) + if not row.get("fault", {}).get("samples"): + errors.append(f"Control flow has no fault-window evidence: {pair}") + if not validation_only and any( + item.get("src_name") == pair["src"] and item.get("dst_name") == pair["dst"] for item in anomalies + ): + errors.append(f"Control flow is anomalous: {pair}") + return { + "valid": not errors, + "errors": errors, + "evidence": evidence, + "unobservable_clients": sorted(set(unobservable)), + "bounded_client_outages": bounded_outages, + "probe_cycle_seconds": executor.current_manifest().require_pingmesh_plan().settings.cycle_interval_seconds, + } + + +def scoped_integrity_errors(observations, audit, effect): + """Explain only proven endpoint outages; retain the original full audit.""" + from .observation import observation_integrity_errors + + excluded = set(effect.get("unobservable_clients", [])) + outages = effect.get("bounded_client_outages", []) + if not excluded and not outages: + return observation_integrity_errors(observations) + errors = [] + if observations.get("data_source_status") != "ok": + errors.append("Observation ingestion/query failure") + if (observations.get("_baseline_coverage") or {}).get("coverage_status") != "complete": + errors.append("Healthy baseline coverage is incomplete") + if audit.get("unexpected_rows"): + errors.append("Unexpected peer/frame records remain") + if "missing_tasks" not in audit or "invalid_tasks" not in audit: + errors.append("Detailed coverage audit unavailable") + if outages: + explained_tasks = set() + rows = audit.get("invalid_rows", []) + if len(rows) != audit.get("invalid_socket_rows"): + errors.append("Timed invalid-row audit unavailable") + for row in rows: + if not _outage_explains_local_error(row, outages, effect["probe_cycle_seconds"]): + errors.append(f"Unexplained local probe error {row}") + else: + explained_tasks.add((row["src"], row["dst"], row.get("port_batch_index"))) + errors.extend( + f"Unobserved periodic probe task {task}" + for task in audit.get("missing_tasks", []) + if tuple(task) not in explained_tasks + ) + if not audit.get("observable_pairs"): + errors.append("No remaining observable probe pairs") + return errors + rows = audit.get("invalid_rows", []) + if len(rows) != audit.get("invalid_socket_rows", 0): + errors.append("Detailed invalid-row audit unavailable") + for row in rows: + if row.get("socket_batch_valid") is not True: + errors.append(f"Incorrect port batch {row}") + for task in audit.get("missing_tasks", []) + audit.get("invalid_tasks", []): + if task[0] not in excluded and task[1] not in excluded: + errors.append(f"Unexplained probe task {task}") + if not any(src not in excluded and dst not in excluded for src, dst in audit.get("observable_pairs", [])): + errors.append("No remaining observable probe pairs") + return errors diff --git a/netopsbench/platform/scenario/episode_runner.py b/netopsbench/platform/scenario/episode_runner.py index 299475e..2607747 100644 --- a/netopsbench/platform/scenario/episode_runner.py +++ b/netopsbench/platform/scenario/episode_runner.py @@ -2,8 +2,7 @@ from __future__ import annotations -import time -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import Any from netopsbench.logging_utils import get_logger @@ -17,39 +16,34 @@ def observe_episode( episode: EpisodeSpec, *, baseline_window: dict[str, Any], + result: dict[str, Any] | None = None, ) -> dict[str, Any]: """Activate one episode and collect its diagnostic observation window. Fault recovery intentionally does not happen here. ``IncidentEngine.close`` owns recovery for both benchmark and simulator callers. """ - result: dict[str, Any] = { - "episode_id": episode.episode_id, - "description": episode.description, - "episode": episode.model_dump(mode="json", exclude_none=True), - "start_time": datetime.now(UTC).isoformat(), - "success": False, - "state": "preparing", - } + result = {} if result is None else result + result.update( + { + "episode_id": episode.episode_id, + "description": episode.description, + "episode": episode.model_dump(mode="json", exclude_none=True), + "start_time": datetime.now(UTC).isoformat(), + "success": False, + "state": "preparing", + } + ) if episode.is_healthy: logger.info("[Healthy Observation] Monitoring without fault injection") - observations = executor._wait_and_observe( - episode.duration_seconds, - baseline_window=baseline_window, - ) - coverage = observations.pop("_coverage_audit", None) - observations.pop("_baseline_health", None) - result["observations"] = observations - if coverage is not None: - result["coverage_audit"] = coverage - result["state"] = "active" - return result - - injection = executor._inject_fault(episode) - result["injection"] = injection - if not injection.get("success"): - raise RuntimeError(f"Fault injection failed: {injection}") + executor.timings.skip("injection", "healthy scenario") + else: + with executor.timings.measure("injection", timeout_seconds=executor.observation_timeout_seconds): + injection = executor._inject_fault(episode) + result["injection"] = injection + if not injection.get("success"): + raise RuntimeError(f"Fault injection failed: {injection}") early_seconds = int( episode.metadata.get( @@ -59,7 +53,7 @@ def observe_episode( ) if early_seconds >= episode.duration_seconds: early_seconds = max(0, episode.duration_seconds - 10) - stabilization_seconds = max(0, int(episode.stabilization_time)) + stabilization_seconds = 0 if episode.is_healthy else max(0, int(episode.stabilization_time)) steady_seconds = episode.duration_seconds - early_seconds - stabilization_seconds if steady_seconds < 1: raise ValueError( @@ -68,17 +62,32 @@ def observe_episode( f"stabilization={stabilization_seconds}" ) - windows: list[dict[str, Any]] = [] + # A single capture; early/steady are slices of the same queried records. + with executor.timings.measure("observation", planned_seconds=episode.duration_seconds): + window = executor._capture_observation_window(episode.duration_seconds, "full") + start = datetime.fromisoformat(window["start_time"].replace("Z", "+00:00")) + windows = [] if early_seconds: - windows.append(executor._capture_observation_window(early_seconds, "early")) - _sleep(executor, stabilization_seconds) - windows.append(executor._capture_observation_window(steady_seconds, "steady")) - - observations = executor._merge_observation_windows( - windows, - total_duration_seconds=episode.duration_seconds, - baseline_window=baseline_window, + windows.append( + { + **window, + "name": "early", + "end_time": (start + timedelta(seconds=early_seconds)).isoformat(), + "duration_seconds": early_seconds, + } + ) + windows.append( + { + **window, + "name": "steady", + "start_time": (start + timedelta(seconds=early_seconds + stabilization_seconds)).isoformat(), + "duration_seconds": steady_seconds, + } ) + with executor.timings.measure("observation_query", timeout_seconds=executor.observation_timeout_seconds): + observations = executor._merge_observation_windows( + windows, total_duration_seconds=episode.duration_seconds, baseline_window=baseline_window + ) coverage = observations.pop("_coverage_audit", None) observations.pop("_baseline_health", None) result["observations"] = observations @@ -88,8 +97,4 @@ def observe_episode( return result -def _sleep(executor: Any, seconds: float) -> None: - getattr(executor, "sleep", time.sleep)(seconds) - - __all__ = ["observe_episode"] diff --git a/netopsbench/platform/scenario/executor.py b/netopsbench/platform/scenario/executor.py index 40eef2d..cdce379 100644 --- a/netopsbench/platform/scenario/executor.py +++ b/netopsbench/platform/scenario/executor.py @@ -14,6 +14,7 @@ from netopsbench.evaluator.scorer import Evaluator from netopsbench.logging_utils import get_logger from netopsbench.models.profiles import ScaleRegistry, default_scale_registry +from netopsbench.models.recovery import RecoveryPolicy from netopsbench.models.runtime import RuntimeIdentity from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec from netopsbench.platform.faults.injector import FaultInjector @@ -28,12 +29,15 @@ from netopsbench.platform.traffic.controller import TrafficController from netopsbench.platform.traffic.scenario_execution import setup_traffic as _setup_traffic_impl from netopsbench.platform.traffic.scenario_execution import stop_traffic as _stop_traffic_impl +from netopsbench.platform.utils.control import OperationControl, current_operation_control, operation_scope +from netopsbench.platform.utils.measurements import count_operation +from .baseline import BaselineHandoff, RuntimeScope, frr_snapshot, restored_scope_errors, runtime_scope, scope_changes from .incident_backend import ExecutorIncidentBackend from .observation import analyze_observation_windows as _analyze_observation_windows_impl from .observation import capture_baseline_window as _capture_baseline_window_impl from .observation import capture_observation_window as _capture_observation_window_impl -from .observation import wait_and_observe as _wait_and_observe_impl +from .timing import PhaseTimings logger = get_logger(__name__) @@ -60,8 +64,7 @@ def __init__( self, topology_dir: str = "clab-topology", topology_metadata: dict | None = None, - minimum_baseline_seconds: int = 60, - post_recovery_wait_seconds: int = 2, + minimum_baseline_seconds: int | None = None, influxdb_url: str | None = None, influxdb_token: str | None = None, influxdb_org: str | None = None, @@ -88,14 +91,19 @@ def __init__( if metadata is None: raise ValueError(f"Canonical topology metadata is required for ScenarioExecutor: {topology_dir}") manifest = coerce_topology_manifest(metadata) + self.manifest = manifest + self._manifest_file_stamp = self._topology_file_stamp() + self._detector = None + self._detector_scope = None self.fault_registry = fault_registry or create_fault_registry() self.scale_registry = scale_registry or default_scale_registry() - self.scale_registry.get(manifest.scale) + self.experiment = self.scale_registry.get(manifest.scale).experiment self.topology_metadata = manifest.model_dump(mode="json") self.injector = FaultInjector( clab_dir=topology_dir, topology_metadata=self.topology_metadata, fault_registry=self.fault_registry, + experiment=self.experiment, ) self.traffic_controller: TrafficController | None = None self.topology_id = topology_id or manifest.topology_id @@ -103,46 +111,195 @@ def __init__( self.influxdb_token = influxdb_token self.influxdb_org = influxdb_org self.influxdb_bucket = influxdb_bucket - self.minimum_baseline_seconds = max(0, int(minimum_baseline_seconds)) - self.post_recovery_wait_seconds = max( - 0, - int(post_recovery_wait_seconds), - manifest.pingmesh.cycle_interval_seconds, + self.observation_timeout_seconds = self.scale_registry.get(manifest.scale).health_timeout_seconds + self.minimum_baseline_seconds = ( + self.experiment.observation_seconds + if minimum_baseline_seconds is None + else max(0, int(minimum_baseline_seconds)) ) self._sleep_fn = sleep_fn or time.sleep + self._cancel_event = None + self._recovering = False self.evaluator = evaluator or Evaluator() self.runtime_worker = runtime_worker + self._baseline_handoff = BaselineHandoff() + self._candidate_paths = None + self._candidate_scope = None + self._traffic_config = None + self._pingmesh_runtime_start = None + self.recovery_policy = RecoveryPolicy() + self._last_calibration = None + self._calibration_current = False + self.begin_case() + + def begin_case(self) -> None: + """Reset per-case state without invalidating runtime traffic or baseline handoff.""" + self.timings = PhaseTimings() + self._case_frr_before = None + self._case_initial_scope = None + self._case_routes = None + self._case_affected_pairs = [] + self._case_probe_pairs = [] + + def _topology_file_stamp(self): + path = Path(self.topology_dir) / "topology.json" + if not path.exists(): + return None + stat = path.stat() + return stat.st_ino, stat.st_mtime_ns, stat.st_size + + def current_manifest(self): + """Reload changed topology artifacts without reparsing every window.""" + stamp = self._topology_file_stamp() + if stamp != self._manifest_file_stamp: + manifest = load_topology_manifest(self.topology_dir) + if manifest.topology_id != self.topology_id: + raise ValueError("Executor topology identity changed; create a new executor") + self.manifest = manifest + self.topology_metadata = manifest.model_dump(mode="json") + self._manifest_file_stamp = stamp + self._baseline_handoff.clear() + return self.manifest def sleep(self, seconds: float) -> None: + self._check_cancelled() self._sleep_fn(seconds) + self._check_cancelled() + + def _check_cancelled(self) -> None: + if not self._recovering and self._cancel_event is not None and self._cancel_event.is_set(): + raise RuntimeError("scenario cancelled") def _setup_traffic(self, scale: str, profile: str) -> dict: - return _setup_traffic_impl(self, scale, profile) + self._traffic_config = _setup_traffic_impl(self, scale, profile) + return self._traffic_config def _stop_traffic(self): _stop_traffic_impl(self) def close(self) -> None: """Release runtime-owned traffic after the worker or simulator is done.""" + self._baseline_handoff.clear() self._stop_traffic() + def _baseline_scope(self, scenario: ScenarioSpec) -> RuntimeScope | None: + try: + return runtime_scope(self, scenario) + except Exception as exc: + logger.warning("Baseline handoff disabled: %s", type(exc).__name__) + return None + def _inject_fault(self, episode: EpisodeSpec) -> dict: + self._check_cancelled() + self._case_frr_before = None + if self.runtime_worker is not None and ( + episode.fault_type.startswith(("bgp_", "route_")) + or episode.fault_type + in {"ecmp_misconfig", "routing_loop", "static_route_misconfig", "blackhole_route", "device_down"} + ): + self._case_frr_before = frr_snapshot(self, episode.target_device) return _inject_fault_impl(self, episode) - def _wait_and_observe( - self, - duration: int, - *, - baseline_window: dict, - ) -> dict: - return _wait_and_observe_impl(self, duration, baseline_window=baseline_window) - def _capture_baseline_window(self) -> dict: return _capture_baseline_window_impl(self, self.minimum_baseline_seconds) def _capture_observation_window(self, duration: int, name: str) -> dict: return _capture_observation_window_impl(self, duration, name=name) + def calibrate(self, scenario, reason, *, deadline=None): + """Full environment and data-plane validation; independent of fault undo.""" + from .observation import baseline_gate_errors + + if self.injector.active_faults: + raise RuntimeError("Cannot calibrate a runtime with unresolved faults") + self._last_calibration = {"success": False, "reason": reason} + self._calibration_current = False + deadline = deadline or monotonic() + self.experiment.recovery_timeout_seconds + phase = "calibration" + sequence = 1 + while phase in self.timings.phases: + sequence += 1 + phase = f"calibration_{sequence}" + with ( + self.timings.measure(phase) as measurement, + operation_scope(OperationControl(None if self._recovering else self._cancel_event, deadline)), + ): + measurement["reason"] = reason + with self.timings.measure_step(phase, "environment"): + if self.runtime_worker is not None: + errors = check_worker_health( + self.runtime_worker, + scale_registry=self.scale_registry, + all_routing_devices=True, + deadline=deadline, + route_snapshot={"nodes": {}}, + expected_routes=self._case_routes, + ) + if errors: + raise RuntimeError("Calibration environment failed: " + "; ".join(errors)) + before = self._baseline_scope(scenario) + with self.timings.measure_step(phase, "window_wait"): + window = self._capture_baseline_window() + with self.timings.measure_step(phase, "window_query") as query_step: + observation = self._merge_observation_windows( + [window], + int(window["duration_seconds"]), + baseline_window=(self._baseline_handoff.window if before == self._baseline_handoff.scope else None) + or window, + ) + query_step["ingestion"] = { + "baseline": (observation.get("_baseline_coverage") or {}).get("ingestion", {}), + "current": (observation.get("_coverage_audit") or {}).get("ingestion", {}), + } + errors = baseline_gate_errors(observation) + absolute = observation.get("_baseline_health") or {} + required = {"absolute_unreachable_paths", "absolute_packet_loss_paths", "absolute_network_mtu_paths"} + if not required <= absolute.keys(): + errors.append("missing_absolute_health") + after = self._baseline_scope(scenario) + if errors: + measurement["failed_validation"] = observation + if errors or (self.runtime_worker is not None and (before is None or after != before)): + raise RuntimeError("Calibration failed: " + "; ".join(errors or ["runtime identity changed"])) + current_operation_control().remaining() + handoff = self._baseline_handoff + handoff.publish(window, after, scenario.id, self.minimum_baseline_seconds, verified=True) + if self.runtime_worker is not None and not handoff.ready: + raise RuntimeError("Calibration baseline could not be published") + self._last_calibration = { + "success": True, + "reason": reason, + "window": dict(window), + "validation_level": "full_window", + "scope": after.digest if after else None, + "phase_timing": measurement, + } + self._calibration_current = True + return dict(window) + + def final_calibration(self, scenario, *, destroy_after_run=False): + if self.injector.active_faults: + raise RuntimeError("Cannot finish a runtime with unresolved faults") + if destroy_after_run: + return {"status": "skipped", "reason": "runtime_will_be_destroyed", "validation_level": "state_checked"} + handoff = self._baseline_handoff + scope = self._baseline_scope(scenario) + from .baseline import window_error + + if ( + self._calibration_current + and handoff.ready + and scope == handoff.scope + and window_error(handoff.window, self.minimum_baseline_seconds) is None + ): + return {**self._last_calibration, "reused": True} + try: + self.calibrate(scenario, "run_end") + except BaseException: + handoff.clear("final_calibration_failed") + raise + return self._last_calibration + def _recover_fault(self): return _recover_fault_impl(self) @@ -169,32 +326,38 @@ def _cleanup_after_scenario( """Recover the fault while runtime-owned background traffic remains active.""" started = monotonic() profile = self.scale_registry.get(scenario.topology_scale) - timeout_seconds = float(profile.health_timeout_seconds) + timeout_seconds = float(profile.experiment.recovery_timeout_seconds) deadline = started + timeout_seconds attempts = 0 errors: list[str] = [] recovery_attempted = False - post_recovery_waited = False convergence_pending = False terminal_recovery_failure = False + state_audit = {} + full_validation_reason = None prior_recovery = episode_result.get("recovery") if isinstance(episode_result, dict) else None recovery_results = prior_recovery while attempts == 0 or monotonic() < deadline: attempts += 1 - active_faults = list(getattr(self.injector, "active_faults", []) or []) + count_operation("recovery_attempts") + active_faults = list(self.injector.active_faults or []) recovery_complete = not active_faults and ( recovery_results is None or self._recovery_results_succeeded(recovery_results) ) if not recovery_complete: try: recovery_attempted = True - recovery_results = self._recover_fault() - active_faults = list(getattr(self.injector, "active_faults", []) or []) + with ( + self.timings.measure_step("recovery", "fault_restore"), + operation_scope(OperationControl(deadline=deadline)), + ): + recovery_results = self._recover_fault() + active_faults = list(self.injector.active_faults or []) recovery_complete = self._recovery_results_succeeded(recovery_results) and not active_faults if not recovery_complete: errors.append( - f"fault_recovery: remaining_faults={len(active_faults)} " f"results={recovery_results!r}" + f"fault_recovery: remaining_faults={len(active_faults)} results={recovery_results!r}" ) terminal_recovery_failure = self._recovery_has_terminal_failure(recovery_results) except Exception as exc: # noqa: BLE001 - bounded retry records the failure @@ -202,69 +365,122 @@ def _cleanup_after_scenario( errors.append(f"fault_recovery: {type(exc).__name__}: {exc}") if recovery_complete: - if recovery_attempted and recovery_results and not post_recovery_waited: - post_recovery_wait = getattr(self, "post_recovery_wait_seconds", 0) - if post_recovery_wait: - self.sleep(post_recovery_wait) - post_recovery_waited = True convergence_errors: list[str] = [] - controller = getattr(self, "traffic_controller", None) - if controller is not None and ( - not bool(controller.active_flows) or not controller.verify_active_flows() - ): - convergence_errors.append("background traffic is not fully ready") - runtime_worker = getattr(self, "runtime_worker", None) + controller = self.traffic_controller + if controller is not None: + with self.timings.measure_step("recovery", "traffic_check"): + if not bool(controller.active_flows) or not controller.verify_active_flows( + control=OperationControl(deadline=deadline) + ): + convergence_errors.append("background traffic is not fully ready") + runtime_worker = self.runtime_worker if runtime_worker is not None: - convergence_errors.extend( - check_worker_health( - runtime_worker, - scale_registry=self.scale_registry, - all_routing_devices=True, + route_snapshot = {"nodes": {}} + with self.timings.measure_step("recovery", "health_check"): + convergence_errors.extend( + check_worker_health( + runtime_worker, + scale_registry=self.scale_registry, + all_routing_devices=True, + deadline=deadline, + route_snapshot=route_snapshot, + expected_routes=self._case_routes, + state_only=True, + recovery_audit=state_audit, + ) ) - ) if convergence_errors: convergence_pending = True errors.extend(f"post_recovery: {error}" for error in convergence_errors) remaining = deadline - monotonic() if remaining <= 0: break - self.sleep(min(float(HEALTH_POLL_INTERVAL_SECONDS), remaining)) + with self.timings.measure_step("recovery", "retry_wait"): + self.sleep(min(float(HEALTH_POLL_INTERVAL_SECONDS), remaining)) continue validated_baseline = None - if recovery_attempted and baseline_window is not None: - validation = self._wait_and_observe( - int(baseline_window["duration_seconds"]), - baseline_window=baseline_window, - ) - from .observation import baseline_gate_errors - - baseline_errors = baseline_gate_errors(validation) - if baseline_errors: - errors.extend(f"post_recovery_baseline: {error}" for error in baseline_errors) + verified_scope = None + config_proof = None + verified_callbacks = all(item.get("readback_verified") is True for item in (recovery_results or [])) + full_validation_reason = ( + "custom_callback" + if not verified_callbacks + else "recovery_retried" if attempts > 1 or state_audit.get("had_errors") else None + ) + if (recovery_attempted or full_validation_reason) and baseline_window is not None: + try: + with self.timings.measure_step("recovery", "configuration_identity"): + if self._case_frr_before is not None: + before = self._case_frr_before + after = frr_snapshot(self, before["device"]) + restored = before["running"] == after["running"] and ( + before["saved_bytes"] == after["saved_bytes"] or after["saved"] == after["running"] + ) + config_proof = {"before": before, "after": after, "restored": restored} + if not restored: + return { + "success": False, + "status": "configuration_recovery_failed", + "configuration_recovery": config_proof, + } + window_scope = self._baseline_scope(scenario) if runtime_worker is not None else None + if runtime_worker is not None and self._case_initial_scope is not None: + changed = restored_scope_errors( + self._case_initial_scope, window_scope, scenario, config_proof + ) + if changed: + return { + "success": False, + "status": "recovery_identity_changed", + "scope_changes": changed, + } + if full_validation_reason: + self.calibrate(scenario, full_validation_reason, deadline=deadline) + validated_baseline = dict(self._baseline_handoff.window) + if monotonic() >= deadline: + raise TimeoutError("Recovery deadline exceeded during observation validation") + if runtime_worker is not None and window_scope is not None: + with self.timings.measure_step("recovery", "configuration_identity"): + verified_scope = self._baseline_scope(scenario) + if verified_scope is None or scope_changes(window_scope, verified_scope): + return { + "success": False, + "status": "recovery_identity_changed", + "scope_changes": scope_changes(window_scope, verified_scope), + } + except TimeoutError as exc: + errors.append(f"post_recovery_baseline: {exc}") return { "success": False, - "status": "post_recovery_baseline_failed", + "status": "recovery_timeout", "attempts": attempts, "duration_seconds": max(0.0, monotonic() - started), "errors": list(dict.fromkeys(errors)), } - validated_baseline = { - "name": "baseline", - "start_time": validation["start_time"], - "end_time": validation["end_time"], - "duration_seconds": validation["duration_seconds"], - } + if monotonic() >= deadline: + errors.append("Recovery deadline exceeded") + break result: dict[str, Any] = { "success": True, "status": "clean" if attempts == 1 else "recovered_after_retry", "attempts": attempts, "duration_seconds": max(0.0, monotonic() - started), "errors": list(dict.fromkeys(errors)), + "validation_level": ("state_checked" if not full_validation_reason else "full_window"), + "full_validation_reason": full_validation_reason, + "state_validation": state_audit, + "recovery_policy": self.recovery_policy.model_dump(mode="json"), } if recovery_results is not None: result["recovery"] = recovery_results if validated_baseline is not None: result["validated_baseline"] = validated_baseline + if verified_scope is not None: + result["validated_baseline_scope"] = verified_scope + if verified_scope is not None: + result["restored_scope"] = verified_scope + if config_proof is not None: + result["configuration_recovery"] = config_proof return result if terminal_recovery_failure: @@ -272,7 +488,8 @@ def _cleanup_after_scenario( remaining = deadline - monotonic() if remaining <= 0: break - self.sleep(min(float(HEALTH_POLL_INTERVAL_SECONDS), remaining)) + with self.timings.measure_step("recovery", "retry_wait"): + self.sleep(min(float(HEALTH_POLL_INTERVAL_SECONDS), remaining)) return { "success": False, @@ -284,7 +501,7 @@ def _cleanup_after_scenario( "attempts": attempts, "duration_seconds": max(0.0, monotonic() - started), "timeout_seconds": timeout_seconds, - "remaining_faults": len(getattr(self.injector, "active_faults", []) or []), + "remaining_faults": len(self.injector.active_faults or []), "errors": list(dict.fromkeys(errors)), } @@ -316,16 +533,19 @@ def run_scenario( Returns: Scenario result dict """ - logger.info(f"\n{'#'*70}") + logger.info(f"\n{'#' * 70}") logger.info(f"# Scenario: {scenario.name}") logger.info(f"# ID: {scenario.scenario_id}") logger.info(f"# Description: {scenario.description}") logger.info(f"# Topology: {scenario.topology_scale}") logger.info(f"# Traffic Profile: {scenario.traffic_profile}") logger.info("# Episode: 1") - logger.info(f"{'#'*70}") + logger.info(f"{'#' * 70}") + self.begin_case() + case_started = monotonic() scenario_result: dict[str, Any] = { + "fault_catalog_version": scenario.metadata.get("fault_catalog_version"), "scenario_id": scenario.scenario_id, "name": scenario.name, "start_time": datetime.now(UTC).isoformat(), @@ -334,6 +554,7 @@ def run_scenario( "episode": None, "case_valid": False, "success": False, + "phase_timings": self.timings.phases, } incident = None @@ -352,6 +573,7 @@ def run_scenario( ) incident = IncidentEngine(lambda: backend, evaluator=self.evaluator).prepare(scenario) + scenario_result["baseline_preparation"] = backend.baseline_preparation scenario_result["traffic_config"] = backend.traffic_config scenario_result["episode"] = backend.episode_result if incident.state is IncidentState.BROKEN: @@ -365,22 +587,26 @@ def run_scenario( session = incident.open_session( SimulatorConfig( max_tool_calls=1_000, - max_agent_seconds=86_400, + max_agent_seconds=self.experiment.diagnosis_timeout_seconds, max_tool_result_bytes=64 * 1024 * 1024, - orphan_lease_ttl_seconds=86_700, + orphan_lease_ttl_seconds=self.experiment.diagnosis_timeout_seconds + 300, ) ) + session.phase_timings = self.timings try: - diagnosis = diagnosis_callback( - episode_result, - diagnostic_session=session, - diagnostic_payload={ - "case_id": incident.case_id, - "topology": backend.topology, - "symptoms": backend.symptoms, - "canonical_observation": incident.observation, - }, - ) + with self.timings.measure( + "diagnosis", timeout_seconds=self.experiment.diagnosis_timeout_seconds + ): + diagnosis = diagnosis_callback( + episode_result, + diagnostic_session=session, + diagnostic_payload={ + "case_id": incident.case_id, + "topology": backend.topology, + "symptoms": backend.symptoms, + "canonical_observation": incident.observation, + }, + ) except Exception as exc: # noqa: BLE001 - agent errors are scored outcomes diagnosis = { "error": str(exc), @@ -390,11 +616,16 @@ def run_scenario( "error_type": type(exc).__name__, }, } + cleanup_time = self.timings.phases.get("agent_cleanup", {}).get("actual_seconds", 0) + self.timings.phases["diagnosis"]["actual_seconds"] = max( + 0, self.timings.phases["diagnosis"]["actual_seconds"] - cleanup_time + ) episode_result["diagnosis"] = diagnosis - if not diagnosis or diagnosis.get("error"): + if not diagnosis or diagnosis.get("error") or diagnosis.get("success") is False: + self.timings.phases["diagnosis"]["status"] = "failed" transition = session.terminate_failure( domain=FailureDomain.AGENT, - message=(diagnosis or {}).get("error", "diagnosis unavailable"), + message=(diagnosis or {}).get("error") or "diagnosis unavailable", reason=TerminationReason.AGENT_ERROR, ) else: @@ -431,9 +662,12 @@ def run_scenario( episode_result["execution"] = transition.model_dump(mode="json") if session.evaluation_result is not None: episode_result["evaluation_result"] = session.evaluation_result - episode_result["success"] = True + execution_success = not (episode_result.get("execution") or {}).get("failure") + episode_result["success"] = execution_success episode_result["state"] = "terminal" - scenario_result["success"] = True + scenario_result["success"] = execution_success + if diagnosis_callback is None: + self.timings.skip("diagnosis", "effects mode") except Exception as e: # noqa: BLE001 - scenario result records infrastructure failures logger.info(f"\n✗ Scenario failed: {e}") scenario_result["error"] = str(e) @@ -458,10 +692,29 @@ def run_scenario( scenario_result["cleanup_failed"] = True scenario_result["end_time"] = datetime.now(UTC).isoformat() - - logger.info(f"\n{'#'*70}") + for phase in ( + "baseline", + "baseline_query", + "baseline_routes", + "traffic_readiness", + "injection", + "observation", + "observation_query", + "effect_validation", + "diagnosis", + "agent_cleanup", + "recovery", + ): + if phase not in self.timings.phases: + self.timings.skip(phase, "not reached or not applicable") + self.timings.phases["total"] = { + "status": "completed" if scenario_result["success"] else "failed", + "actual_seconds": monotonic() - case_started, + } + + logger.info(f"\n{'#' * 70}") logger.info("# Scenario Complete") logger.info(f"# Success: {scenario_result['success']}") - logger.info(f"{'#'*70}") + logger.info(f"{'#' * 70}") return scenario_result diff --git a/netopsbench/platform/scenario/generator.py b/netopsbench/platform/scenario/generator.py index 9162725..9a1c9f5 100644 --- a/netopsbench/platform/scenario/generator.py +++ b/netopsbench/platform/scenario/generator.py @@ -5,19 +5,26 @@ import hashlib import ipaddress import random -import re -from collections.abc import Callable -from dataclasses import dataclass, field +from dataclasses import dataclass from importlib.resources import files from pathlib import Path from typing import Any import yaml +from netopsbench.models.profiles import ScaleRegistry, default_scale_registry from netopsbench.models.scenario import ScenarioSpec -from netopsbench.models.topology import DeviceRole, TopologyManifest -from netopsbench.platform.topology.configdb_payload import interface_names_for_config, interface_networks_for_config +from netopsbench.models.topology import TopologyManifest +from netopsbench.platform.faults.defaults import IMPAIRMENT_PARAMETERS +from netopsbench.platform.topology.configdb_payload import ( + interface_names_from_payload, + interface_networks_from_payload, + load_configdb_payload, +) from netopsbench.platform.topology.topology_utils import load_topology_manifest +from netopsbench.platform.utils.frr import parse_bgp_config + +from .candidates import CandidatePaths def default_campaign_spec() -> Path: @@ -29,50 +36,13 @@ def default_campaign_spec() -> Path: @dataclass class TopologyContext: - topology_dir: Path manifest: TopologyManifest - device_interfaces: dict[str, list[str]] - leaf_interface_roles: dict[str, dict[str, list[str]]] - client_interfaces: dict[str, list[str]] - device_asns: dict[str, int] = field(default_factory=dict) - bgp_neighbors: dict[str, list[dict[str, Any]]] = field(default_factory=dict) - bgp_networks: dict[str, list[dict[str, Any]]] = field(default_factory=dict) + bgp_neighbors: dict[str, list[dict[str, Any]]] @property def scale(self) -> str: return self.manifest.scale - @property - def metadata(self) -> dict[str, Any]: - return self.manifest.to_agent_topology() - - def _device_names(self, role: DeviceRole) -> list[str]: - return [device.name for device in self.manifest.devices_by_role(role)] - - @property - def spines(self) -> list[str]: - return self._device_names(DeviceRole.SPINE) - - @property - def leafs(self) -> list[str]: - return self._device_names(DeviceRole.LEAF) - - @property - def cores(self) -> list[str]: - return self._device_names(DeviceRole.CORE) - - @property - def aggs(self) -> list[str]: - return self._device_names(DeviceRole.AGG) - - @property - def edges(self) -> list[str]: - return self._device_names(DeviceRole.EDGE) - - @property - def clients(self) -> list[dict[str, Any]]: - return self.metadata["devices"]["clients"] - def load_yaml(path: Path) -> dict[str, Any]: with path.open("r", encoding="utf-8") as f: @@ -90,31 +60,25 @@ def load_topology(scale: str, topology_dir: str | None) -> TopologyContext: raise FileNotFoundError(f"Topology metadata not found: {metadata_path}") manifest = load_topology_manifest(metadata_path) - device_interfaces, leaf_interface_roles, client_interfaces = _interface_facts_from_manifest(manifest) - device_asns: dict[str, int] = {} bgp_neighbors: dict[str, list[dict[str, Any]]] = {} - bgp_networks: dict[str, list[dict[str, Any]]] = {} config_dir = topo_dir / "configs" switch_devices = [device.name for device in manifest.switches()] for device in switch_devices: - cfg = _device_config_path(config_dir, device) + cfg = config_dir / "sonic" / device / "config_db.json" frr_cfg = config_dir / "frr" / f"{device}.conf" if not cfg.is_file(): raise FileNotFoundError(f"SONiC ConfigDB artifact not found: {cfg}") if not frr_cfg.is_file(): raise FileNotFoundError(f"FRR artifact not found: {frr_cfg}") - parsed_interfaces = parse_network_interfaces(cfg) - if not parsed_interfaces: + configdb = load_configdb_payload(cfg) + if not interface_names_from_payload(configdb): raise ValueError(f"SONiC ConfigDB has no interfaces: {cfg}") - device_interfaces[device] = parsed_interfaces - bgp_info = parse_bgp_config(frr_cfg) + bgp_info = parse_bgp_config(frr_cfg.read_text()) if bgp_info.get("local_as") is None: raise ValueError(f"FRR artifact has no BGP router stanza: {frr_cfg}") - device_asns[device] = int(bgp_info["local_as"]) neighbors = list(bgp_info.get("neighbors") or []) - interface_networks = interface_networks_for_config(cfg) - interface_roles = leaf_interface_roles.get(device) or {} + interface_networks = interface_networks_from_payload(configdb) for neighbor in neighbors: try: peer_ip = ipaddress.ip_address(str(neighbor["peer_ip"])) @@ -131,724 +95,343 @@ def load_topology(scale: str, topology_dir: str | None) -> TopologyContext: if interface is None: continue neighbor["interface"] = interface - neighbor["interface_role"] = next( - (role for role in ("uplink", "downlink") if interface in (interface_roles.get(role) or [])), - None, - ) bgp_neighbors[device] = neighbors - bgp_networks[device] = list(bgp_info.get("networks") or []) - - return TopologyContext( - topology_dir=topo_dir, - manifest=manifest, - device_interfaces=device_interfaces, - leaf_interface_roles=leaf_interface_roles, - client_interfaces=client_interfaces, - device_asns=device_asns, - bgp_neighbors=bgp_neighbors, - bgp_networks=bgp_networks, - ) - -def _device_config_path(config_dir: Path, device: str) -> Path: - return config_dir / "sonic" / device / "config_db.json" - - -def parse_network_interfaces(cfg_path: Path) -> list[str]: - return interface_names_for_config(cfg_path) - - -def parse_bgp_config(cfg_path: Path) -> dict[str, Any]: - """Parse local ASN, neighbors, and advertised networks from one FRR config.""" - info: dict[str, Any] = {"local_as": None, "neighbors": [], "networks": []} - if not cfg_path.exists(): - return info - - local_as_re = re.compile(r"^router bgp (\d+)$") - neighbor_re = re.compile(r"^neighbor (\S+) remote-as (\d+)$") - neighbor_rm_re = re.compile(r"^neighbor (\S+) route-map (\S+) (in|out)$") - network_re = re.compile(r"^network (\S+)(?: route-map (\S+))?$") - - neighbors: dict[str, dict[str, Any]] = {} - networks: list[dict[str, Any]] = [] - seen_networks = set() - - with cfg_path.open("r", encoding="utf-8") as f: - for raw in f: - line = raw.strip() - match = local_as_re.match(line) - if match: - info["local_as"] = int(match.group(1)) - continue - - match = neighbor_re.match(line) - if match: - peer_ip = match.group(1) - peer = neighbors.setdefault( - peer_ip, - {"peer_ip": peer_ip, "remote_as": None, "route_maps": []}, - ) - peer["remote_as"] = int(match.group(2)) - continue - - match = neighbor_rm_re.match(line) - if match: - peer_ip, route_map, direction = match.groups() - peer = neighbors.setdefault( - peer_ip, - {"peer_ip": peer_ip, "remote_as": None, "route_maps": []}, - ) - attachment = {"name": route_map, "direction": direction} - if attachment not in peer["route_maps"]: - peer["route_maps"].append(attachment) - continue - - match = network_re.match(line) - if match: - prefix, route_map = match.groups() - identity = (prefix, route_map or "") - if identity in seen_networks: - continue - seen_networks.add(identity) - networks.append({"prefix": prefix, "route_map": route_map}) - - info["neighbors"] = sorted(neighbors.values(), key=lambda item: item["peer_ip"]) - info["networks"] = sorted(networks, key=lambda item: item["prefix"]) - return info - - -def _interface_facts_from_manifest( - manifest: TopologyManifest, -) -> tuple[dict[str, list[str]], dict[str, dict[str, list[str]]], dict[str, list[str]]]: - """Derive interface ownership and fabric direction from canonical links.""" - devices = {device.name: device for device in manifest.devices} - switch_interfaces: dict[str, set[str]] = {} - client_interfaces: dict[str, set[str]] = {} - interface_roles: dict[str, dict[str, set[str]]] = {} - - def add_role(device: str, interface: str, role: str) -> None: - normalized = normalize_sonic_interface(interface) - if normalized is None: - return - roles = interface_roles.setdefault(device, {"uplink": set(), "downlink": set(), "any": set()}) - roles[role].add(normalized) - roles["any"].add(normalized) - - uplink_peers = { - DeviceRole.LEAF: {DeviceRole.SPINE}, - DeviceRole.EDGE: {DeviceRole.AGG}, - DeviceRole.AGG: {DeviceRole.CORE}, - } - downlink_peers = { - DeviceRole.LEAF: {DeviceRole.CLIENT}, - DeviceRole.EDGE: {DeviceRole.CLIENT}, - DeviceRole.AGG: {DeviceRole.EDGE}, - } - for link in manifest.links: - left, right = link.endpoints - for endpoint, peer in ((left, right), (right, left)): - device = devices[endpoint.device] - peer_role = devices[peer.device].role - if device.role is DeviceRole.CLIENT: - client_interfaces.setdefault(device.name, set()).add(endpoint.interface) - continue - normalized = normalize_sonic_interface(endpoint.interface) - if normalized is not None: - switch_interfaces.setdefault(device.name, set()).add(normalized) - if peer_role in uplink_peers.get(device.role, set()): - add_role(device.name, endpoint.interface, "uplink") - elif peer_role in downlink_peers.get(device.role, set()): - add_role(device.name, endpoint.interface, "downlink") - - return ( - {name: sorted(interfaces) for name, interfaces in switch_interfaces.items()}, - { - name: {role: sorted(interfaces) for role, interfaces in roles.items()} - for name, roles in interface_roles.items() - }, - {name: sorted(interfaces) for name, interfaces in client_interfaces.items()}, - ) - - -def normalize_sonic_interface(name: str | None) -> str | None: - """Normalize interface names to SONiC EthernetX when possible.""" - if not name: - return name - raw = name.strip() - lower = raw.lower() - if lower.startswith("ethernet") and raw[8:].isdigit(): - return f"Ethernet{int(raw[8:])}" - if lower.startswith("eth") and raw[3:].isdigit(): - idx = int(raw[3:]) - if idx >= 1: - return f"Ethernet{(idx - 1) * 4}" - if lower.startswith("e1-") and raw[3:].isdigit(): - idx = int(raw[3:]) - if idx >= 1: - return f"Ethernet{(idx - 1) * 4}" - if "ethernet-1/" in lower: - try: - idx = int(raw.split("/")[-1]) - if idx >= 1: - return f"Ethernet{(idx - 1) * 4}" - except ValueError: - return raw - return raw - - -def count_for_scale(item: dict[str, Any], scale: str, default_count: int) -> int: - cps = item.get("count_per_scale", {}) - if isinstance(cps, dict) and scale in cps: - return int(cps[scale]) - return int(item.get("count", default_count)) - - -def device_candidates(role: str, topo: TopologyContext) -> list[str]: - if role == "spine": - return topo.cores if topo.cores else topo.spines - if role == "core": - return topo.cores if topo.cores else topo.spines - if role == "leaf": - return topo.edges if topo.edges else topo.leafs - if role == "edge": - return topo.edges if topo.edges else topo.leafs - if role == "agg": - if not topo.aggs: - raise ValueError("device_role 'agg' requires a fat-tree topology") - return topo.aggs - if role == "client": - return [c["name"] for c in topo.clients] - raise ValueError(f"Unknown role: {role}") - - -def pick_device(role: str, topo: TopologyContext, rng: random.Random) -> str: - return rng.choice(device_candidates(role, topo)) - - -def pick_network_interface(device: str, topo: TopologyContext, rng: random.Random) -> str: - candidates = topo.device_interfaces.get(device) or ["Ethernet0"] - normalized: list[str] = [] - for candidate in candidates: - interface = normalize_sonic_interface(candidate) - if interface is not None: - normalized.append(interface) - return rng.choice(normalized) if normalized else "Ethernet0" - - -def pick_bgp_neighbor( - device: str, - topo: TopologyContext, - rng: random.Random, - interface_role: str | None = None, -) -> dict[str, Any]: - candidates = topo.bgp_neighbors.get(device) or [] - if interface_role: - candidates = [item for item in candidates if item.get("interface_role") == interface_role] - if not candidates: - suffix = f" for interface_role={interface_role}" if interface_role else "" - raise ValueError(f"Device {device} has no parsed BGP neighbors{suffix}") - return dict(rng.choice(candidates)) - - -def pick_advertised_network(device: str, topo: TopologyContext, rng: random.Random) -> dict[str, Any]: - candidates = topo.bgp_networks.get(device) or [] - if not candidates: - raise ValueError(f"Device {device} has no parsed BGP networks") - return dict(rng.choice(candidates)) - - -def _client_leaf(client: dict[str, Any]) -> str: - return str(client.get("leaf") or client.get("edge") or "").strip() - - -def _pick_client_for_route_fault( - topo: TopologyContext, - rng: random.Random, - excluded_leaf: str | None = None, -) -> dict[str, Any]: - # Prefer remote leaf destinations to avoid selecting a local directly-connected subnet - # on the same leaf where the route fault is injected. - candidates = list(topo.clients) - if excluded_leaf: - remote = [c for c in candidates if _client_leaf(c) != excluded_leaf] - if remote: - candidates = remote - return rng.choice(candidates) - - -def _client_subnet(client: dict[str, Any], prefix_len: int = 30) -> str: - ip_str = str(client.get("data_ip") or "").strip() - if not ip_str: - raise ValueError(f"Client {client.get('name', 'unknown')} missing data_ip in topology metadata") - ip_obj = ipaddress.ip_address(ip_str) - net = ipaddress.ip_network(f"{ip_obj}/{prefix_len}", strict=False) - return str(net) - - -def _client_host_route(client: dict[str, Any]) -> str: - ip_str = str(client.get("data_ip") or "").strip() - if not ip_str: - raise ValueError(f"Client {client.get('name', 'unknown')} missing data_ip in topology metadata") - return f"{ip_str}/32" - - -def pick_link_down_interface(device: str, topo: TopologyContext, rng: random.Random) -> str: - candidates = topo.device_interfaces.get(device) or ["Ethernet0"] - normalized: list[str] = [] - for candidate in candidates: - interface = normalize_sonic_interface(candidate) - if interface is not None: - normalized.append(interface) - candidates = normalized or ["Ethernet0"] - manifest_device = topo.manifest.device(device) - if manifest_device is not None and manifest_device.role in {DeviceRole.LEAF, DeviceRole.EDGE}: - roles = topo.leaf_interface_roles.get(device) - if roles and roles.get("downlink"): - return rng.choice(roles["downlink"]) - return rng.choice(candidates) - - -def pick_leaf_interface(device: str, topo: TopologyContext, rng: random.Random, role: str) -> str: - roles = topo.leaf_interface_roles.get(device) or {} - role = (role or "any").lower() - pool = roles.get(role) or roles.get("any") - if pool: - return rng.choice(pool) - return pick_network_interface(device, topo, rng) - - -def is_role_aware_switch(device: str, topo: TopologyContext) -> bool: - manifest_device = topo.manifest.device(device) - return manifest_device is not None and manifest_device.role in { - DeviceRole.LEAF, - DeviceRole.EDGE, - DeviceRole.AGG, - } - - -def pick_client_interface(device: str, topo: TopologyContext, rng: random.Random) -> str: - candidates = topo.client_interfaces.get(device) - if candidates: - return rng.choice(candidates) - return "eth1" + return TopologyContext(manifest=manifest, bgp_neighbors=bgp_neighbors) @dataclass -class FaultBuildTarget: +class _Placement: device: str - interface: str | None = None - prefix: str | None = None - mtu: int | None = None - metadata: dict[str, Any] = field(default_factory=dict) - - -def _generic_fault_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - return FaultBuildTarget(device=target_device or pick_device(template.get("device_role", "leaf"), topo, rng)) - - -def _link_down_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - interface_role = template.get("interface_role") - if not interface_role: - target.interface = pick_link_down_interface(target.device, topo, rng) - elif is_role_aware_switch(target.device, topo): - target.interface = pick_leaf_interface(target.device, topo, rng, interface_role) - else: - target.interface = pick_network_interface(target.device, topo, rng) - return target - - -def _role_interface_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - role = template.get("interface_role") or "uplink" - target.interface = ( - pick_leaf_interface(target.device, topo, rng, role) - if is_role_aware_switch(target.device, topo) - else pick_network_interface(target.device, topo, rng) - ) - return target - - -def _packet_fault_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - manifest_device = topo.manifest.device(target.device) - if manifest_device is not None and manifest_device.role is DeviceRole.CLIENT: - target.interface = pick_client_interface(target.device, topo, rng) - elif is_role_aware_switch(target.device, topo): - target.interface = pick_leaf_interface( - target.device, - topo, - rng, - template.get("interface_role") or "uplink", - ) - else: - target.interface = pick_network_interface(target.device, topo, rng) - return target - + interface: str | None + peer: str | None + prefix: str + parameters: dict[str, Any] + witnesses: list[dict[str, str]] + controls: list[dict[str, str]] + + +class _CandidateIndex(CandidatePaths): + """Shortest-path DAG membership, without enumerating complete paths.""" + + def __init__(self, topo: TopologyContext, seed: int): + from collections import Counter + + super().__init__(topo.manifest) + self.topo = topo + random.Random(seed).shuffle(self.pairs) + self.device_uses, self.pod_uses, self.link_uses = Counter(), Counter(), Counter() + self.seed = seed + + def _roots(self, unit): + candidates = [d for d in self.topo.manifest.switches() if d.role.value == unit.role] + + # Prefer unused pods, devices and low/middle/high number ranges. High + # numbered nodes are eligible from the first cycle, including K18 >155. + def key(d): + pod = d.metadata.get("pod") + rank = next(i for i, item in enumerate(candidates) if item.name == d.name) + bucket = min(2, rank * 3 // max(1, len(candidates))) + return ( + self.pod_uses[unit.role, pod] if pod is not None else 0, + self.device_uses[d.name], + self.pod_uses[unit.role, "bucket", bucket], + _stable_template_seed(self.seed, self.topo.scale, unit.id + d.name), + ) -def _blackhole_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - client = _pick_client_for_route_fault(topo, rng, excluded_leaf=target.device) - target.prefix = _client_subnet(client, prefix_len=30) - return target + return sorted(candidates, key=key) + + def place(self, unit): + fault = unit.fault_type + for device in self._roots(unit): + root = device.name + peers = [None] + if unit.position: + peer_role = unit.position.split("-")[-1] + peers = [ + peer for (node, peer) in self.ports if node == root and self.devices[peer].role.value == peer_role + ] + peers.sort( + key=lambda peer: ( + self.link_uses[frozenset((root, peer))], + _stable_template_seed(self.seed, self.topo.scale, unit.id + peer), + ) + ) + for peer in peers: + found = [] + parameters = {} + for src, dst in self.pairs: + source, target = self.clients[src], self.clients[dst] + reverse = fault in {"routing_loop", "route_flapping"} or unit.mechanism == "export_filter" + member = self.contains(src, dst, root, peer) if not reverse else self.contains(src, dst, peer, root) + if not member: + continue + if fault == "route_origination_misconfig" or unit.scope == "destination": + if target.attached_switch != root: + continue + if unit.scope == "source" or fault == "static_route_misconfig": + if source.attached_switch != root or target.attached_switch == root: + continue + if fault in {"ecmp_misconfig", "route_filter_misconfig"} and not reverse: + hops = [ + neighbor + for neighbor in self.adj[root] + if self.distance(target.attached_switch)[neighbor] + 1 + == self.distance(target.attached_switch)[root] + ] + if not hops: + continue + if fault == "ecmp_misconfig" or unit.scope in {"reduced", "reduced_remote_pod"}: + if len(hops) < 2: + continue + if unit.role == "agg" and (fault == "ecmp_misconfig" or unit.scope == "reduced_remote_pod"): + if device.metadata.get("pod") == self.devices[target.attached_switch].metadata.get("pod"): + continue + else: + hops = [] + prefix = str(ipaddress.ip_network(f"{target.data_ip}/30", strict=False)) + parameters = {"mechanism": unit.mechanism} if unit.mechanism else {} + if ( + fault.startswith("bgp_") + and fault != "bgp_process_down" + or fault == "route_flapping" + or unit.mechanism == "export_filter" + ): + parameters["peer_ip"] = self._peer_ip(root, peer) + if unit.mechanism == "import_filter": + chosen = self.adj[root] if unit.scope == "missing" else hops[:1] + parameters["peer_ips"] = [self._peer_ip(root, neighbor) for neighbor in chosen] + if fault == "static_route_misconfig": + local = [c for c in self.clients.values() if c.attached_switch == root and c.name != src] + if not local: + continue + parameters.update(target_ip=f"{target.data_ip}/32", wrong_nexthop=local[0].data_ip) + prefix = f"{target.data_ip}/32" + if fault == "blackhole_route": + prefix = f"{target.data_ip}/32" + if fault == "routing_loop": + parameters["next_hop"] = self._peer_ip(root, peer) + prefix = f"{target.data_ip}/32" + if fault.startswith("acl_"): + parameters["direction"] = "out" + if fault == "acl_source_misconfig": + parameters["source_prefix"] = f"{source.data_ip}/32" + if fault == "acl_l4_port_misconfig": + parameters["destination_port"] = 33434 + parameters.update(IMPAIRMENT_PARAMETERS.get(fault, {})) + found.append({"src": src, "dst": dst}) + break + if not found: + continue + affected = found[0] + found = self.affected_pairs(fault, root, peer, affected, reverse=reverse) + # Choose controls from the same immutable plan, based on the + # scope of this configuration rather than synthetic extra traffic. + controls = [] + for src, dst in self.pairs: + if {"src": src, "dst": dst} == affected: + continue + if fault == "acl_source_misconfig": + eligible = affected["src"] not in {src, dst} and self.contains(src, dst, root, peer) + elif fault == "acl_destination_misconfig": + eligible = dst != affected["dst"] and src != affected["dst"] + elif fault in { + "route_origination_misconfig", + "route_filter_misconfig", + "routing_loop", + "blackhole_route", + "static_route_misconfig", + "route_flapping", + }: + eligible = dst != affected["dst"] and src != affected["dst"] + elif fault in {"device_down", "bgp_process_down", "ecmp_misconfig"}: + eligible = not self.contains(src, dst, root) + else: + eligible = not self.contains(src, dst, root, peer) + if peer and peer not in self.clients: + eligible = eligible and not self.contains(src, dst, peer, root) + if peer in self.clients: + eligible = eligible and peer not in {src, dst} + if eligible: + controls.append({"src": src, "dst": dst}) + break + if not controls: + if self.topo.manifest.purpose != "validation": + continue + # XS has only two directed flows; the reverse is a comparison, + # not proof of an unaffected path. XS is validation only. + controls = [{"src": affected["dst"], "dst": affected["src"]}] + self.device_uses[root] += 1 + self.pod_uses[unit.role, device.metadata.get("pod")] += 1 + candidates = [d for d in self.topo.manifest.switches() if d.role.value == unit.role] + rank = next(i for i, d in enumerate(candidates) if d.name == root) + self.pod_uses[unit.role, "bucket", min(2, rank * 3 // len(candidates))] += 1 + if peer: + self.link_uses[frozenset((root, peer))] += 1 + return _Placement(root, self.ports.get((root, peer)), peer, prefix, parameters, found, controls) + raise ValueError(f"No planned candidate for necessary coverage unit {unit.id} in {self.topo.scale}") + + def _peer_ip(self, root, peer): + interface = self.ports.get((root, peer)) + neighbors = self.topo.bgp_neighbors.get(root, []) + match = next((n for n in neighbors if n.get("interface") == interface), None) + if not match: + raise ValueError(f"No configured neighbor for {root}->{peer}") + return match["peer_ip"] -def _static_route_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - device = target_device or pick_device("leaf", topo, rng) - client = _pick_client_for_route_fault(topo, rng, excluded_leaf=device) - return FaultBuildTarget( - device=device, - metadata={"target_ip": _client_host_route(client), "wrong_nexthop": "auto"}, - ) - - -def _bgp_neighbor_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - neighbor = pick_bgp_neighbor( - target.device, - topo, - rng, - interface_role=template.get("interface_role"), - ) - target.metadata = { - "peer_ip": neighbor["peer_ip"], - "misconfig_kind": template.get("misconfig_kind", "peer_as_mismatch"), - } - if neighbor.get("remote_as") is not None: - target.metadata["original_remote_as"] = int(neighbor["remote_as"]) - return target +def _stable_template_seed(seed: int, scale: str, template_name: str) -> int: + return int.from_bytes(hashlib.sha256(f"{seed}\0{scale}\0{template_name}".encode()).digest()[:8], "big") -def _route_policy_target( - topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - network = pick_advertised_network(target.device, topo, rng) - target.prefix = network["prefix"] - target.metadata = {"misconfig_kind": template.get("misconfig_kind", "network_statement_missing")} - if network.get("route_map"): - target.metadata["route_map"] = network["route_map"] - return target - - -def _acl_target( +def generate( + spec: dict[str, Any], topo: TopologyContext, - rng: random.Random, - template: dict[str, Any], - target_device: str | None = None, -) -> FaultBuildTarget: - target = _generic_fault_target(topo, rng, template, target_device) - target.prefix = pick_advertised_network(target.device, topo, rng)["prefix"] - target.interface = ( - pick_leaf_interface(target.device, topo, rng, "uplink") - if is_role_aware_switch(target.device, topo) - else pick_network_interface(target.device, topo, rng) - ) - target.metadata = {"direction": template.get("direction", "in")} - return target - - -FaultScenarioBuilder = Callable[ - [TopologyContext, random.Random, dict[str, Any], str | None], - FaultBuildTarget, -] - -FAULT_SCENARIO_BUILDERS: dict[str, FaultScenarioBuilder] = { - "device_down": _generic_fault_target, - "link_down": _link_down_target, - "link_flapping": _role_interface_target, - "mtu_mismatch": _role_interface_target, - "high_latency": _role_interface_target, - "packet_loss": _packet_fault_target, - "packet_corruption": _packet_fault_target, - "blackhole_route": _blackhole_target, - "static_route_misconfig": _static_route_target, - "bgp_neighbor_misconfig": _bgp_neighbor_target, - "route_policy_misconfig": _route_policy_target, - "acl_misconfig": _acl_target, -} - - -def diagnostic_observation_duration(base_duration: int, manifest: TopologyManifest) -> int: - """Return one complete Pingmesh epoch plus topology-derived ingestion grace.""" - complete_seconds = manifest.pingmesh.complete_window_seconds(manifest.facts.total_clients) - return max(base_duration, complete_seconds) - - -def _validate_traffic_profiles(spec: dict[str, Any]) -> None: - configured = [spec.get("defaults", {}).get("traffic_profile")] - configured.extend(template.get("traffic_profile") for template in spec.get("fault_templates", [])) - invalid = next((profile for profile in configured if profile not in (None, "standard")), None) - if invalid is not None: - raise ValueError(f"Only the standard traffic profile is supported, got: {invalid}") - - -def build_fault_instance( - fault_type: str, - difficulty: str, - topo: TopologyContext, - rng: random.Random, - defaults: dict[str, Any], - template: dict[str, Any], - idx: int, - target_device: str | None = None, -) -> dict[str, Any]: - # Healthy scenarios use the same diagnosable episode lifecycle without injection. - if fault_type == "none": - observation_duration = diagnostic_observation_duration( - int(defaults.get("fault_duration_seconds", 30)), - topo.manifest, - ) - scenario_id = f"generated_healthy_network_{topo.scale}_{idx:03d}" - return { + out_dir: Path, + seed: int, + *, + scale_registry: ScaleRegistry | None = None, +) -> list[Path]: + import json + + from netopsbench.platform.faults.catalog import FAULT_CATALOG_VERSION, coverage_units + + if spec.get("fault_catalog_version") != FAULT_CATALOG_VERSION: + raise ValueError("Obsolete campaign spec; use fault catalog version 2 and regenerate") + defaults = spec.get("defaults", {}) + if "fault_duration_seconds" in defaults: + raise ValueError("Configure experiment.observation_seconds in scale profiles and regenerate scenarios") + from netopsbench.models.recovery import RecoveryPolicy + + recovery_policy = RecoveryPolicy.model_validate(spec.get("recovery_policy", {})) + policy = (scale_registry or default_scale_registry()).get(topo.scale).experiment + duration = policy.window_seconds(topo.manifest.require_pingmesh_plan().settings.complete_window_seconds) + if defaults.get("traffic_profile", "standard") != "standard": + raise ValueError("Only standard traffic is supported") + validation = topo.manifest.purpose == "validation" + units = coverage_units(topo.manifest.family, validation=validation) + index = _CandidateIndex(topo, seed) + out_dir.mkdir(parents=True, exist_ok=True) + rows, paths = [], [] + fault_indices = {} + for unit in units: + placement = index.place(unit) + rng = random.Random(_stable_template_seed(seed, topo.scale, unit.id)) + if unit.fault_type == "interface_ip_misconfig": + placement.parameters["fault_address"] = f"198.51.100.{rng.randrange(64) * 4 + 1}/30" + if unit.fault_type == "bgp_update_source_mismatch": + placement.parameters["fault_update_source"] = f"Loopback{rng.randrange(1, 4096)}" + placement.parameters.update(affected_candidates=placement.witnesses, control_candidates=placement.controls) + if unit.scope: + placement.parameters["impact_scope"] = unit.scope + if unit.fault_type in {"link_flapping", "route_flapping"}: + placement.parameters.update(down_time=policy.flapping_down_seconds, up_time=policy.flapping_up_seconds) + fault_indices[unit.fault_type] = fault_indices.get(unit.fault_type, 0) + 1 + scenario_id = f"generated_{unit.fault_type}_{topo.scale}_{fault_indices[unit.fault_type]:03d}" + episode = { + "episode_id": "diagnosis", + "fault_type": unit.fault_type, + "target_device": placement.device, + "duration_seconds": duration, + "stabilization_time": 0, + "parameters": placement.parameters, + } + if placement.interface: + episode["target_interface"] = placement.interface + if unit.fault_type in { + "routing_loop", + "route_origination_misconfig", + "route_filter_misconfig", + "route_flapping", + "ecmp_misconfig", + "blackhole_route", + "static_route_misconfig", + "acl_source_misconfig", + "acl_destination_misconfig", + "acl_l4_port_misconfig", + }: + episode["target_prefix"] = placement.prefix + payload = { "schema_version": "1", "scenario_id": scenario_id, - "name": f"Generated healthy network case #{idx} ({topo.scale})", - "description": f"Auto-generated healthy network scenario ({topo.scale} topology).", + "name": scenario_id, "topology_scale": topo.scale, "traffic_profile": "standard", "metadata": { - "difficulty": difficulty, - "generator": { - "seed": defaults.get("seed"), - "topology_dir": str(topo.topology_dir), - "template": template.get("name", "healthy_network"), - }, + "fault_catalog_version": FAULT_CATALOG_VERSION, + "difficulty": "medium", + "coverage_unit": unit.id, + "purpose": "validation" if validation else "benchmark", + "experiment": policy.model_dump(mode="json"), + "recovery_policy": recovery_policy.model_dump(mode="json"), + "generator": {"seed": seed, "version": 3}, + }, + "episode": episode, + } + scenario = ScenarioSpec.model_validate(payload) + path = out_dir / f"{scenario_id}.yaml" + path.write_text(yaml.safe_dump(scenario.model_dump(mode="json", exclude_none=True), sort_keys=False)) + paths.append(path) + rows.append( + { + "scenario_id": scenario_id, + "unit": unit.id, + "fault_type": unit.fault_type, + "mechanism": unit.mechanism or unit.fault_type, + "root": placement.device, + "role": unit.role, + "pod": index.devices[placement.device].metadata.get("pod"), + "interface": placement.interface, + "neighbor": placement.peer, + "prefix": placement.prefix, + "affected_candidates": placement.witnesses, + "control_candidates": placement.controls, + } + ) + for number in range(1, (1 if validation else 4) + 1): + scenario_id = f"generated_healthy_network_{topo.scale}_{number:03d}" + payload = { + "schema_version": "1", + "scenario_id": scenario_id, + "name": scenario_id, + "topology_scale": topo.scale, + "metadata": { + "negative_sample": True, + "generator": {"seed": seed, "version": 3}, + "difficulty": "medium", + "fault_catalog_version": FAULT_CATALOG_VERSION, + "purpose": "validation" if validation else "benchmark", + "experiment": policy.model_dump(mode="json"), + "recovery_policy": recovery_policy.model_dump(mode="json"), }, "episode": { "episode_id": "diagnosis", - "description": "Observe healthy network without fault injection", "fault_type": "none", - "duration_seconds": observation_duration, "stabilization_time": 0, + "duration_seconds": duration, }, } - - # Merge nested ``parameters`` dict into the top-level template so that - # campaign-level overrides like ``parameters: {misconfig_kind: ...}`` - # are visible to ``template.get("misconfig_kind")`` lookups below. - if "parameters" in template: - template = {**template, **template["parameters"]} - try: - builder = FAULT_SCENARIO_BUILDERS[fault_type] - except KeyError as exc: - raise ValueError(f"No scenario builder registered for fault type: {fault_type}") from exc - target = builder(topo, rng, template, target_device) - extra_episode_metadata = dict(target.metadata) - - if template.get("variant"): - extra_episode_metadata["variant"] = template["variant"] - if template.get("recovery_mode"): - extra_episode_metadata["recovery_mode"] = template["recovery_mode"] - - parameter_defaults = { - "link_flapping": {"iterations": 6, "down_time": 2, "up_time": 3}, - "packet_loss": {"loss_pct": 30}, - "packet_corruption": {"corruption_pct": 20}, - "high_latency": {"latency_ms": 100}, - } - for key, default in parameter_defaults.get(fault_type, {}).items(): - extra_episode_metadata[key] = int(template.get(key, default)) - if fault_type == "mtu_mismatch": - target.mtu = int(template.get("mtu", 1400)) - - scenario_id = f"generated_{fault_type}_{topo.scale}_{idx:03d}" - scenario_name = f"Generated {fault_type} case #{idx} ({topo.scale})" - - fault_duration = diagnostic_observation_duration( - int(defaults.get("fault_duration_seconds", 30)), - topo.manifest, - ) - fault_stabilization = int( - template.get("fault_stabilization_seconds", defaults.get("fault_stabilization_seconds", 5)) - ) - episode_fault: dict[str, Any] = { - "episode_id": "diagnosis", - "description": f"Inject {fault_type} on {target.device}", - "fault_type": fault_type, - "target_device": target.device, - "duration_seconds": fault_duration, - "stabilization_time": fault_stabilization, - "metadata": {"severity": template.get("severity", "medium")}, - } - if target.interface: - episode_fault["target_interface"] = target.interface - if target.prefix: - episode_fault["target_prefix"] = target.prefix - if target.mtu: - episode_fault["mtu"] = target.mtu - episode_fault["metadata"].update(extra_episode_metadata) - - return { - "schema_version": "1", - "scenario_id": scenario_id, - "name": scenario_name, - "description": template.get( - "description", - f"Auto-generated {fault_type} localization scenario for {topo.scale} topology.", - ), - "topology_scale": topo.scale, - "traffic_profile": "standard", - "metadata": { - "difficulty": difficulty, - "generator": { - "seed": defaults.get("seed"), - "topology_dir": str(topo.topology_dir), - "template": template.get("name", fault_type), - }, - }, - "episode": episode_fault, + scenario = ScenarioSpec.model_validate(payload) + path = out_dir / f"{scenario_id}.yaml" + path.write_text(yaml.safe_dump(scenario.model_dump(mode="json", exclude_none=True), sort_keys=False)) + paths.append(path) + matrix = { + "fault_catalog_version": FAULT_CATALOG_VERSION, + "scale": topo.scale, + "seed": seed, + "plan_id": topo.manifest.require_pingmesh_plan().settings.plan_id, + "coverage_units": rows, + "positive_cases": len(rows), + "negative_cases": 1 if validation else 4, } - - -def _stable_template_seed(seed: int, scale: str, template_name: str) -> int: - identity = f"{seed}\0{scale}\0{template_name}".encode() - return int.from_bytes(hashlib.sha256(identity).digest()[:8], "big") - - -def _ordered_template_devices( - role: str, - topo: TopologyContext, - rng: random.Random, -) -> list[str]: - candidates = device_candidates(role, topo) - by_name = {device.name: device for device in topo.manifest.devices} - pod_groups: dict[int, list[str]] = {} - without_pod: list[str] = [] - for name in candidates: - pod = (by_name[name].metadata or {}).get("pod") - if pod is None: - without_pod.append(name) - else: - pod_groups.setdefault(int(pod), []).append(name) - - if not pod_groups: - shuffled = list(candidates) - rng.shuffle(shuffled) - return shuffled - - pod_order = sorted(pod_groups) - rng.shuffle(pod_order) - for names in pod_groups.values(): - rng.shuffle(names) - rng.shuffle(without_pod) - - ordered: list[str] = [] - while any(pod_groups.values()): - for pod in pod_order: - if pod_groups[pod]: - ordered.append(pod_groups[pod].pop()) - ordered.extend(without_pod) - return ordered - - -def generate(spec: dict[str, Any], topo: TopologyContext, out_dir: Path, seed: int) -> list[Path]: - _validate_traffic_profiles(spec) - defaults = dict(spec.get("defaults", {})) - defaults["seed"] = seed - default_count = int(defaults.get("count_per_fault", 5)) - - out_dir.mkdir(parents=True, exist_ok=True) - generated: list[Path] = [] - next_index_by_fault: dict[str, int] = {} - - for template in spec.get("fault_templates", []): - fault_type = template["fault_type"] - difficulty = template.get("difficulty", "medium") - count = count_for_scale(template, topo.scale, default_count) - if count <= 0: - continue - - template_name = str(template.get("name") or fault_type) - rng = random.Random(_stable_template_seed(seed, topo.scale, template_name)) - target_devices: list[str | None] = [] - if fault_type == "none": - target_devices.extend([None] * count) - else: - # Static-route faults intentionally remain access/origin scoped to - # match the current handler's device-local route semantics. - role = "leaf" if fault_type == "static_route_misconfig" else str(template.get("device_role") or "leaf") - ordered_devices = _ordered_template_devices(role, topo, rng) - if count > len(ordered_devices): - raise ValueError( - f"Template {template_name} requests {count} unique {role} devices, " - f"but topology {topo.scale} has only {len(ordered_devices)}" - ) - target_devices.extend(ordered_devices[:count]) - - for target_device in target_devices: - idx = next_index_by_fault.get(fault_type, 0) + 1 - next_index_by_fault[fault_type] = idx - payload = build_fault_instance( - fault_type=fault_type, - difficulty=difficulty, - topo=topo, - rng=rng, - defaults=defaults, - template=template, - idx=idx, - target_device=target_device, - ) - scenario = ScenarioSpec.model_validate(payload) - out_path = out_dir / f"{payload['scenario_id']}.yaml" - with out_path.open("w", encoding="utf-8") as f: - yaml.safe_dump( - scenario.model_dump(mode="json", exclude_none=True), - f, - sort_keys=False, - allow_unicode=False, - ) - generated.append(out_path) - - return generated + (out_dir / "coverage.json").write_text(json.dumps(matrix, indent=2) + "\n") + return paths def cleanup_existing_outputs(out_dir: Path) -> int: if not out_dir.exists(): return 0 - - removed = 0 - for pattern in ("*.yaml", "*.yml"): - for existing in out_dir.glob(pattern): - if existing.is_file(): - existing.unlink() - removed += 1 - return removed + paths = [p for pattern in ("*.yaml", "*.yml", "coverage.json") for p in out_dir.glob(pattern) if p.is_file()] + for path in paths: + path.unlink() + return len(paths) diff --git a/netopsbench/platform/scenario/incident_backend.py b/netopsbench/platform/scenario/incident_backend.py index e29aae3..5821600 100644 --- a/netopsbench/platform/scenario/incident_backend.py +++ b/netopsbench/platform/scenario/incident_backend.py @@ -2,6 +2,8 @@ from __future__ import annotations +import time +from datetime import UTC, datetime from typing import Any from netopsbench.models.scenario import ScenarioSpec @@ -15,10 +17,12 @@ from netopsbench.platform.incident.contracts import ToolAction from netopsbench.platform.scenario.episode_runner import observe_episode from netopsbench.platform.scenario.observation import ( - baseline_gate_errors, + baseline_window_seconds, observation_integrity_errors, ) +from netopsbench.platform.toolkit.public import public_tool_result from netopsbench.platform.toolkit.toolkit import AgentToolkit +from netopsbench.platform.utils.control import current_operation_control class ExecutorIncidentBackend: @@ -28,14 +32,11 @@ def __init__( self, executor: Any, *, - setup_traffic: bool = True, - baseline_window: dict[str, Any] | None = None, influxdb_bucket: str | None = None, topology_id: str | None = None, ): self.executor = executor - self.setup_traffic = setup_traffic - self.baseline_window = baseline_window + self.baseline_window: dict[str, Any] | None = None self.influxdb_bucket = influxdb_bucket self.topology_id = topology_id self.topology_dir = str(executor.topology_dir) @@ -48,10 +49,38 @@ def __init__( self.pingmesh_query_window: dict[str, Any] = {} self.cleanup_result: dict[str, Any] | None = None self._finished = False + self.baseline_preparation: dict[str, Any] = {"mode": "explicit"} + self._scope = None def prepare(self, scenario: ScenarioSpec) -> dict[str, Any]: self.scenario = scenario - if self.setup_traffic: + from netopsbench.models.recovery import RecoveryPolicy + + policy = RecoveryPolicy.from_metadata(scenario.metadata) + handoff = self.executor._baseline_handoff + if self.executor.recovery_policy != policy: + handoff.clear("recovery_policy_changed") + self.executor.recovery_policy = policy + handoff.max_cases = policy.baseline_max_cases + if self.executor.injector.active_faults: + raise RuntimeError("Runtime contains unresolved faults; recovery is required before preparation") + if scenario.metadata.get("experiment") is not None: + experiment_policy = self.executor.experiment + window = experiment_policy.window_seconds( + self.executor.current_manifest().require_pingmesh_plan().settings.complete_window_seconds + ) + if ( + scenario.metadata["experiment"] != experiment_policy.model_dump(mode="json") + or scenario.episode.duration_seconds != window + or scenario.episode.stabilization_time + ): + raise ValueError("Campaign experiment configuration changed; regenerate scenarios in a new campaign") + if scenario.episode.fault_type in {"link_flapping", "route_flapping"} and ( + scenario.episode.parameters.get("down_time") != experiment_policy.flapping_down_seconds + or scenario.episode.parameters.get("up_time") != experiment_policy.flapping_up_seconds + ): + raise ValueError("Per-case periodic timing override is not allowed in a frozen campaign") + with self.executor.timings.measure("traffic_readiness"): controller = self.executor.traffic_controller traffic_ready = ( controller is not None and bool(controller.active_flows) and controller.verify_active_flows() @@ -63,29 +92,124 @@ def prepare(self, scenario: ScenarioSpec) -> dict[str, Any]: scenario.scale, scenario.traffic_profile, ) - if self.baseline_window is None: - reference = self.executor._capture_baseline_window() - validation = self.executor._wait_and_observe( - int(reference["duration_seconds"]), - baseline_window=reference, - ) - gate_errors = baseline_gate_errors(validation) - if gate_errors: - raise RuntimeError("Healthy baseline is unavailable: " + "; ".join(gate_errors)) - self.baseline_window = { - "name": "baseline", - "start_time": validation["start_time"], - "end_time": validation["end_time"], - "duration_seconds": validation["duration_seconds"], - } + if traffic_ready: + self.traffic_config = self.executor._traffic_config + handoff = self.executor._baseline_handoff if self.baseline_window is None: - raise RuntimeError("Incident preparation requires an explicit Pingmesh baseline window") + self._scope = self.executor._baseline_scope(scenario) + self.baseline_window, reason = handoff.take( + self._scope, baseline_window_seconds(self.executor, self.executor.minimum_baseline_seconds) + ) + self.baseline_preparation = { + "mode": "reused" if self.baseline_window else "fresh", + "reason": reason, + "source_scenario_id": handoff.source if self.baseline_window else None, + "scope_changes": handoff.last_changes, + } + if self.baseline_window is None: + self.executor.calibrate(scenario, self.baseline_preparation.get("reason", "initial")) + self._scope = self.executor._baseline_scope(scenario) + self.baseline_window, reason = handoff.take( + self._scope, baseline_window_seconds(self.executor, self.executor.minimum_baseline_seconds) + ) + if self.baseline_window is None: + raise RuntimeError("Calibrated baseline unavailable: " + reason) + self.executor.timings.skip("baseline", "verified healthy window handoff") + self.executor._case_initial_scope = self._scope + self.baseline_preparation.update( + uses=handoff.uses, + recovery_policy=policy.model_dump(mode="json"), + window=dict(self.baseline_window), + age_seconds=( + datetime.now(UTC) - datetime.fromisoformat(self.baseline_window["end_time"].replace("Z", "+00:00")) + ).total_seconds(), + ) + catalog_v2 = scenario.metadata.get("fault_catalog_version") == 2 + self.executor._case_affected_pairs = [] + self.executor._case_probe_pairs = [] + if catalog_v2 and not scenario.episode.is_healthy and scenario.episode.parameters.get("affected_candidates"): + from netopsbench.platform.utils.interface_names import to_sonic_interface + + from .candidates import CandidatePaths + + episode = scenario.episode + manifest = self.executor.current_manifest() + scope = (id(manifest), manifest.topology_id, manifest.require_pingmesh_plan().settings.plan_id) + if self.executor._candidate_scope != scope: + self.executor._candidate_paths = CandidatePaths(manifest) + self.executor._candidate_scope = scope + candidates = self.executor._candidate_paths + peer = next( + ( + peer + for (root, peer), interface in candidates.ports.items() + if root == episode.target_device and interface == to_sonic_interface(episode.target_interface) + ), + None, + ) + self.executor._case_affected_pairs = candidates.affected_pairs( + episode.fault_type, + episode.target_device, + peer, + episode.parameters["affected_candidates"][0], + reverse=( + episode.fault_type == "route_flapping" or episode.parameters.get("mechanism") == "export_filter" + ), + ) + self.executor._case_probe_pairs = self.executor._case_affected_pairs + episode.parameters.get( + "control_candidates", [] + ) + from netopsbench.platform.observability.routes import collect_routes + + with self.executor.timings.measure( + "baseline_routes", + timeout_seconds=self.executor.scale_registry.get(scenario.scale).health_timeout_seconds, + ): + self.executor._case_routes = collect_routes( + self.executor.current_manifest(), + cancel_event=self.executor._cancel_event, + deadline=time.monotonic() + self.executor.scale_registry.get(scenario.scale).health_timeout_seconds, + ) + if any( + row.get("error") or row.get("bgp_collection_ok") is False + for row in self.executor._case_routes["nodes"].values() + ): + raise RuntimeError("Healthy route snapshot is unavailable") + self.executor._calibration_current = False + self.episode_result = {} self.episode_result = observe_episode( self.executor, scenario.episode, baseline_window=self.baseline_window, + result=self.episode_result, ) - integrity_errors = observation_integrity_errors(self.episode_result.get("observations") or {}) + if catalog_v2: + from netopsbench.platform.observability.routes import collect_routes + + from .effects import scoped_integrity_errors, validate_effect + + with self.executor.timings.measure( + "effect_validation", + timeout_seconds=self.executor.scale_registry.get(scenario.scale).health_timeout_seconds, + ): + current = collect_routes( + self.executor.current_manifest(), + cancel_event=self.executor._cancel_event, + deadline=time.monotonic() + self.executor.scale_registry.get(scenario.scale).health_timeout_seconds, + ) + self.episode_result["route_evidence"] = {"baseline": self.executor._case_routes, "fault": current} + effect = validate_effect( + self.executor, scenario.episode, self.episode_result, self.executor._case_routes, current + ) + self.episode_result["effect_audit"] = effect + integrity_errors = scoped_integrity_errors( + self.episode_result.get("observations") or {}, + self.episode_result.get("coverage_audit") or {}, + effect, + ) + integrity_errors.extend(effect["errors"]) + else: + integrity_errors = observation_integrity_errors(self.episode_result.get("observations") or {}) if integrity_errors: raise RuntimeError("Incident observation is incomplete: " + "; ".join(integrity_errors)) self.toolkit = AgentToolkit( @@ -119,8 +243,11 @@ def call_tool(self, action: ToolAction) -> dict[str, Any]: method = getattr(self.toolkit, action.name, None) if not callable(method): raise ValueError(f"Toolkit action is not implemented: {action.name}") - result = method(**action.arguments) - return result.to_dict() if hasattr(result, "to_dict") else {"success": True, "data": result} + with self.executor.timings.measure_step("tool_queries", action.name) as timing: + result = method(**action.arguments) + if not result.success: + timing["failed_calls"] += 1 + return public_tool_result(result) def refresh(self, *, min_seconds: float = 0.0) -> None: del min_seconds @@ -129,18 +256,105 @@ def finish(self, *, broken: bool = False) -> None: if self._finished: return self._finished = True - if self.scenario is not None: - self.cleanup_result = self.executor._cleanup_after_scenario( - self.scenario, - self.episode_result, - baseline_window=self.baseline_window, + if self.scenario is None: + return + self.executor._recovering = True + try: + with self.executor.timings.measure( + "recovery", timeout_seconds=self.executor.experiment.recovery_timeout_seconds + ): + self.cleanup_result = self.executor._cleanup_after_scenario( + self.scenario, + self.episode_result, + baseline_window=self.baseline_window, + ) + if self.episode_result is not None and "recovery" in self.cleanup_result: + self.episode_result["recovery"] = self.cleanup_result["recovery"] + if "validated_baseline" in self.cleanup_result: + self.baseline_window = dict(self.cleanup_result["validated_baseline"]) + with self.executor.timings.measure_step("recovery", "handoff"): + self._publish_baseline() + current_operation_control().remaining() + if not self.cleanup_result.get("success", False): + raise RuntimeError(f"Scenario cleanup failed: {self.cleanup_result}") + except BaseException as exc: + if self.cleanup_result is None: + self.cleanup_result = {"success": False, "status": "recovery_failed", "errors": [str(exc)]} + handoff = self.executor._baseline_handoff + handoff.clear("recovery_failed") + if self.cleanup_result.get("success", True): + self.cleanup_result.update( + success=False, + status="recovery_timeout" if isinstance(exc, TimeoutError) else "recovery_failed", + ) + self.cleanup_result.update(baseline_handoff=False, baseline_handoff_reason="recovery_failed") + raise + finally: + self.executor._recovering = False + + def _publish_baseline(self) -> None: + from .baseline import RuntimeScope, scope_changes + + handoff = self.executor._baseline_handoff + if self.cleanup_result is None or self.scenario is None: + raise RuntimeError("Cannot publish a baseline before cleanup") + if self.executor._last_calibration and not self.executor._last_calibration["success"]: + handoff.clear("calibration_failed") + self.cleanup_result.update( + success=False, baseline_handoff=False, baseline_handoff_reason="calibration_failed" + ) + return + if self.cleanup_result.get("validation_level") == "state_checked": + scope = self.executor._baseline_scope(self.scenario) + restored = self.cleanup_result.pop("restored_scope", self._scope) + success = bool(self.cleanup_result.get("success")) and scope is not None and scope == restored + if success: + handoff.scope = scope + handoff.ready = True + handoff.last_reason = "state_verified_baseline_retained" + else: + handoff.clear("recovery_identity_changed") + self.cleanup_result["success"] = False + self.cleanup_result.update( + baseline_handoff=success, baseline_handoff_reason=handoff.last_reason, baseline_uses=handoff.uses ) - if self.episode_result is not None and "recovery" in self.cleanup_result: - self.episode_result["recovery"] = self.cleanup_result["recovery"] - if "validated_baseline" in self.cleanup_result: - self.baseline_window = dict(self.cleanup_result["validated_baseline"]) - if not self.cleanup_result.get("success", False): - raise RuntimeError(f"Scenario cleanup failed: {self.cleanup_result}") + return + self.cleanup_result.pop("restored_scope", None) + recovered = self.cleanup_result.get("validated_baseline") + candidate = recovered + scope = self.executor._baseline_scope(self.scenario) + bound = self.cleanup_result.get("validated_baseline_scope", self._scope) + if not self.cleanup_result.get("success"): + reason = "recovery_failed" + elif candidate is None: + reason = "no_verified_healthy_window" + elif self._scope is None or scope is None: + reason = "scope_unavailable" + elif scope != bound: + reason = "scope_changed" + else: + reason = None + if reason: + handoff.clear(reason) + published = False + else: + # A failed incident may still have an independently verified recovery + # window. Publishing it never changes the preceding case's result. + published = handoff.publish( + candidate, + scope, + self.scenario.id, + baseline_window_seconds(self.executor, self.executor.minimum_baseline_seconds), + verified=True, + ) + self.cleanup_result.update( + baseline_handoff=published, + baseline_handoff_reason=handoff.last_reason, + baseline_scope_changes=scope_changes(self._scope, scope), + ) + verified_scope = self.cleanup_result.get("validated_baseline_scope") + if isinstance(verified_scope, RuntimeScope): + self.cleanup_result["validated_baseline_scope"] = {"digest": verified_scope.digest} __all__ = ["ExecutorIncidentBackend"] diff --git a/netopsbench/platform/scenario/migration.py b/netopsbench/platform/scenario/migration.py new file mode 100644 index 0000000..a3ac0c8 --- /dev/null +++ b/netopsbench/platform/scenario/migration.py @@ -0,0 +1,69 @@ +"""Explicit, non-destructive migration of frozen scenarios to recovery v3.""" + +from __future__ import annotations + +import hashlib +import json +import shutil +import tempfile +from pathlib import Path + +from netopsbench.models.recovery import RecoveryPolicy +from netopsbench.platform.scenario.parser import parse_scenario_file, save_scenario_file + + +def migrate_recovery(source: Path, output: Path) -> Path: + source, output = source.resolve(), output.resolve() + if output.exists() or source == output or (source.is_dir() and source in output.parents): + raise ValueError("Migration requires a new output directory outside the source") + paths = [source] if source.is_file() else sorted({*source.rglob("*.yaml"), *source.rglob("*.yml")}) + if not paths: + raise ValueError("No scenario YAML files found") + scenarios = [(path, parse_scenario_file(path)) for path in paths] + provenance = [ + { + "path": str(p.relative_to(source) if source.is_dir() else p.name), + "sha256": hashlib.sha256(p.read_bytes()).hexdigest(), + "scenario_digest": s.digest, + } + for p, s in scenarios + ] + policy = RecoveryPolicy().model_dump(mode="json") + campaign_id = hashlib.sha256( + json.dumps({"sources": provenance, "recovery_policy": policy}, sort_keys=True).encode() + ).hexdigest() + output.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=".recovery-migration-", dir=output.parent)) + try: + for (_, scenario), origin in zip(scenarios, provenance, strict=True): + metadata = { + **scenario.metadata, + "recovery_policy": policy, + "recovery_migration": {"campaign_id": campaign_id, "source": origin}, + } + migrated = scenario.model_copy(update={"metadata": metadata}) + save_scenario_file(migrated, staging / origin["path"]) + (staging / "migration.json").write_text( + json.dumps( + { + "campaign_id": campaign_id, + "recovery_policy": policy, + "sources": provenance, + }, + indent=2, + ) + + "\n" + ) + if source.is_dir() and (source / "coverage.json").is_file(): + shutil.copyfile(source / "coverage.json", staging / "coverage.json") + # Exclusive reservation prevents replacing a concurrently-created destination. + output.mkdir() + try: + for path in staging.iterdir(): + path.rename(output / path.name) + except BaseException: + shutil.rmtree(output) + raise + finally: + shutil.rmtree(staging) + return output diff --git a/netopsbench/platform/scenario/observation.py b/netopsbench/platform/scenario/observation.py index 65d7fbf..37dcffd 100644 --- a/netopsbench/platform/scenario/observation.py +++ b/netopsbench/platform/scenario/observation.py @@ -3,11 +3,11 @@ from __future__ import annotations import time -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from netopsbench.config import config from netopsbench.logging_utils import get_logger -from netopsbench.platform.topology.topology_utils import coerce_topology_manifest +from netopsbench.platform.utils.control import OperationControl, current_operation_control logger = get_logger(__name__) @@ -21,8 +21,8 @@ def _utc_iso(dt: datetime) -> str: def complete_window_seconds(runner) -> int: """Return the topology-derived complete Pingmesh observation window.""" - manifest = coerce_topology_manifest(runner.topology_metadata) - return manifest.pingmesh.complete_window_seconds(manifest.facts.total_clients) + manifest = runner.current_manifest() + return manifest.require_pingmesh_plan().settings.complete_window_seconds def baseline_window_seconds(runner, minimum_seconds: int) -> int: @@ -30,22 +30,36 @@ def baseline_window_seconds(runner, minimum_seconds: int) -> int: return max(max(0, int(minimum_seconds)), complete_window_seconds(runner)) -def capture_observation_window(runner, duration: int, *, name: str = "window") -> dict: +def capture_observation_window(runner, duration: int, *, name: str = "window", deadline: float | None = None) -> dict: """Record one observation interval without querying observability backends.""" safe_duration = max(0, int(duration)) + inherited = current_operation_control() + limits = [value for value in (deadline, inherited.deadline if inherited else None) if value is not None] + control = OperationControl(inherited.cancel_event if inherited else None, min(limits) if limits else None) + if control.deadline is not None and control.remaining() < safe_duration: + raise TimeoutError("Insufficient recovery budget for a complete observation window") logger.info(f"\n[Observation] Monitoring for {safe_duration} seconds...") - start_time = datetime.now(UTC).replace(microsecond=0) + started = time.monotonic() + stop = started + safe_duration + start_time = datetime.now(UTC) sleep_fn = getattr(runner, "sleep", time.sleep) - for index in range(safe_duration): - sleep_fn(1) - if (index + 1) % 10 == 0: - logger.info(f" Observed {index + 1}/{safe_duration}s...") - end_time = datetime.now(UTC).replace(microsecond=0) + next_progress = 10 + while (remaining := stop - time.monotonic()) > 0: + sleep_fn(control.remaining(min(1.0, remaining))) + control.remaining() + elapsed = time.monotonic() - started + if elapsed >= next_progress: + logger.info(f" Observed {min(int(elapsed), safe_duration)}/{safe_duration}s...") + next_progress = (int(elapsed) // 10 + 1) * 10 + actual = max(0.0, time.monotonic() - started) return { "name": name, + "plan_id": runner.topology_metadata["pingmesh_plan"]["settings"]["plan_id"], "start_time": _utc_iso(start_time), - "end_time": _utc_iso(end_time), + "end_time": _utc_iso(start_time + timedelta(seconds=safe_duration)), "duration_seconds": safe_duration, + "actual_wait_seconds": actual, + "wake_overrun_seconds": max(0.0, actual - safe_duration), } @@ -60,30 +74,19 @@ def capture_baseline_window(runner, minimum_seconds: int) -> dict: def baseline_gate_errors(observation: dict) -> list[str]: """Return absolute health failures for a candidate healthy Pingmesh window.""" - errors: list[str] = [] - if observation.get("data_source_status") != "ok": - errors.append(f"data={observation.get('data_source_status')}") - if observation.get("coverage_status") != "complete": - errors.append(f"coverage={observation.get('coverage_status')}") - baseline_coverage = observation.get("_baseline_coverage") or {} - if baseline_coverage.get("coverage_status") != "complete": - errors.append(f"baseline_coverage={baseline_coverage.get('coverage_status') or 'missing'}") - + errors = observation_integrity_errors(observation) report = observation.get("pingmesh_metrics") or {} summary = report.get("summary") or {} quality = report.get("quality") or {} absolute_health = observation.get("_baseline_health") or quality current_paths = int(quality.get("current_paths_observed", 0) or 0) if current_paths <= 0: - errors.append("current_paths_observed=0") return errors exact_zero = { "absolute_unreachable_paths": int(absolute_health.get("absolute_unreachable_paths", 0) or 0), "latency_spikes": int(summary.get("latency_spikes", 0) or 0), "absolute_network_mtu_paths": int(absolute_health.get("absolute_network_mtu_paths", 0) or 0), - "local_df_mtu_drops": int(quality.get("local_df_mtu_drops", 0) or 0), - "local_probe_errors": int(quality.get("local_probe_errors", 0) or 0), } errors.extend(f"{name}={value}" for name, value in exact_zero.items() if value) @@ -129,13 +132,36 @@ def _summary_for_window(anomalies: list[dict], window_name: str) -> dict: } +def observation_detector(runner): + from netopsbench.platform.pingmesh.detector import AnomalyDetector + + manifest = runner.current_manifest() + settings = { + "influxdb_url": runner.influxdb_url or config.influxdb_url, + "token": runner.influxdb_token or config.influxdb_token, + "org": runner.influxdb_org or config.influxdb_org, + "bucket": runner.influxdb_bucket or config.influxdb_bucket, + "topology_id": runner.topology_id, + "runtime_start_time": getattr(runner, "_pingmesh_runtime_start", None), + } + scope = (manifest.topology_id, manifest.require_pingmesh_plan().settings.plan_id, *settings.values()) + if runner._detector_scope != scope: + runner._detector = AnomalyDetector(topology_metadata=manifest, **settings) + runner._detector_scope = scope + return runner._detector + + def analyze_observation_windows( runner, windows: list[dict], total_duration_seconds: int, baseline_window: dict, + deadline: float | None = None, ) -> dict: """Analyze captured intervals using one baseline and one current snapshot.""" + control = current_operation_control() + if control is not None and control.deadline is not None: + deadline = min(deadline, control.deadline) if deadline is not None else control.deadline valid_windows = [window for window in windows if isinstance(window, dict) and window.get("start_time")] if not valid_windows: now = _utc_iso(datetime.now(UTC).replace(microsecond=0)) @@ -150,8 +176,6 @@ def analyze_observation_windows( "observation_windows": [], } - from netopsbench.platform.pingmesh.detector import AnomalyDetector - baseline_start = str(baseline_window.get("start_time") or "") baseline_end = str(baseline_window.get("end_time") or "") if not baseline_start or not baseline_end: @@ -159,14 +183,7 @@ def analyze_observation_windows( current_start = str(valid_windows[0]["start_time"]) current_end = str(valid_windows[-1]["end_time"]) - detector = AnomalyDetector( - influxdb_url=runner.influxdb_url or config.influxdb_url, - token=runner.influxdb_token or config.influxdb_token, - org=runner.influxdb_org or config.influxdb_org, - bucket=runner.influxdb_bucket or config.influxdb_bucket, - topology_metadata=runner.topology_metadata, - topology_id=runner.topology_id, - ) + detector = observation_detector(runner) report = detector.generate_windowed_anomaly_report( baseline_start=baseline_start, baseline_end=baseline_end, @@ -174,13 +191,18 @@ def analyze_observation_windows( current_end=current_end, windows=valid_windows, include_internal_health=True, + **({"deadline": deadline} if deadline is not None else {}), + **({"evidence_pairs": runner._case_probe_pairs} if getattr(runner, "_case_probe_pairs", None) else {}), ) baseline_health = report.pop("_baseline_health", {}) baseline_coverage = report.pop("_baseline_coverage", {}) + probe_evidence = report.pop("_probe_evidence", []) query_status = report.get("query_status", {}) query_ok = bool(query_status.get("ok")) anomalies = report.get("anomalies", []) or [] - coverage = report.get("coverage", {}) or {} + coverage = dict(report.get("coverage", {}) or {}) + for key in ("missing_tasks", "invalid_tasks", "invalid_rows", "observable_pairs", "unexpected_records"): + report.get("coverage", {}).pop(key, None) observation_windows = [ { **window, @@ -198,27 +220,12 @@ def analyze_observation_windows( "data_source_status": "ok" if query_ok else f"error: {query_status.get('error') or 'query_failed'}", "observation_windows": observation_windows, "_coverage_audit": coverage, + "_probe_evidence": probe_evidence, "_baseline_health": baseline_health, "_baseline_coverage": baseline_coverage, } -def wait_and_observe( - runner, - duration: int, - *, - baseline_window: dict, -) -> dict: - """Capture and analyze one observation window.""" - window = capture_observation_window(runner, duration, name="steady") - return analyze_observation_windows( - runner, - [window], - total_duration_seconds=duration, - baseline_window=baseline_window, - ) - - __all__ = [ "analyze_observation_windows", "baseline_gate_errors", @@ -227,5 +234,4 @@ def wait_and_observe( "capture_observation_window", "complete_window_seconds", "observation_integrity_errors", - "wait_and_observe", ] diff --git a/netopsbench/platform/scenario/specs/fault_campaign.yaml b/netopsbench/platform/scenario/specs/fault_campaign.yaml index 6be11b4..0a6ec63 100644 --- a/netopsbench/platform/scenario/specs/fault_campaign.yaml +++ b/netopsbench/platform/scenario/specs/fault_campaign.yaml @@ -1,476 +1,3 @@ -version: v1 - +fault_catalog_version: 2 defaults: traffic_profile: standard - count_per_fault: 4 - fault_duration_seconds: 30 - fault_stabilization_seconds: 5 - -fault_templates: - # Access link failures remain the easy anchor. Larger topologies also cover - # both ends of redundant fabric links. - - name: link_down_access - fault_type: link_down - difficulty: easy - device_role: leaf - interface_role: downlink - fault_stabilization_seconds: 5 - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 2 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: link_down_leaf_fabric - fault_type: link_down - difficulty: medium - device_role: leaf - interface_role: uplink - count: 0 - count_per_scale: - xlarge: 2 - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: link_down_spine_fabric - fault_type: link_down - difficulty: hard - device_role: spine - count: 0 - count_per_scale: - xlarge: 2 - fat-tree-k8: 0 - fat-tree-k12: 0 - - - name: link_down_agg_edge - fault_type: link_down - difficulty: medium - device_role: agg - interface_role: downlink - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: link_down_agg_core - fault_type: link_down - difficulty: hard - device_role: agg - interface_role: uplink - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: link_down_core_agg - fault_type: link_down - difficulty: hard - device_role: core - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: blackhole_route_leaf - fault_type: blackhole_route - difficulty: medium - device_role: leaf - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: blackhole_route_spine - fault_type: blackhole_route - difficulty: hard - device_role: spine - count: 0 - count_per_scale: - xlarge: 3 - - - name: blackhole_route_agg - fault_type: blackhole_route - difficulty: hard - device_role: agg - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: blackhole_route_core - fault_type: blackhole_route - difficulty: hard - device_role: core - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: mtu_mismatch_spine - fault_type: mtu_mismatch - difficulty: hard - device_role: spine - mtu: 1400 - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: mtu_mismatch_leaf - fault_type: mtu_mismatch - difficulty: hard - device_role: leaf - interface_role: uplink - mtu: 1400 - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: mtu_mismatch_agg - fault_type: mtu_mismatch - difficulty: hard - device_role: agg - interface_role: uplink - mtu: 1400 - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: high_latency_leaf - fault_type: high_latency - difficulty: medium - device_role: leaf - interface_role: uplink - latency_ms: 120 - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: high_latency_spine - fault_type: high_latency - difficulty: hard - device_role: spine - latency_ms: 120 - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: high_latency_agg_edge - fault_type: high_latency - difficulty: hard - device_role: agg - interface_role: downlink - latency_ms: 120 - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: high_latency_agg_core - fault_type: high_latency - difficulty: hard - device_role: agg - interface_role: uplink - latency_ms: 120 - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: static_route_misconfig - fault_type: static_route_misconfig - difficulty: hard - device_role: leaf - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 4 - fat-tree-k8: 4 - fat-tree-k12: 4 - - - name: packet_loss_leaf - fault_type: packet_loss - difficulty: medium - device_role: leaf - interface_role: uplink - loss_pct: 30 - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: packet_loss_spine - fault_type: packet_loss - difficulty: hard - device_role: spine - loss_pct: 30 - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: packet_loss_agg_edge - fault_type: packet_loss - difficulty: hard - device_role: agg - interface_role: downlink - loss_pct: 30 - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: packet_loss_agg_core - fault_type: packet_loss - difficulty: hard - device_role: agg - interface_role: uplink - loss_pct: 30 - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: packet_corruption_leaf - fault_type: packet_corruption - difficulty: hard - device_role: leaf - interface_role: uplink - corruption_pct: 25 - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: packet_corruption_spine - fault_type: packet_corruption - difficulty: hard - device_role: spine - corruption_pct: 25 - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: packet_corruption_agg_edge - fault_type: packet_corruption - difficulty: hard - device_role: agg - interface_role: downlink - corruption_pct: 25 - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: packet_corruption_agg_core - fault_type: packet_corruption - difficulty: hard - device_role: agg - interface_role: uplink - corruption_pct: 25 - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: link_flapping_leaf - fault_type: link_flapping - difficulty: hard - device_role: leaf - interface_role: uplink - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: link_flapping_spine - fault_type: link_flapping - difficulty: hard - device_role: spine - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: link_flapping_agg_edge - fault_type: link_flapping - difficulty: hard - device_role: agg - interface_role: downlink - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: link_flapping_agg_core - fault_type: link_flapping - difficulty: hard - device_role: agg - interface_role: uplink - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: bgp_neighbor_misconfig_leaf - fault_type: bgp_neighbor_misconfig - difficulty: hard - device_role: leaf - interface_role: uplink - parameters: - misconfig_kind: peer_as_mismatch - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: bgp_neighbor_misconfig_spine - fault_type: bgp_neighbor_misconfig - difficulty: hard - device_role: spine - parameters: - misconfig_kind: peer_as_mismatch - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: bgp_neighbor_misconfig_agg_edge - fault_type: bgp_neighbor_misconfig - difficulty: hard - device_role: agg - interface_role: downlink - parameters: - misconfig_kind: peer_as_mismatch - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: bgp_neighbor_misconfig_agg_core - fault_type: bgp_neighbor_misconfig - difficulty: hard - device_role: agg - interface_role: uplink - parameters: - misconfig_kind: peer_as_mismatch - count: 0 - count_per_scale: - fat-tree-k8: 1 - fat-tree-k12: 1 - - - name: route_policy_misconfig_leaf - fault_type: route_policy_misconfig - difficulty: hard - device_role: leaf - parameters: - misconfig_kind: network_statement_missing - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 4 - fat-tree-k8: 4 - fat-tree-k12: 4 - - - name: device_down_leaf - fault_type: device_down - difficulty: easy - device_role: leaf - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: device_down_spine - fault_type: device_down - difficulty: hard - device_role: spine - count: 0 - count_per_scale: - xlarge: 3 - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: device_down_agg - fault_type: device_down - difficulty: hard - device_role: agg - count: 0 - count_per_scale: - fat-tree-k8: 2 - fat-tree-k12: 2 - - - name: acl_misconfig_leaf - fault_type: acl_misconfig - difficulty: hard - device_role: leaf - count_per_scale: - xs: 1 - small: 1 - medium: 2 - large: 4 - xlarge: 4 - fat-tree-k8: 4 - fat-tree-k12: 4 - - - name: healthy_network - fault_type: none - difficulty: easy - count_per_scale: - xs: 2 - small: 3 - medium: 4 - large: 4 - xlarge: 4 - fat-tree-k8: 4 - fat-tree-k12: 4 diff --git a/netopsbench/platform/scenario/timing.py b/netopsbench/platform/scenario/timing.py new file mode 100644 index 0000000..17d9829 --- /dev/null +++ b/netopsbench/platform/scenario/timing.py @@ -0,0 +1,81 @@ +"""Monotonic phase measurements, separate from public observations.""" + +from contextlib import contextmanager, nullcontext +from contextvars import ContextVar +from time import monotonic + +from netopsbench.platform.toolkit._core.control import finish_diagnosis_work +from netopsbench.platform.utils.control import OperationControl, operation_scope +from netopsbench.platform.utils.measurements import measurement_scope + +_current_timings = ContextVar("case_phase_timings", default=None) + + +@contextmanager +def timing_scope(timings): + token = _current_timings.set(timings) + try: + yield + finally: + _current_timings.reset(token) + + +@contextmanager +def agent_cleanup_timing(): + finish_diagnosis_work() + timings = _current_timings.get() + if timings is None: + yield + else: + with timings.measure("agent_cleanup"): + yield + + +class PhaseTimings: + def __init__(self): + self.phases = {} + + @contextmanager + def measure(self, name, *, planned_seconds=None, timeout_seconds=None): + started = monotonic() + record = {"status": "running", "planned_seconds": planned_seconds, "timeout_seconds": timeout_seconds} + self.phases[name] = record + try: + with ( + operation_scope(OperationControl(deadline=started + timeout_seconds)) + if timeout_seconds is not None and name != "diagnosis" + else nullcontext() + ): + with measurement_scope(record.setdefault("operations", {})): + yield record + except BaseException: + record["status"] = "failed" + raise + else: + if record["status"] == "running": + record["status"] = "completed" + finally: + record["actual_seconds"] = max(0, monotonic() - started) + + def skip(self, name, reason): + self.phases[name] = {"status": "skipped", "actual_seconds": 0.0, "reason": reason} + + @contextmanager + def measure_step(self, parent, name): + """Accumulate repeated work inside a phase, without creating a new budget.""" + steps = self.phases.setdefault(parent, {}).setdefault("steps", {}) + record = steps.setdefault(name, {"actual_seconds": 0.0, "calls": 0, "failed_calls": 0}) + started = monotonic() + record["calls"] += 1 + record["status"] = "running" + try: + with measurement_scope(record.setdefault("operations", {})): + yield record + except BaseException: + record["failed_calls"] += 1 + record["status"] = "failed" + raise + else: + record["status"] = "completed" + finally: + record["actual_seconds"] += max(0.0, monotonic() - started) diff --git a/netopsbench/platform/scenario/validator.py b/netopsbench/platform/scenario/validator.py index e0ed00e..9977175 100644 --- a/netopsbench/platform/scenario/validator.py +++ b/netopsbench/platform/scenario/validator.py @@ -37,6 +37,12 @@ def validate_scenario( registry = fault_registry or create_fault_registry() scales = scale_registry or default_scale_registry() errors: list[str] = [] + from netopsbench.models.recovery import RecoveryPolicy + + try: + RecoveryPolicy.from_metadata(scenario.metadata) + except ValueError as exc: + errors.append(f"Invalid recovery_policy: {exc}") if not scenario.scenario_id: errors.append("Missing scenario_id") @@ -144,7 +150,7 @@ def validate_scenario_topology(scenario, topology_dir: str) -> dict: f"actual='{actual_scale}'. Use matching scenario files or redeploy the topology." ) - required_duration = manifest.pingmesh.complete_window_seconds(manifest.facts.total_clients) + required_duration = manifest.require_pingmesh_plan().settings.complete_window_seconds if scenario.episode.duration_seconds < required_duration: errors.append( f"[scenario={scenario.scenario_id} episode={scenario.episode.episode_id}] " diff --git a/netopsbench/platform/session/acceptance.py b/netopsbench/platform/session/acceptance.py new file mode 100644 index 0000000..a58e62e --- /dev/null +++ b/netopsbench/platform/session/acceptance.py @@ -0,0 +1,735 @@ +"""Internal acceptance orchestration over the canonical suite execution path.""" + +from __future__ import annotations + +import csv +import hashlib +import io +import json +import shutil +import signal +import subprocess +import threading +import time +from datetime import UTC, datetime +from pathlib import Path + +import requests + +from netopsbench.config import config +from netopsbench.evaluator.scorer import Evaluator +from netopsbench.models.profiles import get_scale_profile +from netopsbench.models.topology import TopologyManifest +from netopsbench.platform.faults.catalog import FAULT_CATALOG_VERSION +from netopsbench.platform.observability.bgp_collector import ( + DEFAULT_BGP_FULL_SNAPSHOT_INTERVAL_SECONDS, + DEFAULT_BGP_POLL_INTERVAL_SECONDS, +) +from netopsbench.platform.observability.influxdb import query_flux +from netopsbench.platform.runtime.health import check_worker_health, expected_network_counts +from netopsbench.platform.runtime.resources import ( + ResourceMonitor, + capacity_check, + peak_sample, + require_capacity, + storage_snapshot, +) +from netopsbench.platform.runtime.toolchain import runtime_backend_identity +from netopsbench.platform.scenario.generator import generate, load_topology, load_yaml +from netopsbench.platform.scenario.parser import parse_scenario_file +from netopsbench.platform.session.dispatch import ExecutionControl, is_recovered_case_failure +from netopsbench.platform.topology.config import config_for_scale +from netopsbench.platform.topology.generator import generate_topology +from netopsbench.platform.topology.topology_utils import load_topology_manifest +from netopsbench.platform.utils.control import OperationControl +from netopsbench.platform.utils.files import atomic_write_json + +_CHECKPOINT_LOCK = threading.RLock() + + +def ingestion_latency(worker, plan_id: str) -> dict: + """Measure write-to-query visibility in this runtime's own bucket.""" + stamp = time.time_ns() + started = time.monotonic() + response = requests.post( + f"{config.influxdb_url.rstrip('/')}/api/v2/write", + params={"org": config.influxdb_org, "bucket": worker.bucket, "precision": "ns"}, + headers={"Authorization": f"Token {config.influxdb_token}"}, + data=f"acceptance_ingestion_probe,plan_id={plan_id} value=1i {stamp}", + proxies={"http": "", "https": ""}, + timeout=30, + ) + response.raise_for_status() + write_seconds = time.monotonic() - started + query = ( + f'from(bucket: "{worker.bucket}") |> range(start: time(v: {stamp})) ' + f'|> filter(fn: (r) => r._measurement == "acceptance_ingestion_probe" and r.plan_id == "{plan_id}") ' + "|> limit(n: 1)" + ) + while time.monotonic() - started < 30: + result = query_flux(config.influxdb_url, config.influxdb_token, config.influxdb_org, query) + if result.status == "ok" and "acceptance_ingestion_probe" in result.text: + return {"write_seconds": write_seconds, "query_visible_seconds": time.monotonic() - started} + time.sleep(0.2) + raise RuntimeError("Runtime ingestion probe was not queryable within thirty seconds") + + +def bgp_observation(worker, manifest, output: Path, *, control: OperationControl | None = None) -> dict: + freshness_seconds = int(2 * DEFAULT_BGP_FULL_SNAPSHOT_INTERVAL_SECONDS + DEFAULT_BGP_POLL_INTERVAL_SECONDS) + query = ( + f'from(bucket: "{worker.bucket}") |> range(start: -{freshness_seconds}s) ' + f'|> filter(fn: (r) => r._measurement == "bgp_neighbors" and r.topology_id == "{worker.topology_id}" ' + 'and r._field == "session_state") |> last() ' + '|> group(columns: ["source", "neighbor_address"]) |> sort(columns: ["_time"]) |> last() |> group() ' + '|> keep(columns: ["source", "neighbor_address", "_value", "_time"])' + ) + while True: + result = query_flux( + config.influxdb_url, + config.influxdb_token, + config.influxdb_org, + query, + timeout=control.remaining(60) if control else 60, + deadline=control.deadline if control else None, + ) + if result.status != "ok": + raise RuntimeError(f"BGP observation query failed: {result.error}") + output.write_text(result.text) + rows = csv.DictReader( + io.StringIO("\n".join(line for line in result.text.splitlines() if not line.startswith("#"))) + ) + neighbors = { + (row.get("source"), row.get("neighbor_address")): row.get("_value", "") + for row in rows + if row.get("_time") not in {None, "", "_time"} + } + expected = sum(row["bgp_neighbors"] for row in expected_network_counts(manifest).values()) + established = sum(state.lower() == "established" for state in neighbors.values()) + if len(neighbors) == expected and established == expected: + break + message = ( + f"Incomplete BGP observations: {len(neighbors)} neighbors, {established} established, expected {expected}" + ) + if control is None: + raise RuntimeError(message) + control.sleep(DEFAULT_BGP_POLL_INTERVAL_SECONDS) + return { + "neighbors": len(neighbors), + "established": established, + "expected": expected, + "freshness_seconds": freshness_seconds, + } + + +def finished_case_ids(entry: dict) -> set[str]: + """Skip scored diagnoses and fully recovered case failures already attempted.""" + return { + summary["scenario_id"] + for report in entry.get("cases", []) + if not report.get("acceptance_error") + for summary in report.get("scenario_summaries", []) + if (report.get("mode") != "effects" and is_recovered_case_failure(summary)) + or ( + summary.get("case_valid") is True + and ( + ( + report.get("mode") == "effects" + and not summary.get("cleanup_failed") + and summary.get("status") == "completed" + ) + or (report.get("mode") != "effects" and report.get("diagnosis_complete") is True) + ) + ) + } + + +def checkpoint(output, result): + with _CHECKPOINT_LOCK: + atomic_write_json(output / "acceptance.json", result, default=str) + + +def freeze_cases(records, paths): + cases = [parse_scenario_file(path) for path in paths] + hashes = {case.id: hashlib.sha256(path.read_bytes()).hexdigest() for case, path in zip(cases, paths, strict=True)} + if len(hashes) != len(cases): + raise ValueError("Acceptance scenario IDs must be unique") + selected = records.get("selected_cases") + if selected is not None and set(selected) != set(hashes): + raise ValueError("Acceptance scenario set changed; use a separate campaign") + previous = records.get("scenario_sha256") + if previous is not None and previous != hashes: + raise ValueError("Acceptance scenario contents changed; use a separate campaign") + records.setdefault("selected_cases", list(hashes)) + records.setdefault("scenario_sha256", hashes) + return cases + + +def expected_identities(result, backends): + identities = {} + for entry in result["scales"].values(): + for backend, record in entry.get("agents", {}).items(): + if backend in backends: + if backend in identities and identities[backend] != record["identity"]: + raise ValueError("Campaign contains inconsistent agent configurations") + identities[backend] = record["identity"] + return identities + + +def qualified_codex_smoke(args, identities, backend_identity): + """Reuse only the exact qualification receipt frozen by the campaign driver.""" + path = getattr(args, "codex_smoke_receipt", None) + if path is None: + return None + payload = Path(path).read_bytes() + digest = hashlib.sha256(payload).hexdigest() + if digest != getattr(args, "codex_smoke_receipt_sha256", None): + raise ValueError("Codex qualification receipt fingerprint changed") + receipt = json.loads(payload) + recorded_agent = receipt.get("agent_identity") or {} + actual_agent = identities.get("codex") or {} + # Docker's classic and containerd stores can expose different image IDs for + # an identical imported image. Keep both actual IDs and compare its content. + recorded_config = {key: value for key, value in recorded_agent.items() if key != "image_id"} + actual_config = {key: value for key, value in actual_agent.items() if key != "image_id"} + if ( + receipt.get("schema_version") != 1 + or receipt.get("status") != "passed" + or receipt.get("runtime_disposition") != "torn_down" + or receipt.get("final_health", {}).get("status") != "passed" + or receipt.get("runtime_backend") != backend_identity + or not identities.get("codex") + or not recorded_agent.get("image_content_sha256") + or recorded_config != actual_config + or not receipt.get("source_tree_sha256") + or receipt.get("source_tree_sha256") != getattr(args, "source_tree_sha256", None) + ): + raise ValueError("Codex qualification configuration or final health differs") + cases = receipt.get("cases", []) + if ( + len(cases) != 4 + or len({case.get("id") for case in cases}) != 4 + or {case.get("fault_type") for case in cases} != {"none", "link_down", "device_down", "bgp_auth_mismatch"} + or not all( + case.get("valid") is True + and case.get("diagnosis_complete") is True + and case.get("status") == "completed" + and not case.get("cleanup_failed") + for case in cases + ) + ): + raise ValueError("Codex qualification requires four completed, valid XS cases") + return {"sha256": digest, **receipt, "execution_image_id": actual_agent["image_id"]} + + +def validate_campaign_cases(entry, scale, backends, output, runtime, select_cases, smoke_cases): + """Reject changes before provider calls, warm, teardown or redeployment.""" + if entry.get("runtime_backend") != runtime_backend_identity(): + raise ValueError("Campaign runtime backend changed or is unrecorded; start a separate campaign") + if entry.get("profile_sha256") != get_scale_profile(scale).digest: + raise ValueError("Resumed campaign profile differs from the accepted cases") + records = entry.get("agents", {}) + if entry.get("cases") or not records: + raise ValueError("Legacy acceptance checkpoint; retain it as an archive and start a new campaign") + if set(records) != set(backends): + raise ValueError("Acceptance agent set changed; use a separate campaign") + for record in records.values(): + if "selected_cases" not in record or "scenario_sha256" not in record: + raise ValueError("Checkpoint lacks immutable case identity; start a separate campaign") + if entry.get("client_images"): + image = config_for_scale(scale).client_image + actual = subprocess.check_output( + ["docker", "image", "inspect", image, "--format", "{{.Id}}"], text=True, timeout=30 + ).strip() + if entry["client_images"] != [actual]: + raise ValueError("Resumed client image differs from the accepted cases") + if runtime is not None and (runtime.workers[0].topology_dir / "topology.json").exists(): + manifest = load_topology_manifest(runtime.workers[0].topology_dir) + elif entry.get("manifest"): + manifest = TopologyManifest.model_validate(entry["manifest"]) + else: + raise ValueError("Checkpoint lacks topology identity; start a separate campaign") + if entry.get("plan") and manifest.require_pingmesh_plan().settings.plan_id != entry["plan"]["plan_id"]: + raise ValueError("Resumed campaign Pingmesh plan changed") + paths = sorted((output / "scenarios" / scale).glob("*.yaml")) + selected = ( + smoke_cases(paths, manifest) + if scale == "xs" and entry.get("smoke_cases") + else select_cases(paths, True, manifest) + ) + for record in records.values(): + freeze_cases(record, selected) + + +def validate_resume(entry, runtime, scale, *, allow_unplanned=False): + identity = runtime_backend_identity() + if entry.get("runtime_backend") != identity or runtime.metadata.get("runtime_backend") != identity: + raise ValueError("Resumed runtime backend changed or is unrecorded; start a separate campaign") + if runtime.scale != scale or len(runtime.workers) != 1: + raise ValueError("Resume runtime must match the scale and contain exactly one worker") + digest = entry.get("profile_sha256") + if digest is not None and digest != runtime.scale_registry.get(scale).digest: + raise ValueError("Resumed runtime profile differs from the accepted cases") + if allow_unplanned and not entry.get("plan"): + return None + plan = load_topology_manifest(runtime.workers[0].topology_dir).require_pingmesh_plan() + if entry.get("plan", {}).get("plan_id") != plan.settings.plan_id: + raise ValueError("Resumed runtime Pingmesh plan differs from the accepted cases") + return plan + + +def release_runtime(runtime, *, owned, completed, emergency=False): + """Only an explicitly owned, completed (or resource-emergency) lab is released.""" + if owned and (completed or emergency): + runtime.teardown() + return "torn_down" + return "quarantined" if runtime.metadata.get("quarantined") else "retained" + + +def quarantine_partial_deployment(runtime, entry, output): + """Retain an owned incomplete deployment and its logs for explicit rebuild.""" + deploy = runtime.stage_results.get("deploy") + if not entry.get("runtime_owned") or deploy is None or deploy.status == "completed": + return False + entry["partial_deployment"] = runtime.describe() + logs = runtime.root_dir / "logs" + if logs.exists(): + shutil.copytree(logs, output / "failed-deployments" / runtime.name, dirs_exist_ok=True) + runtime.mark_quarantined("incomplete_deployment") + entry["runtime_disposition"] = "quarantined" + return True + + +def require_full_health(runtime, cancel=None): + errors = check_worker_health( + runtime.workers[0], all_routing_devices=True, scale_registry=runtime.scale_registry, cancel_event=cancel + ) + if errors: + runtime.mark_quarantined("acceptance_health_failure") + raise RuntimeError("Full health failed: " + "; ".join(errors)) + return { + "status": "passed", + "time": datetime.now(UTC).isoformat(), + "all_routing_devices": True, + "switches_checked": runtime.scale_registry.get(runtime.scale).total_switches, + } + + +def run_cases(bench, runtime, paths, *, backend, vendor, entry, identity, output, result, cancel, agent_factory=None): + records = entry.setdefault("agents", {}).setdefault(backend, {"cases": [], "identity": identity}) + if records["identity"] != identity: + raise ValueError(f"Cannot change {backend} configuration when resuming acceptance") + cases = freeze_cases(records, paths) + completed = finished_case_ids(records) + pending = [case for case in cases if case.id not in completed] + if not pending: + return False + effects_only = backend == "effects" + raw_agent = ( + None + if effects_only + else ( + agent_factory(backend)(vendor=vendor) + if backend == "deepagent" + else agent_factory(backend)(artifacts_dir=output / "codex-traces" / runtime.scale) + ) + ) + agent = None if effects_only else bench.agents.wrap(raw_agent) + + def on_case(summary, raw, evaluations): + aggregate = ( + {"mode": "effects", "effect_audit": (raw.get("episode") or {}).get("effect_audit")} + if effects_only + else Evaluator().generate_report(evaluations, agent_name=agent.name, topology_scale=runtime.scale) + ) + if not effects_only: + episode = raw.get("episode") or {} + execution = episode.get("execution") or {} + aggregate["diagnosis_complete"] = ( + (episode.get("diagnosis") or {}).get("success") is True + and execution.get("case_valid") is True + and execution.get("termination_reason") == "submitted" + ) + records["cases"].append({**aggregate, "scenario_summaries": [summary]}) + records["last_recovery"] = raw.get("cleanup") + print(f"[{runtime.scale}/{backend}] {summary['scenario_id']}: {summary['status']}", flush=True) + checkpoint(output, result) + + report = bench.sessions._executor._run_with_existing_runtime( + mode="effects" if effects_only else "suite", + scenarios=pending, + runtime=runtime, + agent=agent, + artifacts_dir=output / "runs" / runtime.scale / backend, + trace=True, + control=ExecutionControl(on_case=on_case, stop_on_failure=True, cancel_event=cancel, effects_only=effects_only), + ).wait() + records.setdefault("suite_reports", []).append(report.artifact_paths["report"]) + checkpoint(output, result) + if cancel.is_set() or any( + row.get("status") != "completed" and not is_recovered_case_failure(row) for row in report.scenario_summaries + ): + raise RuntimeError(f"{backend} acceptance interrupted; runtime retained after fault recovery") + return True + + +def run_acceptance(args, *, bench_factory, agent_factory, preflight, select_cases, smoke_cases) -> int: + mode = getattr(args, "mode", "diagnose") + backends_requested = ["effects"] if mode == "effects" else args.agents + scales = args.scales.split(",") + if args.resume_runtime and len(scales) != 1: + raise ValueError("--resume-runtime requires exactly one scale") + if args.rebuild_runtime and not args.resume_runtime: + raise ValueError("--rebuild-runtime requires --resume-runtime") + backend_identity = runtime_backend_identity() + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + result = ( + json.loads((output / "acceptance.json").read_text()) + if args.resume_runtime + else { + "started": datetime.now(UTC).isoformat(), + "vendor": args.vendor, + "scales": {}, + "mode": mode, + "fault_catalog_version": FAULT_CATALOG_VERSION, + } + ) + if args.resume_runtime: + if result.get("runtime_backend") != backend_identity: + raise ValueError("Campaign runtime backend changed or is unrecorded; start a separate campaign") + if result.get("mode") != mode or result.get("fault_catalog_version") != FAULT_CATALOG_VERSION: + raise ValueError("Campaign mode or fault catalog changed; start a separate campaign") + if result["vendor"] != args.vendor: + raise ValueError("Cannot change the diagnosis vendor when resuming acceptance") + recorded = result["scales"].get(scales[0]) + if recorded is None or Path(recorded["runtime"]).resolve() != args.resume_runtime.resolve(): + raise ValueError("Resume runtime must match the recorded acceptance runtime") + for item in (result, recorded): + if item.get("error"): + item.setdefault("prior_errors", []).append( + {"time": datetime.now(UTC).isoformat(), "error": item.pop("error")} + ) + result.setdefault("resumptions", []).append( + { + "time": datetime.now(UTC).isoformat(), + "runtime": str(args.resume_runtime.resolve()), + "previous_status": result.get("status"), + "previous_finished": result.get("finished"), + } + ) + result["runtime_backend"] = backend_identity + sample_path = args.capacity_sample or output / "capacity-sample.json" + sample = json.loads(sample_path.read_text()) if sample_path.exists() else None + docker_root = Path(subprocess.check_output(["docker", "info", "--format", "{{.DockerRootDir}}"], text=True).strip()) + # A rebuild's full capacity check runs after its owned old lab is released. + # All new allocations remain gated below, before runtime creation. + if sample is not None and not args.rebuild_runtime: + existing_metadata = args.resume_runtime / "runtime.json" if args.resume_runtime else None + retaining = ( + existing_metadata is not None + and existing_metadata.exists() + and json.loads(existing_metadata.read_text()).get("state") == "warm" + and not args.rebuild_runtime + ) + for scale in scales: + capacity = capacity_check(sample, scale, docker_root, retaining, mode == "diagnose") + require_capacity(capacity, args.allow_tight_capacity) + cancel, emergency = threading.Event(), threading.Event() + previous = {} + for sig in (signal.SIGINT, signal.SIGTERM): + previous[sig] = signal.signal(sig, lambda *_: cancel.set()) + control = OperationControl(cancel) + monitor = ResourceMonitor(result, cancel, emergency, _CHECKPOINT_LOCK) + active_runtime, active_entry = None, None + try: + monitor.start() + control.remaining() + with bench_factory(workspace=str(Path.cwd())) as bench: + # Reject a live resume mismatch before health checks, model requests or mutations. + resumed = None + if args.resume_runtime and (args.resume_runtime / "runtime.json").exists(): + resumed = bench.runtimes.attach(args.resume_runtime)._runtime + validate_resume(recorded, resumed, scales[0], allow_unplanned=args.rebuild_runtime) + active_runtime, active_entry = resumed, recorded + if resumed.metadata.get("quarantined") and not args.rebuild_runtime: + raise RuntimeError("Runtime is quarantined; repair it or explicitly use --rebuild-runtime") + if args.rebuild_runtime: + if not recorded.get("runtime_owned", False): + raise ValueError("Cannot rebuild an externally owned runtime") + if args.resume_runtime: + validate_campaign_cases( + recorded, scales[0], backends_requested, output, resumed, select_cases, smoke_cases + ) + if mode == "effects": + # An empty backend list validates images/toolchain without agents, + # credential writes or model requests. + preflight([], args.vendor, output) + control.remaining() + identities = ( + {"effects": {"mode": mode, "fault_catalog_version": FAULT_CATALOG_VERSION}} + if mode == "effects" + else preflight(args.agents, args.vendor, output, expected=expected_identities(result, args.agents)) + ) + control.remaining() + for backend, identity in identities.items(): + for scale in scales: + old = result["scales"].get(scale, {}).get("agents", {}).get(backend, {}).get("identity") + if old is not None and old != identity: + raise ValueError(f"Cannot change {backend} configuration when resuming acceptance") + if args.rebuild_runtime and resumed is not None: + resumed.teardown() + resumed = None + qualification = qualified_codex_smoke(args, identities, backend_identity) + if qualification is not None: + previous_qualification = result.get("codex_qualification") + if previous_qualification is not None and previous_qualification["sha256"] != qualification["sha256"]: + raise ValueError("Cannot change Codex qualification when resuming acceptance") + result["codex_qualification"] = qualification + needs_smoke = ( + "codex" in backends_requested + and "xs" not in scales + and not result.get("codex_xs_smoke") + and qualification is None + ) + phases = (["xs"] if needs_smoke or sample is None or "xs" in scales else []) + [ + scale for scale in scales if scale != "xs" + ] + for scale in phases: + control.remaining() + current = result["scales"].setdefault(scale, {"resource_samples": []}) + entry = current + completed = False + if sample is not None and scale != "xs": + entry["capacity"] = capacity_check( + sample, + scale, + docker_root, + resumed is not None and scale == scales[0] and resumed.state == "warm", + mode == "diagnose", + ) + require_capacity(entry["capacity"], args.allow_tight_capacity) + if entry["capacity"]["status"] != "passed": + entry["capacity_override"] = "explicitly_authorized_twenty_percent_memory_margin_waiver" + runtime = resumed if resumed is not None and scale == scales[0] else None + if runtime is None: + token = datetime.now(UTC).strftime("%m%d%H%M%S") + rebuilding = args.resume_runtime is not None and scale == scales[0] + if rebuilding and not args.rebuild_runtime: + if entry.get("historical_redeployment"): + raise ValueError("Historical runtime has already been redeployed once") + entry["historical_redeployment"] = True + if rebuilding and ( + not entry.get("runtime_owned") + or args.resume_runtime.resolve() != bench.runtimes.runtime_root_dir / args.resume_runtime.name + ): + raise ValueError("Only an owned runtime in the managed runtime directory can be rebuilt") + runtime = bench.runtimes.create( + scale=scale, + workers=1, + name=args.resume_runtime.name if rebuilding else f"pmv2-{scale}-{token}", + )._runtime + if entry.get("runtime"): + entry.setdefault("prior_runtimes", []).append(entry["runtime"]) + entry.update(runtime=str(runtime.root_dir), runtime_owned=True) + active_runtime, active_entry = runtime, entry + control.remaining() + digest = runtime.scale_registry.get(scale).digest + if entry.get("profile_sha256", digest) != digest: + raise ValueError("Runtime profile differs from the accepted cases") + entry.update( + status="running", + runtime_disposition="active", + profile_sha256=digest, + runtime_spec=runtime.describe(), + mode=mode, + fault_catalog_version=FAULT_CATALOG_VERSION, + runtime_backend=backend_identity, + ) + result["status"] = "running" + result.pop("finished", None) + checkpoint(output, result) + worker = runtime.workers[0] + preflight_topology = output / "preflight-topology" / scale + if not (preflight_topology / "topology.json").exists(): + generate_topology( + scale, + str(preflight_topology), + name=worker.lab_name, + mgmt_subnet=worker.mgmt_subnet, + mgmt_network=worker.mgmt_network, + ) + manifest = load_topology_manifest(preflight_topology) + existing = sorted((output / "scenarios" / scale).glob("*.yaml")) + paths = existing or generate( + load_yaml(Path.cwd() / "netopsbench/platform/scenario/specs/fault_campaign.yaml"), + load_topology(scale, str(preflight_topology)), + output / "scenarios" / scale, + seed=42, + ) + selected = ( + smoke_cases(paths, manifest) + if entry.get("smoke_cases", scale == "xs" and needs_smoke) + else select_cases(paths, True, manifest) + ) + backends = ["codex"] if scale == "xs" and needs_smoke else backends_requested + entry.setdefault("smoke_cases", bool(scale == "xs" and needs_smoke)) + for backend in backends: + record = entry.setdefault("agents", {}).setdefault( + backend, + { + "identity": identities[backend], + "cases": [], + }, + ) + freeze_cases(record, selected) + entry.setdefault("manifest", manifest.model_dump(mode="json")) + checkpoint(output, result) + runtime.operation_control = control + worker = runtime.workers[0] + monitor.watch(entry, worker.lab_name, worker.topology_dir) + try: + if runtime.state != "warm": + runtime.deploy().ensure_observability().ensure_pingmesh() + worker = runtime.workers[0] + manifest = load_topology_manifest(worker.topology_dir) + plan = manifest.require_pingmesh_plan() + if entry.get("plan") and entry["plan"]["plan_id"] != plan.settings.plan_id: + raise ValueError("Rebuilt runtime Pingmesh plan differs from the accepted cases") + entry["plan"] = plan.summary() + names = [f"clab-{worker.lab_name}-{client.name}" for client in manifest.clients()] + images = sorted( + set( + subprocess.check_output( + ["docker", "inspect", "--format", "{{.Image}}", *names], text=True, timeout=60 + ).split() + ) + ) + if entry.get("client_images") and entry["client_images"] != images: + raise ValueError("Runtime client image differs from the accepted cases") + entry["client_images"] = images + entry["manifest"] = manifest.model_dump(mode="json") + if runtime.state == "warm": + entry["start_health"] = require_full_health(runtime, cancel) + else: + runtime.warm() + entry["start_health"] = runtime.stage_results["warm"].details + (output / f"{scale}-coverage.json").write_text(plan.coverage.model_dump_json(indent=2)) + entry["ingestion_latency"] = ingestion_latency(worker, plan.settings.plan_id) + entry["bgp_observation"] = bgp_observation( + worker, + manifest, + output / f"{scale}-bgp.csv", + control=OperationControl( + cancel, + time.monotonic() + + 2 * DEFAULT_BGP_FULL_SNAPSHOT_INTERVAL_SECONDS + + DEFAULT_BGP_POLL_INTERVAL_SECONDS, + ), + ) + entry.setdefault("storage_start", storage_snapshot()) + # Keep prepared identities durable even if the process exits + # during the first case, before its completion callback. + checkpoint(output, result) + + for backend in backends: + control.remaining() + ran_cases = run_cases( + bench, + runtime, + selected, + backend=backend, + vendor=args.vendor, + entry=entry, + identity=identities[backend], + output=output, + result=result, + cancel=cancel, + agent_factory=agent_factory, + ) + # Skip an empty resumed campaign; retain transition and final checks. + if ran_cases or backend == backends[-1]: + entry.setdefault("end_health", {})[backend] = require_full_health(runtime, cancel) + if cancel.is_set(): + raise RuntimeError("Acceptance cancelled") + entry["storage_end"] = storage_snapshot() + entry["agent_execution_failures"] = sorted( + { + summary["scenario_id"] + for record in entry["agents"].values() + for case in record["cases"] + for summary in case["scenario_summaries"] + if is_recovered_case_failure(summary) and summary["failure_stage"] == "agent" + } + ) + entry["invalid_cases"] = sorted( + { + summary["scenario_id"] + for record in entry["agents"].values() + for case in record["cases"] + for summary in case["scenario_summaries"] + if summary.get("case_valid") is False + } + ) + if entry["invalid_cases"]: + entry["status"] = "completed_with_case_failures" + elif entry["agent_execution_failures"]: + entry["status"] = "completed_with_agent_failures" + else: + entry["status"] = "passed" + if scale == "xs" and needs_smoke: + result["codex_xs_smoke"] = True + completed = True + except BaseException as exc: + entry["error"] = f"{type(exc).__name__}: {exc}" + quarantine_partial_deployment(runtime, entry, output) + entry["status"] = "quarantined" if runtime.metadata.get("quarantined") else "failed_retained" + raise + finally: + monitor.watch(None, None, None) + runtime.operation_control = None + if entry["resource_samples"]: + sample = peak_sample(([sample] if sample else []) + entry["resource_samples"]) + atomic_write_json(output / "capacity-sample.json", sample) + if emergency.is_set(): + entry["resource_emergency"] = "MemAvailable below 12 GiB" + checkpoint(output, result) + if runtime.state != "torn_down": + entry["runtime_disposition"] = release_runtime( + runtime, + owned=entry.get("runtime_owned", False), + completed=completed, + emergency=emergency.is_set(), + ) + checkpoint(output, result) + if any(entry.get("invalid_cases") for entry in result["scales"].values()): + result["status"] = "completed_with_case_failures" + elif any(entry.get("agent_execution_failures") for entry in result["scales"].values()): + result["status"] = "completed_with_agent_failures" + else: + result["status"] = "passed" + return 0 + except BaseException as exc: + result["status"] = "failed_retained" + result["error"] = f"{type(exc).__name__}: {exc}" + raise + finally: + monitor.close() + if ( + emergency.is_set() + and active_runtime is not None + and active_entry is not None + and active_runtime.state != "torn_down" + ): + try: + active_entry["runtime_disposition"] = release_runtime( + active_runtime, + owned=active_entry.get("runtime_owned", False), + completed=False, + emergency=True, + ) + except Exception as exc: + active_entry["emergency_cleanup_error"] = str(exc) + result["finished"] = datetime.now(UTC).isoformat() + checkpoint(output, result) + for sig, handler in previous.items(): + signal.signal(sig, handler) diff --git a/netopsbench/platform/session/atif.py b/netopsbench/platform/session/atif.py index e36d038..4003cb0 100644 --- a/netopsbench/platform/session/atif.py +++ b/netopsbench/platform/session/atif.py @@ -103,26 +103,15 @@ def build_atif_payload(trace: dict[str, Any]) -> dict[str, Any]: def _normalise_steps(steps: list[Any], *, model_metadata: dict[str, Any]) -> list[dict[str, Any]]: normalised: list[dict[str, Any]] = [] - saw_runtime_event = False - seen_copied_context: set[str] = set() for index, item in enumerate(steps, 1): step = dict(item) if isinstance(item, dict) else {"content": str(item)} step.setdefault("index", index) step["type"] = str(step.get("type") or step.get("role") or step.get("source") or "message") - if step.get("is_copied_context"): - fingerprint = _message_fingerprint(step) - if saw_runtime_event or fingerprint in seen_copied_context: - continue - seen_copied_context.add(fingerprint) - step.pop("is_copied_context", None) - step["is_initial_context"] = True - else: - saw_runtime_event = True if model_metadata and step["type"] == "llm": step.setdefault("model", model_metadata.get("model")) step.setdefault("provider", model_metadata.get("provider")) normalised.append(_jsonable(step)) - return normalised + return _collapse_copied_context_steps(normalised) def _atif_steps(trace: dict[str, Any]) -> list[dict[str, Any]]: diff --git a/netopsbench/platform/session/diagnosis.py b/netopsbench/platform/session/diagnosis.py index 6fed1b0..4f10236 100644 --- a/netopsbench/platform/session/diagnosis.py +++ b/netopsbench/platform/session/diagnosis.py @@ -12,26 +12,55 @@ from netopsbench.agents.base import DiagnosticContext from netopsbench.agents.handle import AgentHandle from netopsbench.agents.tracing import AgentTraceRecorder +from netopsbench.evaluator.scorer import AgentOutput from netopsbench.logging_utils import get_logger from netopsbench.platform.incident.context import ( extract_episode_pingmesh_query_window, ) from netopsbench.platform.incident.engine import DiagnosticSession, SessionToolGateway +from netopsbench.platform.scenario.timing import timing_scope from netopsbench.platform.session.trace_store import TraceWriter from netopsbench.platform.session.types import WorkerExecutionContext +from netopsbench.platform.toolkit._core.control import diagnosis_budget_scope from netopsbench.platform.utils.files import atomic_write_json logger = get_logger(__name__) -def run_agent_diagnose(handle: Any, context: DiagnosticContext): +def run_agent_diagnose( + handle: Any, context: DiagnosticContext, cancel_event=None, *, timeout_seconds=None, timings=None +): """Execute a sync or async diagnosis handle from a synchronous session.""" + + async def invoke(): + async def bounded(): + with timing_scope(timings): + async with diagnosis_budget_scope(timeout_seconds): + return await handle.diagnose(context) + + task = asyncio.create_task(bounded()) + try: + while not task.done(): + if cancel_event is not None and cancel_event.is_set(): + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + raise RuntimeError("diagnosis cancelled") + await asyncio.wait({task}, timeout=0.2) + return await task + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + try: asyncio.get_running_loop() except RuntimeError: - return asyncio.run(handle.diagnose(context)) + return asyncio.run(invoke()) with ThreadPoolExecutor(max_workers=1) as executor: - future = executor.submit(lambda: asyncio.run(handle.diagnose(context))) + future = executor.submit(lambda: asyncio.run(invoke())) return future.result() @@ -51,13 +80,12 @@ def build_runtime_diagnosis_callback( worker_name: str | None = None, runtime_id: str | None = None, scenario_scale: str | None = None, + cancel_event=None, ): """Build the episode callback that presents observations to one agent.""" handle = agent if isinstance(agent, AgentHandle) else AgentHandle(agent) context_dir = Path(topology_dir) / ".netopsbench" context_file = context_dir / "pingmesh_context.json" - worker_env = worker_context.as_env() if worker_context is not None else {} - worker_env["NETOPSBENCH_PINGMESH_CONTEXT_FILE"] = str(context_file) def callback( episode_result: dict, @@ -78,8 +106,6 @@ def callback( symptoms = diagnostic_payload["symptoms"] canonical_observation = diagnostic_payload["canonical_observation"] metadata: dict[str, Any] = {"canonical_observation": canonical_observation} - if worker_env: - metadata["worker_env"] = worker_env context = DiagnosticContext( scenario_id=case_id, topology=topology, @@ -89,81 +115,51 @@ def callback( metadata=metadata, ) try: - diagnosis = run_agent_diagnose(handle, context) + limit = diagnostic_session.config.max_agent_seconds + diagnosis = run_agent_diagnose( + handle, + context, + cancel_event, + timeout_seconds=limit, + timings=getattr(diagnostic_session, "phase_timings", None), + ) except Exception as exc: trace_recorder.record_error(stage="agent", error=exc) ended_at = datetime.now(UTC) + failure_metadata: dict[str, Any] = {} + cause: BaseException | None = exc + while cause is not None: + failure_metadata.update(getattr(cause, "agent_metadata", {})) + cause = cause.__cause__ diagnosis_payload: dict[str, Any] = { "error": str(exc), "success": False, "time_taken_seconds": max(0.0, (ended_at - start_time).total_seconds()), - "metadata": {"agent_failure_stage": "diagnose", "error_type": type(exc).__name__}, + "metadata": {**failure_metadata, "agent_failure_stage": "diagnose", "error_type": type(exc).__name__}, } - if trace_writer is not None: - try: - trace_result = trace_writer.write_case_trace( - case_id=context.scenario_id, - scenario_id=scenario_id, - episode_result=episode_result, - worker=worker_name or "worker", - topology_id=(worker_context.topology_id if worker_context is not None else None), - topology_scale=scenario_scale, - runtime_id=runtime_id or "", - agent=agent, - diagnostic_context=context, - diagnosis=SimpleNamespace( - agent_name=getattr(handle, "name", "agent"), - success=False, - findings={"error": str(exc)}, - metadata=diagnosis_payload["metadata"], - ), - diagnosis_payload=diagnosis_payload, - started_at=start_time, - ended_at=ended_at, - pingmesh_window=pingmesh_query_window, - error=str(exc), - trace_recorder=trace_recorder, - ) - diagnosis_payload["trace"] = { - "trace_id": trace_result.trace_id, - "case_id": trace_result.case_id, - "worker": trace_result.worker, - "atif_path": trace_result.atif_path, - } - except Exception: - logger.debug("failed to persist failed agent runtime trace", exc_info=True) - diagnosis_payload["metadata"] = _strip_runtime_trace_metadata(diagnosis_payload["metadata"]) - return diagnosis_payload - - findings = dict(diagnosis.findings or {}) - location = findings.get("location") or {} - if not isinstance(location, dict): - location = {} - ended_at = datetime.now(UTC) - metadata = dict(diagnosis.metadata or {}) - recorder_metrics = trace_recorder.metrics() - for key in ("input_tokens", "output_tokens", "total_tokens", "llm_call_count"): - if recorder_metrics.get(key): - metadata[key] = recorder_metrics[key] - recorded_tool_calls = trace_recorder.tool_calls() - diagnosis_payload = { - "verdict": diagnosis.verdict, - "fault_type": findings.get("fault_type") or metadata.get("fault_type"), - "location": { - key: value - for key, value in { - "device": location.get("device") or findings.get("device"), - "interface": location.get("interface") or findings.get("interface"), - }.items() - if value is not None - }, - "evidence": list(findings.get("evidence") or []), - "confidence": float(diagnosis.confidence or 0.0), - "reasoning": diagnosis.reasoning, - "tool_calls": recorded_tool_calls or list(metadata.get("tool_calls") or []), - "time_taken_seconds": max(0.0, (ended_at - start_time).total_seconds()), - "metadata": metadata, - } + diagnosis = SimpleNamespace( + agent_name=getattr(handle, "name", "agent"), + success=False, + findings={"error": str(exc)}, + metadata=diagnosis_payload["metadata"], + ) + else: + ended_at = datetime.now(UTC) + output = AgentOutput.from_diagnosis( + diagnosis, + merge_location_fields=True, + metadata_evidence=False, + findings_tool_calls=False, + time_taken_seconds=max(0.0, (ended_at - start_time).total_seconds()), + ) + recorder_metrics = trace_recorder.metrics() + for key in ("input_tokens", "output_tokens", "total_tokens", "llm_call_count"): + if recorder_metrics.get(key): + output.metadata[key] = recorder_metrics[key] + output.tool_calls = trace_recorder.tool_calls() or output.tool_calls + diagnosis_payload = {"success": diagnosis.success, **vars(output)} + if not diagnosis.success: + diagnosis_payload["error"] = diagnosis.reasoning or "agent diagnosis failed" if trace_writer is not None: try: trace_result = trace_writer.write_case_trace( @@ -182,6 +178,7 @@ def callback( ended_at=ended_at, pingmesh_window=pingmesh_query_window, trace_recorder=trace_recorder, + error=diagnosis_payload.get("error"), ) diagnosis_payload["trace"] = { "trace_id": trace_result.trace_id, diff --git a/netopsbench/platform/session/dispatch.py b/netopsbench/platform/session/dispatch.py index 5daed87..0de74bf 100644 --- a/netopsbench/platform/session/dispatch.py +++ b/netopsbench/platform/session/dispatch.py @@ -16,6 +16,7 @@ from netopsbench.models.runtime import RuntimeIdentity from netopsbench.models.scenario import ScenarioSpec from netopsbench.platform.runtime.manager import RuntimePool +from netopsbench.platform.scenario.artifacts import persist_result from netopsbench.platform.scenario.executor import ScenarioExecutor from netopsbench.platform.scenario.validator import require_scenario_topology from netopsbench.platform.session.context import build_worker_execution_context @@ -24,13 +25,38 @@ from netopsbench.platform.session.scoring import score_scenario_episode from netopsbench.platform.session.trace_store import TraceWriter from netopsbench.platform.session.types import WorkerExecutionContext -from netopsbench.platform.utils.files import atomic_write_json logger = logging.getLogger(__name__) WorkerRunResult = tuple[list[Any], list[dict[str, Any]], dict[str, Any]] +@dataclass +class ExecutionControl: + """Internal acceptance hooks; ordinary SDK sessions keep their defaults.""" + + on_case: Callable[[dict[str, Any], dict[str, Any], list[Any]], None] | None = None + stop_on_failure: bool = False + cancel_event: Any = None + effects_only: bool = False + + +def is_recovered_case_failure(summary: dict[str, Any]) -> bool: + """Finished diagnosis or effect failures can advance after verified recovery.""" + return summary.get("cleanup_failed") is False and ( + ( + summary.get("status") == "failed" + and summary.get("failure_stage") == "agent" + and summary.get("case_valid") is True + ) + or ( + summary.get("status") == "invalid" + and summary.get("failure_stage") == "effect_validation" + and summary.get("case_valid") is False + ) + ) + + @dataclass(frozen=True) class PoolDispatchResult: evaluations: list[Any] @@ -90,20 +116,19 @@ def _build_scenario_executor( *, worker: RuntimeIdentity, fault_registry: Any, - minimum_baseline_seconds: int, - post_recovery_wait_seconds: int, + minimum_baseline_seconds: int | None, scale_registry: ScaleRegistry, + effects_only: bool = False, ) -> ScenarioExecutor: runner = ScenarioExecutor( topology_dir=str(worker_context.topology_dir), topology_metadata=load_topology_metadata(worker_context.topology_dir), minimum_baseline_seconds=minimum_baseline_seconds, - post_recovery_wait_seconds=post_recovery_wait_seconds, influxdb_bucket=worker_context.influxdb_bucket, topology_id=worker_context.topology_id, fault_registry=fault_registry, scale_registry=scale_registry, - evaluator=_create_evaluator(), + evaluator=Evaluator() if effects_only else _create_evaluator(), runtime_worker=worker, ) return runner @@ -121,11 +146,12 @@ def _run_worker( raw_dir: Path, trace_writer: TraceWriter | None, fault_registry: Any, - minimum_baseline_seconds: int, - post_recovery_wait_seconds: int, + minimum_baseline_seconds: int | None, scale_registry: ScaleRegistry, worker: RuntimeIdentity, scenarios: list[ScenarioSpec], + control: ExecutionControl | None = None, + destroy_after_run: bool = False, ) -> WorkerRunResult: worker_context = build_worker_execution_context(worker, worker.topology_dir) for scenario in scenarios: @@ -137,34 +163,45 @@ def _run_worker( worker=worker, fault_registry=fault_registry, minimum_baseline_seconds=minimum_baseline_seconds, - post_recovery_wait_seconds=post_recovery_wait_seconds, scale_registry=scale_registry, + **({"effects_only": True} if control and control.effects_only else {}), ) evaluator = runner.evaluator + if control: + runner._cancel_event = control.cancel_event evaluations: list[Any] = [] scenario_summaries: list[dict[str, Any]] = [] worker_success = True executed_count = 0 + final_calibration = None try: for scenario_index, scenario in enumerate(scenarios): - callback = build_runtime_diagnosis_callback( - agent, - str(worker_context.topology_dir), - scenario.id, - worker_context, - trace_writer, - worker.worker_id, - runtime.id, - scenario.scale, + if control and control.cancel_event and control.cancel_event.is_set(): + worker_success = False + break + callback = ( + None + if control and control.effects_only + else build_runtime_diagnosis_callback( + agent, + str(worker_context.topology_dir), + scenario.id, + worker_context, + trace_writer, + worker.worker_id, + runtime.id, + scenario.scale, + cancel_event=control.cancel_event if control else None, + ) ) scenario_result = runner.run_scenario(scenario, diagnosis_callback=callback) executed_count += 1 raw_result_path = _persist_raw_scenario_result(worker_raw_dir, scenario.id, scenario_result) case_valid = bool(scenario_result.get("case_valid", scenario_result.get("success"))) scored: list[Any] = [] - if case_valid: + if case_valid and not (control and control.effects_only): try: scored = score_scenario_episode( scenario, @@ -194,16 +231,41 @@ def _run_worker( logger.debug("failed to persist trace evaluation results", exc_info=True) evaluations.extend(scored) cleanup_success = bool((scenario_result.get("cleanup") or {}).get("success", True)) + episode_result = scenario_result.get("episode") or {} + execution_failure = (episode_result.get("execution") or {}).get("failure") or {} + diagnosis_metadata = (episode_result.get("diagnosis") or {}).get("metadata") or {} + recovered = (scenario_result.get("cleanup") or {}).get("success") is True and not ( + control and control.cancel_event and control.cancel_event.is_set() + ) + recovered_agent_failure = ( + case_valid + and not scenario_result.get("error") + and execution_failure.get("domain") in {"agent", "protocol"} + and execution_failure.get("phase") in {"diagnosis", "limits"} + and not diagnosis_metadata.get("cleanup_errors") + and recovered + ) + recovered_effect_failure = ( + not case_valid + and not (control and control.effects_only) + and (episode_result.get("effect_audit") or {}).get("valid") is False + and not episode_result.get("diagnosis") + and bool((scenario_result.get("cleanup") or {}).get("validated_baseline")) + and recovered + ) success = case_valid and bool(scenario_result.get("success")) and cleanup_success if not case_valid: status = "invalid" - failure_stage = "infrastructure" + failure_stage = "effect_validation" if recovered_effect_failure else "infrastructure" elif success: status = "completed" failure_stage = None else: status = "failed" - failure_stage = "cleanup" if not cleanup_success else "execution" + if not cleanup_success: + failure_stage = "cleanup" + else: + failure_stage = "agent" if recovered_agent_failure else "execution" scenario_summaries.append( { "scenario_id": scenario.id, @@ -213,22 +275,45 @@ def _run_worker( "worker": worker.worker_id, "raw_result_path": raw_result_path, "cleanup_failed": not cleanup_success, + "phase_timings": scenario_result.get("phase_timings", {}), **({"failure_stage": failure_stage} if failure_stage else {}), } ) worker_success &= success if not cleanup_success: + runtime.mark_quarantined("scenario_cleanup_failure", [worker.worker_id]) + if control and control.on_case: + control.on_case(scenario_summaries[-1], scenario_result, scored) + if not cleanup_success or ( + control + and control.stop_on_failure + and not success + and not is_recovered_case_failure(scenario_summaries[-1]) + ): for skipped in scenarios[scenario_index + 1 :]: scenario_summaries.append( { "scenario_id": skipped.id, - "status": "skipped_infrastructure_failure", + "status": ( + "skipped_infrastructure_failure" if not cleanup_success else "skipped_execution_failure" + ), "scale": skipped.scale, "worker": worker.worker_id, - "failure_stage": "prior_case_cleanup", + "failure_stage": "prior_case_cleanup" if not cleanup_success else "prior_case_execution", } ) break + if executed_count and not any(item.get("cleanup_failed") for item in scenario_summaries): + try: + final_calibration = runner.final_calibration(scenario, destroy_after_run=destroy_after_run) + except BaseException as exc: + worker_success = False + final_calibration = {"success": False, "error": str(exc)} + runtime.mark_quarantined("final_calibration_failure", [worker.worker_id]) + if not isinstance(exc, Exception): + persist_result(worker_raw_dir / "final_calibration.json", final_calibration) + raise + persist_result(worker_raw_dir / "final_calibration.json", final_calibration) finally: runner.close() @@ -240,6 +325,7 @@ def _run_worker( "executed_count": executed_count, "skipped_count": len(scenarios) - executed_count, "success": worker_success, + **({"final_calibration": final_calibration} if final_calibration is not None else {}), } return evaluations, scenario_summaries, worker_summary @@ -252,7 +338,7 @@ def _persist_raw_scenario_result( safe_id = "".join(ch if ch.isalnum() or ch in {"-", "_", "."} else "_" for ch in str(scenario_id)) timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S_%f") result_path = worker_raw_dir / f"{safe_id}_{timestamp}.json" - atomic_write_json(result_path, scenario_result, default=str) + persist_result(result_path, scenario_result) scenario_result["result_file"] = str(result_path) return str(result_path) @@ -265,10 +351,15 @@ def execute_on_runtime_pool( raw_dir: Path, trace_writer: TraceWriter | None = None, fault_registry: Any = None, - minimum_baseline_seconds: int = 60, - post_recovery_wait_seconds: int = 2, + minimum_baseline_seconds: int | None = None, + control: ExecutionControl | None = None, + destroy_after_run: bool = False, ) -> PoolDispatchResult: """Run scenarios on an existing runtime and return ordered execution data.""" + from netopsbench.models.recovery import RecoveryPolicy + + for scenario in scenarios: + RecoveryPolicy.from_metadata(scenario.metadata) if runtime.state != "warm" or bool(runtime.metadata.get("quarantined")): raise RuntimeError( f"Runtime {runtime.id!r} is not eligible for execution: " @@ -287,21 +378,18 @@ def execute_on_runtime_pool( trace_writer=trace_writer, fault_registry=fault_registry, minimum_baseline_seconds=minimum_baseline_seconds, - post_recovery_wait_seconds=post_recovery_wait_seconds, scale_registry=runtime.scale_registry, worker=worker, scenarios=assigned, + control=control, + destroy_after_run=destroy_after_run, ), ) cleanup_failures = sorted( {str(item["worker"]) for item in result.scenarios if item.get("cleanup_failed") is True and item.get("worker")} ) if cleanup_failures: - runtime.state = "quarantined" - runtime.metadata["quarantined"] = True - runtime.metadata["quarantine_reason"] = "scenario_cleanup_failure" - runtime.metadata["quarantined_workers"] = cleanup_failures - runtime._write_metadata() + runtime.mark_quarantined("scenario_cleanup_failure", cleanup_failures) return result diff --git a/netopsbench/platform/session/orchestrator.py b/netopsbench/platform/session/orchestrator.py index b13cd41..35fa6bf 100644 --- a/netopsbench/platform/session/orchestrator.py +++ b/netopsbench/platform/session/orchestrator.py @@ -13,7 +13,7 @@ from netopsbench.models.scenario import ScenarioSpec from netopsbench.platform.runtime.manager import RuntimeManager, RuntimePool from netopsbench.platform.scenario.parser import parse_scenario_file -from netopsbench.platform.session.dispatch import execute_on_runtime_pool +from netopsbench.platform.session.dispatch import ExecutionControl, execute_on_runtime_pool from netopsbench.platform.session.reporting import ( LocalArtifactStore, artifacts_root, @@ -148,6 +148,10 @@ def _run_with_platform_runtime( artifacts_dir: str | Path | None, trace: bool, ) -> Any: + from netopsbench.models.recovery import RecoveryPolicy + + for scenario in scenarios: + RecoveryPolicy.from_metadata(scenario.metadata) started_at = self._timestamp() run_id = reserve_run_id(self._artifacts_root(artifacts_dir), started_at=started_at) runtime_id = f"{run_id}-runtime" @@ -157,8 +161,8 @@ def _run_with_platform_runtime( name=runtime_id, root_dir=root_dir, ) - execution_failure: Exception | None = None - cleanup_failure: Exception | None = None + execution_failure: BaseException | None = None + cleanup_failure: BaseException | None = None handle: Any | None = None try: handle = self._execute_on_runtime_pool( @@ -173,12 +177,12 @@ def _run_with_platform_runtime( teardown=("preserved" if keep_runtime else "pending"), started_at=started_at, ) - except Exception as exc: + except BaseException as exc: execution_failure = exc if not keep_runtime: try: runtime.teardown() - except Exception as exc: + except BaseException as exc: cleanup_failure = exc teardown = "preserved" if keep_runtime else ("failed" if cleanup_failure is not None else "performed") self._finalize_lifecycle_report( @@ -215,6 +219,7 @@ def _run_with_existing_runtime( agent: Any, artifacts_dir: str | Path | None, trace: bool, + control: ExecutionControl | None = None, ) -> Any: started_at = self._timestamp() run_id = reserve_run_id(self._artifacts_root(artifacts_dir), started_at=started_at) @@ -229,6 +234,7 @@ def _run_with_existing_runtime( runtime_owner="user", teardown="skipped", started_at=started_at, + control=control, ) def _execute_on_runtime_pool( @@ -244,6 +250,7 @@ def _execute_on_runtime_pool( runtime_owner: str, teardown: str, started_at: datetime, + control: ExecutionControl | None = None, ) -> Any: artifact_dir = self._artifacts_root(artifacts_dir) / run_id raw_dir = artifact_dir / "raw" @@ -259,6 +266,8 @@ def _execute_on_runtime_pool( raw_dir=raw_dir, trace_writer=trace_writer, fault_registry=getattr(getattr(self.platform, "faults", None), "spec_registry", None), + control=control, + destroy_after_run=runtime_owner == "platform" and teardown == "pending", ) aggregate_report = ( Evaluator().generate_report( @@ -269,6 +278,8 @@ def _execute_on_runtime_pool( if dispatched.evaluations else {"summary": {"total_cases": 0, "average_score": 0.0}, "detailed_results": []} ) + if control and control.effects_only: + aggregate_report = {"summary": {"execution_mode": "effects"}, "detailed_results": []} completed_at = self._timestamp() traces_dir = trace_writer.root_dir if trace_writer is not None else None report_payload = create_run_report( @@ -344,15 +355,15 @@ def _finalize_lifecycle_report( started_at: datetime, runtime_owner: str, teardown: str, - execution_failure: Exception | None, - cleanup_failure: Exception | None, + execution_failure: BaseException | None, + cleanup_failure: BaseException | None, ) -> None: artifact_dir = self._artifacts_root(artifacts_dir) / run_id report_path = artifact_dir / "report.json" metadata_path = artifact_dir / "metadata.json" completed_at = self._timestamp() - def failure_payload(error: Exception | None) -> dict[str, str] | None: + def failure_payload(error: BaseException | None) -> dict[str, str] | None: if error is None: return None return {"type": type(error).__name__, "message": str(error)} diff --git a/netopsbench/platform/session/reporting.py b/netopsbench/platform/session/reporting.py index 3bb9aa7..62c44d6 100644 --- a/netopsbench/platform/session/reporting.py +++ b/netopsbench/platform/session/reporting.py @@ -2,15 +2,17 @@ from __future__ import annotations +import csv from collections.abc import Iterable, Sequence from datetime import UTC, datetime +from io import StringIO from pathlib import Path from typing import Any from netopsbench.logging_utils import get_logger from netopsbench.models.scenario import ScenarioSpec from netopsbench.platform.topology.topology_utils import load_topology_manifest -from netopsbench.platform.utils.files import atomic_write_json +from netopsbench.platform.utils.files import atomic_write_json, atomic_write_text logger = get_logger(__name__) @@ -54,7 +56,7 @@ def reserve_run_id(artifact_root: Path, *, started_at: datetime | None = None) - def resolve_scale(scenarios: Iterable[ScenarioSpec]) -> str: scenario_list = list(scenarios) - return scenario_list[0].scale if scenario_list else "xs" + return scenario_list[0].scale if scenario_list else "medium" def create_run_report( @@ -82,7 +84,9 @@ def create_run_report( overall_success = all(summary.get("success", False) for summary in worker_summaries) if worker_summaries else True status = "completed" if overall_success else "failed" reported_agent_name = str( - aggregate_report.get("agent_name") or getattr(agent, "name", agent.__class__.__name__) or "unknown" + aggregate_report.get("agent_name") + or ("effects" if agent is None else getattr(agent, "name", agent.__class__.__name__)) + or "unknown" ) reported_topology_scale = str( aggregate_report.get("topology_scale") @@ -92,6 +96,7 @@ def create_run_report( ) profile = runtime.scale_registry.get(reported_topology_scale) scale_profile = profile.model_dump(mode="json") + included_in_benchmark = profile.purpose == "benchmark" and mode != "effects" artifact_paths = { "report": str(report_path), "metadata": str(metadata_path), @@ -104,7 +109,84 @@ def create_run_report( if trace_results_path is not None: artifact_paths["trace_results"] = str(trace_results_path) + timing_path = artifact_dir / "phase-timings.csv" + timing_csv = StringIO() + writer = csv.DictWriter( + timing_csv, + fieldnames=[ + "scenario_id", + "scale", + "phase", + "status", + "planned_seconds", + "timeout_seconds", + "actual_seconds", + "reason", + ], + ) + writer.writeheader() + for scenario in scenario_summaries: + for phase, measurement in scenario.get("phase_timings", {}).items(): + writer.writerow( + { + "scenario_id": scenario["scenario_id"], + "scale": scenario.get("scale"), + "phase": phase, + **{key: value for key, value in measurement.items() if key in writer.fieldnames}, + } + ) + atomic_write_text(timing_path, timing_csv.getvalue()) + artifact_paths["phase_timings"] = str(timing_path) + + # Keep child measurements out of the existing phase CSV, so consumers do + # not add them to their parent and double-count recovery wall time. + step_csv = StringIO() + step_writer = csv.DictWriter( + step_csv, + fieldnames=[ + "scenario_id", + "scale", + "step", + "status", + "actual_seconds", + "calls", + "failed_calls", + "baseline_query_requests", + "current_query_requests", + ], + ) + step_writer.writeheader() + has_steps = False + for scenario in scenario_summaries: + steps = scenario.get("phase_timings", {}).get("recovery", {}).get("steps", {}) + for name, measurement in steps.items(): + has_steps = True + ingestion = measurement.get("ingestion", {}) + step_writer.writerow( + { + "scenario_id": scenario["scenario_id"], + "scale": scenario.get("scale"), + "step": name, + **{ + key: measurement[key] + for key in ("status", "actual_seconds", "calls", "failed_calls") + if key in measurement + }, + "baseline_query_requests": ingestion.get("baseline", {}).get("query_requests"), + "current_query_requests": ingestion.get("current", {}).get("query_requests"), + } + ) + if has_steps: + step_path = artifact_dir / "recovery-steps.csv" + atomic_write_text(step_path, step_csv.getvalue()) + artifact_paths["recovery_steps"] = str(step_path) + + from netopsbench.platform.faults.catalog import FAULT_CATALOG_VERSION + return { + "fault_catalog_version": FAULT_CATALOG_VERSION, + "purpose": profile.purpose, + "included_in_benchmark": included_in_benchmark, "id": f"run:{run_id}", "run_id": run_id, "agent_name": reported_agent_name, @@ -117,6 +199,9 @@ def create_run_report( "resolved_scale_profile": scale_profile, "summary": { **dict(aggregate_report.get("summary") or {}), + "fault_catalog_version": FAULT_CATALOG_VERSION, + "purpose": profile.purpose, + "included_in_benchmark": included_in_benchmark, "agent_name": reported_agent_name, "mode": mode, "status": status, @@ -132,6 +217,9 @@ def create_run_report( "detailed_results": list(aggregate_report.get("detailed_results") or []), "artifact_paths": artifact_paths, "raw": { + "fault_catalog_version": FAULT_CATALOG_VERSION, + "purpose": profile.purpose, + "included_in_benchmark": included_in_benchmark, "status": status, "mode": mode, "runtime_id": runtime.id, diff --git a/netopsbench/platform/session/scoring.py b/netopsbench/platform/session/scoring.py index 96dd79a..9a5fb4e 100644 --- a/netopsbench/platform/session/scoring.py +++ b/netopsbench/platform/session/scoring.py @@ -21,7 +21,7 @@ def diagnosis_to_agent_output(diagnosis: dict[str, Any] | None) -> AgentOutput: metadata={"final_status": "diagnosis_unavailable", "error": error}, ) return AgentOutput( - verdict=diagnosis.get("verdict", "network_healthy"), + verdict=diagnosis.get("verdict") or "inconclusive", fault_type=diagnosis.get("fault_type"), location=diagnosis.get("location") or {}, evidence=diagnosis.get("evidence") or [], @@ -42,17 +42,19 @@ def score_scenario_episode( scored_results: list[EvaluationResult] = [] scenario_difficulty = (scenario.metadata or {}).get("difficulty", "unknown") episode_result = scenario_result.get("episode") or {} + if (episode_result.get("execution") or {}).get("failure"): + return scored_results episode_info = episode_result.get("episode", {}) if not episode_info: return scored_results testcase_id = f"{scenario.scenario_id}:{episode_info.get('episode_id', 'unknown')}" - ground_truth = ( - {} if episode_info.get("fault_type") == "none" else build_episode_ground_truth(episode_info, topology_dir) - ) persisted_evaluation = episode_result.get("evaluation_result") if isinstance(persisted_evaluation, dict): eval_result = EvaluationResult(**persisted_evaluation) else: + ground_truth = ( + {} if episode_info.get("fault_type") == "none" else build_episode_ground_truth(episode_info, topology_dir) + ) agent_output = diagnosis_to_agent_output(episode_result.get("diagnosis")) eval_result = evaluator.evaluate(agent_output, ground_truth, testcase_id) eval_result.details["difficulty"] = scenario_difficulty diff --git a/netopsbench/platform/session/types.py b/netopsbench/platform/session/types.py index 9cae33d..68bae1d 100644 --- a/netopsbench/platform/session/types.py +++ b/netopsbench/platform/session/types.py @@ -14,11 +14,5 @@ class WorkerExecutionContext: topology_id: str influxdb_bucket: str - def as_env(self) -> dict[str, str]: - return { - "NETOPSBENCH_TOPOLOGY_DIR": str(self.topology_dir), - "NETOPSBENCH_INFLUXDB_BUCKET": self.influxdb_bucket, - } - __all__ = ["WorkerExecutionContext"] diff --git a/netopsbench/platform/simulator/environment.py b/netopsbench/platform/simulator/environment.py index 6554259..6b9505b 100644 --- a/netopsbench/platform/simulator/environment.py +++ b/netopsbench/platform/simulator/environment.py @@ -23,9 +23,10 @@ IncidentEngine, IncidentState, PreparedIncident, - SessionState, + SessionTransition, TerminationReason, ) +from netopsbench.platform.toolkit.public import public_failure class ResetResult(BaseModel): @@ -42,20 +43,10 @@ class ResetResult(BaseModel): error: str | None = None -class StepResult(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) +class StepResult(SessionTransition): + # Public construction requires these flags; internal transitions default them. valid: bool case_valid: bool - state: SessionState - observation: dict[str, Any] = Field(default_factory=dict) - reward: float | None = None - reward_components: dict[str, float] = Field(default_factory=dict) - metrics: dict[str, Any] = Field(default_factory=dict) - termination_reason: TerminationReason | None = None - failure: ExecutionFailure | None = None - cleanup_failure: ExecutionFailure | None = None - cleanup_status: CleanupStatus = CleanupStatus.NOT_STARTED - error: str | None = None class DiagnosticEnvironment: @@ -87,7 +78,7 @@ def reset(self) -> ResetResult: raise RuntimeError("Diagnostic environments are single-use; create a new environment") self.incident = self.engine.prepare(self.scenario) if self.incident.state is IncidentState.BROKEN: - failure = self.incident.failure + failure = public_failure(self.incident.failure) self._notify_close() return ResetResult( valid=False, @@ -95,7 +86,7 @@ def reset(self) -> ResetResult: state=self.incident.state, case_id=self.incident.case_id, failure=failure, - cleanup_failure=self.incident.cleanup_failure, + cleanup_failure=public_failure(self.incident.cleanup_failure), cleanup_status=self.incident.cleanup_status, error=failure.message if failure else "incident preparation failed", ) @@ -118,7 +109,7 @@ def step(self, action: ToolAction | SubmitDiagnosisAction) -> StepResult: else: transition = self.session.submit(action.diagnosis, usage=action.usage) cleanup = self.incident.close() if self.incident is not None else CleanupStatus.NOT_STARTED - cleanup_failure = self.incident.cleanup_failure if self.incident is not None else None + cleanup_failure = public_failure(self.incident.cleanup_failure) if self.incident is not None else None transition = transition.model_copy( update={ "cleanup_status": cleanup, @@ -139,7 +130,7 @@ def terminate_protocol(self, message: str) -> StepResult: reason=TerminationReason.PROTOCOL_ERROR, ) cleanup = self.incident.close() if self.incident is not None else CleanupStatus.NOT_STARTED - cleanup_failure = self.incident.cleanup_failure if self.incident is not None else None + cleanup_failure = public_failure(self.incident.cleanup_failure) if self.incident is not None else None if cleanup_failure is not None: transition = transition.model_copy( update={ diff --git a/netopsbench/platform/simulator/runtime.py b/netopsbench/platform/simulator/runtime.py index 8651a40..fd7617f 100644 --- a/netopsbench/platform/simulator/runtime.py +++ b/netopsbench/platform/simulator/runtime.py @@ -5,22 +5,18 @@ import threading import time import uuid +from contextlib import contextmanager from dataclasses import dataclass -from pathlib import Path from typing import Any from netopsbench.logging_utils import get_logger from netopsbench.models.profiles import ScaleRegistry from netopsbench.models.scenario import ScenarioSpec from netopsbench.platform.incident.contracts import SimulatorConfig, ToolAction -from netopsbench.platform.runtime.health import check_worker_health -from netopsbench.platform.runtime.lifecycle import ensure_worker_client_agent, ensure_worker_observability -from netopsbench.platform.runtime.manager import RuntimeManager, RuntimePool +from netopsbench.platform.runtime.manager import RuntimeManager, RuntimePool, RuntimeProvisionError from netopsbench.platform.scenario.executor import ScenarioExecutor from netopsbench.platform.scenario.incident_backend import ExecutorIncidentBackend -from netopsbench.platform.scenario.observation import baseline_gate_errors from netopsbench.platform.scenario.validator import require_scenario_topology -from netopsbench.platform.topology.topology_utils import load_topology_manifest logger = get_logger(__name__) @@ -28,18 +24,13 @@ _LEASE_WAIT_TIMEOUT_SECONDS = 1_800 -class _BaselineNotReadyError(RuntimeError): - """The runtime is healthy, but its initial observation is not yet clean.""" - - @dataclass class WarmRuntime: runtime: RuntimePool - runner: ScenarioExecutor + runner: ScenarioExecutor | None in_use: bool = False lease_deadline: float = 0.0 - baseline_signature: str | None = None - baseline: dict[str, Any] | None = None + cleaning: bool = False quarantined: bool = False @@ -60,92 +51,164 @@ def __init__( self._runtimes: dict[str, list[WarmRuntime]] = {} self._lock = threading.RLock() self._condition = threading.Condition(self._lock) + self._pending = 0 + self._draining = False + self.lease_acquire_seconds = 0.0 + self.lock_wait_seconds = 0.0 + self.condition_wait_seconds = 0.0 + + @contextmanager + def _locked(self): + started = time.monotonic() + self._condition.acquire() + self.lock_wait_seconds += time.monotonic() - started + try: + yield + finally: + self._condition.release() + + def _wait(self, timeout=None): + started = time.monotonic() + try: + self._condition.wait(timeout=timeout) + finally: + self.condition_wait_seconds += time.monotonic() - started def acquire(self, scale: str) -> WarmRuntime: - deadline = time.monotonic() + _LEASE_WAIT_TIMEOUT_SECONDS - with self._condition: - while True: - self.reap_orphans() - records = self._runtimes.setdefault(scale, []) - available = next( - (record for record in records if not record.in_use and not record.quarantined), - None, - ) - if available is None: - self._make_capacity_for(scale) - records = self._runtimes.setdefault(scale, []) - if available is None and self._runtime_count() < self.config.max_active_runtimes: - available = self._provision(scale) - records.append(available) + started = time.monotonic() + deadline = started + _LEASE_WAIT_TIMEOUT_SECONDS + while True: + self.reap_orphans() + victim = None + with self._locked(): + if self._draining: + raise RuntimeError("Runtime pool is draining") + available = next((r for r in self._runtimes.get(scale, []) if not r.in_use and not r.quarantined), None) if available is not None: available.in_use = True available.lease_deadline = time.monotonic() + self.config.orphan_lease_ttl_seconds + self.lease_acquire_seconds += time.monotonic() - started return available - - remaining = deadline - time.monotonic() - if remaining <= 0: - raise RuntimeError( - f"Timed out waiting for runtime lease for scale {scale}; " - f"global capacity is {self.config.max_active_runtimes}" - ) - self._condition.wait(timeout=self._next_wait_timeout(remaining)) + if self._runtime_count() + self._pending < self.config.max_active_runtimes: + self._pending += 1 + break + victim = next( + ( + r + for key, records in self._runtimes.items() + if key != scale + for r in records + if not r.in_use and not r.quarantined + ), + None, + ) + if victim is not None: + victim.quarantined = True + else: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise RuntimeError(f"Timed out waiting for runtime lease for scale {scale}") + self._wait(timeout=self._next_wait_timeout(remaining)) + if victim is not None: + self.quarantine(victim) + try: + record = self._provision(scale) + except BaseException: + with self._locked(): + self._pending -= 1 + self._condition.notify_all() + raise + with self._locked(): + self._pending -= 1 + self._runtimes.setdefault(scale, []).append(record) + draining = self._draining + if not draining: + record.in_use = True + record.lease_deadline = time.monotonic() + self.config.orphan_lease_ttl_seconds + self.lease_acquire_seconds += time.monotonic() - started + self._condition.notify_all() + if draining: + # drain owns this newly published record and its teardown. + raise RuntimeError("Runtime pool was drained during provisioning") + return record def release(self, record: WarmRuntime) -> None: - with self._condition: + with self._locked(): record.in_use = False record.lease_deadline = 0.0 self._condition.notify_all() def refresh(self, record: WarmRuntime, *, min_seconds: float = 0.0) -> None: - with self._condition: + with self._locked(): if record.in_use and not record.quarantined: ttl = max(float(self.config.orphan_lease_ttl_seconds), float(min_seconds) + 300.0) record.lease_deadline = time.monotonic() + ttl def quarantine(self, record: WarmRuntime) -> None: - with self._condition: + with self._locked(): + while record.cleaning: + self._wait() + if record not in self._runtimes.get(record.runtime.scale, []): + return record.quarantined = True record.in_use = False record.lease_deadline = 0.0 + record.cleaning = True + try: try: - record.runner._stop_traffic() + if record.runner is not None: + record.runner._stop_traffic() except Exception: logger.warning("Failed to stop traffic while quarantining runtime", exc_info=True) - try: - record.runtime.teardown() - except Exception: - logger.warning("Failed to tear down quarantined runtime", exc_info=True) + record.runtime.teardown() + except BaseException: + # Failed teardown continues to occupy capacity and is never leased. + raise + else: + with self._locked(): + self._remove(record) + finally: + with self._locked(): + record.cleaning = False self._condition.notify_all() - raise - self._remove(record) - self._condition.notify_all() def drain(self, scales: set[str] | None = None) -> None: - failures: list[str] = [] - with self._lock: + failures = [] + with self._locked(): + while self._draining: + self._wait() + self._draining = True + while self._pending: + self._wait() selected = [ - record - for scale, records in self._runtimes.items() - if scales is None or scale in scales - for record in records + r for scale, records in self._runtimes.items() if scales is None or scale in scales for r in records ] + for record in selected: + record.quarantined = True + try: for record in selected: try: self.quarantine(record) except Exception as exc: - logger.warning("Failed to drain quarantined runtime", exc_info=True) - failures.append(f"{record.runtime.name}: {type(exc).__name__}: {exc}") + failures.append(f"{record.runtime.scale}: {type(exc).__name__}: {exc}") + finally: + with self._locked(): + self._draining = False + self._condition.notify_all() if failures: raise RuntimeError("Simulator runtime drain failed: " + "; ".join(failures)) def reap_orphans(self) -> None: - now = time.monotonic() - stale = [ - record - for records in self._runtimes.values() - for record in records - if record.in_use and record.lease_deadline and now > record.lease_deadline - ] + with self._locked(): + now = time.monotonic() + stale = [ + r + for records in self._runtimes.values() + for r in records + if r.in_use and r.lease_deadline and now > r.lease_deadline + ] + for record in stale: + record.quarantined = True for record in stale: try: self.quarantine(record) @@ -167,45 +230,47 @@ def _next_wait_timeout(self, remaining: float) -> float: return remaining return min(remaining, max(0.01, min(active_deadlines) - now)) - def _make_capacity_for(self, scale: str) -> None: - if self._runtime_count() < self.config.max_active_runtimes: - return - candidates = [ - record - for candidate_scale, records in self._runtimes.items() - if candidate_scale != scale - for record in records - if not record.in_use and not record.quarantined - ] - for record in candidates: - try: - self.quarantine(record) - except Exception: - continue - if self._runtime_count() < self.config.max_active_runtimes: - return - def _remove(self, record: WarmRuntime) -> None: records = self._runtimes.get(record.runtime.scale, []) if record in records: records.remove(record) + def _retain_failed_provision(self, runtime: RuntimePool) -> None: + with self._locked(): + self._runtimes.setdefault(runtime.scale, []).append( + WarmRuntime(runtime=runtime, runner=None, quarantined=True) + ) + def _provision(self, scale: str) -> WarmRuntime: - with _PROVISION_LOCK: - runtime = self.manager.provision( - scale=scale, - workers=1, - name=f"sim-{scale}-{uuid.uuid4().hex[:8]}", + try: + with _PROVISION_LOCK: + runtime = self.manager.provision( + scale=scale, + workers=1, + name=f"sim-{scale}-{uuid.uuid4().hex[:8]}", + ) + except RuntimeProvisionError as exc: + self._retain_failed_provision(exc.runtime) + raise + try: + worker = runtime.workers[0] + runner = ScenarioExecutor( + topology_dir=str(worker.topology_dir), + topology_id=worker.topology_id, + influxdb_bucket=worker.bucket, + fault_registry=self.fault_registry, + scale_registry=self.registry, + runtime_worker=worker, ) - worker = runtime.workers[0] - runner = ScenarioExecutor( - topology_dir=str(worker.topology_dir), - topology_id=worker.topology_id, - influxdb_bucket=worker.bucket, - fault_registry=self.fault_registry, - scale_registry=self.registry, - runtime_worker=worker, - ) + except BaseException as exc: + try: + runtime.teardown() + except Exception as cleanup_error: + self._retain_failed_provision(runtime) + raise RuntimeProvisionError( + runtime, f"Executor setup and cleanup failed: {exc}; {cleanup_error}" + ) from cleanup_error + raise return WarmRuntime(runtime=runtime, runner=runner) @@ -220,8 +285,13 @@ def __init__(self, leases: RuntimeLeasePool, registry: ScaleRegistry): self.topology_dir: str | None = None def prepare(self, scenario: ScenarioSpec) -> dict[str, Any]: + from netopsbench.models.recovery import RecoveryPolicy + + RecoveryPolicy.from_metadata(scenario.metadata) self.record = self.leases.acquire(scenario.scale) runner = self.record.runner + if runner is None: + raise RuntimeError("Cannot use an incomplete runtime") worker = self.record.runtime.workers[0] self.topology_dir = str(worker.topology_dir) try: @@ -231,46 +301,18 @@ def prepare(self, scenario: ScenarioSpec) -> dict[str, Any]: self.record = None self.leases.release(record) raise - try: - recovery = runner._recover_fault() - if any(not item.get("recovered", False) for item in recovery): - raise RuntimeError(f"Runtime recovery failed: {recovery}") - if recovery: - runner.sleep(runner.post_recovery_wait_seconds) - self.record.baseline_signature = None - self.record.baseline = None - errors = self._health_errors(self.record) - if errors: - raise RuntimeError("Runtime health check failed: " + "; ".join(errors)) - traffic_is_complete = ( - runner.traffic_controller is not None - and bool(runner.traffic_controller.active_flows) - and runner.traffic_controller.verify_active_flows() - ) - if not traffic_is_complete: - runner._stop_traffic() - runner._setup_traffic(scenario.scale, "standard") - self.record.baseline_signature = None - self.record.baseline = None - self._ensure_baseline(scenario) - self.delegate = ExecutorIncidentBackend( - runner, - setup_traffic=False, - baseline_window=self.record.baseline, - influxdb_bucket=worker.bucket, - topology_id=worker.topology_id, - ) - observation = self.delegate.prepare(scenario) - return observation - except _BaselineNotReadyError: - # A newly started Pingmesh/traffic window can contain transient - # anomalies while the otherwise healthy runtime settles. Reuse it - # for the caller's reset retry instead of paying for a full - # teardown/provision cycle. - self.finish(broken=False) - raise - except Exception: - raise + # Preparation, traffic, baseline identity and recovery are shared with + # benchmark execution. An unhealthy lease is handled by incident cleanup. + runner.begin_case() + # Every prepare acquires a new lease; no cross-user baseline handoff. + runner._baseline_handoff.clear("lease_transfer") + runner._calibration_current = False + self.delegate = ExecutorIncidentBackend( + runner, + influxdb_bucket=worker.bucket, + topology_id=worker.topology_id, + ) + return self.delegate.prepare(scenario) def call_tool(self, action: ToolAction) -> dict[str, Any]: if self.delegate is None: @@ -290,13 +332,7 @@ def finish(self, *, broken: bool = False) -> None: delegate = self.delegate try: if delegate is not None: - try: - delegate.finish(broken=broken) - if delegate.baseline_window is not None: - record.baseline = dict(delegate.baseline_window) - except Exception as exc: - broken = True - failure = f"{type(exc).__name__}: {exc}" + delegate.finish(broken=broken) except Exception as exc: broken = True failure = f"{type(exc).__name__}: {exc}" @@ -310,42 +346,6 @@ def finish(self, *, broken: bool = False) -> None: if broken and not requested_broken: raise RuntimeError(failure or "Runtime cleanup failed") - def _ensure_baseline(self, scenario: ScenarioSpec) -> None: - if self.record is None: - raise RuntimeError("Runtime lease is missing") - runner = self.record.runner - manifest = load_topology_manifest(Path(runner.topology_dir)) - profile = self.registry.get(scenario.scale) - signature = f"{profile.digest}:{manifest.model_dump_json()}:{id(runner.traffic_controller)}" - if self.record.baseline_signature == signature and self.record.baseline is not None: - return - reference = runner._capture_baseline_window() - validation = runner._wait_and_observe( - int(reference["duration_seconds"]), - baseline_window=reference, - ) - gate_errors = baseline_gate_errors(validation) - if gate_errors: - raise _BaselineNotReadyError("Healthy baseline is unavailable: " + "; ".join(gate_errors)) - self.record.baseline_signature = signature - self.record.baseline = { - "name": "baseline", - "start_time": validation["start_time"], - "end_time": validation["end_time"], - "duration_seconds": validation["duration_seconds"], - } - - def _health_errors(self, record: WarmRuntime) -> list[str]: - worker = record.runtime.workers[0] - errors = check_worker_health(worker, scale_registry=self.registry) - if not errors: - return errors - ensure_worker_observability(worker) - ensure_worker_client_agent(worker) - record.baseline_signature = None - record.baseline = None - return check_worker_health(worker, scale_registry=self.registry) - __all__ = [ "RuntimeEpisodeBackend", diff --git a/netopsbench/platform/simulator/service.py b/netopsbench/platform/simulator/service.py deleted file mode 100644 index 8e964fa..0000000 --- a/netopsbench/platform/simulator/service.py +++ /dev/null @@ -1,297 +0,0 @@ -"""Optional localhost HTTP facade for the generic simulator.""" - -from __future__ import annotations - -import json -import logging -import os -import threading -import time -import uuid -from contextlib import asynccontextmanager -from dataclasses import dataclass, field -from datetime import UTC, datetime -from pathlib import Path -from typing import Annotated, Any - -from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, ValidationError - -from netopsbench.models.scenario import ScenarioSpec -from netopsbench.platform.incident.context import build_public_case_id -from netopsbench.platform.incident.contracts import ( - SimulatorConfig, - SubmitDiagnosisAction, - ToolAction, -) - -Action = Annotated[ToolAction | SubmitDiagnosisAction, Field(discriminator="type")] -_ACTION_ADAPTER: TypeAdapter[Action] = TypeAdapter(Action) -logger = logging.getLogger(__name__) -_TERMINAL_TOMBSTONE_TTL_SECONDS = 3_600.0 -_MAX_TERMINAL_TOMBSTONES = 1_024 -_EVENT_LOG_MAX_BYTES = 10 * 1024 * 1024 -_EVENT_LOG_BACKUP_COUNT = 2 - - -def scenario_case_id(scenario: ScenarioSpec) -> str: - return build_public_case_id( - scenario_id=scenario.id, - episode_result={"episode": {"episode_id": scenario.episode.episode_id}}, - ) - - -class CreateEnvironmentRequest(BaseModel): - model_config = ConfigDict(extra="forbid") - case_id: str - - -class StepRequest(BaseModel): - model_config = ConfigDict(extra="forbid") - action: dict[str, Any] - - -@dataclass -class _EnvironmentSlot: - environment: Any | None - case_id: str - terminal: bool = False - terminal_at: float | None = None - lock: threading.Lock = field(default_factory=threading.Lock) - - -class TerminalEnvironmentError(RuntimeError): - """The environment already produced a terminal transition.""" - - -class SimulatorService: - def __init__( - self, - manager: Any, - scenarios: list[ScenarioSpec] | tuple[ScenarioSpec, ...], - config: SimulatorConfig | None = None, - *, - event_log: Path | None = None, - ): - self.manager = manager - self.config = config or SimulatorConfig() - self.scenarios = {scenario_case_id(scenario): scenario for scenario in scenarios} - if len(self.scenarios) != len(scenarios): - raise ValueError("Simulator scenarios must produce unique opaque case ids") - self.environments: dict[str, _EnvironmentSlot] = {} - self._lock = threading.RLock() - self._event_lock = threading.Lock() - self._event_log = event_log - if event_log is not None: - event_log.parent.mkdir(parents=True, exist_ok=True) - - def list_cases(self) -> list[str]: - return sorted(self.scenarios) - - def create(self, case_id: str) -> dict[str, Any]: - scenario = self.scenarios.get(case_id) - if scenario is None: - raise KeyError(case_id) - environment = self.manager.create(scenario=scenario, config=self.config) - environment_id = uuid.uuid4().hex - result = environment.reset().model_dump(mode="json") - terminal = not bool(result.get("valid")) - if terminal: - environment.close() - with self._lock: - self._prune_terminal_environments() - self.environments[environment_id] = _EnvironmentSlot( - None if terminal else environment, - case_id, - terminal=terminal, - terminal_at=time.monotonic() if terminal else None, - ) - self._prune_terminal_environments() - self._record_event( - { - "event": "create", - "environment_id": environment_id, - "case_id": case_id, - "valid": result.get("valid"), - "state": result.get("state"), - "error": result.get("error"), - } - ) - return {"environment_id": environment_id, "reset": result} - - def step(self, environment_id: str, action: dict[str, Any]) -> dict[str, Any]: - with self._lock: - self._prune_terminal_environments() - slot = self.environments.get(environment_id) - if slot is None: - raise KeyError(environment_id) - with slot.lock: - if slot.terminal: - raise TerminalEnvironmentError(environment_id) - environment = slot.environment - if environment is None: - raise TerminalEnvironmentError(environment_id) - try: - parsed = _ACTION_ADAPTER.validate_python(action) - except ValidationError as exc: - result = environment.terminate_protocol(str(exc)).model_dump(mode="json") - else: - result = environment.step(parsed).model_dump(mode="json") - slot.terminal = result.get("state") == "terminal" - if slot.terminal: - environment.close() - slot.environment = None - slot.terminal_at = time.monotonic() - with self._lock: - self._prune_terminal_environments() - self._record_event( - { - "event": "step", - "environment_id": environment_id, - "case_id": slot.case_id, - "action_type": action.get("type"), - "result": self._summarize_result(result), - } - ) - return result - - def delete(self, environment_id: str) -> None: - with self._lock: - slot = self.environments.pop(environment_id, None) - if slot is None: - raise KeyError(environment_id) - with slot.lock: - if slot.environment is not None: - slot.environment.close() - slot.environment = None - self._record_event({"event": "delete", "environment_id": environment_id, "case_id": slot.case_id}) - - def close(self) -> None: - with self._lock: - slots = list(self.environments.values()) - self.environments.clear() - for slot in slots: - try: - with slot.lock: - if slot.environment is not None: - slot.environment.close() - slot.environment = None - except Exception: - logger.warning("Failed to close simulator environment", exc_info=True) - self.manager.close() - - def _record_event(self, event: dict[str, Any]) -> None: - if self._event_log is None: - return - payload = {"timestamp": datetime.now(UTC).isoformat(), **event} - serialized = json.dumps(payload, ensure_ascii=False, sort_keys=True) + "\n" - with self._event_lock: - self._rotate_event_log(len(serialized.encode("utf-8"))) - with self._event_log.open("a", encoding="utf-8") as stream: - stream.write(serialized) - - def _prune_terminal_environments(self) -> None: - """Keep lightweight terminal tombstones briefly for stable HTTP semantics.""" - now = time.monotonic() - terminal = [ - (environment_id, slot) - for environment_id, slot in self.environments.items() - if slot.terminal and slot.environment is None and slot.terminal_at is not None - ] - for environment_id, slot in terminal: - terminal_at = slot.terminal_at - if terminal_at is not None and now - terminal_at >= _TERMINAL_TOMBSTONE_TTL_SECONDS: - self.environments.pop(environment_id, None) - terminal_ids = [ - environment_id - for environment_id, slot in sorted( - self.environments.items(), - key=lambda item: item[1].terminal_at or float("inf"), - ) - if slot.terminal and slot.environment is None - ] - for environment_id in terminal_ids[:-_MAX_TERMINAL_TOMBSTONES]: - self.environments.pop(environment_id, None) - - @staticmethod - def _summarize_result(result: dict[str, Any]) -> dict[str, Any]: - keys = ( - "valid", - "case_valid", - "state", - "reward", - "reward_components", - "metrics", - "termination_reason", - "failure", - "cleanup_failure", - "cleanup_status", - "error", - ) - return {key: result[key] for key in keys if key in result} - - def _rotate_event_log(self, incoming_bytes: int) -> None: - if self._event_log is None or not self._event_log.exists(): - return - if self._event_log.stat().st_size + incoming_bytes <= _EVENT_LOG_MAX_BYTES: - return - oldest = self._event_log.with_name(f"{self._event_log.name}.{_EVENT_LOG_BACKUP_COUNT}") - oldest.unlink(missing_ok=True) - for index in range(_EVENT_LOG_BACKUP_COUNT - 1, 0, -1): - source = self._event_log.with_name(f"{self._event_log.name}.{index}") - if source.exists(): - os.replace(source, self._event_log.with_name(f"{self._event_log.name}.{index + 1}")) - os.replace(self._event_log, self._event_log.with_name(f"{self._event_log.name}.1")) - - -def create_app(service: SimulatorService): - try: - from fastapi import FastAPI, HTTPException - except ImportError as exc: - raise RuntimeError("Install NetOpsBench with the 'simulator' extra to run the service") from exc - - @asynccontextmanager - async def lifespan(_app): - yield - service.close() - - app = FastAPI(title="NetOpsBench Simulator", version="1", lifespan=lifespan) - - @app.get("/v1/cases") - def list_cases(): - return {"case_ids": service.list_cases()} - - @app.post("/v1/environments") - def create_environment(request: CreateEnvironmentRequest): - try: - return service.create(request.case_id) - except KeyError as exc: - raise HTTPException(status_code=404, detail="Unknown simulator case") from exc - - @app.post("/v1/environments/{environment_id}/actions") - def step_environment(environment_id: str, request: StepRequest): - try: - return service.step(environment_id, request.action) - except KeyError as exc: - raise HTTPException(status_code=404, detail="Unknown simulator environment") from exc - except TerminalEnvironmentError as exc: - raise HTTPException(status_code=409, detail="Simulator environment is terminal") from exc - - @app.delete("/v1/environments/{environment_id}") - def delete_environment(environment_id: str): - try: - service.delete(environment_id) - except KeyError as exc: - raise HTTPException(status_code=404, detail="Unknown simulator environment") from exc - return {"deleted": True} - - return app - - -__all__ = [ - "CreateEnvironmentRequest", - "SimulatorService", - "StepRequest", - "TerminalEnvironmentError", - "create_app", - "scenario_case_id", -] diff --git a/netopsbench/platform/toolkit/_core/common.py b/netopsbench/platform/toolkit/_core/common.py index 53646b5..279246d 100644 --- a/netopsbench/platform/toolkit/_core/common.py +++ b/netopsbench/platform/toolkit/_core/common.py @@ -1,9 +1,17 @@ """Shared agent toolkit types.""" from dataclasses import asdict, dataclass +from enum import StrEnum from typing import Any +class PublicArgumentError(StrEnum): + """Fixed, safe argument guidance; never contains runtime or user-supplied text.""" + + BGP_VIEW = "Invalid view: use detail or advertised_routes (aliases: advertised-routes, advertised). Received routes are not supported." + BGP_FORMAT = "Invalid format: use structured, raw or both (json is an alias for structured)." + + @dataclass class ToolResult: """Result from a tool invocation.""" diff --git a/netopsbench/platform/toolkit/_core/control.py b/netopsbench/platform/toolkit/_core/control.py new file mode 100644 index 0000000..1c00fe1 --- /dev/null +++ b/netopsbench/platform/toolkit/_core/control.py @@ -0,0 +1,76 @@ +"""Propagate a diagnostic session's remaining time into existing tool transports.""" + +from __future__ import annotations + +import asyncio +import time +from contextlib import asynccontextmanager, contextmanager +from contextvars import ContextVar +from dataclasses import dataclass + +from netopsbench.platform.utils.control import OperationControl + +_current_control: ContextVar[OperationControl | None] = ContextVar("diagnostic_tool_control", default=None) +_current_budget = ContextVar("diagnosis_budget", default=None) + + +@dataclass +class _DiagnosisBudget: + deadline: float + timer: asyncio.Timeout + parent: _DiagnosisBudget | None + finished_at: float | None = None + + +@asynccontextmanager +async def diagnosis_budget_scope(seconds: float | None): + """Share the earliest work deadline; required cleanup has separate timing.""" + previous = _current_budget.get() + deadline = time.monotonic() + seconds if seconds is not None else None + if previous is not None and (deadline is None or previous.deadline <= deadline): + yield previous + return + if deadline is None: + yield None + return + budget = _DiagnosisBudget(deadline, asyncio.timeout_at(deadline), previous) + token = _current_budget.set(budget) + try: + with tool_deadline_scope(deadline): + async with budget.timer: + yield budget + # Sync work can block the event loop past its deadline. + if (budget.finished_at if budget.finished_at is not None else time.monotonic()) >= deadline: + raise TimeoutError("Total diagnosis timeout exceeded") + finally: + _current_budget.reset(token) + + +def finish_diagnosis_work(): + """Stop work timers when the adapter enters its final resource cleanup.""" + budget = _current_budget.get() + now = time.monotonic() + while budget is not None: + if budget.finished_at is None: + budget.finished_at = now + if not budget.timer.expired(): + budget.timer.reschedule(None) + budget = budget.parent + + +def current_tool_control() -> OperationControl | None: + return _current_control.get() + + +@contextmanager +def tool_deadline_scope(deadline: float): + previous = current_tool_control() + control = OperationControl( + deadline=min(previous.deadline, deadline) if previous and previous.deadline else deadline + ) + token = _current_control.set(control) + try: + control.remaining() + yield control + finally: + _current_control.reset(token) diff --git a/netopsbench/platform/toolkit/_core/device/connectivity_ops.py b/netopsbench/platform/toolkit/_core/device/connectivity_ops.py index 5048ba8..e0936d0 100644 --- a/netopsbench/platform/toolkit/_core/device/connectivity_ops.py +++ b/netopsbench/platform/toolkit/_core/device/connectivity_ops.py @@ -10,8 +10,10 @@ class ConnectivityOpsMixin: - def traceroute(self, src: str, dst_ip: str) -> ToolResult: + def traceroute(self, src: str, dst_ip: str, max_hops: int = 8) -> ToolResult: try: + if not 1 <= max_hops <= 32: + raise ValueError("max_hops must be in 1..32") safe_src = self._validate_device_name(src, field_name="source") safe_dst_ip = self._validate_ip_address(dst_ip, field_name="destination IP") source_device = self.manifest.device(safe_src) @@ -19,13 +21,13 @@ def traceroute(self, src: str, dst_ip: str) -> ToolResult: raise ValueError(f"Unknown source: {safe_src}") if source_device.role is not DeviceRole.CLIENT: raise ValueError( - "Traceroute source must be a client device, " f"got {safe_src} ({source_device.role.value})" + f"Traceroute source must be a client device, got {safe_src} ({source_device.role.value})" ) container = self._resolve_container(safe_src, field_name="source") result = self._docker_exec( container, - ["traceroute", "-n", "-q", "1", "-w", "1", "-m", "8", safe_dst_ip], - timeout=12, + ["traceroute", "-n", "-q", "1", "-w", "1", "-m", str(max_hops), safe_dst_ip], + timeout=max_hops + 4, ) if result.returncode != 0: output = (result.stderr or result.stdout or "unknown error").strip() @@ -63,6 +65,16 @@ def ping_test( cmd.extend(["-M", "do"]) cmd.append(safe_dst_ip) result = self._docker_exec(container, cmd, timeout=30) + # Docker/OCI execution failures are not ping observations. iputils + # itself uses 1 for unanswered probes and 2 for local errors (e.g. + # "message too long, mtu=..."); retain those diagnostic messages. + if result.returncode not in {0, 1, 2} or ( + result.returncode + and not result.stdout + and result.stderr + and not result.stderr.lstrip().startswith("ping:") + ): + return ToolResult(success=False, data=None, error="Probe execution unavailable") return ToolResult( success=True, data={ diff --git a/netopsbench/platform/toolkit/_core/device/interface_ops.py b/netopsbench/platform/toolkit/_core/device/interface_ops.py index 5d4f213..731ddbc 100644 --- a/netopsbench/platform/toolkit/_core/device/interface_ops.py +++ b/netopsbench/platform/toolkit/_core/device/interface_ops.py @@ -1,80 +1,104 @@ -"""Interface-oriented device toolkit operations.""" +"""Interface observations without simulator traffic-control state.""" from __future__ import annotations +import json +import re import subprocess +from datetime import UTC, datetime from netopsbench.platform.topology.topology_utils import is_network_device_name +from netopsbench.platform.utils.interface_names import are_interfaces_equivalent from ..common import ToolResult from .interface_parsers import merge_interface_tables, parse_ip_link_stats from .text_parsers import parse_table +def _link_observations(text: str, interface: str | None) -> str: + """Select complete ip-link records and omit the qdisc implementation field.""" + blocks = re.split(r"(?m)(?=^\d+: )", text) + selected = [] + for block in blocks: + match = re.match(r"^\d+:\s+([^:@]+)(?:@[^:]+)?:", block) + if not match or (interface and not are_interfaces_equivalent(match[1], interface)): + continue + lines = block.splitlines(keepends=True) + lines[0] = re.sub(r"\s+qdisc\s+\S+", "", lines[0]) + selected.append("".join(lines)) + return "".join(selected) + + +def _interface_table(text: str, interface: str | None) -> str: + if not interface: + return text + # Keep table headings/separators, selecting rows by their first column. + return "\n".join( + line + for line in text.splitlines() + if not line.strip() + or line.lstrip().startswith(("Interface", "IFACE", "Port", "---")) + or are_interfaces_equivalent(line.split()[0], interface) + ) + + class InterfaceOpsMixin: - def get_device_interfaces(self, device: str, format: str = "structured") -> ToolResult: + def get_device_interfaces( + self, device: str, format: str = "structured", interface: str | None = None + ) -> ToolResult: try: self._validate_device_name(device) - safe_format = (format or "raw").lower() - if safe_format not in {"raw", "structured", "summary", "both"}: + if interface is not None: + self._validate_interface_name(interface) + view = (format or "raw").lower() + if view not in {"raw", "structured", "summary", "both"}: return ToolResult(success=False, data=None, error=f"Invalid format: {format}") container = self._resolve_container(device) + raw = None if is_network_device_name(device): - brief_result = self._docker_exec(container, ["bash", "-lc", "show interfaces status"], timeout=30) - detail_result = self._docker_exec(container, ["bash", "-lc", "show interfaces counters"], timeout=30) - if brief_result.returncode != 0 and detail_result.returncode != 0: - fallback = self._docker_exec(container, ["ip", "-s", "link", "show"], timeout=30) - if fallback.returncode != 0: - return ToolResult(success=False, data=None, error=fallback.stderr) - raw_data = { - "device": device, - "brief": "show interfaces status unavailable; using ip link", - "detail": fallback.stdout, - } - structured = parse_ip_link_stats(fallback.stdout) - if safe_format == "summary": - return ToolResult(success=True, data=self._summarize_interface_data(device, structured)) - if safe_format == "structured": - return ToolResult(success=True, data={"device": device, "interfaces": structured}) - if safe_format == "both": - return ToolResult( - success=True, data={"device": device, "raw": raw_data, "structured": structured} - ) - return ToolResult(success=True, data=raw_data) - raw_data = { - "device": device, - "brief": brief_result.stdout if brief_result.returncode == 0 else "Unable to get brief", - "detail": detail_result.stdout if detail_result.returncode == 0 else "Unable to get details", + brief = self._docker_exec(container, ["bash", "-lc", "show interfaces status"], timeout=30) + detail = self._docker_exec(container, ["bash", "-lc", "show interfaces counters"], timeout=30) + if brief.returncode == 0 or detail.returncode == 0: + brief_text = _interface_table(brief.stdout if brief.returncode == 0 else "", interface) + detail_text = _interface_table(detail.stdout if detail.returncode == 0 else "", interface) + raw = {"device": device, "brief": brief_text, "detail": detail_text} + rows = merge_interface_tables(parse_table(brief_text), parse_table(detail_text)) + # SONiC's port tables omit real non-port interfaces such as lo and + # management interfaces. Check Linux before declaring one absent. + if raw is None or (interface and not rows): + result = self._docker_exec(container, ["ip", "-s", "link", "show"], timeout=30) + if result.returncode: + return ToolResult(success=False, data=None, error="Interface state unavailable") + text = _link_observations(result.stdout, interface) + rows = parse_ip_link_stats(text) + raw = {"device": device, "interfaces": text} + if interface and not rows: + return ToolResult(success=False, data=None, error="Interface not found in collected device state") + structured = {"device": device, "interfaces": rows} + if not rows: + structured["warning"] = "Unable to parse interface tables; check raw output." + data = raw if view == "raw" else structured + if view == "summary": + data = self._summarize_interface_data(device, rows) + elif view == "both": + data = {"device": device, "raw": raw, "structured": structured} + addresses = self._docker_exec(container, ["ip", "-j", "-4", "addr", "show"], timeout=30) + if addresses.returncode: + data["address_collection_error"] = "Address collection failed" + else: + data["addresses"] = { + row["ifname"]: [f"{a['local']}/{a['prefixlen']}" for a in row.get("addr_info", [])] + for row in json.loads(addresses.stdout) + if not interface or are_interfaces_equivalent(row["ifname"], interface) } - if safe_format in {"structured", "summary", "both"}: - status_rows = parse_table(brief_result.stdout if brief_result.returncode == 0 else "") - counter_rows = parse_table(detail_result.stdout if detail_result.returncode == 0 else "") - merged = merge_interface_tables(status_rows, counter_rows) - structured = {"device": device, "interfaces": merged} - if not merged: - structured["warning"] = "Unable to parse interface tables; check raw output." - if safe_format == "summary": - return ToolResult(success=True, data=self._summarize_interface_data(device, merged)) - if safe_format == "structured": - return ToolResult(success=True, data=structured) - return ToolResult(success=True, data={"device": device, "raw": raw_data, "structured": structured}) - return ToolResult(success=True, data=raw_data) - result = self._docker_exec(container, ["ip", "-s", "link", "show"], timeout=30) - if result.returncode != 0: - return ToolResult(success=False, data=None, error=result.stderr) - raw_data = {"device": device, "interfaces": result.stdout} - if safe_format in {"structured", "summary", "both"}: - structured = parse_ip_link_stats(result.stdout) - if safe_format == "summary": - return ToolResult(success=True, data=self._summarize_interface_data(device, structured)) - if safe_format == "structured": - return ToolResult(success=True, data={"device": device, "interfaces": structured}) - return ToolResult(success=True, data={"device": device, "raw": raw_data, "structured": structured}) - return ToolResult(success=True, data=raw_data) + data["collected_at"] = datetime.now(UTC).isoformat() + return ToolResult(success=True, data=data) except subprocess.TimeoutExpired: return ToolResult(success=False, data=None, error="Command timed out") - except Exception as e: - return ToolResult(success=False, data=None, error=str(e)) + except ValueError: + return ToolResult(success=False, data=None, error="Invalid interface request or device response") + except Exception: + return ToolResult(success=False, data=None, error="Interface collection failed") @staticmethod def _summarize_interface_data(device: str, interfaces: list[dict]) -> dict: diff --git a/netopsbench/platform/toolkit/_core/device/interface_parsers.py b/netopsbench/platform/toolkit/_core/device/interface_parsers.py index eefcbe2..173732c 100644 --- a/netopsbench/platform/toolkit/_core/device/interface_parsers.py +++ b/netopsbench/platform/toolkit/_core/device/interface_parsers.py @@ -43,11 +43,17 @@ def parse_ip_link_stats(text: str) -> list[dict[str, Any]]: if not match: i += 1 continue - name = match.group(1) + name = match.group(1).split("@", 1)[0] entry: dict[str, Any] = {"name": name} mtu_match = re.search(r"\bmtu\s+(\d+)", line) if mtu_match: entry["mtu"] = int(mtu_match.group(1)) + state = re.search(r"\bstate\s+(\S+)", line) + if state: + entry["state"] = state[1] + flags = re.search(r"<([^>]*)>", line) + if flags: + entry["admin"] = "up" if "UP" in flags[1].split(",") else "down" i += 1 while i < len(lines) and lines[i].startswith(" "): sub = lines[i].strip() @@ -72,14 +78,7 @@ def parse_ip_link_stats(text: str) -> list[dict[str, Any]]: return results -def get_live_interface_snapshot(toolkit, device: str, interface: str) -> dict[str, Any] | None: - result = toolkit.get_device_interfaces(device, format="structured") - if not result.success: - return None - data = result.data or {} - interfaces = data.get("interfaces", []) - if not isinstance(interfaces, list): - return None +def select_live_interface(interfaces: list[dict], interface: str) -> dict[str, Any] | None: candidate_names = set(resolve_interface_metric_identities(interface)["names"]) for entry in interfaces: if not isinstance(entry, dict): @@ -90,14 +89,7 @@ def get_live_interface_snapshot(toolkit, device: str, interface: str) -> dict[st return None -def get_active_interface_names(toolkit, device: str) -> list[str]: - result = toolkit.get_device_interfaces(device, format="structured") - if not result.success: - return [] - data = result.data or {} - interfaces = data.get("interfaces", []) - if not isinstance(interfaces, list): - return [] +def active_interface_names(interfaces: list[dict]) -> list[str]: active: list[str] = [] for entry in interfaces: if not isinstance(entry, dict): diff --git a/netopsbench/platform/toolkit/_core/device/log_ops.py b/netopsbench/platform/toolkit/_core/device/log_ops.py index 56f2f73..948db3f 100644 --- a/netopsbench/platform/toolkit/_core/device/log_ops.py +++ b/netopsbench/platform/toolkit/_core/device/log_ops.py @@ -2,6 +2,8 @@ from __future__ import annotations +import json + from netopsbench.platform.observability.influxdb import query_flux from ..common import ToolResult @@ -22,34 +24,13 @@ def get_device_logs( try: safe_device = self._validate_device_name(device) safe_minutes = max(1, min(int(time_range_minutes), 24 * 60)) - explicit_start = str(start_time or "").strip() - explicit_end = str(end_time or "").strip() - if bool(explicit_start) != bool(explicit_end): - raise ValueError("start_time and end_time must be provided together") - start_dt = end_dt = None - if explicit_start: - start_dt = parse_iso8601_timestamp(explicit_start, "start_time") - end_dt = parse_iso8601_timestamp(explicit_end, "end_time") - if start_dt >= end_dt: - raise ValueError("start_time must be earlier than end_time") - normalized_start = start_dt.isoformat().replace("+00:00", "Z") - normalized_end = end_dt.isoformat().replace("+00:00", "Z") - range_clause = ( - f' |> range(start: time(v: "{normalized_start}"), ' f'stop: time(v: "{normalized_end}"))' - ) - time_scope = { - "mode": "absolute", - "source": "explicit", - "start_time": normalized_start, - "end_time": normalized_end, - } - else: - range_clause = f" |> range(start: -{safe_minutes}m)" - time_scope = { - "mode": "rolling", - "source": "time_range_minutes", - "time_range_minutes": safe_minutes, - } + scope = self._resolve_pingmesh_time_scope(safe_minutes, start_time, end_time) + range_clause = scope["range_clause"] + time_scope = {key: value for key, value in scope.items() if key != "range_clause"} + start_dt = ( + parse_iso8601_timestamp(scope["start_time"], "start_time") if scope["mode"] == "absolute" else None + ) + end_dt = parse_iso8601_timestamp(scope["end_time"], "end_time") if scope["mode"] == "absolute" else None severity_filter = "" if severity: safe_severity = severity.lower() @@ -61,6 +42,7 @@ def get_device_logs( query = f"""\nfrom(bucket: "{self.influxdb_bucket}") {range_clause} |> filter(fn: (r) => r._measurement == "syslog") + |> filter(fn: (r) => r.topology_id == {json.dumps(self.topology_id)}) |> filter(fn: (r) => r.source == "{safe_device}") |> filter(fn: (r) => r._field == "message") {severity_filter} diff --git a/netopsbench/platform/toolkit/_core/device/routing_ops.py b/netopsbench/platform/toolkit/_core/device/routing_ops.py index a1d042a..ecc236c 100644 --- a/netopsbench/platform/toolkit/_core/device/routing_ops.py +++ b/netopsbench/platform/toolkit/_core/device/routing_ops.py @@ -2,25 +2,77 @@ from __future__ import annotations +import json +import re import subprocess +from datetime import UTC, datetime from netopsbench.logging_utils import get_logger from netopsbench.platform.observability.bgp_parser import parse_bgp_summary from netopsbench.platform.topology.topology_utils import is_network_device_name -from ..common import ToolResult, truncate_text_lines +from ..common import PublicArgumentError, ToolResult, truncate_text_lines from .route_parsers import parse_route_table logger = get_logger(__name__) class RoutingOpsMixin: + def get_device_status(self, device: str) -> ToolResult: + """Read container, accessibility and supported service state without diagnosis labels.""" + import time + + from netopsbench.platform.utils.control import OperationControl + from netopsbench.platform.utils.proc import docker_prefix, safe_run + + try: + container = self._resolve_container(device) + from ..control import current_tool_control + + parent = current_tool_control() + deadline = time.monotonic() + 30 + control = OperationControl(deadline=min(deadline, parent.deadline) if parent else deadline) + result = safe_run( + [*docker_prefix(), "docker", "inspect", "--format", "{{json .State}}", container], + timeout=control.remaining(15), + control=control, + ) + if result.returncode: + return ToolResult(success=False, data=None, error=result.stderr or "Cannot inspect node") + state = json.loads(result.stdout) + data = { + "device": device, + "running": bool(state.get("Running")), + "runtime_state": state.get("Status"), + "accessible": False, + "services": {}, + "collected_at": datetime.now(UTC).isoformat(), + } + if data["running"]: + probe = self._docker_exec(container, ["true"], timeout=control.remaining(5)) + data["accessible"] = probe.returncode == 0 + if is_network_device_name(device) and data["accessible"]: + services = self._docker_exec( + container, ["supervisorctl", "status", "bgpd", "zebra"], timeout=control.remaining(10) + ) + for line in services.stdout.splitlines(): + fields = line.split() + if len(fields) >= 2 and fields[0] in {"bgpd", "zebra"}: + data["services"][fields[0]] = fields[1] + if not data["services"]: + data["service_collection_error"] = services.stderr or "Service states unavailable" + return ToolResult(success=True, data=data) + except Exception as exc: + return ToolResult(success=False, data=None, error=str(exc)) + def get_bgp_neighbors(self, device: str, format: str = "structured") -> ToolResult: try: - self._validate_device_name(device) safe_format = (format or "raw").lower() + if safe_format == "json": + safe_format = "structured" if safe_format not in {"raw", "structured", "both"}: - return ToolResult(success=False, data=None, error=f"Invalid format: {format}") + return ToolResult(success=False, data=None, error=PublicArgumentError.BGP_FORMAT) + self._validate_device_name(device) if not is_network_device_name(device): return ToolResult(success=False, data=None, error=f"Device {device} does not run BGP") container = self._resolve_container(device) @@ -48,14 +100,42 @@ def get_bgp_neighbors(self, device: str, format: str = "structured") -> ToolResu except Exception as e: return ToolResult(success=False, data=None, error=str(e)) - def get_bgp_neighbor(self, device: str, peer: str) -> ToolResult: + def get_bgp_neighbor(self, device: str, peer: str, view: str = "detail", prefix: str | None = None) -> ToolResult: """Return live detail for one BGP session on one device.""" + if view in {"advertised-routes", "advertised"}: + view = "advertised_routes" + if view not in {"detail", "advertised_routes"}: + return ToolResult(success=False, data=None, error=PublicArgumentError.BGP_VIEW) try: self._validate_device_name(device) safe_peer = self._validate_ip_address(peer, "peer") if not is_network_device_name(device): return ToolResult(success=False, data=None, error=f"Device {device} does not run BGP") container = self._resolve_container(device) + if view == "advertised_routes": + safe_prefix = self._validate_prefix(prefix) if prefix else None + result = self._docker_exec( + container, + ["vtysh", "-c", f"show bgp ipv4 unicast neighbors {safe_peer} advertised-routes json"], + timeout=30, + ) + if result.returncode: + return ToolResult(success=False, data=None, error=result.stderr) + advertised = json.loads(result.stdout) + routes = advertised.get("advertisedRoutes", {}) + if safe_prefix: + routes = {key: value for key, value in routes.items() if key == safe_prefix} + return ToolResult( + success=True, + data={ + "device": device, + "peer": safe_peer, + "prefix": safe_prefix, + "view": view, + "advertised_routes": routes, + "collected_at": datetime.now(UTC).isoformat(), + }, + ) detail_result = self._docker_exec( container, ["vtysh", "-c", f"show ip bgp neighbors {safe_peer}"], @@ -155,6 +235,7 @@ def get_route_table( format: str = "structured", max_routes: int = 100, max_lines: int = 500, + view: str = "frr", ) -> ToolResult: try: self._validate_device_name(device) @@ -164,6 +245,32 @@ def get_route_table( if not is_network_device_name(device): return ToolResult(success=False, data=None, error=f"Device {device} is not a router") container = self._resolve_container(device) + if view not in {"frr", "kernel"}: + raise ValueError("view must be frr or kernel") + if view == "kernel": + safe_prefix = self._validate_prefix(prefix) if prefix else None + command = ["ip", "-j", "-4", "route", "show"] + if safe_prefix: + command += ["exact", safe_prefix] + result = self._docker_exec(container, command, timeout=30) + if result.returncode: + return ToolResult(success=False, data=None, error=result.stderr) + rows = json.loads(result.stdout) + limit = max(1, min(int(max_routes), 1000)) + structured = { + "device": device, + "prefix": safe_prefix, + "view": view, + "routes": rows[:limit], + "total_routes": len(rows), + "truncated": len(rows) > limit, + "collected_at": datetime.now(UTC).isoformat(), + } + if safe_format == "raw": + structured = {"device": device, "prefix": safe_prefix, "view": view, "route_table": result.stdout} + elif safe_format == "both": + structured = {"device": device, "raw": {"route_table": result.stdout}, "structured": structured} + return ToolResult(success=True, data=structured) if prefix: safe_prefix = self._validate_prefix(prefix) sr_command = f"show ip route {safe_prefix}" @@ -204,17 +311,14 @@ def get_device_config(self, device: str, section: str = "", max_lines: int = 500 if not is_network_device_name(device): return ToolResult(success=False, data=None, error=f"Device {device} does not support running-config") container = self._resolve_container(device) - if section: - import re - - safe_section = re.sub(r"[^a-zA-Z0-9 _-]", "", section) - cmd = f"show running-config | section {safe_section}" - else: - cmd = "show running-config" - result = self._docker_exec(container, ["vtysh", "-c", cmd], timeout=30) + result = self._docker_exec(container, ["vtysh", "-c", "show running-config"], timeout=30) if result.returncode != 0: return ToolResult(success=False, data=None, error=result.stderr) - config_text, config_meta = truncate_text_lines(result.stdout, max_lines) + text = result.stdout + if section: + blocks = re.split(r"(?m)^!\s*$", text) + text = "\n!\n".join(block.strip("\n") for block in blocks if section.lower() in block.lower()) + config_text, config_meta = truncate_text_lines(text, max_lines) return ToolResult( success=True, data={ @@ -310,6 +414,16 @@ def get_device_acl(self, device: str, view: str = "summary", max_lines: int = 30 "sonic_acl_line_count": sonic_meta["total_lines"], "iptables_line_count": iptables_meta["total_lines"], "truncated": sonic_meta["truncated"] or iptables_meta["truncated"], + "collected_at": datetime.now(UTC).isoformat(), + "collection_errors": [ + {"source": source, "error": result.stderr or "Command failed"} + for source, result in ( + ("acl_tables", acl_table_result), + ("acl_rules", acl_rule_result), + ("iptables", ipt_result), + ) + if result.returncode + ], } if safe_view in {"summary", "frr", "all"}: data["sonic_acl_config"] = sonic_acl_output @@ -317,7 +431,8 @@ def get_device_acl(self, device: str, view: str = "summary", max_lines: int = 30 if safe_view in {"summary", "iptables", "all"}: data["iptables_forward_rules"] = iptables_rules data["iptables_truncated"] = iptables_meta["truncated"] - return ToolResult(success=True, data=data) + available = len(data["collection_errors"]) < 3 + return ToolResult(success=available, data=data, error=None if available else "ACL state unavailable") except subprocess.TimeoutExpired: return ToolResult(success=False, data=None, error="Command timed out") except Exception as e: diff --git a/netopsbench/platform/toolkit/_core/device/telemetry_parsers.py b/netopsbench/platform/toolkit/_core/device/telemetry_parsers.py index e8381af..bc9d7f2 100644 --- a/netopsbench/platform/toolkit/_core/device/telemetry_parsers.py +++ b/netopsbench/platform/toolkit/_core/device/telemetry_parsers.py @@ -3,13 +3,13 @@ from __future__ import annotations import csv +import json import re from dataclasses import dataclass, field from datetime import datetime -from io import StringIO from typing import Any, Literal -from netopsbench.platform.observability.influxdb import query_flux +from netopsbench.platform.observability.influxdb import iter_annotated_csv_rows, query_flux def parse_influx_timestamp(value: str | None) -> datetime | None: @@ -83,7 +83,8 @@ def get_recent_influx_interface_identities( ) -> list[dict[str, str | None]]: safe_device = toolkit._validate_device_name(device) safe_minutes = max(1, min(int(time_range_minutes), 24 * 60)) - query = f"""\nfrom(bucket: "{toolkit.influxdb_bucket}")\n |> range(start: -{safe_minutes}m)\n |> filter(fn: (r) => r._measurement == "interfaces")\n |> filter(fn: (r) => r.source == "{safe_device}")\n |> keep(columns: ["_time", "name", "path", "source"])\n |> limit(n: 2000)\n""" + scope = toolkit._resolve_pingmesh_time_scope(safe_minutes) + query = f"""\nfrom(bucket: "{toolkit.influxdb_bucket}")\n{scope["range_clause"]}\n |> filter(fn: (r) => r._measurement == "interfaces")\n |> filter(fn: (r) => r.topology_id == {json.dumps(toolkit.topology_id)})\n |> filter(fn: (r) => r.source == "{safe_device}")\n |> keep(columns: ["_time", "name", "path", "source"])\n |> limit(n: 2000)\n""" result = query_flux( toolkit.influxdb_url, toolkit.influxdb_token, @@ -147,27 +148,16 @@ class InfluxQueryError(RuntimeError): """Raised when a structured InfluxDB query result reports failure.""" -def _iter_annotated_csv_rows(csv_text: str): - """Parse Flux CSV while honoring the repeated headers emitted by multiple yields.""" - header: list[str] | None = None - for values in csv.reader(StringIO(csv_text)): - if not values or (values[0] and values[0].startswith("#")): - continue - if "result" in values and "table" in values: - header = values - continue - if header is None: - continue - padded = [*values, *([""] * max(0, len(header) - len(values)))] - yield dict(zip(header, padded[: len(header)], strict=False)) - - def query_influx(toolkit, query: str, require_value: bool = True) -> InfluxQueryResult: - result = query_flux(toolkit.influxdb_url, toolkit.influxdb_token, toolkit.influxdb_org, query) + from ..control import current_tool_control + + control = current_tool_control() + kwargs = {"timeout": control.remaining(60), "deadline": control.deadline} if control else {} + result = query_flux(toolkit.influxdb_url, toolkit.influxdb_token, toolkit.influxdb_org, query, **kwargs) if result.status != "ok": return InfluxQueryResult(status="error", error=result.error) rows: list[dict[str, Any]] = [] - for row in _iter_annotated_csv_rows(result.text): + for row in iter_annotated_csv_rows(result.text): if row.get("result", "") == "result": continue if require_value and row.get("_value") in (None, ""): diff --git a/netopsbench/platform/toolkit/_core/device/validators.py b/netopsbench/platform/toolkit/_core/device/validators.py index d54b2a2..54e27c2 100644 --- a/netopsbench/platform/toolkit/_core/device/validators.py +++ b/netopsbench/platform/toolkit/_core/device/validators.py @@ -48,4 +48,7 @@ def resolve_container(toolkit, device: str, field_name: str = "device") -> str: def docker_exec(container: str, cmd_args: list[str], timeout: int) -> subprocess.CompletedProcess: args = [*docker_prefix(), "docker", "exec", container] + [str(arg) for arg in cmd_args] - return safe_run(args, capture_output=True, text=True, timeout=timeout, check=False) + from ..control import current_tool_control + + control = current_tool_control() + return safe_run(args, capture_output=True, text=True, timeout=timeout, check=False, control=control) diff --git a/netopsbench/platform/toolkit/_core/observability/bgp_ops.py b/netopsbench/platform/toolkit/_core/observability/bgp_ops.py index 0e0c4b7..55f7b09 100644 --- a/netopsbench/platform/toolkit/_core/observability/bgp_ops.py +++ b/netopsbench/platform/toolkit/_core/observability/bgp_ops.py @@ -26,6 +26,54 @@ def _bool(value: object) -> bool: return value is True or str(value).lower() == "true" +def _session_event(fields, states, transition_pairs, state_filter): + saw_down = any(value != "ESTABLISHED" for value in states) + down = any(before == "ESTABLISHED" and after != "ESTABLISHED" for before, after in transition_pairs) + recovered = any(before != "ESTABLISHED" and after == "ESTABLISHED" for before, after in transition_pairs) + if down and recovered: + event_type = "session_flap" + elif down: + event_type = "session_down" + elif recovered: + event_type = "session_recovered" + elif saw_down: + event_type = "non_established_observed" + elif state_filter == "all": + event_type = "established_observed" + else: + return None + if state_filter == "non_established" and not saw_down: + return None + if state_filter == "established" and fields["latest_state"] != "ESTABLISHED": + return None + return {**fields, "event_type": event_type, "states_observed": list(dict.fromkeys(states))} + + +def _with_collection_gaps(events, collections, roles, device, peer, role): + selected = {name for name, kind in roles.items() if (not device or name == device) and (not role or kind == role)} + missing = selected - collections.keys() if not peer or device else set() + for source in sorted(missing): + collections[source] = {"error_type": "no_collection_samples"} + for source, collection in collections.items(): + if not _bool(collection.get("collection_ok")): + events.append( + { + "device": source, + "role": roles[source], + "peer": None, + "event_type": "collection_gap", + "previous_state": None, + "latest_state": None, + "states_observed": [], + "first_seen": collection.get("first_seen"), + "last_seen": collection.get("last_seen"), + "sample_count": int(collection.get("sample_count") or 0), + "error_type": collection.get("error_type"), + } + ) + return sorted(events, key=lambda event: (str(event.get("last_seen") or ""), event["device"]), reverse=True) + + class BgpOpsMixin: def query_bgp_events( self, @@ -37,10 +85,13 @@ def query_bgp_events( role: str | None = None, state: str = "non_established", limit: int = 100, + event_type: str = "session", ) -> ToolResult: """Find BGP session transitions without logging in to every router.""" try: - if state not in _VALID_STATES: + if event_type not in {"session", "prefix_count"}: + raise ValueError("event_type must be session or prefix_count") + if event_type == "session" and state not in _VALID_STATES: raise ValueError(f"Invalid state: {state}. Expected one of {sorted(_VALID_STATES)}") safe_device = self._validate_device_name(device) if device else None safe_peer = self._validate_ip_address(peer, "peer") if peer else None @@ -60,6 +111,51 @@ def query_bgp_events( if (not safe_device or name == safe_device) and (not role or device_role == role) } role_filter = self._bgp_source_filter(selected_devices) if role and not safe_device else "" + if event_type == "prefix_count": + query = f""" +from(bucket: "{self.influxdb_bucket}") +{scope["range_clause"]} |> filter(fn: (r) => r._measurement == "bgp_prefix_events") + |> filter(fn: (r) => r.topology_id == "{self._flux_string(self.topology_id)}") +{filters + role_filter} |> pivot(rowKey: ["_time", "source", "neighbor_address"], columnKey: ["_field"], valueColumn: "_value") + |> group() |> sort(columns: ["_time"], desc: true) |> limit(n: {safe_limit + 1}) +""" + rows = self._query_influx_rows(query, require_value=False) + index_rows = self._query_bgp_event_index(scope, device_filter + role_filter) + index_complete = self._bgp_event_index_covers_scope(index_rows, scope, selected_devices) + collection_query = f""" +from(bucket: "{self.influxdb_bucket}") +{scope["range_clause"]} |> filter(fn: (r) => r._measurement == "bgp_collection") + |> filter(fn: (r) => r.topology_id == "{self._flux_string(self.topology_id)}") +{device_filter + role_filter} |> pivot(rowKey: ["_time", "source"], columnKey: ["_field"], valueColumn: "_value") + |> filter(fn: (r) => not r.collection_ok) + |> group() |> sort(columns: ["_time"], desc: true) |> limit(n: {safe_limit}) +""" + gaps = self._query_influx_rows(collection_query, require_value=False) + events = [ + { + "device": row.get("source"), + "peer": row.get("neighbor_address"), + "role": roles.get(row.get("source")), + "event_type": "prefix_count", + "prefixes_before": row.get("prefixes_before"), + "prefixes_after": row.get("prefixes_after"), + "timestamp": row.get("_time"), + } + for row in rows + ] + return ToolResult( + success=True, + data={ + "status": "ok" if index_complete and not gaps else "incomplete", + "collection_errors": gaps, + "event_type": event_type, + "time_scope": {k: v for k, v in scope.items() if k != "range_clause"}, + "events": events[:safe_limit], + "returned_events": min(len(events), safe_limit), + "truncated": len(events) > safe_limit, + "data_freshness_seconds": self._bgp_freshness_seconds(index_rows, scope), + }, + ) index_rows = self._query_bgp_event_index(scope, device_filter + role_filter) if self._bgp_event_index_covers_scope(index_rows, scope, selected_devices): rows = self._query_bgp_event_fast_rows( @@ -70,7 +166,6 @@ def query_bgp_events( ) events = self._build_bgp_events_fast( rows, - scope, roles, safe_device, safe_peer, @@ -83,7 +178,7 @@ def query_bgp_events( filters + role_filter, device_filter + role_filter, ) - events = self._build_bgp_events(rows, scope, roles, safe_device, safe_peer, role, state) + events = self._build_bgp_events(rows, roles, safe_device, safe_peer, role, state) truncated = len(events) > safe_limit returned = events[:safe_limit] freshness = self._bgp_freshness_seconds(rows + index_rows, scope) @@ -349,24 +444,11 @@ def _bgp_session_candidate_filter(self, candidates: set[tuple[str, str]]) -> str return f" |> filter(fn: (r) => {' or '.join(predicates)})\n" def _bgp_device_roles(self) -> dict[str, str]: - devices = self.topology_metadata.get("devices", []) if self.topology_metadata else [] - if isinstance(devices, dict): - return { - str(item["name"]): str(role).removesuffix("s") - for role, entries in devices.items() - for item in entries - if role != "clients" and item.get("name") - } - return { - str(item["name"]): str(item.get("role", "unknown")) - for item in devices - if item.get("name") and item.get("role") != "client" - } + return {device.name: device.role.value for device in self.manifest.switches()} def _build_bgp_events_fast( self, rows: list[dict[str, Any]], - scope: dict[str, Any], roles: dict[str, str], device: str | None, peer: str | None, @@ -460,7 +542,6 @@ def _build_bgp_events_fast( latest, ] states = list(dict.fromkeys(states)) - saw_down = any(value != "ESTABLISHED" for value in states) transition_pairs = [ ( @@ -471,29 +552,6 @@ def _build_bgp_events_fast( ] if previous is not None: transition_pairs.insert(0, (previous, first_state)) - down_transition = any( - before == "ESTABLISHED" and after != "ESTABLISHED" for before, after in transition_pairs - ) - recovery_transition = any( - before != "ESTABLISHED" and after == "ESTABLISHED" for before, after in transition_pairs - ) - if down_transition and recovery_transition: - event_type = "session_flap" - elif down_transition: - event_type = "session_down" - elif recovery_transition: - event_type = "session_recovered" - elif saw_down: - event_type = "non_established_observed" - elif state_filter == "all": - event_type = "established_observed" - else: - continue - if state_filter == "non_established" and not saw_down: - continue - if state_filter == "established" and latest != "ESTABLISHED": - continue - prefixes_after = session.get("prefixes_received") if _timestamp(session.get("prefixes_received_time")) != _timestamp(last_seen): prefixes_after = None @@ -502,69 +560,32 @@ def _build_bgp_events_fast( session.get("prior_session_state_time") ): prefixes_before = None - events.append( + event = _session_event( { "device": source, "role": roles[source], "peer": neighbor, "peer_as": session.get("asn"), - "event_type": event_type, "previous_state": previous, "latest_state": latest, - "states_observed": states, "first_seen": session.get("first_seen") or (transitions[0].get("_time") if transitions else None), "last_seen": last_seen, "sample_count": int(session.get("sample_count") or 0), "prefixes_before": prefixes_before, "prefixes_after": prefixes_after, - } + }, + states, + transition_pairs, + state_filter, ) + if event is not None: + events.append(event) - for source, collection in collections.items(): - if not _bool(collection.get("collection_ok")): - events.append( - { - "device": source, - "role": roles[source], - "peer": None, - "event_type": "collection_gap", - "previous_state": None, - "latest_state": None, - "states_observed": [], - "first_seen": collection.get("first_seen"), - "last_seen": collection.get("last_seen"), - "sample_count": int(collection.get("sample_count") or 0), - "error_type": collection.get("error_type"), - } - ) - selected_devices = { - name - for name, device_role in roles.items() - if (not device or name == device) and (not role or device_role == role) - } - missing_devices = selected_devices - collections.keys() if not peer or device else set() - for source in missing_devices: - events.append( - { - "device": source, - "role": roles[source], - "peer": None, - "event_type": "collection_gap", - "previous_state": None, - "latest_state": None, - "states_observed": [], - "first_seen": None, - "last_seen": None, - "sample_count": 0, - "error_type": "no_collection_samples", - } - ) - return sorted(events, key=lambda event: (str(event.get("last_seen") or ""), event["device"]), reverse=True) + return _with_collection_gaps(events, collections, roles, device, peer, role) def _build_bgp_events( self, rows: list[dict[str, Any]], - scope: dict[str, Any], roles: dict[str, str], device: str | None, peer: str | None, @@ -595,92 +616,39 @@ def _build_bgp_events( states = [str(row.get("session_state") or "UNKNOWN").upper() for row in window] previous = str(prior[-1].get("session_state") or "UNKNOWN").upper() if prior else None latest = states[-1] - saw_down = any(value != "ESTABLISHED" for value in states) transition_states = ([previous] if previous else []) + states - down_transition = any( - before == "ESTABLISHED" and after != "ESTABLISHED" - for before, after in zip(transition_states, transition_states[1:], strict=False) - ) - recovery_transition = any( - before != "ESTABLISHED" and after == "ESTABLISHED" - for before, after in zip(transition_states, transition_states[1:], strict=False) - ) - if down_transition and recovery_transition: - event_type = "session_flap" - elif down_transition: - event_type = "session_down" - elif recovery_transition: - event_type = "session_recovered" - elif saw_down: - event_type = "non_established_observed" - elif state_filter == "all": - event_type = "established_observed" - else: - continue - if state_filter == "non_established" and not saw_down: - continue - if state_filter == "established" and latest != "ESTABLISHED": - continue - unique_states = list(dict.fromkeys(states)) - events.append( + transition_pairs = list(zip(transition_states, transition_states[1:], strict=False)) + event = _session_event( { "device": source, "role": roles[source], "peer": neighbor, "peer_as": window[-1].get("asn"), - "event_type": event_type, "previous_state": previous, "latest_state": latest, - "states_observed": unique_states, "first_seen": window[0].get("_time"), "last_seen": window[-1].get("_time"), "sample_count": len(window), "prefixes_before": prior[-1].get("prefixes_received") if prior else None, "prefixes_after": window[-1].get("prefixes_received"), - } + }, + states, + transition_pairs, + state_filter, ) - - for source, samples in collections.items(): - latest = samples[-1] - if not _bool(latest.get("collection_ok")): - events.append( - { - "device": source, - "role": roles[source], - "peer": None, - "event_type": "collection_gap", - "previous_state": None, - "latest_state": None, - "states_observed": [], - "first_seen": samples[0].get("_time"), - "last_seen": latest.get("_time"), - "sample_count": len(samples), - "error_type": latest.get("error_type"), - } - ) - selected_devices = { - name - for name, device_role in roles.items() - if (not device or name == device) and (not role or device_role == role) + if event is not None: + events.append(event) + + collection_summaries = { + source: { + **samples[-1], + "first_seen": samples[0].get("_time"), + "last_seen": samples[-1].get("_time"), + "sample_count": len(samples), + } + for source, samples in collections.items() } - missing_devices = selected_devices - collections.keys() if not peer or device else set() - for source in missing_devices: - events.append( - { - "device": source, - "role": roles[source], - "peer": None, - "event_type": "collection_gap", - "previous_state": None, - "latest_state": None, - "states_observed": [], - "first_seen": None, - "last_seen": None, - "sample_count": 0, - "error_type": "no_collection_samples", - } - ) - return sorted(events, key=lambda event: (str(event.get("last_seen") or ""), event["device"]), reverse=True) + return _with_collection_gaps(events, collection_summaries, roles, device, peer, role) @staticmethod def _bgp_freshness_seconds(rows: list[dict[str, Any]], scope: dict[str, Any]) -> int | None: diff --git a/netopsbench/platform/toolkit/_core/observability/metrics_ops.py b/netopsbench/platform/toolkit/_core/observability/metrics_ops.py index c7d802c..f31e4eb 100644 --- a/netopsbench/platform/toolkit/_core/observability/metrics_ops.py +++ b/netopsbench/platform/toolkit/_core/observability/metrics_ops.py @@ -2,13 +2,14 @@ from __future__ import annotations +import json from typing import Any from netopsbench.platform.observability.influxdb import query_flux from netopsbench.platform.utils.interface_names import resolve_interface_metric_identities from ..common import ToolResult -from ..device.interface_parsers import get_active_interface_names, get_live_interface_snapshot +from ..device.interface_parsers import active_interface_names, select_live_interface from ..device.telemetry_parsers import ( get_recent_influx_interface_identities, parse_influx_metric_rows, @@ -31,6 +32,8 @@ def get_interface_metrics( safe_device = self._validate_device_name(device) safe_interface = self._validate_interface_name(interface) safe_minutes = max(1, min(int(time_range_minutes), 24 * 60)) + scope = self._resolve_pingmesh_time_scope(safe_minutes) + time_scope = {key: value for key, value in scope.items() if key != "range_clause"} safe_metric_type = (metric_type or "all").lower() safe_view = (view or "summary").lower() safe_max_points = max(1, min(int(max_points), 2000)) @@ -62,8 +65,9 @@ def get_interface_metrics( name_filter = " or ".join(identity_clauses) query = f""" from(bucket: "{self.influxdb_bucket}") - |> range(start: -{safe_minutes}m) +{scope["range_clause"]} |> filter(fn: (r) => r._measurement == "interfaces") + |> filter(fn: (r) => r.topology_id == {json.dumps(self.topology_id)}) |> filter(fn: (r) => r.source == "{safe_device}") |> filter(fn: (r) => {name_filter}) |> filter(fn: (r) => {field_filter}) @@ -82,6 +86,7 @@ def get_interface_metrics( "device": safe_device, "interface": safe_interface, "time_range_minutes": safe_minutes, + "time_scope": time_scope, "metric_type": safe_metric_type, "view": safe_view, "metrics": result.text, @@ -94,9 +99,11 @@ def get_interface_metrics( observed_interfaces = sorted( {str(item.get("name")).strip() for item in observed_identities if item.get("name")} ) - active_interfaces = get_active_interface_names(self, safe_device) + live = self.get_device_interfaces(safe_device, format="structured") + interfaces = live.data.get("interfaces", []) if live.success else [] + active_interfaces = active_interface_names(interfaces) missing_active_interfaces = [name for name in active_interfaces if name not in observed_interfaces] - live_snapshot = get_live_interface_snapshot(self, safe_device, safe_interface) + live_snapshot = select_live_interface(interfaces, safe_interface) warning_parts: list[str] = [] if observed_interfaces: warning_parts.append( @@ -122,12 +129,14 @@ def get_interface_metrics( "device": safe_device, "interface": safe_interface, "time_range_minutes": safe_minutes, + "time_scope": time_scope, "metric_type": safe_metric_type, "view": safe_view, "summary": {}, "series": {}, "warning": warning, "current_snapshot": live_snapshot, + "snapshot_collected_at": live.data.get("collected_at") if live.success else None, "fallback_source": "live_cli_snapshot" if live_snapshot else None, "observed_interfaces": observed_interfaces, "active_interfaces": active_interfaces, @@ -157,6 +166,7 @@ def get_interface_metrics( "device": safe_device, "interface": safe_interface, "time_range_minutes": safe_minutes, + "time_scope": time_scope, "metric_type": safe_metric_type, "view": safe_view, "summary": summary, @@ -173,6 +183,7 @@ def get_interface_metrics( "device": safe_device, "interface": safe_interface, "time_range_minutes": safe_minutes, + "time_scope": time_scope, "metric_type": safe_metric_type, "view": safe_view, "summary": summary, diff --git a/netopsbench/platform/toolkit/_core/observability/pingmesh_ops.py b/netopsbench/platform/toolkit/_core/observability/pingmesh_ops.py index abac2f4..7e3038c 100644 --- a/netopsbench/platform/toolkit/_core/observability/pingmesh_ops.py +++ b/netopsbench/platform/toolkit/_core/observability/pingmesh_ops.py @@ -8,11 +8,23 @@ class PingmeshOpsMixin: + def _pingmesh_plan_filter(self) -> str: + plan_id = self.manifest.require_pingmesh_plan().settings.plan_id + filters = {"topology_id": self.topology_id, "plan_id": plan_id} + clauses = [] + for tag, value in filters.items(): + if value: + safe = str(value).replace("\\", "\\\\").replace('"', '\\"') + clauses.append(f' |> filter(fn: (r) => r.{tag} == "{safe}")\n') + return "".join(clauses) + def get_pingmesh_summary( self, time_range_minutes: int = 10, start_time: str | None = None, end_time: str | None = None, + src_client: str | None = None, + dst_client: str | None = None, ) -> ToolResult: try: time_scope = self._resolve_pingmesh_time_scope( @@ -20,10 +32,15 @@ def get_pingmesh_summary( start_time=start_time, end_time=end_time, ) - topology_filter = "" - if self.topology_id: - safe = str(self.topology_id).replace("\\", "\\\\").replace('"', '\\"') - topology_filter = f' |> filter(fn: (r) => r.topology_id == "{safe}")\n' + topology_filter = self._pingmesh_plan_filter() + for tag, client in (("src_name", src_client), ("dst_name", dst_client)): + if client: + self._validate_device_name(client) + node = self.manifest.device(client) + if node is None or node.role.value != "client": + raise ValueError(f"Unknown client: {client}") + topology_filter += f' |> filter(fn: (r) => r.{tag} == "{client}")\n' + query = f""" from(bucket: "{self.influxdb_bucket}") {time_scope["range_clause"]} |> filter(fn: (r) => r._measurement == "pingmesh") @@ -47,6 +64,7 @@ def get_pingmesh_summary( return ToolResult( success=True, data={ + "plan_id": self.manifest.require_pingmesh_plan().settings.plan_id, "time_scope": {key: value for key, value in time_scope.items() if key != "range_clause"}, "path_type_summary": summary, "rows": rows, @@ -71,10 +89,7 @@ def get_pingmesh_hotspots( end_time=end_time, ) safe_limit = max(1, min(int(limit), 50)) - topology_filter = "" - if self.topology_id: - safe = str(self.topology_id).replace("\\", "\\\\").replace('"', '\\"') - topology_filter = f' |> filter(fn: (r) => r.topology_id == "{safe}")\n' + topology_filter = self._pingmesh_plan_filter() query = f""" from(bucket: "{self.influxdb_bucket}") {time_scope["range_clause"]} |> filter(fn: (r) => r._measurement == "pingmesh") @@ -102,6 +117,7 @@ def get_pingmesh_hotspots( return ToolResult( success=True, data={ + "plan_id": self.manifest.require_pingmesh_plan().settings.plan_id, "time_scope": {key: value for key, value in time_scope.items() if key != "range_clause"}, "limit": safe_limit, "hotspots": hotspots, diff --git a/netopsbench/platform/toolkit/fastmcp_server.py b/netopsbench/platform/toolkit/fastmcp_server.py index 03c9194..45c026b 100644 --- a/netopsbench/platform/toolkit/fastmcp_server.py +++ b/netopsbench/platform/toolkit/fastmcp_server.py @@ -1,4 +1,9 @@ -"""FastMCP server exposing NetOpsBench toolkit tools.""" +"""FastMCP server exposing the single canonical toolkit registry.""" + +import asyncio +import inspect +from functools import wraps +from typing import get_type_hints from .mcp.registry import group_tool_names, load_tool_specs @@ -10,7 +15,7 @@ EXPOSED_TOOLS_BY_GROUP = group_tool_names(_TOOL_SPECS) -def create_server(): +def create_server(*, gateway=None, auth=None, trace=None, max_tool_calls=None): """Create the optional FastMCP server only when it is actually used.""" try: from fastmcp import FastMCP @@ -18,9 +23,41 @@ def create_server(): raise RuntimeError( "fastmcp is not installed. Install with: pip install -e '.[agent]' or pip install -e '.[dev,agent]'" ) from exc - server = FastMCP("netopsbench") + server = FastMCP("netopsbench", auth=auth) + budget = {"calls": 0} + lock = asyncio.Lock() + + def bind(spec): + @wraps(spec.handler) + async def invoke(**kwargs): + async with lock: + if max_tool_calls is not None and budget["calls"] >= max_tool_calls: + raise RuntimeError("MCP tool-call budget exhausted") + budget["calls"] += 1 + call_id = trace.record_tool_start(name=spec.name, args=kwargs) if trace else None + try: + result = await asyncio.to_thread(getattr(gateway, spec.name), **kwargs) + if trace: + trace.record_tool_end(output=result.to_dict(), run_id=call_id) + return result.to_dict() + except Exception as exc: + if trace: + trace.record_tool_error(error=exc, run_id=call_id) + raise + + hints = get_type_hints(spec.handler) + invoke.__signature__ = inspect.signature(spec.handler).replace( + parameters=[ + parameter.replace(annotation=hints.get(name, parameter.annotation)) + for name, parameter in inspect.signature(spec.handler).parameters.items() + ], + return_annotation=dict, + ) + invoke.__annotations__ = {**hints, "return": dict} + return invoke + for spec in _TOOL_SPECS: - server.tool(name=spec.name)(spec.handler) + server.tool(name=spec.name)(bind(spec) if gateway is not None else spec.handler) return server diff --git a/netopsbench/platform/toolkit/mcp/connectivity.py b/netopsbench/platform/toolkit/mcp/connectivity.py index 5f7cbe2..e9cf06c 100644 --- a/netopsbench/platform/toolkit/mcp/connectivity.py +++ b/netopsbench/platform/toolkit/mcp/connectivity.py @@ -2,9 +2,9 @@ from .contracts import ToolSpec -def traceroute(src: str, dst_ip: str): +def traceroute(src: str, dst_ip: str, max_hops: int = 8): """Run traceroute from a client device to a destination IP.""" - return as_payload(get_toolkit().traceroute(src=src, dst_ip=dst_ip)) + return as_payload(get_toolkit().traceroute(src=src, dst_ip=dst_ip, max_hops=max_hops)) def ping_test( diff --git a/netopsbench/platform/toolkit/mcp/context.py b/netopsbench/platform/toolkit/mcp/context.py index f03d611..b499aad 100644 --- a/netopsbench/platform/toolkit/mcp/context.py +++ b/netopsbench/platform/toolkit/mcp/context.py @@ -1,3 +1,4 @@ +from netopsbench.platform.toolkit.public import public_tool_result from netopsbench.platform.toolkit.toolkit import AgentToolkit _toolkit: AgentToolkit | None = None @@ -11,4 +12,5 @@ def get_toolkit() -> AgentToolkit: def as_payload(result): - return result.data if result.success else {"error": result.error} + payload = public_tool_result(result) + return payload["data"] if payload["success"] else {"error": payload["error"]} diff --git a/netopsbench/platform/toolkit/mcp/inventory.py b/netopsbench/platform/toolkit/mcp/inventory.py index 76a8d49..824751a 100644 --- a/netopsbench/platform/toolkit/mcp/inventory.py +++ b/netopsbench/platform/toolkit/mcp/inventory.py @@ -1,3 +1,5 @@ +from typing import Literal + from .context import as_payload, get_toolkit from .contracts import ToolSpec @@ -7,19 +9,27 @@ def get_topology(): return as_payload(get_toolkit().get_topology()) -def get_device_interfaces(device: str, format: str = "summary"): +def get_device_interfaces(device: str, format: str = "summary", interface: str | None = None): """Get interface state and counters for a device.""" - return as_payload(get_toolkit().get_device_interfaces(device=device, format=format)) + return as_payload(get_toolkit().get_device_interfaces(device=device, format=format, interface=interface)) -def get_bgp_neighbors(device: str, format: str = "structured"): - """Get BGP neighbor status for a network device.""" +def get_bgp_neighbors(device: str, format: Literal["structured", "raw", "both", "json"] = "structured"): + """Get BGP neighbor status; format: structured (default), raw, both; json aliases structured.""" return as_payload(get_toolkit().get_bgp_neighbors(device=device, format=format)) -def get_bgp_neighbor(device: str, peer: str): - """Get live detail for one BGP neighbor on one network device.""" - return as_payload(get_toolkit().get_bgp_neighbor(device=device, peer=peer)) +def get_bgp_neighbor( + device: str, + peer: str, + view: Literal["detail", "advertised_routes", "advertised-routes", "advertised"] = "detail", + prefix: str | None = None, +): + """Get one BGP peer: detail or advertised_routes (aliases: advertised-routes, advertised); received routes unsupported. + + prefix optionally filters advertised_routes by exact prefix; it does not filter detail. + """ + return as_payload(get_toolkit().get_bgp_neighbor(device=device, peer=peer, view=view, prefix=prefix)) def get_route_table( @@ -28,6 +38,7 @@ def get_route_table( format: str = "structured", max_routes: int = 100, max_lines: int = 500, + view: str = "frr", ): """Get route table for a device, optionally filtered by prefix.""" return as_payload( @@ -35,6 +46,7 @@ def get_route_table( device=device, prefix=prefix, format=format, + view=view, max_routes=max_routes, max_lines=max_lines, ) @@ -56,7 +68,13 @@ def get_device_acl(device: str, view: str = "summary", max_lines: int = 300): return as_payload(get_toolkit().get_device_acl(device=device, view=view, max_lines=max_lines)) +def get_device_status(device: str): + """Read node runtime, accessibility and supported service states.""" + return as_payload(get_toolkit().get_device_status(device=device)) + + TOOL_SPECS = [ + ToolSpec(name="get_device_status", group="inventory", handler=get_device_status), ToolSpec(name="get_topology", group="inventory", handler=get_topology), ToolSpec(name="get_device_interfaces", group="inventory", handler=get_device_interfaces), ToolSpec(name="get_bgp_neighbors", group="inventory", handler=get_bgp_neighbors), diff --git a/netopsbench/platform/toolkit/mcp/observability.py b/netopsbench/platform/toolkit/mcp/observability.py index b61845e..7f682b4 100644 --- a/netopsbench/platform/toolkit/mcp/observability.py +++ b/netopsbench/platform/toolkit/mcp/observability.py @@ -53,6 +53,7 @@ def query_bgp_events( role: str = "", state: str = "non_established", limit: int = 100, + event_type: str = "session", ): """Find BGP session events from centralized historical telemetry.""" return as_payload( @@ -64,6 +65,7 @@ def query_bgp_events( peer=peer or None, role=role or None, state=state, + event_type=event_type, limit=limit, ) ) @@ -73,10 +75,14 @@ def get_pingmesh_summary( time_range_minutes: int = 10, start_time: str = "", end_time: str = "", + src_client: str | None = None, + dst_client: str | None = None, ): """Get Pingmesh summary by path type.""" return as_payload( get_toolkit().get_pingmesh_summary( + src_client=src_client, + dst_client=dst_client, time_range_minutes=time_range_minutes, start_time=start_time or None, end_time=end_time or None, diff --git a/netopsbench/platform/toolkit/mcp/registry.py b/netopsbench/platform/toolkit/mcp/registry.py index f4ed51d..26b09e8 100644 --- a/netopsbench/platform/toolkit/mcp/registry.py +++ b/netopsbench/platform/toolkit/mcp/registry.py @@ -2,6 +2,7 @@ import inspect from collections import OrderedDict +from functools import cache from typing import Any, get_type_hints from pydantic import TypeAdapter, ValidationError @@ -29,18 +30,24 @@ def group_tool_names(tool_specs: list[ToolSpec]) -> dict[str, list[str]]: return grouped +@cache +def _typed_parameters(handler): + hints = get_type_hints(handler) + return { + name: (parameter, TypeAdapter(hints.get(name, Any))) + for name, parameter in inspect.signature(handler).parameters.items() + if name != "self" + } + + def tool_schemas() -> list[dict[str, Any]]: """Return the model-facing JSON schema for the canonical toolkit registry.""" schemas: list[dict[str, Any]] = [] for spec in load_tool_specs(): - signature = inspect.signature(spec.handler) - hints = get_type_hints(spec.handler) properties: dict[str, dict[str, Any]] = {} required: list[str] = [] - for name, parameter in signature.parameters.items(): - if name == "self": - continue - properties[name] = TypeAdapter(hints.get(name, Any)).json_schema() + for name, (parameter, adapter) in _typed_parameters(spec.handler).items(): + properties[name] = adapter.json_schema() if parameter.default is inspect.Parameter.empty: required.append(name) else: @@ -67,17 +74,15 @@ def validate_tool_call(name: str, arguments: dict[str, Any]) -> bool: spec = next((candidate for candidate in load_tool_specs() if candidate.name == name), None) if spec is None: return False - signature = inspect.signature(spec.handler) - hints = get_type_hints(spec.handler) - parameters = {key: value for key, value in signature.parameters.items() if key != "self"} + parameters = _typed_parameters(spec.handler) if set(arguments) - set(parameters): return False - for key, parameter in parameters.items(): + for key, (parameter, adapter) in parameters.items(): if parameter.default is inspect.Parameter.empty and key not in arguments: return False if key in arguments: try: - TypeAdapter(hints.get(key, Any)).validate_python(arguments[key], strict=True) + adapter.validate_python(arguments[key], strict=True) except ValidationError: return False return True diff --git a/netopsbench/platform/toolkit/mcp/session_server.py b/netopsbench/platform/toolkit/mcp/session_server.py new file mode 100644 index 0000000..292ad2a --- /dev/null +++ b/netopsbench/platform/toolkit/mcp/session_server.py @@ -0,0 +1,52 @@ +"""Episode-scoped HTTP transport over the existing diagnostic tool gateway.""" + +import asyncio +import secrets +import socket +from contextlib import asynccontextmanager, contextmanager + + +@asynccontextmanager +async def session_mcp(context, *, host="127.0.0.1", max_tool_calls=None, record_trace=True): + import uvicorn + from fastmcp.server.auth.providers.jwt import StaticTokenVerifier + + from netopsbench.platform.toolkit.fastmcp_server import create_server + + token = secrets.token_urlsafe(32) + auth = StaticTokenVerifier(tokens={token: {"client_id": "diagnosis", "scopes": []}}) + server = create_server( + gateway=context.tools, auth=auth, trace=context.trace if record_trace else None, max_tool_calls=max_tool_calls + ) + app = server.http_app(path="/mcp", stateless_http=True, json_response=True) + listener = socket.socket() + listener.bind((host, 0)) + listener.listen(128) + port = listener.getsockname()[1] + config = uvicorn.Config(app, log_level="error", access_log=False, timeout_graceful_shutdown=5) + + class EpisodeServer(uvicorn.Server): + @contextmanager + def capture_signals(self): + # The acceptance runner owns cancellation and fault recovery. + yield + + http = EpisodeServer(config) + task = asyncio.create_task(http.serve(sockets=[listener])) + try: + for _ in range(100): + if http.started: + break + if task.done(): + await task + raise RuntimeError("Episode MCP server failed to start") + await asyncio.sleep(0.05) + else: + raise TimeoutError("Episode MCP server startup timed out") + yield {"url": f"http://{host}:{port}/mcp", "token": token, "port": port} + finally: + http.should_exit = True + try: + await asyncio.wait_for(task, timeout=10) + finally: + listener.close() diff --git a/netopsbench/platform/toolkit/public.py b/netopsbench/platform/toolkit/public.py new file mode 100644 index 0000000..a14dc73 --- /dev/null +++ b/netopsbench/platform/toolkit/public.py @@ -0,0 +1,59 @@ +"""Projection of diagnostic results; injection/audit objects are never public.""" + +from datetime import UTC, datetime + +from ._core.common import PublicArgumentError + +_PRIVATE_KEYS = frozenset( + { + "injection", + "effect_audit", + "route_evidence", + "recovery", + "recovery_journal", + "fault_type", + "ground_truth", + "target_device", + "target_interface", + "target_prefix", + "mechanism", + "parameters", + "topology_dir", + "artifact_path", + "qdisc", + } +) +_ERROR_KEYS = frozenset({"error", "address_collection_error", "service_collection_error", "collection_error"}) + + +def public_observation(value): + """Strip reserved runtime fields recursively, preserving measured symptoms.""" + if isinstance(value, dict): + projected = {} + for key, child in value.items(): + if key in _PRIVATE_KEYS or (key.startswith("_") and key not in {"_truncation", "_truncated_text"}): + continue + if key in _ERROR_KEYS and child: + projected[key] = child.value if isinstance(child, PublicArgumentError) else "Observation unavailable" + elif key == "data_source_status" and child not in ("ok", "unavailable", "error"): + # Legacy observations append query exceptions to this status. + projected[key] = "error" + else: + projected[key] = public_observation(child) + return projected + if isinstance(value, (list, tuple)): + return [public_observation(child) for child in value] + return value + + +def public_failure(failure): + if failure is None: + return None + return failure.model_copy(update={"message": f"{failure.domain.value} failure during {failure.phase}"}) + + +def public_tool_result(result): + payload = public_observation({"success": result.success, "data": result.data, "error": result.error}) + if isinstance(payload.get("data"), dict): + payload["data"].setdefault("collected_at", datetime.now(UTC).isoformat()) + return payload diff --git a/netopsbench/platform/topology/clos_builder.py b/netopsbench/platform/topology/clos_builder.py index b4c1449..f7da3e2 100644 --- a/netopsbench/platform/topology/clos_builder.py +++ b/netopsbench/platform/topology/clos_builder.py @@ -18,6 +18,7 @@ from .config import TopologyConfig from .plan import BGPNeighborPlan, DevicePlan, FabricPlan from .planning import ( + ClientAddressing, ManagementAddressing, build_render_settings, client_commands, @@ -29,19 +30,18 @@ def _validate_config(config: TopologyConfig) -> None: if not 1 <= config.num_spines <= 255: raise ValueError(f"num_spines must fit in one IPv4 octet (1-255), got {config.num_spines}") - if not 1 <= config.num_leafs <= 155: - raise ValueError( - "num_leafs must fit the client subnet scheme 192.168.(100+leaf).0/24 " f"(1-155), got {config.num_leafs}" - ) - if not 1 <= config.clients_per_leaf <= 64: - raise ValueError( - "clients_per_leaf must fit the per-leaf /30 allocation (1-64), " f"got {config.clients_per_leaf}" - ) + ClientAddressing(config.num_leafs, config.clients_per_leaf) + leaf_end = config.leaf_asn_start + config.num_leafs - 1 + if not (64512 <= config.spine_asn <= 65534 and 64512 <= config.leaf_asn_start <= leaf_end <= 65534): + raise ValueError("CLOS ASNs exceed the private 16-bit pool") + if config.leaf_asn_start <= config.spine_asn <= leaf_end: + raise ValueError("CLOS spine and leaf ASN allocations overlap") def build_clos_plan(config: TopologyConfig) -> FabricPlan: """Return a complete CLOS plan without writing any artifacts.""" _validate_config(config) + client_addressing = ClientAddressing(config.num_leafs, config.clients_per_leaf) spine_mgmt_offset = 10 leaf_mgmt_offset = spine_mgmt_offset + config.num_spines client_mgmt_offset = leaf_mgmt_offset + config.num_leafs @@ -98,14 +98,13 @@ def build_clos_plan(config: TopologyConfig) -> FabricPlan: leaf_name = f"leaf{leaf_idx}" router_id = f"10.0.1.{leaf_idx}" leaf_asn = config.leaf_asn_start + leaf_idx - 1 - subnet_octet = 100 + leaf_idx leaf = Device( name=leaf_name, role=DeviceRole.LEAF, mgmt_ip=addressing.host_ip(leaf_mgmt_offset + leaf_idx), asn=leaf_asn, router_id=router_id, - metadata={"client_subnet": f"192.168.{subnet_octet}.0/24"}, + metadata={"client_subnet": str(client_addressing.rack_subnet(leaf_idx))}, ) interfaces = { sonic_port_name(spine_idx): (f"10.{spine_idx}.{leaf_idx}.2/30",) @@ -117,11 +116,9 @@ def build_clos_plan(config: TopologyConfig) -> FabricPlan: ) networks: list[str] = [] for client_position in range(1, config.clients_per_leaf + 1): - subnet_base = (client_position - 1) * 4 - interfaces[sonic_port_name(config.num_spines + client_position)] = ( - f"192.168.{subnet_octet}.{subnet_base + 1}/30", - ) - networks.append(f"192.168.{subnet_octet}.{subnet_base}/30") + subnet, gateway, client_ip = client_addressing.access(leaf_idx, client_position) + interfaces[sonic_port_name(config.num_spines + client_position)] = (gateway + "/30",) + networks.append(subnet) devices.append(leaf) device_plans.append( DevicePlan( @@ -137,9 +134,7 @@ def build_clos_plan(config: TopologyConfig) -> FabricPlan: for client_position in range(1, config.clients_per_leaf + 1): client_idx = (leaf_idx - 1) * config.clients_per_leaf + client_position - subnet_base = (client_position - 1) * 4 - client_ip = f"192.168.{subnet_octet}.{subnet_base + 2}" - gateway = f"192.168.{subnet_octet}.{subnet_base + 1}" + _, gateway, client_ip = client_addressing.access(leaf_idx, client_position) client = Device( name=f"client{client_idx}", role=DeviceRole.CLIENT, @@ -180,6 +175,7 @@ def build_clos_plan(config: TopologyConfig) -> FabricPlan: topology_id=config.name, name=config.name, scale=scale_name, + purpose=config.purpose, family="clos", management=Management( network=config.mgmt_network_name or f"clab-mgmt-{config.name}", @@ -212,6 +208,9 @@ def build_clos_plan(config: TopologyConfig) -> FabricPlan: # - Observability: Syslog and gNMI """ + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + manifest.pingmesh_plan = compile_pingmesh_plan(manifest) return FabricPlan( manifest=manifest, device_plans=tuple(device_plans), diff --git a/netopsbench/platform/topology/config.py b/netopsbench/platform/topology/config.py index 3e0e441..d281f65 100644 --- a/netopsbench/platform/topology/config.py +++ b/netopsbench/platform/topology/config.py @@ -2,9 +2,11 @@ from __future__ import annotations -from dataclasses import dataclass +import os +from dataclasses import dataclass, field from importlib.resources import files from pathlib import Path +from typing import Literal from netopsbench.models.profiles import ScaleProfile, ScaleRegistry, get_scale_profile from netopsbench.models.topology import PingmeshPolicy @@ -15,9 +17,8 @@ "yyyyyt123/netopsbench-sonic-vs-202505-telemetry" "@sha256:0e039d2fea3f85788f15db8ebad27cf5bd5b2cdaf17e8c31eab852021e23ea73" ) -DEFAULT_CLIENT_IMAGE = ( - "docker.io/yyyyyt123/netopsbench-client" "@sha256:8c3c2997cac3796f9145a5a88f038a86c026972fa5594e157c7d7c323bd9dbd7" -) +DEFAULT_CLIENT_IMAGE = "netopsbench-client:pingmesh-v2" + SONIC_PLATFORM = "x86_64-kvm_x86_64-r0" SONIC_HWSKU = "Force10-S6000" SONIC_HWSKU_PATH = f"/usr/share/sonic/device/{SONIC_PLATFORM}/{SONIC_HWSKU}" @@ -47,12 +48,13 @@ class TopologyConfig: clients_per_leaf: int = 1 nos_kind: str = "sonic-vs" nos_image: str = DEFAULT_SONIC_VS_IMAGE - client_image: str = DEFAULT_CLIENT_IMAGE + client_image: str = field(default_factory=lambda: os.environ.get("NETOPSBENCH_CLIENT_IMAGE", DEFAULT_CLIENT_IMAGE)) mgmt_ipv4_subnet: str = "172.20.20.0/24" mgmt_network_name: str | None = None collector_ip: str | None = None spine_asn: int = 65001 leaf_asn_start: int = 65011 + purpose: Literal["benchmark", "validation"] = "benchmark" scale_name: str | None = None pingmesh_policy: PingmeshPolicy | None = None @@ -65,14 +67,13 @@ class FatTreeConfig: name: str = "dcn" nos_kind: str = "sonic-vs" nos_image: str = DEFAULT_SONIC_VS_IMAGE - client_image: str = DEFAULT_CLIENT_IMAGE + client_image: str = field(default_factory=lambda: os.environ.get("NETOPSBENCH_CLIENT_IMAGE", DEFAULT_CLIENT_IMAGE)) mgmt_ipv4_subnet: str = "172.20.20.0/24" mgmt_network_name: str | None = None collector_ip: str | None = None - core_asn_start: int = 65001 - agg_asn_start: int = 65101 - edge_asn_start: int = 65201 + asn_base: int = 65001 clients_per_edge: int | None = None + purpose: Literal["benchmark", "validation"] = "benchmark" scale_name: str | None = None pingmesh_policy: PingmeshPolicy | None = None @@ -124,6 +125,7 @@ def _clos_config_from_profile(profile: ScaleProfile) -> TopologyConfig: clients_per_leaf=profile.clients_per_attached_switch, mgmt_ipv4_subnet=_topology_mgmt_subnet(profile), scale_name=profile.name, + purpose=profile.purpose, pingmesh_policy=pingmesh_policy_for_profile(profile), ) @@ -134,6 +136,7 @@ def _fat_tree_config_from_profile(profile: ScaleProfile) -> FatTreeConfig: clients_per_edge=profile.clients_per_attached_switch, mgmt_ipv4_subnet=_topology_mgmt_subnet(profile), scale_name=profile.name, + purpose=profile.purpose, pingmesh_policy=pingmesh_policy_for_profile(profile), ) diff --git a/netopsbench/platform/topology/fat_tree_builder.py b/netopsbench/platform/topology/fat_tree_builder.py index 682c77f..8c64ad6 100644 --- a/netopsbench/platform/topology/fat_tree_builder.py +++ b/netopsbench/platform/topology/fat_tree_builder.py @@ -20,6 +20,7 @@ from .config import FatTreeConfig from .plan import BGPNeighborPlan, DevicePlan, FabricPlan from .planning import ( + ClientAddressing, ManagementAddressing, build_render_settings, client_commands, @@ -29,18 +30,25 @@ def _validate_config(config: FatTreeConfig) -> None: - if config.num_total_edge > 155: - raise ValueError( - "num_total_edge must fit the client subnet scheme 192.168.(100+edge).0/24 " - f"(1-155), got {config.num_total_edge}" - ) - if int(config.clients_per_edge or 0) > 64: - raise ValueError("clients_per_edge must fit the per-edge /30 allocation") + ClientAddressing(config.num_total_edge, int(config.clients_per_edge or 0)) + if max(config.num_core, config.num_total_agg, config.num_total_edge) > 255: + raise ValueError("Router ID pool exceeds one IPv4 octet") + if ( + not 64512 <= config.asn_base + or config.asn_base + config.num_core + config.num_total_agg + config.num_total_edge - 1 > 65534 + ): + raise ValueError("Fat-tree ASNs exceed the private 16-bit pool") + if config.k * config.half * config.half > 16384: + raise ValueError("Fat-tree fabric /30 address pool exhausted") def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: """Return a complete fat-tree plan without writing any artifacts.""" _validate_config(config) + client_addressing = ClientAddressing(config.num_total_edge, int(config.clients_per_edge or 0)) + core_asn_start = config.asn_base + agg_asn_start = core_asn_start + config.num_core + edge_asn_start = agg_asn_start + config.num_total_agg half = config.half clients_per_edge = int(config.clients_per_edge or 0) @@ -105,7 +113,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: for core_idx in range(1, config.num_core + 1): name = f"core{core_idx}" router_id = f"10.0.1.{core_idx}" - asn = config.core_asn_start + core_idx - 1 + asn = core_asn_start + core_idx - 1 device = Device( name=name, role=DeviceRole.CORE, @@ -121,7 +129,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: neighbors = tuple( BGPNeighborPlan( peer_ip=core_agg_ips[(core_idx, agg_idx)][1], - remote_as=config.agg_asn_start + agg_idx - 1, + remote_as=agg_asn_start + agg_idx - 1, ) for agg_idx in neighbors_for_device ) @@ -140,7 +148,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: for agg_idx in range(1, config.num_total_agg + 1): name = f"agg{agg_idx}" router_id = f"10.0.2.{agg_idx}" - asn = config.agg_asn_start + agg_idx - 1 + asn = agg_asn_start + agg_idx - 1 device = Device( name=name, role=DeviceRole.AGG, @@ -165,14 +173,14 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: [ BGPNeighborPlan( peer_ip=core_agg_ips[(core_idx, agg_idx)][0], - remote_as=config.core_asn_start + core_idx - 1, + remote_as=core_asn_start + core_idx - 1, ) for core_idx in core_peers ] + [ BGPNeighborPlan( peer_ip=agg_edge_ips[(agg_idx, edge_idx)][1], - remote_as=config.edge_asn_start + edge_idx - 1, + remote_as=edge_asn_start + edge_idx - 1, ) for edge_idx in edge_peers ] @@ -192,7 +200,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: for edge_idx in range(1, config.num_total_edge + 1): name = f"edge{edge_idx}" router_id = f"10.0.3.{edge_idx}" - asn = config.edge_asn_start + edge_idx - 1 + asn = edge_asn_start + edge_idx - 1 device = Device( name=name, role=DeviceRole.EDGE, @@ -201,7 +209,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: router_id=router_id, metadata={ "pod": edge_pod[edge_idx], - "client_subnet": f"192.168.{100 + edge_idx}.0/24", + "client_subnet": str(client_addressing.rack_subnet(edge_idx)), }, ) agg_peers = sorted(edge_agg_neighbors[edge_idx]) @@ -211,13 +219,13 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: } networks: list[str] = [] for client_position in range(1, clients_per_edge + 1): - subnet_base = (client_position - 1) * 4 - interfaces[sonic_port_name(half + client_position)] = (f"192.168.{100 + edge_idx}.{subnet_base + 1}/30",) - networks.append(f"192.168.{100 + edge_idx}.{subnet_base}/30") + subnet, gateway, client_ip = client_addressing.access(edge_idx, client_position) + interfaces[sonic_port_name(half + client_position)] = (gateway + "/30",) + networks.append(subnet) neighbors = tuple( BGPNeighborPlan( peer_ip=agg_edge_ips[(agg_idx, edge_idx)][0], - remote_as=config.agg_asn_start + agg_idx - 1, + remote_as=agg_asn_start + agg_idx - 1, ) for agg_idx in agg_peers ) @@ -238,9 +246,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: for edge_idx in range(1, config.num_total_edge + 1): for client_position in range(1, clients_per_edge + 1): client_idx += 1 - subnet_base = (client_position - 1) * 4 - client_ip = f"192.168.{100 + edge_idx}.{subnet_base + 2}" - gateway = f"192.168.{100 + edge_idx}.{subnet_base + 1}" + _, gateway, client_ip = client_addressing.access(edge_idx, client_position) client = Device( name=f"client{client_idx}", role=DeviceRole.CLIENT, @@ -296,6 +302,7 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: topology_id=config.name, name=config.name, scale=scale_name, + purpose=config.purpose, family="fat-tree", management=Management( network=config.mgmt_network_name or f"clab-mgmt-{config.name}", @@ -318,9 +325,9 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: devices=devices, links=links, routing=RoutingMetadata( - core_asn_range=f"{config.core_asn_start}-{config.core_asn_start + config.num_core - 1}", - agg_asn_range=f"{config.agg_asn_start}-{config.agg_asn_start + config.num_total_agg - 1}", - edge_asn_range=f"{config.edge_asn_start}-{config.edge_asn_start + config.num_total_edge - 1}", + core_asn_range=f"{core_asn_start}-{core_asn_start + config.num_core - 1}", + agg_asn_range=f"{agg_asn_start}-{agg_asn_start + config.num_total_agg - 1}", + edge_asn_range=f"{edge_asn_start}-{edge_asn_start + config.num_total_edge - 1}", ecmp_hash_policy_by_role={DeviceRole.CORE: 1, DeviceRole.AGG: 0, DeviceRole.EDGE: 1}, ), pingmesh=config.pingmesh_policy or pingmesh_policy_for_scale(scale_name), @@ -334,6 +341,9 @@ def build_fat_tree_plan(config: FatTreeConfig) -> FabricPlan: # - Preseeded SONiC startup artifacts """ + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + manifest.pingmesh_plan = compile_pingmesh_plan(manifest) return FabricPlan( manifest=manifest, device_plans=tuple(device_plans), diff --git a/netopsbench/platform/topology/generator.py b/netopsbench/platform/topology/generator.py index 510aa44..8c9f840 100644 --- a/netopsbench/platform/topology/generator.py +++ b/netopsbench/platform/topology/generator.py @@ -59,7 +59,7 @@ def _fat_tree_config( def generate_topology( - scale: str = "xs", + scale: str = "medium", output_dir: str | None = None, name: str | None = None, mgmt_subnet: str | None = None, diff --git a/netopsbench/platform/topology/plan.py b/netopsbench/platform/topology/plan.py index b9f2df1..bbb8ee2 100644 --- a/netopsbench/platform/topology/plan.py +++ b/netopsbench/platform/topology/plan.py @@ -57,11 +57,22 @@ def __post_init__(self) -> None: plan_names = [device_plan.name for device_plan in self.device_plans] if manifest_names != plan_names: raise ValueError("FabricPlan device plans must match canonical manifest device order") + used_interfaces: set[tuple[str, str]] = set() + degrees: dict[str, int] = {} + for link in self.manifest.links: + for endpoint in link.endpoints: + key = (endpoint.device, endpoint.interface) + if key in used_interfaces: + raise ValueError(f"Topology reuses data interface {endpoint.device}:{endpoint.interface}") + used_interfaces.add(key) + degrees[endpoint.device] = degrees.get(endpoint.device, 0) + 1 for device_plan in self.device_plans: if device_plan.is_client: continue if device_plan.required_ports <= 0: raise ValueError(f"switch {device_plan.name} must define required_ports") + if degrees.get(device_plan.name, 0) != device_plan.required_ports: + raise ValueError(f"switch {device_plan.name} port capacity does not match its data links") if device_plan.bgp_asn is None or device_plan.bgp_router_id is None: raise ValueError(f"switch {device_plan.name} must define BGP identity") diff --git a/netopsbench/platform/topology/planning.py b/netopsbench/platform/topology/planning.py index 11f5d90..1936495 100644 --- a/netopsbench/platform/topology/planning.py +++ b/netopsbench/platform/topology/planning.py @@ -3,6 +3,7 @@ from __future__ import annotations import ipaddress +import shlex from dataclasses import dataclass from netopsbench.models.profiles import ScaleProfile, ScaleRegistry, get_scale_profile @@ -79,17 +80,47 @@ def sonic_port_name(eth_index: int) -> str: return f"Ethernet{(eth_index - 1) * 4}" +@dataclass(frozen=True, slots=True) +class ClientAddressing: + """One /24 per rack and one /30 per access link, for both fabric families.""" + + rack_count: int + clients_per_rack: int + + def __post_init__(self) -> None: + if not 1 <= self.rack_count <= 255: + raise ValueError("Client address pool supports 1-255 racks") + if not 1 <= self.clients_per_rack <= 64: + raise ValueError("Each client /24 supports 1-64 access links") + + def rack_subnet(self, rack: int) -> ipaddress.IPv4Network: + if not 1 <= rack <= self.rack_count: + raise ValueError("Client rack index exceeds allocated address pool") + return ipaddress.IPv4Network((int(ipaddress.IPv4Address("192.168.0.0")) + rack * 256, 24)) + + def access(self, rack: int, position: int) -> tuple[str, str, str]: + if not 1 <= position <= self.clients_per_rack: + raise ValueError("Client position exceeds allocated rack capacity") + network = ipaddress.IPv4Network((int(self.rack_subnet(rack).network_address) + (position - 1) * 4, 30)) + gateway, client = network.hosts() + return str(network), str(gateway), str(client) + + def client_commands(client_ip: str, gateway: str) -> tuple[str, ...]: - return ( + commands = ( + "sysctl -w net.ipv4.ip_forward=0", "ip link set dev eth1 mtu 9232", - f"ip addr add {client_ip}/30 dev eth1", - f"ip route add 192.168.0.0/16 via {gateway}", + f"ip addr add {shlex.quote(client_ip + '/30')} dev eth1", + f"ip route add 192.168.0.0/16 via {shlex.quote(gateway)}", "ethtool -K eth1 rx off tx off tso off gso off gro off sg off tx-udp-segmentation off", ) + # One container exec, retaining command order and the first failure status. + return (shlex.join(["sh", "-ec", " && ".join(commands)]),) def pingmesh_policy_for_profile(profile: ScaleProfile) -> PingmeshPolicy: return PingmeshPolicy( + cross_rack_pairs=profile.pingmesh.cross_rack_pairs, destination_batch_size=profile.pingmesh_destination_batch_size, rtt_port_pool_size=profile.pingmesh_rtt_port_pool_size, rtt_ports_per_cycle=profile.pingmesh_rtt_ports_per_cycle, diff --git a/netopsbench/platform/topology/sonic_start.sh b/netopsbench/platform/topology/sonic_start.sh index c5a1a98..8854bf6 100755 --- a/netopsbench/platform/topology/sonic_start.sh +++ b/netopsbench/platform/topology/sonic_start.sh @@ -205,46 +205,44 @@ supervisorctl start portsyncd supervisorctl start orchagent supervisorctl start coppmgrd - supervisorctl start neighsyncd - supervisorctl start fdbsyncd - supervisorctl start teamsyncd - supervisorctl start fpmsyncd - supervisorctl start teammgrd - supervisorctl start vrfmgrd - supervisorctl start portmgrd - supervisorctl start intfmgrd - supervisorctl start vlanmgrd - supervisorctl start zebra - supervisorctl start mgmtd - supervisorctl start staticd - supervisorctl start buffermgrd - supervisorctl start nbrmgrd - supervisorctl start vxlanmgrd - supervisorctl start natmgrd - supervisorctl start natsyncd - supervisorctl start tunnelmgrd - supervisorctl start fabricmgrd -supervisorctl start rebootbackend +# This pinned VS image omits rebootbackend. Skip only an absent service; +# all existing service start failures still propagate under bash -e. +if python3 - <<'CHECK_REBOOTBACKEND' +from supervisor.options import ClientOptions +import sys +options = ClientOptions() +options.realize(args=[]) +with options.getServerProxy() as proxy: + names = {p['name'] for p in proxy.supervisor.getAllProcessInfo()} +sys.exit(0 if 'rebootbackend' in names else 3) +CHECK_REBOOTBACKEND +then + supervisorctl start rebootbackend +else + status=$? + if [ "$status" -ne 3 ]; then exit "$status"; fi + echo "NetOpsBench: optional rebootbackend is absent in this VS image" +fi # Start arp_update when VLAN exists VLAN=`sonic-cfggen -d -v 'VLAN.keys() | join(" ") if VLAN'` diff --git a/netopsbench/platform/topology/topology_utils.py b/netopsbench/platform/topology/topology_utils.py index 9ea9d17..76eecfc 100644 --- a/netopsbench/platform/topology/topology_utils.py +++ b/netopsbench/platform/topology/topology_utils.py @@ -23,7 +23,7 @@ def coerce_topology_manifest(topology: TopologyInput) -> TopologyManifest: if isinstance(topology, TopologyManifest): return topology if not isinstance(topology, dict): - raise TypeError("Topology must be a TopologyManifest or schema-v3 dictionary") + raise TypeError("Topology must be a TopologyManifest or schema-v4 dictionary") schema_version = topology.get("schema_version") if schema_version != SCHEMA_VERSION: rendered = "missing" if schema_version is None else repr(schema_version) @@ -32,7 +32,13 @@ def coerce_topology_manifest(topology: TopologyInput) -> TopologyManifest: "Regenerate topology.json with the current topology generator." ) try: - return TopologyManifest.model_validate(topology) + manifest = TopologyManifest.model_validate(topology) + plan = manifest.require_pingmesh_plan() + from netopsbench.platform.pingmesh.planner import plan_fingerprint + + if plan.settings.plan_id != plan_fingerprint(manifest, plan): + raise ValueError("Stale Pingmesh plan fingerprint; regenerate topology.json") + return manifest except ValidationError as exc: raise ValueError(f"Invalid topology schema_version {SCHEMA_VERSION!r} manifest: {exc}") from exc diff --git a/netopsbench/platform/traffic/controller.py b/netopsbench/platform/traffic/controller.py index 70289c4..c46fd70 100644 --- a/netopsbench/platform/traffic/controller.py +++ b/netopsbench/platform/traffic/controller.py @@ -8,11 +8,15 @@ import uuid from collections import defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed +from contextvars import copy_context from dataclasses import asdict, dataclass, field from netopsbench.logging_utils import get_logger from netopsbench.platform.client_agent.contract import HEARTBEAT_MAX_AGE_SECONDS, TRAFFIC_CONTROL_PORT from netopsbench.platform.client_agent.control import request_agent +from netopsbench.platform.utils.control import OperationControl, current_operation_control, operation_scope + +from .estimator import bandwidth_to_bps logger = get_logger(__name__) @@ -69,7 +73,11 @@ def _request(self, client: str, operation: str, payload: dict) -> dict: TRAFFIC_CONTROL_PORT, operation, payload, - timeout=CONTROL_TIMEOUT_SECONDS, + timeout=( + current_operation_control().remaining(CONTROL_TIMEOUT_SECONDS) + if current_operation_control() + else CONTROL_TIMEOUT_SECONDS + ), ) except RuntimeError as exc: raise RuntimeError(f"Traffic process on {client}: {exc}") from exc @@ -81,7 +89,8 @@ def _request_with_retry(self, client: str, operation: str, payload: dict) -> dic except (OSError, json.JSONDecodeError): if attempt == 1: raise - time.sleep(0.1) + control = current_operation_control() + control.sleep(0.1) if control else time.sleep(0.1) raise AssertionError("unreachable") def _parallel_requests(self, requests: dict[str, tuple[str, dict]]) -> dict[str, dict]: @@ -89,7 +98,7 @@ def _parallel_requests(self, requests: dict[str, tuple[str, dict]]) -> dict[str, failures: list[str] = [] with ThreadPoolExecutor(max_workers=min(CONTROL_PARALLELISM, max(1, len(requests)))) as executor: futures = { - executor.submit(self._request_with_retry, client, operation, payload): client + executor.submit(copy_context().run, self._request_with_retry, client, operation, payload): client for client, (operation, payload) in requests.items() } for future in as_completed(futures): @@ -184,11 +193,12 @@ def start_matrix(self, flows: list[TrafficFlow]) -> list[str]: def _status_all(self) -> dict[str, dict]: return self._parallel_requests({client: ("status", {}) for client in self.management_ips}) - def verify_active_flows(self) -> bool: + def verify_active_flows(self, *, control: OperationControl | None = None) -> bool: if not self.active_flows or not self.generation: return False try: - statuses = self._status_all() + with operation_scope(control or OperationControl()): + statuses = self._status_all() except RuntimeError as exc: logger.warning("Native traffic health check failed: %s", exc) return False @@ -263,7 +273,7 @@ def _client_plans(clients: dict[str, str], flows: list[TrafficFlow]) -> dict[str "protocol": protocol, "dst_ip": flow.dst_ip, "dst_port": int(flow.dst_port), - "bandwidth_bps": _parse_bandwidth_bps(flow.bandwidth), + "bandwidth_bps": int(bandwidth_to_bps(str(flow.bandwidth))), "payload_bytes": max(1, int(payload_bytes)), "tcp_mss": max(0, int(flow.tcp_mss if protocol == "tcp" else 0)), } @@ -292,14 +302,6 @@ def _plan_digest(plan: dict) -> str: return hashlib.sha256(encoded).hexdigest() -def _parse_bandwidth_bps(value: str) -> int: - text = str(value).strip().upper() - factors = {"K": 1_000, "M": 1_000_000, "G": 1_000_000_000} - if text and text[-1:] in factors: - return int(float(text[:-1]) * factors[text[-1]]) - return int(float(text)) - - __all__ = [ "TrafficController", "TrafficFlow", diff --git a/netopsbench/platform/traffic/estimator.py b/netopsbench/platform/traffic/estimator.py index aa6b3b0..a8ff263 100644 --- a/netopsbench/platform/traffic/estimator.py +++ b/netopsbench/platform/traffic/estimator.py @@ -8,8 +8,6 @@ def bandwidth_to_bps(bandwidth: str) -> float: - if not bandwidth: - return 0.0 value = bandwidth.strip().upper() if value.endswith("K"): return float(value[:-1]) * 1_000 @@ -20,23 +18,6 @@ def bandwidth_to_bps(bandwidth: str) -> float: return float(value) -def infer_topology_link_mtu(topology: dict, default_link_mtu_bytes: int) -> int: - candidates = [ - topology.get("defaults", {}).get("link_mtu"), - topology.get("fabric", {}).get("link_mtu"), - topology.get("routing", {}).get("link_mtu"), - topology.get("link_mtu"), - ] - for candidate in candidates: - if isinstance(candidate, int) and candidate > 0: - return candidate - for client in topology.get("devices", {}).get("clients", []): - client_mtu = client.get("mtu") - if isinstance(client_mtu, int) and client_mtu > 0: - return client_mtu - return default_link_mtu_bytes - - def estimate_packet_size_bytes( flow: dict, *, @@ -61,7 +42,7 @@ def estimate_flow_pps( ) -> float: if flow.get("protocol") not in ["udp", "tcp"]: return 0.0 - bps = bandwidth_to_bps(flow.get("bandwidth", "0")) + bps = bandwidth_to_bps(flow.get("bandwidth") or "0") if bps <= 0: return 0.0 packet_size_bytes = estimate_packet_size_bytes( diff --git a/netopsbench/platform/traffic/generator.py b/netopsbench/platform/traffic/generator.py index 759490f..3877061 100644 --- a/netopsbench/platform/traffic/generator.py +++ b/netopsbench/platform/traffic/generator.py @@ -11,7 +11,6 @@ from .estimator import estimate_client_pps as _estimate_client_pps from .estimator import estimate_flow_pps as _estimate_flow_pps from .estimator import estimate_switch_pps as _estimate_switch_pps -from .estimator import infer_topology_link_mtu from .planner import build_candidate_flow as _build_candidate_flow from .planner import generate_traffic_config_from_topology as plan_standard_traffic from .settings import TrafficSettings @@ -36,7 +35,7 @@ def _max_pps_per_client(scale: str, switch_pps_limit: int | None, registry: Scal base = get_scale_profile(scale, registry).traffic_max_pps_per_client if switch_pps_limit is None: return base - return max(1, int(round(base * switch_pps_limit / BASE_SWITCH_PPS_LIMIT))) + return min(base, max(1, int(round(base * switch_pps_limit / BASE_SWITCH_PPS_LIMIT)))) def _standard_bandwidths(max_pps_per_client: int) -> dict[str, str]: @@ -70,11 +69,12 @@ def generate_traffic_config_from_topology( if profile_type != "standard": raise ValueError(f"Only the standard traffic profile is supported, got: {profile_type}") get_scale_profile(scale, scale_registry) - projected = coerce_topology_manifest(topology).to_agent_topology() + manifest = coerce_topology_manifest(topology) + projected = manifest.to_agent_topology() settings = settings or TrafficSettings() max_pps_per_client = _max_pps_per_client(scale, settings.switch_pps_limit, scale_registry) bandwidths = _standard_bandwidths(max_pps_per_client) - link_mtu_bytes = infer_topology_link_mtu(projected, DEFAULT_LINK_MTU_BYTES) + link_mtu_bytes = manifest.defaults.link_mtu build_flow = partial( _build_candidate_flow, diff --git a/netopsbench/platform/utils/control.py b/netopsbench/platform/utils/control.py new file mode 100644 index 0000000..58ceea9 --- /dev/null +++ b/netopsbench/platform/utils/control.py @@ -0,0 +1,77 @@ +"""Cancellation and elapsed-time budgets for internal runtime operations.""" + +from __future__ import annotations + +import asyncio +import time +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from threading import Event +from typing import overload + +_operation_control = ContextVar("operation_control", default=None) + + +async def finish_cleanup(awaitable): + """Drain owned cleanup despite repeated cancellation; report deferred cancellation.""" + task = asyncio.ensure_future(awaitable) + cancelled = False + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError: + cancelled = True + return task.result(), cancelled + + +def current_operation_control(): + return _operation_control.get() + + +@contextmanager +def operation_scope(control): + previous = current_operation_control() + if previous is not None: + deadlines = [v for v in (previous.deadline, control.deadline) if v is not None] + control = OperationControl(control.cancel_event or previous.cancel_event, min(deadlines) if deadlines else None) + token = _operation_control.set(control) + try: + control.remaining() + yield control + finally: + _operation_control.reset(token) + + +class OperationCancelled(RuntimeError): + """The caller requested cancellation before the next side effect.""" + + +@dataclass(frozen=True) +class OperationControl: + cancel_event: Event | None = None + deadline: float | None = None + + @overload + def remaining(self, maximum: float) -> float: ... + + @overload + def remaining(self, maximum: None = None) -> float | None: ... + + def remaining(self, maximum: float | None = None) -> float | None: + if self.cancel_event is not None and self.cancel_event.is_set(): + raise OperationCancelled("Operation cancelled") + if self.deadline is None: + return maximum + remaining = self.deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError("Operation deadline exceeded") + return remaining if maximum is None else min(remaining, maximum) + + def sleep(self, seconds: float) -> None: + duration = self.remaining(seconds) + if self.cancel_event is None: + time.sleep(duration) + else: + self.cancel_event.wait(duration) + self.remaining() diff --git a/netopsbench/platform/utils/files.py b/netopsbench/platform/utils/files.py index a170230..e7e23a1 100644 --- a/netopsbench/platform/utils/files.py +++ b/netopsbench/platform/utils/files.py @@ -11,13 +11,18 @@ def atomic_write_text(path: str | Path, text: str, *, encoding: str = "utf-8") -> None: """Replace ``path`` atomically with fully flushed text.""" + atomic_write_bytes(path, text.encode(encoding)) + + +def atomic_write_bytes(path: str | Path, payload: bytes) -> None: + """Replace an owned artifact only after its complete contents are flushed.""" target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) fd, temporary_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent) temporary = Path(temporary_name) try: - with os.fdopen(fd, "w", encoding=encoding) as handle: - handle.write(text) + with os.fdopen(fd, "wb") as handle: + handle.write(payload) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, target) @@ -33,4 +38,4 @@ def atomic_write_json(path: str | Path, payload: Any, *, default: Any = None) -> ) -__all__ = ["atomic_write_json", "atomic_write_text"] +__all__ = ["atomic_write_bytes", "atomic_write_json", "atomic_write_text"] diff --git a/netopsbench/platform/utils/frr.py b/netopsbench/platform/utils/frr.py new file mode 100644 index 0000000..6026381 --- /dev/null +++ b/netopsbench/platform/utils/frr.py @@ -0,0 +1,38 @@ +"""Parse BGP configuration for scenario generation and live fault injection.""" + +from __future__ import annotations + +import re +from typing import Any + + +def parse_bgp_config(text: str) -> dict[str, Any]: + local_as = None + neighbors = {} + networks = {} + for raw in text.splitlines(): + line = raw.strip() + if match := re.fullmatch(r"router bgp (\d+)", line): + local_as = int(match[1]) + elif match := re.fullmatch(r"neighbor (\S+) (remote-as|password|update-source) (\S+)", line): + address, option, value = match.groups() + neighbor = neighbors.setdefault(address, {"peer_ip": address, "remote_as": None, "route_maps": []}) + if option == "remote-as": + if value.isdigit(): + neighbor["remote_as"] = int(value) + else: + neighbor[option.replace("-", "_")] = value + elif match := re.fullmatch(r"neighbor (\S+) route-map (\S+) (in|out)", line): + address, name, direction = match.groups() + neighbor = neighbors.setdefault(address, {"peer_ip": address, "remote_as": None, "route_maps": []}) + attachment = {"name": name, "direction": direction} + if attachment not in neighbor["route_maps"]: + neighbor["route_maps"].append(attachment) + elif match := re.fullmatch(r"network (\S+)(?: route-map (\S+))?", line): + prefix, route_map = match.groups() + networks[prefix, route_map] = {"prefix": prefix, "route_map": route_map} + return { + "local_as": local_as, + "neighbors": sorted(neighbors.values(), key=lambda peer: peer["peer_ip"]), + "networks": sorted(networks.values(), key=lambda network: network["prefix"]), + } diff --git a/netopsbench/platform/utils/measurements.py b/netopsbench/platform/utils/measurements.py new file mode 100644 index 0000000..c7e4979 --- /dev/null +++ b/netopsbench/platform/utils/measurements.py @@ -0,0 +1,23 @@ +"""Private operation counts, scoped to execution and propagated to worker tasks.""" + +from contextlib import contextmanager +from contextvars import ContextVar +from threading import Lock + +_scopes = ContextVar("operation_measurements", default=()) +_lock = Lock() + + +def count_operation(name, amount=1): + with _lock: + for record in _scopes.get(): + record[name] = record.get(name, 0) + amount + + +@contextmanager +def measurement_scope(record): + token = _scopes.set((*_scopes.get(), record)) + try: + yield record + finally: + _scopes.reset(token) diff --git a/netopsbench/platform/utils/proc.py b/netopsbench/platform/utils/proc.py index 770dd28..7c8f008 100644 --- a/netopsbench/platform/utils/proc.py +++ b/netopsbench/platform/utils/proc.py @@ -5,10 +5,15 @@ import logging import os import re +import signal import subprocess +import time from collections.abc import Sequence from pathlib import Path +from .control import OperationControl, current_operation_control +from .measurements import count_operation + logger = logging.getLogger(__name__) @@ -70,6 +75,7 @@ def safe_run( input: str | None = None, stdout=None, stderr=None, + control: OperationControl | None = None, ) -> subprocess.CompletedProcess: """Run a subprocess with a sane default timeout and structured logging. @@ -105,6 +111,9 @@ def safe_run( non-zero. """ cmd_list = list(cmd) + count_operation("subprocess_calls") + if any(Path(str(part)).name == "docker" for part in cmd_list[:3]): + count_operation("docker_commands") # When explicit stdout/stderr file handles are provided, capture_output # must not be set (they are mutually exclusive in subprocess.run). if stdout is not None or stderr is not None: @@ -131,6 +140,9 @@ def safe_run( input=input, ) try: + control = control or current_operation_control() + if control is not None: + return _controlled_run(cmd_list, run_kwargs, control) return subprocess.run(cmd_list, **run_kwargs) except subprocess.TimeoutExpired: logger.error( @@ -139,3 +151,49 @@ def safe_run( _redacted_command(cmd_list), ) raise + + +def _controlled_run(cmd: list[str], kwargs: dict, control: OperationControl) -> subprocess.CompletedProcess: + """Own and reap a process group on cancellation or deadline expiry.""" + timeout = control.remaining(kwargs.pop("timeout")) + deadline = None if timeout is None else time.monotonic() + timeout + check = kwargs.pop("check") + data = kwargs.pop("input", None) + if kwargs.pop("capture_output", False): + kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if data is not None: + kwargs["stdin"] = subprocess.PIPE + with subprocess.Popen(cmd, start_new_session=True, **kwargs) as process: + try: + first = True + while True: + control.remaining() + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and remaining <= 0: + raise subprocess.TimeoutExpired(cmd, timeout) + try: + stdout, stderr = process.communicate( + input=data if first else None, + timeout=min(0.2, remaining) if remaining is not None else 0.2, + ) + break + except subprocess.TimeoutExpired: + first = False + except BaseException: + # Descendants may outlive the group leader; signal the owned group. + for sig in (signal.SIGTERM, signal.SIGKILL): + try: + os.killpg(process.pid, sig) + except ProcessLookupError: + pass + if sig == signal.SIGTERM: + try: + process.communicate(timeout=1) + except subprocess.TimeoutExpired: + pass + process.communicate() + raise + result = subprocess.CompletedProcess(cmd, process.returncode, stdout, stderr) + if check and result.returncode: + raise subprocess.CalledProcessError(result.returncode, cmd, stdout, stderr) + return result diff --git a/netopsbench/sdk/__init__.py b/netopsbench/sdk/__init__.py index 67f14bc..d0feaa3 100644 --- a/netopsbench/sdk/__init__.py +++ b/netopsbench/sdk/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations _EXPORT_MAP: dict[str, tuple[str, str]] = { + "RecoveryPolicy": ("netopsbench.models.recovery", "RecoveryPolicy"), "NetOpsBench": ("netopsbench.sdk.core", "NetOpsBench"), "ScenarioSpec": ("netopsbench.sdk.types", "ScenarioSpec"), "EpisodeSpec": ("netopsbench.sdk.types", "EpisodeSpec"), diff --git a/netopsbench/sdk/evaluators.py b/netopsbench/sdk/evaluators.py index 06f990e..57ed580 100644 --- a/netopsbench/sdk/evaluators.py +++ b/netopsbench/sdk/evaluators.py @@ -55,8 +55,8 @@ def _score_scenario(self, scenario: ScenarioSpec, diagnosis_results: list[Diagno scored_results = [] for index, diagnosis in enumerate(diagnosis_results): result = self._scorer.evaluate( - agent_output=_diagnosis_to_agent_output(diagnosis), - ground_truth=_build_ground_truth(scenario, index), + agent_output=AgentOutput.from_diagnosis(diagnosis), + ground_truth=_build_ground_truth(scenario), testcase_id=f"{scenario.id}:{index}", ) result.details["difficulty"] = scenario.metadata.get("difficulty", "unknown") @@ -97,7 +97,7 @@ def evaluate_scenario( metadata={ "scenario": scenario.to_dict(), "episode_index": index, - "ground_truth": _build_ground_truth(scenario, index), + "ground_truth": _build_ground_truth(scenario), }, tools=None, ) @@ -122,7 +122,7 @@ def evaluate_suite( scenario_report = self.evaluate_scenario( scenario=scenario, diagnosis_results=[diagnosis], evaluator=evaluator ) - results.extend(_extract_report_results(scenario_report)) + results.extend(dict(item) for item in scenario_report.detailed_results) return _report_from_result_items( identifier=f"suite:{len(scenarios)}", evaluator_name=evaluator, results=results ) @@ -157,10 +157,9 @@ def evaluate_scenario( self, *, scenario: ScenarioSpec, diagnosis_results: builtins.list[DiagnosisResult], evaluator: str = "default" ) -> BenchmarkReport: adapter = self.get(evaluator) - report = adapter.evaluate_scenario( + return adapter.evaluate_scenario( scenario=scenario, diagnosis_results=list(diagnosis_results), evaluator=evaluator ) - return _coerce_report(report, identifier=f"scenario:{scenario.id}", evaluator_name=evaluator) def evaluate_suite( self, @@ -172,8 +171,7 @@ def evaluate_suite( scenario_list = list(scenarios) diagnosis_list = list(diagnosis_results) adapter = self.get(evaluator) - report = adapter.evaluate_suite(scenarios=scenario_list, diagnosis_results=diagnosis_list, evaluator=evaluator) - return _coerce_report(report, identifier=f"suite:{len(scenario_list)}", evaluator_name=evaluator) + return adapter.evaluate_suite(scenarios=scenario_list, diagnosis_results=diagnosis_list, evaluator=evaluator) def create_fault_type_judge_evaluator_adapter( @@ -220,10 +218,6 @@ def _report_from_result_items( ) -def _extract_report_results(report: BenchmarkReport) -> list[dict[str, Any]]: - return [dict(item) for item in report.detailed_results] - - def _report_from_payload(*, identifier: str, payload: Mapping[str, Any]) -> BenchmarkReport: raw = dict(payload) summary = raw.pop("summary", {}) @@ -236,29 +230,7 @@ def _report_from_payload(*, identifier: str, payload: Mapping[str, Any]) -> Benc ) -def _diagnosis_to_agent_output(diagnosis: DiagnosisResult) -> AgentOutput: - findings = dict(diagnosis.findings or {}) - metadata = dict(diagnosis.metadata or {}) - location = findings.get("location") if isinstance(findings.get("location"), dict) else {} - if not location: - location = { - key: findings[key] for key in ("device", "interface") if key in findings and findings[key] is not None - } - return AgentOutput( - verdict=diagnosis.verdict, - fault_type=findings.get("fault_type") or metadata.get("fault_type"), - location=location, - evidence=list(findings.get("evidence") or metadata.get("evidence") or []), - confidence=float(diagnosis.confidence or 0.0), - reasoning=diagnosis.reasoning, - tool_calls=list(metadata.get("tool_calls") or findings.get("tool_calls") or []), - time_taken_seconds=float(metadata.get("time_taken_seconds", 0.0) or 0.0), - metadata=metadata, - ) - - -def _build_ground_truth(scenario: ScenarioSpec, index: int) -> dict[str, Any]: - del index +def _build_ground_truth(scenario: ScenarioSpec) -> dict[str, Any]: episode: dict[str, Any] = scenario.episode.model_dump(mode="json") fault_type = episode.get("fault_type") or scenario.metadata.get("expected_diagnosis") location = {} diff --git a/netopsbench/sdk/scenarios.py b/netopsbench/sdk/scenarios.py index 81611e9..a9dee80 100644 --- a/netopsbench/sdk/scenarios.py +++ b/netopsbench/sdk/scenarios.py @@ -7,6 +7,7 @@ from netopsbench.exceptions import ScenarioValidationError from netopsbench.models.profiles import ScaleRegistry, default_scale_registry, supported_scales +from netopsbench.models.recovery import RecoveryPolicy from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec from netopsbench.platform.scenario.parser import parse_scenario_file, save_scenario_file from netopsbench.platform.scenario.validator import validate_scenario @@ -26,19 +27,27 @@ def create( name: str, episode: EpisodeSpec | dict[str, Any], description: str = "", - scale: str = "xs", + scale: str = "medium", traffic_profile: str = "standard", metadata: dict[str, Any] | None = None, parameters: dict[str, Any] | None = None, + recovery_policy: RecoveryPolicy | dict[str, Any] | None = None, ) -> ScenarioSpec: try: - self.scale_registry.get(scale) + profile = self.scale_registry.get(scale) except (KeyError, ValueError) as exc: raise ScenarioValidationError(str(exc)) from exc if traffic_profile != "standard": raise ScenarioValidationError(f"Only the standard traffic profile is supported, got: {traffic_profile}") try: episode_spec = episode if isinstance(episode, EpisodeSpec) else EpisodeSpec.model_validate(episode) + authored_metadata = {"fault_catalog_version": 2, "purpose": profile.purpose, **(metadata or {})} + if recovery_policy is not None and "recovery_policy" in authored_metadata: + raise ValueError("Specify recovery_policy only once") + policy = RecoveryPolicy.model_validate( + recovery_policy if recovery_policy is not None else authored_metadata.get("recovery_policy", {}) + ) + authored_metadata["recovery_policy"] = policy.model_dump(mode="json") return ScenarioSpec( scenario_id=id, name=name, @@ -46,7 +55,7 @@ def create( topology_scale=scale, traffic_profile="standard", episode=episode_spec, - metadata=dict(metadata or {}), + metadata=authored_metadata, parameters=dict(parameters or {}), ) except ValueError as exc: diff --git a/netopsbench/sdk/sessions.py b/netopsbench/sdk/sessions.py index 7e7175d..a33d77c 100644 --- a/netopsbench/sdk/sessions.py +++ b/netopsbench/sdk/sessions.py @@ -42,6 +42,15 @@ def _run_handle_from_payload(payload: dict[str, Any]) -> RunHandle: ) +class _SDKSessionOrchestrator(SessionOrchestrator): + def _execute_on_runtime_pool(self, *, runtime: Any, **kwargs: Any) -> Any: + # Internal execution needs platform pools for quarantine operations. + # Provisioning and teardown still use the SDK's exception mapping. + return super()._execute_on_runtime_pool( + runtime=runtime._runtime if isinstance(runtime, RuntimePool) else runtime, **kwargs + ) + + class SessionManager: """SDK manager delegating benchmark execution to the shared episode kernel.""" @@ -55,7 +64,7 @@ def __init__( ): self.platform = platform self.name = "sessions" - self._executor = SessionOrchestrator( + self._executor = _SDKSessionOrchestrator( platform=platform, workspace=workspace, runtime_manager=runtime_manager, diff --git a/netopsbench/sdk/simulator_service.py b/netopsbench/sdk/simulator_service.py deleted file mode 100644 index 31ff75b..0000000 --- a/netopsbench/sdk/simulator_service.py +++ /dev/null @@ -1,51 +0,0 @@ -"""CLI boundary for the optional generic simulator HTTP service.""" - -from __future__ import annotations - -import argparse -from pathlib import Path - -from netopsbench.platform.incident.contracts import SimulatorConfig -from netopsbench.platform.simulator.service import SimulatorService, create_app -from netopsbench.sdk.core import NetOpsBench - - -def main() -> int: - parser = argparse.ArgumentParser(description="Run the NetOpsBench simulator service") - parser.add_argument("--scenario", action="append", default=[], help="Scenario YAML; may be repeated") - parser.add_argument("--scenario-dir", action="append", default=[], help="Directory of scenario YAML files") - parser.add_argument("--workspace", default=".") - parser.add_argument("--scale-profile", action="append", default=[]) - parser.add_argument("--event-log", type=Path) - parser.add_argument("--max-active-runtimes", type=int, default=1) - parser.add_argument("--host", default="127.0.0.1") - parser.add_argument("--port", type=int, default=8765) - args = parser.parse_args() - try: - import uvicorn - except ImportError as exc: - raise RuntimeError("Install NetOpsBench with the 'simulator' extra to run the service") from exc - - scenario_paths = [Path(value) for value in args.scenario] - for directory in args.scenario_dir: - scenario_paths.extend(sorted(Path(directory).glob("*.y*ml"))) - if not scenario_paths: - parser.error("Provide at least one --scenario or --scenario-dir") - - with NetOpsBench(workspace=args.workspace, scale_profiles=args.scale_profile) as bench: - scenarios = [bench.scenarios.load(path) for path in scenario_paths] - service = SimulatorService( - bench.simulators, - scenarios, - SimulatorConfig(max_active_runtimes=args.max_active_runtimes), - event_log=args.event_log, - ) - uvicorn.run(create_app(service), host=args.host, port=args.port) - return 0 - - -if __name__ == "__main__": # pragma: no cover - raise SystemExit(main()) - - -__all__ = ["main"] diff --git a/pyproject.toml b/pyproject.toml index 45a0115..3560f2b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,9 +36,12 @@ netopsbench = "netopsbench.cli.main:main" netopsbench-bgp-collector = "netopsbench.platform.observability.bgp_collector:main" netopsbench-mcp-server = "netopsbench.platform.toolkit.fastmcp_server:main" netopsbench-runtime = "netopsbench.platform.runtime.cli:main" -netopsbench-simulator = "netopsbench.sdk.simulator_service:main" [project.optional-dependencies] +codex = [ + "fastmcp>=3.4.0", + "uvicorn>=0.30.0", +] agent = [ "openai>=1.0.0", "deepagents>=0.0.12", @@ -46,16 +49,13 @@ agent = [ "langchain-openai>=0.2.0", "langchain-mcp-adapters>=0.1.0", "langsmith>=0.3.0", - "fastmcp>=2.0.0", + "fastmcp>=3.4.0", + "uvicorn>=0.30.0", "json-repair>=0.54.0", ] plots = [ "matplotlib>=3.8.0", ] -simulator = [ - "fastapi>=0.115.0", - "uvicorn>=0.30.0", -] dev = [ "pytest>=6.0.0", "pytest-asyncio>=0.21.0", @@ -76,6 +76,7 @@ netopsbench = [ "models/*.yaml", "platform/topology/*.json", "platform/topology/*.sh", + "platform/runtime/assets/*", "platform/observability/assets/**/*", "platform/scenario/specs/*.yaml", ] @@ -84,6 +85,7 @@ netopsbench = [ "*" = ["**/__pycache__", "**/__pycache__/*", "**/*.pyc"] [tool.pytest.ini_options] +testpaths = ["tests"] markers = [ "real: tests requiring deployed real environment and external services", "slow: tests that are slow but do not need a real environment", diff --git a/scripts/run_all_benchmarks.sh b/scripts/run_all_benchmarks.sh index 48e9777..a36c1ad 100755 --- a/scripts/run_all_benchmarks.sh +++ b/scripts/run_all_benchmarks.sh @@ -8,10 +8,9 @@ # bash scripts/run_all_benchmarks.sh # 前台跑 # # 每个 scale 使用不同并发 worker 数: -# xs: 3 workers (14 scenarios, 3×6=18 containers) -# small: 3 workers (15 scenarios, 3×14=42 containers) -# medium: 2 workers (28 scenarios, 2×28=56 containers) -# large: 2 workers (52 scenarios, 2×84=168 containers) +# xs: 3 workers (4 validation scenarios, 3×6=18 containers) +# medium: 2 workers (64 scenarios, 2×28=56 containers) +# large: 2 workers (64 scenarios, 2×84=168 containers) # xlarge/fat-tree: 1 worker by default # # 跑完后汇总 CSV 写入 scenario_results/benchmark_summary_.csv @@ -32,15 +31,15 @@ VENDOR="${BENCH_VENDOR:-minimax}" # BENCH_WORKERS_LARGE=4 bash scripts/run_all_benchmarks.sh declare -A SCALE_WORKERS=( [xs]="${BENCH_WORKERS_XS:-3}" - [small]="${BENCH_WORKERS_SMALL:-3}" [medium]="${BENCH_WORKERS_MEDIUM:-2}" [large]="${BENCH_WORKERS_LARGE:-2}" [xlarge]="${BENCH_WORKERS_XLARGE:-1}" [fat-tree-k8]="${BENCH_WORKERS_FAT_TREE_K8:-1}" [fat-tree-k12]="${BENCH_WORKERS_FAT_TREE_K12:-1}" + [fat-tree-k18]="${BENCH_WORKERS_FAT_TREE_K18:-1}" ) -# Ordered list of scales to run (override with BENCH_SCALES="xs small") -IFS=' ' read -ra SCALES <<< "${BENCH_SCALES:-xs small medium large}" +# Ordered list of scales to run (override with BENCH_SCALES="medium large") +IFS=' ' read -ra SCALES <<< "${BENCH_SCALES:-medium large}" # 加载 API keys set -a @@ -158,6 +157,7 @@ SUMMARY_CSV="${REPO_ROOT}/scenario_results/benchmark_summary_${TIMESTAMP}.csv" import json, sys, csv from pathlib import Path from datetime import datetime +from netopsbench.models.profiles import get_scale_profile, supported_scales repo = Path(sys.argv[1]) ts = sys.argv[2] @@ -209,11 +209,17 @@ for rj in report_paths: if not sid: raw_ids = (data.get("raw") or {}).get("scenario_ids") or [] sid = raw_ids[0] if raw_ids else "" - for sc in ("xs", "small", "medium", "large", "xlarge", "fat-tree-k8", "fat-tree-k12"): + for sc in supported_scales(): if f"_{sc}_" in sid: scale = sc break + if s.get("included_in_benchmark") is False or ( + scale in supported_scales() and get_scale_profile(scale).purpose == "validation" + ): + print(f"Validation result preserved, excluded from benchmark CSV: {rj}") + continue + reports.append({ "run_dir": str(rj.parent.relative_to(results_dir)), "vendor": vendor, @@ -245,7 +251,7 @@ if not reports: sys.exit(0) # Sort by vendor, scale -scale_order = {"xs": 0, "small": 1, "medium": 2, "large": 3, "xlarge": 4, "fat-tree-k8": 5, "fat-tree-k12": 6} +scale_order = {scale: index for index, scale in enumerate(supported_scales())} reports.sort(key=lambda r: (r["vendor"], scale_order.get(r["scale"], 99), r["started_at"])) # Write CSV diff --git a/scripts/validate_pingmesh_scales.py b/scripts/validate_pingmesh_scales.py new file mode 100644 index 0000000..c550ac1 --- /dev/null +++ b/scripts/validate_pingmesh_scales.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""Sequential real-runtime acceptance; defaults to DeepAgent with DeepSeek.""" + +from __future__ import annotations + +import argparse +import asyncio +import os +import subprocess +from pathlib import Path + +from dotenv import dotenv_values + +from examples._common import agent_class +from netopsbench.platform.faults.catalog import FAULT_MECHANISMS +from netopsbench.platform.runtime.toolchain import runtime_tools +from netopsbench.platform.scenario.parser import parse_scenario_file +from netopsbench.platform.session.acceptance import run_acceptance +from netopsbench.platform.topology.config import DEFAULT_CLIENT_IMAGE, DEFAULT_SONIC_VS_IMAGE +from netopsbench.sdk import NetOpsBench + + +def select_cases(paths: list[Path], include_faults: bool, manifest) -> list[Path]: + """The catalog already contains one case per necessary coverage unit.""" + cases = [parse_scenario_file(path) for path in paths] + if not any(case.episode.is_healthy for case in cases): + raise RuntimeError("Acceptance requires a healthy case") + if any(case.metadata.get("fault_catalog_version") != 2 for case in cases): + raise ValueError("Obsolete scenarios; regenerate fault catalog v2") + healthy = sorted(path for path, case in zip(paths, cases, strict=True) if case.episode.is_healthy) + return ( + healthy + sorted(path for path, case in zip(paths, cases, strict=True) if not case.episode.is_healthy) + if include_faults + else healthy + ) + + +def smoke_cases(paths, manifest): + return select_cases(paths, True, manifest) + + +def preflight_agents(backends, vendor, output, *, expected=None): + """Validate every configuration before making small real model requests.""" + expected = expected or {} + identities, agents = {}, {} + runtime_tools() + image = os.environ.get("NETOPSBENCH_CLIENT_IMAGE", DEFAULT_CLIENT_IMAGE) + subprocess.check_output(["docker", "image", "inspect", image, "--format", "{{.Id}}"], text=True) + subprocess.check_output(["docker", "image", "inspect", DEFAULT_SONIC_VS_IMAGE, "--format", "{{.Id}}"], text=True) + for backend in backends: + if backend == "deepagent": + agent = agent_class(backend)(vendor=vendor) + env = agent._provider.PRESET["api_key_env"] + key = os.environ.get(env) or dotenv_values(Path.cwd() / ".env").get(env) + if not key: + raise RuntimeError(f"{env} must be configured before deployment") + os.environ[env] = key + agent.api_key = key + identities[backend] = { + "vendor": vendor, + "model": agent.model, + "base_url": agent.base_url, + "max_graph_tool_steps": agent.max_tool_calls, + "request_timeout_seconds": agent.timeout_seconds, + } + else: + from examples.agents.codex_agent.runtime import image_content_identity + + agent = agent_class(backend)(artifacts_dir=output / "codex-preflight") + if backend in expected: + current = { + key: getattr(agent, key) + for key in ("cli_version", "model", "reasoning_effort", "service_tier", "timeout_seconds") + } + current["max_mcp_calls"] = agent.max_tool_calls + current["image_id"] = subprocess.check_output( + ["docker", "image", "inspect", agent.image, "--format", "{{.Id}}"], text=True + ).strip() + current["image_content_sha256"] = image_content_identity(agent.image) + if current != expected[backend]: + raise ValueError(f"Cannot change {backend} configuration when resuming acceptance") + identities[backend] = current + agents[backend] = agent + if backend in expected and expected[backend] != identities[backend]: + raise ValueError(f"Cannot change {backend} configuration when resuming acceptance") + for backend, agent in agents.items(): + if backend == "deepagent": + llm = agent._provider.build_llm( + model=agent.model, + api_key=agent.api_key, + base_url=agent.base_url, + temperature=agent.temperature, + max_tokens=32, + timeout_seconds=agent.timeout_seconds, + ) + llm.invoke("Reply with OK only.") + else: + # Every resumed configuration was checked before auth writes or image execution. + identities[backend] = agent.preflight() + if backend in expected and identities[backend] != expected[backend]: + raise ValueError(f"Cannot change {backend} configuration when resuming acceptance") + asyncio.run(agent.check_connection()) + return identities + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--scales", default="medium,large,fat-tree-k8,fat-tree-k12,xlarge,fat-tree-k18") + parser.add_argument("--mode", choices=["effects", "diagnose"], default="diagnose") + parser.add_argument("--fault-types", nargs="+", choices=["none", *FAULT_MECHANISMS]) + parser.add_argument("--vendor", default="deepseek") + parser.add_argument("--agents", nargs="+", choices=["deepagent", "codex"], default=["deepagent"]) + parser.add_argument("--output", type=Path, default=Path(".netopsbench/validation-pingmesh-v2")) + parser.add_argument("--capacity-sample", type=Path) + parser.add_argument("--allow-tight-capacity", action="store_true") + parser.add_argument("--resume-runtime", type=Path) + parser.add_argument("--rebuild-runtime", action="store_true") + args = parser.parse_args() + if args.fault_types and args.mode != "diagnose": + parser.error("--fault-types selects diagnostic cases; effects requires the complete coverage set") + + def requested_cases(paths, include_faults, manifest): + selected = select_cases(paths, include_faults, manifest) + if args.fault_types: + selected = [p for p in selected if parse_scenario_file(p).episode.fault_type in args.fault_types] + if not selected: + raise ValueError("No requested diagnostic types in this profile") + return selected + + return run_acceptance( + args, + bench_factory=NetOpsBench, + agent_factory=agent_class, + preflight=preflight_agents, + select_cases=requested_cases, + smoke_cases=lambda paths, manifest: requested_cases(paths, True, manifest), + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validate_runtime_refactor.py b/scripts/validate_runtime_refactor.py new file mode 100644 index 0000000..233c471 --- /dev/null +++ b/scripts/validate_runtime_refactor.py @@ -0,0 +1,372 @@ +#!/usr/bin/env python3 +"""Isolated deterministic runtime audit, with no model calls or shortened windows. + +For version comparisons, run each snapshot's driver with PYTHONPATH pointing +to that snapshot; this driver only generates recovery policy v3. +One repetition runs a coverage suite with fault/healthy pairs on a fresh lab. +Multiple repetitions measure every requested type (plus healthy) on its own +fresh lab, cold and reused, followed by a healthy check after each fault pair. +Artifacts contain private audit evidence. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +import sys +import threading +import time +from functools import partial +from pathlib import Path +from unittest.mock import patch + +import netopsbench +from netopsbench.platform.incident.contracts import ToolAction +from netopsbench.platform.observability import influxdb +from netopsbench.platform.runtime.manager import RuntimeManager +from netopsbench.platform.runtime.resources import ResourceMonitor, capacity_check, require_capacity +from netopsbench.platform.scenario.executor import ScenarioExecutor +from netopsbench.platform.scenario.generator import generate, load_topology +from netopsbench.platform.scenario.parser import parse_scenario_file +from netopsbench.platform.utils.control import OperationControl + + +def select_cases(paths, fault_types, *, all_cases=False, all_mechanisms=False): + cases = sorted((parse_scenario_file(p) for p in paths), key=lambda case: case.id) + healthy = next(case for case in cases if case.episode.is_healthy) + selected = [] + for fault_type in fault_types: + matches = [case for case in cases if case.episode.fault_type == fault_type] + if not matches: + raise ValueError(f"No generated case for {fault_type}") + if all_mechanisms and not all_cases: + by_mechanism = {} + for case in matches: + by_mechanism.setdefault(case.episode.parameters.get("mechanism", fault_type), case) + matches = list(by_mechanism.values()) + selected.extend(matches if all_cases or all_mechanisms else matches[:1]) + return healthy, selected + + +class CommandCounts: + """Same instrumentation for old/new trees; excludes background processes.""" + + def __init__(self): + self.values = {"subprocess": 0, "docker": 0, "influx_queries": 0} + self.lock = threading.Lock() + self.patches = [] + + def add(self, key): + with self.lock: + self.values[key] += 1 + + def snapshot(self): + with self.lock: + return dict(self.values) + + def __enter__(self): + counts = self + original_popen = subprocess.Popen + original_query = influxdb.query_flux + + class CountedPopen(original_popen): + def __init__(self, args, *pos, **kw): + counts.add("subprocess") + if isinstance(args, (list, tuple)) and any(Path(str(arg)).name == "docker" for arg in args[:2]): + counts.add("docker") + super().__init__(args, *pos, **kw) + + def counted_query(*args, **kwargs): + counts.add("influx_queries") + return original_query(*args, **kwargs) + + self.query_pair = original_query, counted_query + self.patches.append(patch.object(subprocess, "Popen", CountedPopen)) + # Replace already imported aliases too; later imports use the patched module. + for name, module in list(sys.modules.items()): + if name.startswith("netopsbench.") and module is not None: + for key, value in list(vars(module).items()): + if value is original_query: + self.patches.append(patch.object(module, key, counted_query)) + for item in self.patches: + item.start() + return self + + def __exit__(self, *_): + original_query, counted_query = self.query_pair + # Lazy imports during a batch must not retain that batch's counter. + for name, module in list(sys.modules.items()): + if name.startswith("netopsbench.") and module is not None: + for key, value in list(vars(module).items()): + if value is counted_query: + setattr(module, key, original_query) + for item in reversed(self.patches): + item.stop() + + +def deterministic_diagnosis(episode_result, *, diagnostic_session, diagnostic_payload, tool_profile="full"): + calls = [("get_topology", {}), ("get_pingmesh_summary", {})] + devices = diagnostic_payload["topology"]["devices"] + switches = sorted({row["name"] for group, rows in devices.items() if group != "clients" for row in rows}) + if tool_profile == "full": + calls.extend( + (name, {"device": device}) + for device in switches + for name in ("get_device_interfaces", "get_bgp_neighbors", "get_route_table", "get_device_acl") + ) + observations = [] + for name, arguments in calls: + result = diagnostic_session.call_tool(ToolAction(name=name, arguments=arguments)) + observations.append({"name": name, "arguments": arguments, "result": result.model_dump(mode="json")}) + # This audits execution/evidence, not classifier accuracy. Never infer health + # from absent diagnosis or use private ground truth as a diagnosis. + return {"verdict": "inconclusive", "success": True, "metadata": {"scripted_observations": observations}} + + +def verify_residual_rejected(runner, fault_type): + """Suppress undo writes only; all verification reads hit the real devices.""" + from netopsbench.platform.faults.handlers.network import _BGPD_RESTORE_SOURCE + + if fault_type == "device_down": + return {"skipped": "Containerlab node activation is outside the command hook"} + original = runner.injector._cmd.docker_exec + suppressed = [] + + def no_undo(container, commands, *args, **kwargs): + mutation = ( + commands[:1] == ["config"] + or commands[:3] == ["tc", "qdisc", "del"] + or commands[:3] == ["ip", "link", "set"] + or commands[:2] == ["iptables", "-D"] + or commands[:3] == ["sonic-db-cli", "CONFIG_DB", "del"] + or commands[:3] == ["python3", "-c", _BGPD_RESTORE_SOURCE] + or (commands[:1] == ["vtysh"] and "configure terminal" in commands) + ) + if mutation: + suppressed.append(commands[0]) + return subprocess.CompletedProcess(commands, 0, "", "") + return original(container, commands, *args, **kwargs) + + if fault_type in {"link_flapping", "route_flapping"}: + with patch.object(runner.injector._tracker, "stop_background", return_value=False): + results = runner.injector.recover_all() + else: + with patch.object(runner.injector._cmd, "docker_exec", side_effect=no_undo): + results = runner.injector.recover_all() + if not suppressed: + raise RuntimeError("Negative recovery test suppressed no writes") + if not results or all(item.get("recovered") for item in results) or not runner.injector.active_faults: + raise RuntimeError("Recovery incorrectly accepted an unremoved real fault") + return {"passed": True, "suppressed_write_count": len(suppressed), "results": results} + + +def verify_shadow(runner, case): + """Audit data-plane health without publishing a production baseline.""" + from copy import deepcopy + + started = time.monotonic() + baseline = deepcopy(runner._baseline_handoff) + last_calibration = runner._last_calibration + calibration_current = runner._calibration_current + try: + runner.calibrate(case, "shadow_validation") + return {"seconds": time.monotonic() - started, **runner._last_calibration} + finally: + runner._baseline_handoff = baseline + runner._last_calibration = last_calibration + runner._calibration_current = calibration_current + + +def run(args): + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=False) + package = Path(netopsbench.__file__).resolve().parent + source_hash = hashlib.sha256() + for path in sorted(package.rglob("*.py")): + source_hash.update(str(path.relative_to(package)).encode()) + source_hash.update(path.read_bytes()) + report = { + "scale": args.scale, + "recovery_policy": {"version": 3, "baseline_max_cases": 10}, + "tool_profile": args.tool_profile, + "repetitions": [], + "status": "running", + "source_sha256": source_hash.hexdigest(), + "source_root": str(package), + "driver_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + } + + def save(): + (output / "audit.json").write_text(json.dumps(report, indent=2, default=str)) + + manager = RuntimeManager(workspace=str(output)) + save() + batches = ( + [(repetition, kind) for repetition in range(args.repeats) for kind in ("none", *args.fault_types)] + if args.repeats > 1 + else [(repetition, None) for repetition in range(args.batch_repeats)] + ) + for repetition, cold_type in batches: + record = {"repetition": repetition + 1, "cold_type": cold_type, "cases": []} + report["repetitions"].append(record) + if args.scale != "xs": + if args.capacity_sample is None: + raise ValueError("medium requires --capacity-sample from a completed XS acceptance") + docker_root = Path( + subprocess.check_output(["docker", "info", "--format", "{{.DockerRootDir}}"], text=True).strip() + ) + record["capacity"] = capacity_check( + json.loads(args.capacity_sample.read_text()), args.scale, docker_root, False, True + ) + save() + require_capacity(record["capacity"], False) + batch_started = time.monotonic() + runtime = manager.create(scale=args.scale, name=f"audit-{args.scale}-{time.time_ns():x}") + record["runtime"] = str(runtime.root_dir) + runner = None + cancel, emergency = threading.Event(), threading.Event() + monitor = ResourceMonitor(record, cancel, emergency, threading.RLock()) + runtime.operation_control = OperationControl(cancel) + try: + monitor.start() + with CommandCounts() as counts: + started = time.monotonic() + runtime.deploy().ensure_observability().ensure_pingmesh().warm() + record["deploy"] = {"seconds": time.monotonic() - started, "operations": counts.snapshot()} + record["runtime_spec"] = runtime.describe() + worker = runtime.workers[0] + paths = generate( + {"fault_catalog_version": 2, "recovery_policy": {"version": 2}}, + load_topology(args.scale, str(worker.topology_dir)), + output / f"scenarios-{repetition + 1}-{cold_type or 'suite'}", + seed=42, + ) + healthy, faults = select_cases( + paths, args.fault_types, all_cases=args.all_cases, all_mechanisms=args.all_mechanisms + ) + runner = ScenarioExecutor( + topology_dir=str(worker.topology_dir), + topology_id=worker.topology_id, + influxdb_bucket=worker.bucket, + runtime_worker=worker, + scale_registry=runtime.scale_registry, + ) + runner._cancel_event = cancel + sequence = [healthy] + for fault in faults: + sequence.extend([fault, healthy]) + if cold_type is not None: + case = ( + healthy + if cold_type == "none" + else next(case for case in faults if case.episode.fault_type == cold_type) + ) + sequence = [case, case] if cold_type == "none" else [case, healthy, case, healthy] + if args.shadow: + sequence = [healthy, *faults, healthy] + elif args.compact_sequence: + sequence = [healthy, *faults] + sequence = sequence * args.sequence_repeats + + sequence_started = time.monotonic() + for index, case in enumerate(sequence): + before = counts.snapshot() + started = time.monotonic() + negative_checks = [] + recover = runner._recover_fault + + def audit_recovery(case=case, negative_checks=negative_checks, recover=recover, runner=runner): + if args.readback_negatives and not case.episode.is_healthy and not negative_checks: + negative_checks.append(verify_residual_rejected(runner, case.episode.fault_type)) + return recover() + + with patch.object(runner, "_recover_fault", side_effect=audit_recovery): + result = runner.run_scenario( + case, diagnosis_callback=partial(deterministic_diagnosis, tool_profile=args.tool_profile) + ) + item = { + "fault_type": case.episode.fault_type, + "cold": index == 0, + "seconds": time.monotonic() - started, + "operations": {key: value - before[key] for key, value in counts.snapshot().items()}, + "result": result, + "negative_readbacks": negative_checks, + } + if args.shadow and result.get("success"): + item["shadow"] = verify_shadow(runner, case) + record["cases"].append(item) + save() + if not result.get("case_valid") or not result.get("success") or result.get("cleanup_failed"): + raise RuntimeError(f"Case validation/recovery failed: {case.id}") + before = counts.snapshot() + final_started = time.monotonic() + calibration = runner.final_calibration(sequence[-1], destroy_after_run=True) + record["final_calibration"] = { + "seconds": time.monotonic() - final_started, + "result": calibration, + "operations": {key: value - before[key] for key, value in counts.snapshot().items()}, + } + record["sequence_seconds"] = time.monotonic() - sequence_started + save() + except Exception as exc: + record["error"] = f"{type(exc).__name__}: {exc}" + report["status"] = "failed" + raise + finally: + try: + if runner is not None: + runner.close() + finally: + teardown_started = time.monotonic() + try: + runtime.teardown() + record["disposition"] = "torn_down" + except Exception as exc: + record["cleanup_error"] = f"{type(exc).__name__}: {exc}" + record["disposition"] = "quarantined" + report["status"] = "failed" + runtime.mark_quarantined("audit_cleanup_failed") + record["teardown_seconds"] = time.monotonic() - teardown_started + record["batch_seconds"] = time.monotonic() - batch_started + save() + monitor.close() + if report["status"] == "failed": + return 1 + report["status"] = "passed" + save() + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--scale", required=True) + parser.add_argument("--all-mechanisms", action="store_true") + parser.add_argument("--sequence-repeats", type=int, choices=range(1, 5), default=1) + parser.add_argument("--tool-profile", choices=["full", "minimal"], default="full") + parser.add_argument("--all-cases", action="store_true") + parser.add_argument("--readback-negatives", action="store_true") + parser.add_argument("--shadow", action="store_true") + parser.add_argument( + "--compact-sequence", + action="store_true", + help="Batch health and selected faults without interleaved healthy cases", + ) + parser.add_argument("--fault-types", nargs="+", required=True) + parser.add_argument("--repeats", type=int, choices=range(1, 4), default=1) + parser.add_argument( + "--batch-repeats", + type=int, + choices=range(1, 4), + default=1, + help="Repeat the entire sequence on independent fresh runtimes", + ) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--capacity-sample", type=Path) + args = parser.parse_args() + if args.repeats > 1 and args.batch_repeats > 1: + parser.error("Choose either per-type --repeats or whole-suite --batch-repeats") + if args.compact_sequence and args.repeats > 1: + parser.error("--compact-sequence requires whole-suite repetitions") + raise SystemExit(run(args)) diff --git a/tests/fixtures/pingmesh_late_tail.json b/tests/fixtures/pingmesh_late_tail.json new file mode 100644 index 0000000..16f5ff2 --- /dev/null +++ b/tests/fixtures/pingmesh_late_tail.json @@ -0,0 +1,262 @@ +{ + "baseline": [ + { + "_time": "2026-10-23T22:13:35.874031525Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 0.0, + "df_packets_sent": 1.0, + "local_probe_errors": 0.0, + "packets_lost": 0.0, + "packets_sent": 4.0, + "port_batch_index": 3.0, + "probe_cycle": 1054.0, + "rtt_avg": 1.026391, + "rtt_max": 1.313774, + "rtt_min": 0.859518, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:13:44.874501072Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 0.0, + "df_packets_sent": 1.0, + "local_probe_errors": 0.0, + "packets_lost": 0.0, + "packets_sent": 4.0, + "port_batch_index": 0.0, + "probe_cycle": 1057.0, + "rtt_avg": 0.8936435, + "rtt_max": 0.943137, + "rtt_min": 0.860998, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:13:53.874481948Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 0.0, + "df_packets_sent": 1.0, + "local_probe_errors": 0.0, + "packets_lost": 0.0, + "packets_sent": 4.0, + "port_batch_index": 1.0, + "probe_cycle": 1060.0, + "rtt_avg": 0.977075, + "rtt_max": 1.048407, + "rtt_min": 0.878096, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:14:02.874480654Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 0.0, + "df_packets_sent": 1.0, + "local_probe_errors": 0.0, + "packets_lost": 0.0, + "packets_sent": 4.0, + "port_batch_index": 2.0, + "probe_cycle": 1063.0, + "rtt_avg": 0.9151735000000001, + "rtt_max": 1.006273, + "rtt_min": 0.851963, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:14:11.874876723Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 0.0, + "df_packets_sent": 1.0, + "local_probe_errors": 0.0, + "packets_lost": 0.0, + "packets_sent": 4.0, + "port_batch_index": 3.0, + "probe_cycle": 1066.0, + "rtt_avg": 0.9140265, + "rtt_max": 1.043813, + "rtt_min": 0.86715, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + } + ], + "current": [ + { + "_time": "2026-10-23T22:14:22.340386116Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 16.0, + "df_packets_sent": 16.0, + "local_probe_errors": 0.0, + "packets_lost": 0.0, + "packets_sent": 4.0, + "port_batch_index": 0.0, + "probe_cycle": 1069.0, + "rtt_avg": 0.9070542500000001, + "rtt_max": 0.951535, + "rtt_min": 0.795248, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:14:31.341387565Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 16.0, + "df_packets_sent": 16.0, + "local_probe_errors": 0.0, + "packets_lost": 4.0, + "packets_sent": 4.0, + "port_batch_index": 1.0, + "probe_cycle": 1072.0, + "rtt_avg": 0.0, + "rtt_max": 0.0, + "rtt_min": 0.0, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:14:40.341536184Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 16.0, + "df_packets_sent": 16.0, + "local_probe_errors": 0.0, + "packets_lost": 4.0, + "packets_sent": 4.0, + "port_batch_index": 2.0, + "probe_cycle": 1075.0, + "rtt_avg": 0.0, + "rtt_max": 0.0, + "rtt_min": 0.0, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:14:49.343005154Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 16.0, + "df_packets_sent": 16.0, + "local_probe_errors": 0.0, + "packets_lost": 4.0, + "packets_sent": 4.0, + "port_batch_index": 3.0, + "probe_cycle": 1078.0, + "rtt_avg": 0.0, + "rtt_max": 0.0, + "rtt_min": 0.0, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + }, + { + "_time": "2026-10-23T22:14:58.343071597Z", + "dst_ip": "192.168.29.10", + "dst_leaf": "edge29", + "dst_name": "client115", + "path_type": "cross_rack", + "plan_id": "008d9973d2487b2709f2ae1f511d80374ce15734269dea8f7d63bb3fe4105c7c", + "src_ip": "192.168.8.10", + "src_leaf": "edge8", + "src_name": "client31", + "destination_batch_index": 1.0, + "df_mtu_drops": 0.0, + "df_packets_lost": 16.0, + "df_packets_sent": 16.0, + "local_probe_errors": 0.0, + "packets_lost": 4.0, + "packets_sent": 4.0, + "port_batch_index": 0.0, + "probe_cycle": 1081.0, + "rtt_avg": 0.0, + "rtt_max": 0.0, + "rtt_min": 0.0, + "rtt_ports_active": 4.0, + "rtt_ports_total": 16.0 + } + ], + "provenance": { + "case": "generated_routing_loop_fat-tree-k8_001", + "source": "2026-10-24 archived observation CSV; original results unchanged", + "start": "2026-10-23T22:14:20Z", + "end": "2026-10-23T22:15:02Z" + } +} diff --git a/tests/test_api_runtimes.py b/tests/test_api_runtimes.py index 2e3c8eb..a643f6b 100644 --- a/tests/test_api_runtimes.py +++ b/tests/test_api_runtimes.py @@ -8,6 +8,15 @@ import pytest +@pytest.fixture(autouse=True) +def mock_runtime_backend(monkeypatch): + monkeypatch.setattr("netopsbench.platform.runtime.deployment.containerlab_command", lambda: ["containerlab"]) + monkeypatch.setattr( + "netopsbench.platform.runtime.manager.runtime_backend_identity", + lambda: {"provider": "upstream", "containerlab_version": "test"}, + ) + + def _record_lifecycle_operations(monkeypatch, calls, *, fail_stage=None): import netopsbench.platform.runtime.lifecycle as lifecycle @@ -54,11 +63,11 @@ def test_runtime_manager_create_workers_1_returns_runtime_pool(tmp_path): from netopsbench.sdk.runtimes import RuntimeManager, RuntimePool manager = RuntimeManager(workspace=tmp_path) - runtime = manager.create(scale="small", workers=1) + runtime = manager.create(scale="medium", workers=1) assert isinstance(runtime, RuntimePool) assert runtime.id == runtime.name - assert runtime.scale == "small" + assert runtime.scale == "medium" assert len(runtime.workers) == 1 assert runtime.workers[0].worker_id == "worker-1" assert runtime.workers[0].worker_index == 1 @@ -66,34 +75,7 @@ def test_runtime_manager_create_workers_1_returns_runtime_pool(tmp_path): assert runtime.workers[0].topology_dir == runtime.root_dir / "worker-1" assert runtime.root_dir.exists() assert runtime.root_dir == tmp_path / ".netopsbench" / "runtimes" / runtime.name - assert runtime.status() == {"id": runtime.id, "name": runtime.name, "scale": "small", "state": "created"} - - -def test_xlarge_runtime_workers_use_non_overlapping_23_subnets(tmp_path): - from netopsbench.sdk.runtimes import RuntimeManager - - runtime = RuntimeManager(workspace=tmp_path).create(scale="xlarge", workers=2, name="runtime-xlarge") - - subnets = [worker.mgmt_subnet for worker in runtime.workers] - assert subnets[0].endswith("/23") - assert subnets[1].endswith("/23") - assert subnets[0] != subnets[1] - assert int(subnets[0].split(".")[2]) % 2 == 0 - assert int(subnets[1].split(".")[2]) == int(subnets[0].split(".")[2]) + 2 - - -def test_fat_tree_k12_runtime_workers_use_non_overlapping_23_subnets(tmp_path): - from netopsbench.sdk.runtimes import RuntimeManager - - runtime = RuntimeManager(workspace=tmp_path).create(scale="fat-tree-k12", workers=2, name="runtime-ft12") - - subnets = [worker.mgmt_subnet for worker in runtime.workers] - assert subnets[0].endswith("/23") - assert subnets[1].endswith("/23") - assert subnets[0] != subnets[1] - assert int(subnets[0].split(".")[2]) >= 220 - assert int(subnets[0].split(".")[2]) % 2 == 0 - assert int(subnets[1].split(".")[2]) == int(subnets[0].split(".")[2]) + 2 + assert runtime.status() == {"id": runtime.id, "name": runtime.name, "scale": "medium", "state": "created"} def test_runtime_manager_attach_list_get_roundtrip(tmp_path): @@ -121,7 +103,7 @@ def test_runtime_manager_rejects_reusing_an_existing_runtime_name(tmp_path): original_metadata = (original.root_dir / "runtime.json").read_text(encoding="utf-8") with pytest.raises(RuntimeProvisionError, match="already exists"): - manager.create(scale="small", workers=1, name="runtime-xs") + manager.create(scale="medium", workers=1, name="runtime-xs") assert (original.root_dir / "runtime.json").read_text(encoding="utf-8") == original_metadata @@ -171,7 +153,7 @@ def test_same_scale_runtime_identities_are_isolated_and_persisted(tmp_path): assert first_identity.mgmt_network == "clab-mgmt-run-a" payload = json.loads((first.root_dir / "runtime.json").read_text(encoding="utf-8")) - assert payload["schema_version"] == "3" + assert payload["schema_version"] == "4" assert payload["scale_registry_sha256"] == manager.scale_registry.digest assert payload["scale_profile_sha256"] == manager.scale_registry.get("xlarge").digest assert payload["resolved_scale_profile"]["name"] == "xlarge" @@ -282,13 +264,14 @@ def fake_safe_run(command, **kwargs): lambda deployed_worker: calls.append(("pid1", deployed_worker.worker_id)), ) monkeypatch.setattr(deployment, "apply_configs", lambda *args: SimpleNamespace(failed=[])) + monkeypatch.setattr(deployment, "containerlab_command", lambda: ["official-containerlab-test"]) deployment.deploy_worker_lab(worker, "xs") generated = next(item for item in calls if item[0] == "generate")[1] commands = [item[1] for item in calls if item[0] == "command"] assert generated["name"] == "deploy-lab" assert generated["mgmt_subnet"] == worker.mgmt_subnet - assert any("containerlab" in command and "deploy" in command for command in commands) + assert any("official-containerlab-test" in command and "deploy" in command for command in commands) assert ("pid1", worker.worker_id) in calls assert not any("telegraf" in " ".join(command) or "pingmesh" in " ".join(command) for command in commands) @@ -315,10 +298,13 @@ def fake_safe_run(command, **_kwargs): monkeypatch.setattr(deployment, "safe_run", fake_safe_run) monkeypatch.setattr(deployment, "_verify_sonic_pid1_contract", lambda _worker: None) monkeypatch.setattr(deployment, "apply_configs", lambda *args: SimpleNamespace(failed=[])) + monkeypatch.setattr(deployment, "containerlab_command", lambda: ["official-containerlab-test"]) deployment.deploy_worker_lab(worker, "fat-tree-k12") - deploy_command = next(command for command in commands if "containerlab" in command and "deploy" in command) - assert deploy_command[-2:] == ["--max-workers", "1"] + deploy_command = next( + command for command in commands if "official-containerlab-test" in command and "deploy" in command + ) + assert deploy_command[-2:] == ["--max-workers", "16"] def test_removed_containerlab_env_does_not_override_scale_profile(tmp_path, monkeypatch): @@ -345,10 +331,13 @@ def fake_safe_run(command, **_kwargs): monkeypatch.setattr(deployment, "apply_configs", lambda *args: SimpleNamespace(failed=[])) monkeypatch.setenv("NETOPSBENCH_CONTAINERLAB_MAX_WORKERS", "3") + monkeypatch.setattr(deployment, "containerlab_command", lambda: ["official-containerlab-test"]) deployment.deploy_worker_lab(worker, "fat-tree-k12") - deploy_command = next(command for command in commands if "containerlab" in command and "deploy" in command) - assert deploy_command[-2:] == ["--max-workers", "1"] + deploy_command = next( + command for command in commands if "official-containerlab-test" in command and "deploy" in command + ) + assert deploy_command[-2:] == ["--max-workers", "16"] def test_management_subnet_allocation_batches_docker_inspection(monkeypatch): @@ -745,7 +734,7 @@ def test_worker_teardown_without_generated_manifest_uses_exact_lab_name(monkeypa monkeypatch.setattr( deployment, "safe_run", - lambda command, **_kwargs: (commands.append(command) or SimpleNamespace(returncode=0, stdout="", stderr="")), + lambda command, **_kwargs: commands.append(command) or SimpleNamespace(returncode=0, stdout="", stderr=""), ) monkeypatch.setattr(deployment, "_stop_collector", lambda *_paths: None) monkeypatch.setattr(deployment, "_lab_container_names", lambda *_args: []) @@ -1031,3 +1020,149 @@ def fail_cleanup(*_args, **_kwargs): assert runtime.state == "cleanup_failed" assert runtime.metadata["quarantined"] is True assert "cleanup failed" in str(runtime.metadata["cleanup_error"]) + + +def test_upstream_teardown_retries_namespace_cleanup_after_forced_container_removal(tmp_path, monkeypatch): + import subprocess + + from netopsbench.models.runtime import RuntimeIdentity + from netopsbench.platform.runtime import deployment + + topology = tmp_path / "worker-1" + topology.mkdir() + worker = RuntimeIdentity.create( + runtime_id="managed-xs", + worker_id="worker-1", + worker_index=1, + lab_name="managed-xs", + topology_dir=topology, + mgmt_subnet="172.31.1.0/24", + mgmt_network="owned-network", + ) + calls = [] + destroyed = 0 + + def run(command, **kwargs): + nonlocal destroyed + calls.append(command) + if command[0] == "official": + destroyed += 1 + return subprocess.CompletedProcess(command, 1 if destroyed == 1 else 0, "", "") + return subprocess.CompletedProcess(command, 0, "", "") + + monkeypatch.setattr(deployment, "containerlab_command", lambda: ["official"]) + monkeypatch.setattr(deployment, "sudo_prefix", lambda: []) + monkeypatch.setattr(deployment, "docker_prefix", lambda: []) + monkeypatch.setattr(deployment, "safe_run", run) + monkeypatch.setattr(deployment, "_stop_collector", lambda *a: None) + monkeypatch.setattr(deployment, "_lab_container_names", lambda *a: ["clab-managed-xs-client1"]) + monkeypatch.setattr(deployment, "_wait_for_lab_removal", lambda *a: None) + monkeypatch.setattr(deployment, "_container_exists", lambda *a: False) + monkeypatch.setattr(deployment, "_network_exists", lambda *a: False) + deployment.teardown_worker_lab(worker) + first, second = [i for i, c in enumerate(calls) if c[0] == "official"] + removal = calls.index(["docker", "rm", "-f", "clab-managed-xs-client1"]) + assert first < removal < second + + +def test_provision_interrupt_compensates_and_preserves_original(tmp_path, monkeypatch): + import netopsbench.platform.runtime.manager as runtimes_mod + + calls = [] + _record_lifecycle_operations(monkeypatch, calls) + original = KeyboardInterrupt("cancel after deploy") + + def interrupt(runtime): + raise original + + monkeypatch.setattr(runtimes_mod.RuntimePool, "ensure_observability", interrupt) + monkeypatch.setattr(runtimes_mod, "teardown_workers", lambda workers, registry: calls.append("compensated")) + manager = runtimes_mod.RuntimeManager(workspace=tmp_path) + with pytest.raises(KeyboardInterrupt) as caught: + manager.provision(scale="xs", name="cancelled") + assert caught.value is original + assert "compensated" in calls + assert not (manager.runtime_root_dir / "cancelled").exists() + + +@pytest.mark.parametrize("metadata_failure", [False, True]) +def test_provision_interrupt_retains_ownership_on_cleanup_failure(tmp_path, monkeypatch, metadata_failure): + import netopsbench.platform.runtime.manager as runtimes_mod + + calls = [] + _record_lifecycle_operations(monkeypatch, calls) + original = KeyboardInterrupt("cancel after deploy") + cleanup = RuntimeError("cannot destroy owned resources") + + def interrupt(runtime): + raise original + + def fail_cleanup(*args): + if metadata_failure: + + def fail_write(runtime): + raise OSError("metadata disk failure") + + monkeypatch.setattr(runtimes_mod.RuntimePool, "_write_metadata", fail_write) + raise cleanup + + monkeypatch.setattr(runtimes_mod.RuntimePool, "ensure_observability", interrupt) + monkeypatch.setattr(runtimes_mod, "teardown_workers", fail_cleanup) + manager = runtimes_mod.RuntimeManager(workspace=tmp_path) + with pytest.raises(runtimes_mod.RuntimeProvisionError) as caught: + manager.provision(scale="xs", name="cancelled") + error = caught.value + assert error.provision_error is original + assert error.cleanup_error is cleanup + assert error.__cause__ is cleanup + assert error.runtime.state == "cleanup_failed" + assert error.runtime.metadata["quarantined"] is True + assert error.runtime.root_dir.exists() + assert "KeyboardInterrupt" in error.runtime.metadata["provision_error"] + if metadata_failure: + assert "metadata disk failure" in error.runtime.metadata["quarantine_persistence_error"] + else: + payload = json.loads((error.runtime.root_dir / "runtime.json").read_text()) + assert payload["state"] == "cleanup_failed" + + +@pytest.mark.parametrize("scale", ["xlarge", "fat-tree-k12"]) +def test_large_runtime_workers_use_non_overlapping_23_subnets(tmp_path, scale): + from netopsbench.sdk.runtimes import RuntimeManager + + runtime = RuntimeManager(workspace=tmp_path).create(scale=scale, workers=2, name="runtime-subnets") + first, second = [worker.mgmt_subnet for worker in runtime.workers] + assert first.endswith("/23") and second.endswith("/23") + assert first != second + assert int(first.split(".")[2]) % 2 == 0 + assert int(second.split(".")[2]) == int(first.split(".")[2]) + 2 + if scale == "fat-tree-k12": + assert int(first.split(".")[2]) >= 220 + + +def test_teardown_interrupted_deployment_preserves_cleanup_error_when_metadata_fails(tmp_path, monkeypatch): + from netopsbench.platform.runtime import manager as module + + runtime = module.RuntimeManager(workspace=str(tmp_path)).create(scale="xs", name="interrupted") + runtime.metadata["deployment_started"] = True + failure = KeyboardInterrupt("cleanup interrupted") + calls = [] + + def interrupt(self, stage, pool): + calls.append(stage) + assert pool is runtime + raise failure + + def persist_failure(): + raise OSError("metadata unavailable") + + monkeypatch.setattr(module.RuntimeLifecycle, "run", interrupt) + monkeypatch.setattr(runtime, "_write_metadata", persist_failure) + with pytest.raises(KeyboardInterrupt) as caught: + runtime.teardown() + assert caught.value is failure + assert calls == ["teardown"] + assert runtime.state == "cleanup_failed" + assert runtime.metadata["quarantined"] is True + assert "metadata unavailable" in runtime.metadata["quarantine_persistence_error"] + assert runtime.root_dir.exists() diff --git a/tests/test_api_scenarios.py b/tests/test_api_scenarios.py index 1b05c80..044ddf9 100644 --- a/tests/test_api_scenarios.py +++ b/tests/test_api_scenarios.py @@ -12,13 +12,38 @@ from netopsbench.sdk.scenarios import ScenarioManager +def test_recovery_policy_authoring_and_legacy_roundtrip(tmp_path): + from netopsbench.sdk import RecoveryPolicy + + manager = ScenarioManager(workspace=tmp_path) + kwargs = dict( + id="healthy", + name="healthy", + episode={"episode_id": "diagnosis", "fault_type": "none"}, + metadata={"negative_sample": True}, + ) + new = manager.create(**kwargs) + assert RecoveryPolicy.from_metadata(new.metadata).version == 3 + old = new.model_copy(deep=True) + old.metadata.pop("recovery_policy") + digest = old.digest + path = manager.save(old, tmp_path / "legacy.yaml") + with pytest.raises(ScenarioValidationError, match="migrate"): + manager.load(path) + from netopsbench.platform.scenario.parser import parse_scenario_file + + assert parse_scenario_file(path).digest == digest + with pytest.raises(ScenarioValidationError, match="only once"): + manager.create(**{**kwargs, "metadata": {"recovery_policy": {}}}, recovery_policy={}) + + def test_scenario_manager_can_create_and_roundtrip_yaml(tmp_path): manager = ScenarioManager(workspace=tmp_path) scenario = manager.create( id="scenario_x", name="Scenario X", description="desc", - scale="small", + scale="medium", episode={ "episode_id": "diagnosis", "fault_type": "static_route_misconfig", @@ -33,7 +58,7 @@ def test_scenario_manager_can_create_and_roundtrip_yaml(tmp_path): assert loaded == scenario assert loaded.id == "scenario_x" - assert loaded.scale == "small" + assert loaded.scale == "medium" assert loaded.episode.fault_type == "static_route_misconfig" assert scenario_from_dict(scenario.to_dict()) == scenario @@ -86,7 +111,15 @@ def test_scenario_manager_rejects_nonstandard_traffic_profile(tmp_path, profile) def test_supported_scales_are_available_from_public_sdk(): from netopsbench.sdk import supported_scales - assert supported_scales() == ("xs", "small", "medium", "large", "xlarge", "fat-tree-k8", "fat-tree-k12") + assert supported_scales() == ( + "xs", + "medium", + "large", + "xlarge", + "fat-tree-k8", + "fat-tree-k12", + "fat-tree-k18", + ) def test_scenario_validation_uses_fault_registry(tmp_path): @@ -122,7 +155,7 @@ def test_validate_scenario_does_not_mutate_fault_type_alias(): scenario_id="alias_case", name="Alias Case", topology_scale="xs", - metadata={"difficulty": "easy"}, + metadata={"recovery_policy": {"version": 3}, "difficulty": "easy"}, episode=EpisodeSpec( episode_id="diagnosis", fault_type="static_route_misconfiguration", diff --git a/tests/test_api_sessions.py b/tests/test_api_sessions.py index caaf666..0763bd5 100644 --- a/tests/test_api_sessions.py +++ b/tests/test_api_sessions.py @@ -71,7 +71,6 @@ def __init__( topology_dir, topology_metadata=None, minimum_baseline_seconds=5, - post_recovery_wait_seconds=2, influxdb_url=None, influxdb_token=None, influxdb_org=None, @@ -100,7 +99,7 @@ def run_scenario(self, scenario, diagnosis_callback=None): }, "observations": {"start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:01:00Z"}, }, - diagnostic_session=SimpleNamespace(), + diagnostic_session=SimpleNamespace(config=SimpleNamespace(max_agent_seconds=600)), diagnostic_payload={ "case_id": "case-test", "topology": {"devices": {}, "links": []}, @@ -150,6 +149,9 @@ def run_scenario(self, scenario, diagnosis_callback=None): }, } + def final_calibration(self, scenario, **kwargs): + return {"success": True, "reason": "run_end", "destroy_after_run": kwargs["destroy_after_run"]} + def close(self): return None @@ -298,6 +300,7 @@ def test_run_on_runtime_scenario_supports_handle_and_path_without_teardown(tmp_p artifacts_dir=tmp_path / "existing-runs", ) + assert first.report().raw["worker_summaries"][0]["final_calibration"]["destroy_after_run"] is False assert first.runtime_id == "existing-runtime" assert second.runtime_id == "existing-runtime" assert bench.runtimes.get("existing-runtime") is not None @@ -356,7 +359,7 @@ def test_mixed_scale_suite_fails_before_runtime_provision(tmp_path, monkeypatch) bench = NetOpsBench(workspace=str(tmp_path)) scenarios = [ _make_scenario(scenario_id="xs-case"), - _make_scenario(scenario_id="small-case").model_copy(update={"topology_scale": "small"}), + _make_scenario(scenario_id="small-case").model_copy(update={"topology_scale": "medium"}), ] provisioned = [] monkeypatch.setattr( @@ -748,6 +751,8 @@ def test_keep_runtime_false_tears_down_runtime_and_true_preserves_it(tmp_path, m removed = bench.sessions.run_scenario(scenario=scenario, agent=DummyAgent(), keep_runtime=False) preserved = bench.sessions.run_scenario(scenario=scenario, agent=DummyAgent(), keep_runtime=True) + assert removed.report().raw["worker_summaries"][0]["final_calibration"]["destroy_after_run"] is True + assert preserved.report().raw["worker_summaries"][0]["final_calibration"]["destroy_after_run"] is False assert bench.runtimes.get(removed.runtime_id) is None assert not (tmp_path / ".netopsbench" / "runtimes" / removed.runtime_id).exists() assert bench.runtimes.get(preserved.runtime_id) is not None @@ -756,6 +761,107 @@ def test_keep_runtime_false_tears_down_runtime_and_true_preserves_it(tmp_path, m assert preserved.report().raw["execution"] == "real_runtime_runner" +@pytest.mark.parametrize("entry_point", ["run_scenario", "run_suite"]) +@pytest.mark.parametrize("failure_phase", ["cleanup", "final_calibration"]) +@pytest.mark.parametrize("keep_runtime", [False, True]) +def test_sdk_session_failure_quarantines_runtime_and_preserves_report( + tmp_path, monkeypatch, entry_point, failure_phase, keep_runtime +): + import netopsbench.platform.runtime.manager as runtimes_mod + import netopsbench.platform.session.dispatch as dispatch_mod + + _install_real_runtime_mocks(monkeypatch) + _install_platform_runtime_mocks(monkeypatch) + executed, quarantined = [], [] + original_quarantine = runtimes_mod.RuntimePool.mark_quarantined + original_error = f"original {failure_phase} failure" + + class FailingRunner(dispatch_mod.ScenarioExecutor): + def run_scenario(self, scenario, diagnosis_callback=None): + executed.append(scenario.id) + return { + "success": True, + "case_valid": True, + "episode": {}, + "cleanup": { + "success": failure_phase != "cleanup", + "errors": [original_error] if failure_phase == "cleanup" else [], + }, + } + + def final_calibration(self, scenario, **kwargs): + raise RuntimeError(original_error) + + def record_quarantine(runtime, reason, workers=None): + original_quarantine(runtime, reason, workers) + quarantined.append(runtime) + + monkeypatch.setattr(dispatch_mod, "ScenarioExecutor", FailingRunner) + monkeypatch.setattr(runtimes_mod.RuntimePool, "mark_quarantined", record_quarantine) + with NetOpsBench(workspace=str(tmp_path)) as bench: + first = _make_scenario(scenario_id="first") + second = _make_scenario(scenario_id="second") + arguments = {"scenario": first} if entry_point == "run_scenario" else {"scenarios": [first, second]} + run = getattr(bench.sessions, entry_point)( + **arguments, agent=DummyAgent(), keep_runtime=keep_runtime, trace=False + ) + report = run.report() + + assert run.status == "failed" + assert quarantined + runtime = quarantined[0] + reason = "scenario_cleanup_failure" if failure_phase == "cleanup" else "final_calibration_failure" + assert runtime.metadata["quarantine_reason"] == reason + assert runtime.metadata["quarantined_workers"] == ["worker-1"] + assert runtime.metadata["quarantined"] is True + worker = report.raw["worker_summaries"][0] + expected_count = 2 if entry_point == "run_suite" and failure_phase == "final_calibration" else 1 + assert len(executed) == expected_count + assert len(report.detailed_results) == expected_count + assert report.summary["total_cases"] == (2 if entry_point == "run_suite" else 1) + assert report.summary["average_score"] == 1.0 + if failure_phase == "cleanup": + assert report.scenario_summaries[0]["failure_stage"] == "cleanup" + raw = json.loads(Path(report.scenario_summaries[0]["raw_result_path"]).read_text()) + assert raw["cleanup"]["errors"] == [original_error] + if entry_point == "run_suite": + assert report.scenario_summaries[1]["status"] == "skipped_infrastructure_failure" + else: + assert worker["final_calibration"] == {"success": False, "error": original_error} + + preserved = bench.runtimes.get(run.runtime_id) + if keep_runtime: + assert preserved.state == "quarantined" + persisted = json.loads((preserved.root_dir / "runtime.json").read_text()) + assert persisted["metadata"]["quarantined"] is True + else: + assert preserved is None + assert not runtime.root_dir.exists() + assert report.raw["teardown"] == "performed" + + +@pytest.mark.parametrize("failure_phase", ["provision", "teardown"]) +def test_sdk_session_retains_public_runtime_errors(tmp_path, monkeypatch, failure_phase): + import netopsbench.platform.runtime.manager as runtimes_mod + from netopsbench.sdk import RuntimeProvisionError + + _install_real_runtime_mocks(monkeypatch) + _install_platform_runtime_mocks(monkeypatch) + original = OSError(f"original {failure_phase} failure") + + def fail(*args, **kwargs): + raise original + + owner = runtimes_mod.RuntimeManager if failure_phase == "provision" else runtimes_mod.RuntimePool + monkeypatch.setattr(owner, failure_phase, fail) + with NetOpsBench(workspace=str(tmp_path)) as bench: + with pytest.raises(RuntimeProvisionError, match=str(original)) as error: + bench.sessions.run_scenario( + scenario=_make_scenario(scenario_id="runtime-failure"), agent=DummyAgent(), trace=False + ) + assert error.value.__cause__ is original + + def test_benchmark_report_exposes_spec_shape_and_void_helpers(tmp_path, capsys): report = BenchmarkReport( id="report-123", @@ -807,3 +913,66 @@ def test_run_scenario_does_not_leak_fault_ground_truth_into_agent_context(tmp_pa assert "target_device" not in episode assert "target_interface" not in episode assert not hasattr(context, "ground_truth") + + +def test_acceptance_control_reuses_executor_checkpoints_and_stops_after_failed_case(monkeypatch, tmp_path): + import threading + + import netopsbench.platform.session.dispatch as dispatch + from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec + + executions, checkpoints, closes, builds = [], [], [], [] + scenarios = [ + ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, + scenario_id=str(i), + name=str(i), + topology_scale="xs", + episode=EpisodeSpec(episode_id="diagnosis", fault_type="none"), + ) + for i in range(3) + ] + worker = SimpleNamespace(worker_id="worker-1", lab_name="lab", topology_dir=tmp_path) + runtime = SimpleNamespace(id="runtime", metadata={}, state="warm") + + class Runner: + evaluator = None + + def run_scenario(self, scenario, diagnosis_callback=None): + executions.append(scenario.id) + return {"case_valid": True, "success": scenario.id == "0", "cleanup": {"success": True}, "episode": {}} + + def final_calibration(self, scenario, **kwargs): + return {"success": True} + + def close(self): + closes.append(True) + + def build(*a, **kw): + builds.append(True) + return Runner() + + monkeypatch.setattr(dispatch, "_build_scenario_executor", build) + monkeypatch.setattr(dispatch, "build_worker_execution_context", lambda *a: SimpleNamespace(topology_dir=tmp_path)) + monkeypatch.setattr(dispatch, "require_scenario_topology", lambda *a: None) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *a, **kw: None) + control = dispatch.ExecutionControl( + on_case=lambda summary, *a: checkpoints.append(summary), stop_on_failure=True, cancel_event=threading.Event() + ) + result = dispatch._run_worker( + runtime=runtime, + agent=None, + raw_dir=tmp_path, + trace_writer=None, + fault_registry=None, + minimum_baseline_seconds=60, + scale_registry=None, + worker=worker, + scenarios=scenarios, + control=control, + ) + assert executions == ["0", "1"] + assert len(builds) == len(closes) == 1 + assert [item["status"] for item in checkpoints] == ["completed", "failed"] + assert result[1][-1]["status"] == "skipped_execution_failure" + assert runtime.state == "warm" diff --git a/tests/test_apply_configs.py b/tests/test_apply_configs.py index b6471d3..c3f98d4 100644 --- a/tests/test_apply_configs.py +++ b/tests/test_apply_configs.py @@ -10,6 +10,18 @@ def _completed(args, returncode=0, stdout="", stderr=""): return subprocess.CompletedProcess(args=args, returncode=returncode, stdout=stdout, stderr=stderr) +def _install_probe_transport(monkeypatch, fake_command): + from netopsbench.platform.runtime._sonic_probe import probe + + def transport(cmd, **kwargs): + assert cmd[:4] == ["docker", "exec", cmd[2], "python3"] + request = json.loads(cmd[-1]) + result = probe(request["services"], request["expected_port_count"], run=fake_command) + return _completed(cmd, stdout=json.dumps(result)) + + monkeypatch.setattr(apply_configs, "safe_run", transport) + + def test_wait_for_sonic_requires_configdb_after_vtysh(monkeypatch): calls = [] @@ -29,9 +41,9 @@ def fake_safe_run(cmd, **kwargs): raise AssertionError(f"unexpected command: {cmd}") monkeypatch.setattr(apply_configs, "docker_prefix", lambda: []) - monkeypatch.setattr(apply_configs, "safe_run", fake_safe_run) + _install_probe_transport(monkeypatch, fake_safe_run) - assert apply_configs._wait_for_sonic("spine1", "clab-demo-spine1", max_tries=1, delay=0) + assert apply_configs._wait_for_sonic("clab-demo-spine1", max_tries=1, delay=0) assert any("sonic-cfggen" in cmd for cmd in calls) assert any("vtysh" in cmd for cmd in calls) @@ -60,9 +72,9 @@ def fake_safe_run(cmd, **kwargs): raise AssertionError(f"unexpected command: {cmd}") monkeypatch.setattr(apply_configs, "docker_prefix", lambda: []) - monkeypatch.setattr(apply_configs, "safe_run", fake_safe_run) + _install_probe_transport(monkeypatch, fake_safe_run) - assert apply_configs._wait_for_sonic("spine1", "clab-demo-spine1", max_tries=1, delay=0) + assert apply_configs._wait_for_sonic("clab-demo-spine1", max_tries=1, delay=0) repair_calls = [cmd for cmd in calls if "bash" in cmd and any("start.sh" in part for part in cmd)] assert repair_calls == [] @@ -81,9 +93,9 @@ def fake_safe_run(cmd, **kwargs): raise AssertionError(f"unexpected command: {cmd}") monkeypatch.setattr(apply_configs, "docker_prefix", lambda: []) - monkeypatch.setattr(apply_configs, "safe_run", fake_safe_run) + _install_probe_transport(monkeypatch, fake_safe_run) - assert not apply_configs._wait_for_sonic("spine12", "clab-demo-spine12", max_tries=2, delay=0) + assert not apply_configs._wait_for_sonic("clab-demo-spine12", max_tries=2, delay=0) repair_calls = [cmd for cmd in calls if "bash" in cmd and any("start.sh" in part for part in cmd)] assert repair_calls == [] @@ -110,9 +122,9 @@ def fake_safe_run(cmd, **kwargs): raise AssertionError(f"unexpected command: {cmd}") monkeypatch.setattr(apply_configs, "docker_prefix", lambda: []) - monkeypatch.setattr(apply_configs, "safe_run", fake_safe_run) + _install_probe_transport(monkeypatch, fake_safe_run) - assert not apply_configs._wait_for_sonic("spine1", "clab-demo-spine1", max_tries=1, delay=0) + assert not apply_configs._wait_for_sonic("clab-demo-spine1", max_tries=1, delay=0) def test_wait_for_sonic_requires_complete_counters_port_map(monkeypatch): @@ -131,10 +143,9 @@ def fake_safe_run(cmd, **kwargs): raise AssertionError(f"unexpected command: {cmd}") monkeypatch.setattr(apply_configs, "docker_prefix", lambda: []) - monkeypatch.setattr(apply_configs, "safe_run", fake_safe_run) + _install_probe_transport(monkeypatch, fake_safe_run) assert not apply_configs._wait_for_sonic( - "edge1", "clab-demo-edge1", max_tries=1, delay=0, @@ -158,10 +169,9 @@ def fake_safe_run(cmd, **kwargs): raise AssertionError(f"unexpected command: {cmd}") monkeypatch.setattr(apply_configs, "docker_prefix", lambda: []) - monkeypatch.setattr(apply_configs, "safe_run", fake_safe_run) + _install_probe_transport(monkeypatch, fake_safe_run) assert apply_configs._wait_for_sonic( - "edge1", "clab-demo-edge1", max_tries=1, delay=0, @@ -356,3 +366,68 @@ def test_ecmp_hash_policies_reject_preseed_device_missing_from_manifest(tmp_path with pytest.raises(RuntimeError, match="stale1"): apply_configs._ecmp_hash_policies(manifest, ["spine1", "stale1"]) + + +@pytest.mark.parametrize( + "stdout", ["", "null", "[]", "{}", '{"version":1,"ready":true}', '{"version":1,"ready":true,"checks":[]}'] +) +def test_readiness_transport_rejects_incomplete_payload(monkeypatch, stdout): + monkeypatch.setattr(apply_configs, "safe_run", lambda *a, **k: _completed(a[0], stdout=stdout)) + assert not apply_configs._sonic_readiness_snapshot([], "container", 8) + + +def test_readiness_uses_one_exec_and_ordered_checks(monkeypatch): + from netopsbench.platform.runtime._sonic_probe import probe + + inner = [] + outer = [] + + def run(cmd, **kwargs): + inner.append(cmd) + text = "redis-server RUNNING\norchagent RUNNING\nzebra RUNNING" if cmd[0] == "supervisorctl" else "8" + return _completed(cmd, stdout=text) + + def transport(cmd, **kwargs): + outer.append(cmd) + req = json.loads(cmd[-1]) + return _completed(cmd, stdout=json.dumps(probe(req["services"], req["expected_port_count"], run=run))) + + monkeypatch.setattr(apply_configs, "safe_run", transport) + assert apply_configs._sonic_readiness_snapshot([], "container", 8) + assert len(outer) == 1 + assert [c[0] for c in inner] == ["sonic-cfggen", "vtysh", "supervisorctl", "sonic-cfggen", "redis-cli"] + assert not any("start.sh" in c for c in inner) + + +@pytest.mark.parametrize("failed_index", range(5)) +def test_readiness_probe_timeout_at_every_step(failed_index): + from netopsbench.platform.runtime._sonic_probe import probe + + calls = [] + + def run(cmd, **kwargs): + calls.append(cmd) + if len(calls) - 1 == failed_index: + raise subprocess.TimeoutExpired(cmd, 15) + return _completed( + cmd, stdout="redis-server RUNNING\norchagent RUNNING\nzebra RUNNING" if cmd[0] == "supervisorctl" else "8" + ) + + assert probe(["redis-server", "orchagent", "zebra"], 8, run=run)["ready"] is False + assert len(calls) == failed_index + 1 + + +def test_readiness_configdb_can_fail_after_vtysh(): + from netopsbench.platform.runtime._sonic_probe import probe + + cfg_calls = 0 + + def run(cmd, **kwargs): + nonlocal cfg_calls + if cmd[0] == "sonic-cfggen": + cfg_calls += 1 + return _completed(cmd, returncode=0 if cfg_calls == 1 else 1) + return _completed(cmd, stdout="redis-server RUNNING\norchagent RUNNING\nzebra RUNNING") + + assert not probe(["redis-server", "orchagent", "zebra"], run=run)["ready"] + assert cfg_calls == 2 diff --git a/tests/test_baseline_handoff.py b/tests/test_baseline_handoff.py new file mode 100644 index 0000000..66b102e --- /dev/null +++ b/tests/test_baseline_handoff.py @@ -0,0 +1,509 @@ +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +import pytest + +from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec +from netopsbench.platform.scenario.baseline import BaselineHandoff, RuntimeScope, runtime_scope, window_error +from netopsbench.platform.scenario.executor import ScenarioExecutor +from netopsbench.platform.topology.generator import generate_topology + + +def window(age=0, duration=66): + end = datetime.now(UTC) - timedelta(seconds=age) + return { + "name": "baseline", + "start_time": (end - timedelta(seconds=duration)).isoformat(), + "end_time": end.isoformat(), + "duration_seconds": duration, + } + + +def observation(*, healthy=True, complete=True): + return { + **window(), + "data_source_status": "ok", + "coverage_status": "complete" if complete else "incomplete", + "_baseline_coverage": {"coverage_status": "complete"}, + "_baseline_health": { + "absolute_unreachable_paths": 0 if healthy else 2, + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, + "pingmesh_metrics": {"summary": {"latency_spikes": 0}, "quality": {"current_paths_observed": 2}}, + } + + +def scenario(name="case", fault="none"): + return ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, + scenario_id=name, + name=name, + topology_scale="xs", + episode=EpisodeSpec( + episode_id="diagnosis", + fault_type=fault, + duration_seconds=66, + target_device="leaf1" if fault != "none" else None, + ), + ) + + +@pytest.mark.parametrize("age,duration,expected", [(0, 66, True), (601, 66, True), (-10, 66, False), (0, 30, False)]) +def test_window_age_and_full_coverage_duration(age, duration, expected): + assert (window_error(window(age, duration), 60) is None) is expected + + +def test_handoff_requires_recovery_and_does_not_refresh_window(): + h = BaselineHandoff() + w = window() + assert h.publish(w, "scope", "case1", 60, verified=True) + assert h.take("scope", 60)[0] == w + assert h.take("scope", 60) == (None, "previous_case_not_verified") + h.ready = True + assert h.take("scope", 60)[0] == w + assert h.uses == 2 + + +def test_only_a_new_verified_window_refreshes_calibration(monkeypatch): + import netopsbench.platform.scenario.baseline as module + + clock = [0.0] + monkeypatch.setattr(module.time, "monotonic", lambda: clock[0]) + handoff = BaselineHandoff() + first = window() + assert handoff.publish(first, "scope", "first", 60, verified=True) + assert handoff.take("scope", 60)[0] == first + + clock[0] = 601 + newer = window() + assert handoff.publish(newer, "scope", "recovered", 60, verified=True) + assert handoff.epoch == 601 + assert handoff.take("scope", 60)[0] == newer + + clock[0] = 1202 + assert handoff.publish(newer, "scope", "repeated", 60, verified=True) + assert handoff.epoch == 601 + assert handoff.take("scope", 60)[0] == newer + assert handoff.uses == 2 + + +@pytest.mark.parametrize("age,duration,reason", [(-10, 66, "future_window"), (0, 30, "short_window")]) +def test_rejected_publication_preserves_the_reason(age, duration, reason): + handoff = BaselineHandoff() + assert not handoff.publish(window(age, duration), "scope", "case", 60, verified=True) + assert handoff.last_reason == reason + assert handoff.take("scope", 60) == (None, reason) + + +def test_unavailable_and_changed_scopes_have_distinct_reasons(): + handoff = BaselineHandoff() + assert not handoff.publish(window(), None, "case", 60, verified=True) + assert handoff.last_reason == "scope_unavailable" + handoff.publish(window(), "old", "case", 60, verified=True) + assert handoff.take("new", 60) == (None, "scope_changed") + + +def test_scope_differences_identify_the_changed_component(): + from netopsbench.platform.scenario.baseline import RuntimeScope, scope_changes + + first = RuntimeScope({"plan": "p"}, {"frr/a": "old"}, {"a": ["id"]}) + second = RuntimeScope({"plan": "p"}, {"frr/a": "new"}, {"a": ["id"]}) + assert scope_changes(first, second) == ["configs:frr/a"] + assert first.digest != second.digest + + +def test_frr_normalization_preserves_context_and_order(): + from netopsbench.platform.scenario.baseline import normalized_frr + + text = "frr version 10.3\nrouter bgp 65001\n neighbor 10.0.0.1 remote-as 65002\n!\nline vty\n" + assert normalized_frr(text) == normalized_frr( + "Building configuration...\nCurrent configuration:\n! saved now\n" + text + "end\n" + ) + assert normalized_frr(text) != normalized_frr(text.replace(" neighbor", "neighbor")) + assert normalized_frr(text) != normalized_frr(text.replace("65002", "65003")) + + +def test_only_proven_owned_rewrite_can_change_recovery_scope(): + from netopsbench.platform.scenario.baseline import RuntimeScope, restored_scope_errors + + before = RuntimeScope({"plan": "p"}, {"configs/frr/leaf1.conf": "old"}, {}) + after = RuntimeScope({"plan": "p"}, {"configs/frr/leaf1.conf": "new"}, {}) + case = scenario(fault="link_down") + assert restored_scope_errors(before, after, case, None) + assert not restored_scope_errors(before, after, case, {"restored": True}) + after.identity["plan"] = "changed" + assert restored_scope_errors(before, after, case, {"restored": True}) == ["identity:plan"] + + +@pytest.fixture +def runner(tmp_path, monkeypatch): + metadata = generate_topology("xs", str(tmp_path), name="test")["metadata"] + r = ScenarioExecutor(topology_metadata=metadata, topology_dir=str(tmp_path), sleep_fn=lambda _: None) + r.calls = [] + + def setup(*args): + r.calls.append("traffic") + r.traffic_controller = SimpleNamespace(active_flows={"a": 1}, verify_active_flows=lambda: True) + return {} + + def reference(): + r.calls.append("reference") + return window() + + def observe(*a, **k): + r.calls.append("observe") + return observation() + + monkeypatch.setattr(r, "_setup_traffic", setup) + monkeypatch.setattr(r, "_capture_baseline_window", reference) + monkeypatch.setattr(r, "_capture_observation_window", lambda seconds, name: window(duration=seconds)) + monkeypatch.setattr(r, "_merge_observation_windows", observe) + monkeypatch.setattr(r, "_baseline_scope", lambda _: RuntimeScope({}, {}, {})) + monkeypatch.setattr("netopsbench.platform.observability.routes.collect_routes", lambda *a, **k: {"nodes": {}}) + monkeypatch.setattr( + r, + "_cleanup_after_scenario", + lambda *a, **k: {"success": True, "status": "clean", "validation_level": "state_checked"}, + ) + return r + + +def run(r, name, fault="none"): + return r.run_scenario(scenario(name, fault), diagnosis_callback=lambda *a, **k: {"verdict": "network_healthy"}) + + +def test_two_healthy_cases_keep_independent_observations_and_share_verified_baseline(runner): + first = run(runner, "one") + second = run(runner, "two") + assert first["success"] and second["success"] + assert first["baseline_preparation"]["mode"] == "fresh" + assert { + k: second["baseline_preparation"][k] for k in ("mode", "reason", "source_scenario_id", "scope_changes") + } == { + "mode": "reused", + "reason": "verified_previous_case", + "source_scenario_id": "one", + "scope_changes": [], + } + assert runner.calls == ["traffic", "reference", "observe", "observe", "observe"] + assert first["cleanup"]["baseline_handoff"] and second["cleanup"]["baseline_handoff"] + + +def test_failed_baseline_retains_window_coverage_and_health_without_diagnosis(runner, monkeypatch): + validation = observation() + validation["_baseline_health"]["absolute_network_mtu_paths"] = 1 + validation["_coverage_audit"] = {"plan_id": "current-plan", "coverage_status": "complete"} + monkeypatch.setattr(runner, "_merge_observation_windows", lambda *a, **k: validation) + + result = run(runner, "failed-baseline") + + assert result["case_valid"] is False + assert result["episode"] is None + assert "absolute_network_mtu_paths=1" in result["error"] + assert result["phase_timings"]["calibration"]["failed_validation"] == validation + assert result["cleanup"]["success"] is False + assert result["cleanup_failed"] + assert not runner._baseline_handoff.ready + + +@pytest.mark.parametrize("invalid", ["scope", "case_limit", "cleanup", "unhealthy", "incomplete", "missing_absolute"]) +def test_invalid_candidate_forces_fresh_single_baseline(runner, monkeypatch, invalid): + if invalid in {"unhealthy", "incomplete", "missing_absolute"}: + candidate = observation(healthy=invalid != "unhealthy", complete=invalid != "incomplete") + if invalid == "missing_absolute": + candidate.pop("_baseline_health") + monkeypatch.setattr(runner, "_merge_observation_windows", lambda *a, **k: candidate) + result = run(runner, "invalid-baseline") + assert not result["success"] + assert result["cleanup_failed"] + assert not runner._baseline_handoff.ready + return + if invalid == "cleanup": + monkeypatch.setattr(runner, "_cleanup_after_scenario", lambda *a, **k: {"success": False}) + run(runner, "one") + if invalid == "scope": + monkeypatch.setattr(runner, "_baseline_scope", lambda _: "new") + if invalid == "case_limit": + runner._baseline_handoff.uses = runner._baseline_handoff.max_cases + monkeypatch.setattr( + runner, "_cleanup_after_scenario", lambda *a, **k: {"success": True, "validation_level": "state_checked"} + ) + second = run(runner, "two") + assert second["baseline_preparation"]["mode"] == "fresh" + assert runner.calls.count("reference") == 2 + + +@pytest.mark.parametrize("next_fault", ["none", "link_down"]) +def test_fault_recovery_window_is_handed_to_next_case(runner, monkeypatch, next_fault): + monkeypatch.setattr(runner, "_inject_fault", lambda *a: {"success": True}) + monkeypatch.setattr(runner, "_capture_observation_window", lambda seconds, name: window(duration=seconds)) + monkeypatch.setattr( + runner, + "_merge_observation_windows", + lambda windows, *a, **k: observation(healthy=all(w.get("name") == "baseline" for w in windows)), + ) + monkeypatch.setattr( + runner, "_cleanup_after_scenario", lambda *a, **k: {"success": True, "validated_baseline": window()} + ) + first = run(runner, "fault", "link_down") + second = run(runner, "next", next_fault) + assert first["case_valid"] and first["cleanup"]["baseline_handoff"] + assert second["baseline_preparation"]["mode"] == "reused" + + +def test_verified_recovery_window_is_bound_to_its_new_identity(runner, monkeypatch): + identities = iter([RuntimeScope({"id": i}, {}, {}) for i in ["before"] * 4 + ["recovered"] * 6]) + monkeypatch.setattr(runner, "_baseline_scope", lambda _: next(identities)) + monkeypatch.setattr( + runner, + "_cleanup_after_scenario", + lambda *a, **k: { + "success": True, + "validated_baseline": window(), + "validated_baseline_scope": RuntimeScope({"id": "recovered"}, {}, {}), + }, + ) + first = run(runner, "one") + second = run(runner, "two") + assert first["cleanup"]["baseline_handoff"] + assert second["baseline_preparation"]["mode"] == "reused" + assert second["baseline_preparation"]["scope_changes"] == [] + + +@pytest.mark.parametrize("failure", ["observation", "agent"]) +def test_failed_case_preserves_failure_and_publishes_verified_recovery(runner, monkeypatch, failure): + def analyze(windows, *args, **kwargs): + if any(w.get("name") != "baseline" for w in windows): + raise RuntimeError("Fault observation is invalid") + return observation() + + if failure == "observation": + monkeypatch.setattr(runner, "_inject_fault", lambda *a: {"success": True}) + monkeypatch.setattr(runner, "_merge_observation_windows", analyze) + monkeypatch.setattr( + runner, + "_cleanup_after_scenario", + lambda *a, **k: { + "success": True, + "validated_baseline": window(), + "validated_baseline_scope": RuntimeScope({}, {}, {}), + }, + ) + first = runner.run_scenario( + scenario("failed", "link_down" if failure == "observation" else "none"), + diagnosis_callback=lambda *a, **k: ( + {"success": False, "error": "agent failed"} if failure == "agent" else {"verdict": "network_healthy"} + ), + ) + assert first["case_valid"] is (failure == "agent") + assert first["success"] is False + assert first["cleanup"]["baseline_handoff"] is True + assert first["cleanup"]["baseline_handoff_reason"] == "verified_window_published" + monkeypatch.setattr(runner, "_merge_observation_windows", lambda *a, **k: observation()) + second = run(runner, "next") + assert second["baseline_preparation"]["mode"] == "reused" + assert second["baseline_preparation"]["source_scenario_id"] == "failed" + + +def test_runtime_scope_changes_on_restart_config_policy_and_traffic(tmp_path, monkeypatch): + from netopsbench.platform.scenario import baseline + + metadata = generate_topology("xs", str(tmp_path), name="test")["metadata"] + r = ScenarioExecutor(topology_metadata=metadata, topology_dir=str(tmp_path)) + r.runtime_worker = SimpleNamespace(lab_name="test", runtime_id="test", worker_id="worker-1") + r.traffic_controller = SimpleNamespace(generation=1, plan_digests={"client1": "plan"}) + started = ["first"] + monkeypatch.setattr( + baseline, + "safe_run", + lambda *a, **k: SimpleNamespace(stdout="\n".join(f"id{i} image {started[0]} 1 true false" for i in range(6))), + ) + a = runtime_scope(r, scenario()) + assert a + r.traffic_controller.plan_digests["client1"] = "other" + assert runtime_scope(r, scenario()) != a + r.traffic_controller.plan_digests["client1"] = "plan" + assert runtime_scope(r, scenario()) == a + r.traffic_controller.generation = 2 + assert runtime_scope(r, scenario()) != a + r.traffic_controller.generation = 1 + started[0] = "restarted" + assert runtime_scope(r, scenario()) != a + started[0] = "first" + (tmp_path / "configs" / "changed").write_text("changed") + assert runtime_scope(r, scenario()) != a + (tmp_path / "configs" / "changed").unlink() + assert runtime_scope(r, scenario()) == a + r.topology_id = "different" + assert runtime_scope(r, scenario()) != a + + +def test_observation_reuses_static_detector_and_queries_each_window(tmp_path, monkeypatch): + from netopsbench.platform.pingmesh import detector + from netopsbench.platform.scenario.observation import analyze_observation_windows + from netopsbench.platform.topology.generator import generate_topology + + metadata = generate_topology("xs", str(tmp_path), name="reuse-xs")["metadata"] + runner = ScenarioExecutor(topology_dir=str(tmp_path), topology_metadata=metadata) + instances, queries = [], [] + + class Detector: + def __init__(self, **kwargs): + instances.append(kwargs) + + def generate_windowed_anomaly_report(self, **kwargs): + queries.append(kwargs) + return {"query_status": {"ok": True}, "summary": {}, "coverage": {"coverage_status": "complete"}} + + monkeypatch.setattr(detector, "AnomalyDetector", Detector) + baseline = {"start_time": "2026-10-12T00:00:00Z", "end_time": "2026-10-12T00:01:00Z"} + window = {"name": "fault", "start_time": "2026-10-12T00:02:00Z", "end_time": "2026-10-12T00:03:00Z"} + for _ in range(2): + analyze_observation_windows(runner, [window], 60, baseline) + assert len(instances) == 1 and len(queries) == 2 + assert instances[0]["topology_metadata"] is runner.manifest + runner.influxdb_bucket = "new-bucket" + analyze_observation_windows(runner, [window], 60, baseline) + assert len(instances) == 2 and len(queries) == 3 + + +@pytest.mark.parametrize("entry", ["benchmark", "simulator"]) +def test_entrypoints_share_single_capture_and_verified_reuse(runner, monkeypatch, entry): + from netopsbench.models.profiles import default_scale_registry + from netopsbench.platform.incident.engine import IncidentEngine + from netopsbench.platform.simulator.runtime import RuntimeEpisodeBackend, WarmRuntime + + worker = SimpleNamespace(topology_dir=runner.topology_dir, bucket="bucket", topology_id=runner.topology_id) + record = WarmRuntime(runtime=SimpleNamespace(workers=[worker]), runner=runner) + leases = SimpleNamespace(acquire=lambda scale: record, release=lambda record: None) + monkeypatch.setattr("netopsbench.platform.simulator.runtime.require_scenario_topology", lambda *args: None) + for name in ("one", "two"): + if entry == "benchmark": + assert run(runner, name)["success"] + else: + backend = RuntimeEpisodeBackend(leases, default_scale_registry()) + incident = IncidentEngine(lambda backend=backend: backend).prepare(scenario(name)) + assert incident.state.value == "active", incident.failure + incident.close() + assert incident.cleanup_status.value == "succeeded", incident.cleanup_failure + assert runner.calls.count("reference") == (2 if entry == "simulator" else 1) + assert runner.calls.count("observe") == (4 if entry == "simulator" else 3) + + +def test_cleanup_exception_before_result_retains_original_failure(runner, monkeypatch): + from netopsbench.platform.scenario.incident_backend import ExecutorIncidentBackend + + backend = ExecutorIncidentBackend(runner) + backend.scenario = scenario() + monkeypatch.setattr( + runner, "_cleanup_after_scenario", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("restore failed")) + ) + with pytest.raises(RuntimeError, match="restore failed"): + backend.finish() + assert backend.cleanup_result["success"] is False + assert backend.cleanup_result["errors"] == ["restore failed"] + assert runner._recovering is False + backend.finish() # idempotent; original failed outcome is retained + + +def test_state_checked_cases_reuse_ten_times_then_calibrate(runner, monkeypatch): + from netopsbench.models.recovery import RecoveryPolicy + from netopsbench.platform.observability import routes + from netopsbench.platform.scenario.baseline import RuntimeScope + + scope = RuntimeScope({"traffic_generation": "one"}, {}, {}) + monkeypatch.setattr(runner, "_baseline_scope", lambda _: scope) + monkeypatch.setattr(routes, "collect_routes", lambda *a, **k: {"nodes": {}}) + monkeypatch.setattr( + runner, + "_cleanup_after_scenario", + lambda *a, **k: {"success": True, "validation_level": "state_checked", "status": "clean"}, + ) + cases = [] + for i in range(11): + case = scenario(str(i)) + case.metadata["recovery_policy"] = RecoveryPolicy().model_dump() + cases.append(case) + result = runner.run_scenario(case, diagnosis_callback=lambda *a, **k: {"verdict": "network_healthy"}) + assert result["success"], result + assert result["baseline_preparation"]["uses"] == (i % 10) + 1 + assert result["cleanup"]["validation_level"] == "state_checked" + assert runner.calls.count("reference") == 2 + assert runner.final_calibration(cases[-1])["success"] + assert runner.calls.count("reference") == 3 + assert runner.final_calibration(cases[-1])["reused"] + assert runner.calls.count("reference") == 3 + assert runner.timings.phases["calibration"]["reason"] == "case_limit" + assert runner.timings.phases["calibration_2"]["reason"] == "run_end" + assert all(runner.timings.phases[name]["status"] == "completed" for name in ("calibration", "calibration_2")) + + +def test_failed_state_recovery_cannot_reuse_previous_baseline(runner, monkeypatch): + from netopsbench.models.recovery import RecoveryPolicy + from netopsbench.platform.observability import routes + from netopsbench.platform.scenario.baseline import RuntimeScope + + monkeypatch.setattr(runner, "_baseline_scope", lambda _: RuntimeScope({}, {}, {})) + monkeypatch.setattr(routes, "collect_routes", lambda *a, **k: {"nodes": {}}) + monkeypatch.setattr( + runner, + "_cleanup_after_scenario", + lambda *a, **k: {"success": False, "validation_level": "state_checked", "errors": ["residual ACL"]}, + ) + case = scenario() + case.metadata["recovery_policy"] = RecoveryPolicy().model_dump() + result = runner.run_scenario(case, diagnosis_callback=lambda *a, **k: {"verdict": "network_healthy"}) + assert result["cleanup_failed"] and result["cleanup"]["success"] is False + assert runner._baseline_handoff.window is None + assert not runner._baseline_handoff.ready + + +def test_case_reset_preserves_runtime_state_and_clears_all_case_evidence(tmp_path): + generate_topology("xs", str(tmp_path)) + runner = ScenarioExecutor(topology_dir=str(tmp_path)) + traffic = runner.traffic_controller = object() + handoff = runner._baseline_handoff + runner._case_frr_before = {"old": True} + runner._case_initial_scope = object() + runner._case_routes = {"old": True} + runner._case_affected_pairs = ["old"] + runner._case_probe_pairs = ["old"] + runner.timings.skip("injection", "old") + runner.begin_case() + assert runner.traffic_controller is traffic + assert runner._baseline_handoff is handoff + assert runner.timings.phases == {} + assert runner._case_frr_before is None + assert runner._case_initial_scope is runner._case_routes is None + assert runner._case_affected_pairs == runner._case_probe_pairs == [] + + +@pytest.mark.parametrize("entry", ["benchmark", "simulator"]) +def test_elapsed_hours_do_not_refresh_or_replace_a_verified_baseline(runner, monkeypatch, entry): + from netopsbench.platform.scenario import baseline + from netopsbench.platform.scenario.incident_backend import ExecutorIncidentBackend + + def execute(name): + if entry == "benchmark": + return run(runner, name) + backend = ExecutorIncidentBackend(runner) + backend.prepare(scenario(name)) + backend.finish() + return {"baseline_preparation": backend.baseline_preparation} + + execute("first") + original = dict(runner._baseline_handoff.window) + later = datetime.fromisoformat(original["end_time"]) + timedelta(hours=2) + + class LaterDatetime(datetime): + @classmethod + def now(cls, tz=None): + return later + + monkeypatch.setattr(baseline, "datetime", LaterDatetime) + second = execute("second") + assert second["baseline_preparation"]["mode"] == "reused" + assert runner._baseline_handoff.window == original + assert runner._baseline_handoff.uses == 2 + assert runner.calls.count("reference") == 1 diff --git a/tests/test_bgp_collector.py b/tests/test_bgp_collector.py index 6ce6a0a..76dddf9 100644 --- a/tests/test_bgp_collector.py +++ b/tests/test_bgp_collector.py @@ -35,6 +35,38 @@ def _write_topology( Device(name="spine1", role=DeviceRole.SPINE), Device(name="leaf1", role=DeviceRole.LEAF), ] + switches = [device for device in devices if device.role is not DeviceRole.CLIENT] + clients = [device for device in devices if device.role is DeviceRole.CLIENT] + while len(clients) < 2: + index = len(clients) + 1 + client = Device( + name=f"client{index}", role=DeviceRole.CLIENT, attached_switch=switches[-1 if index == 1 else 0].name + ) + devices.append(client) + clients.append(client) + from netopsbench.models.topology import Link, LinkEndpoint + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + links = [ + Link( + kind="fabric", + endpoints=( + LinkEndpoint(device=a.name, interface=f"eth{i}"), + LinkEndpoint(device=b.name, interface=f"eth{i}"), + ), + ) + for i, (a, b) in enumerate(zip(switches, switches[1:], strict=False), start=1) + ] + links.extend( + Link( + kind="access", + endpoints=( + LinkEndpoint(device=client.attached_switch, interface=f"eth{10+i}"), + LinkEndpoint(device=client.name, interface="eth1"), + ), + ) + for i, client in enumerate(clients) + ) manifest = TopologyManifest( topology_id=name, name=name, @@ -61,8 +93,9 @@ def _write_topology( ecmp_hash_policy_by_role={device.role: 1 for device in devices if device.role is not DeviceRole.CLIENT} ), devices=devices, - links=[], + links=links, ) + manifest.pingmesh_plan = compile_pingmesh_plan(manifest) path.write_text(manifest.model_dump_json(), encoding="utf-8") diff --git a/tests/test_bgp_observability.py b/tests/test_bgp_observability.py index 93d0f12..a7f24ec 100644 --- a/tests/test_bgp_observability.py +++ b/tests/test_bgp_observability.py @@ -395,11 +395,6 @@ def fake_query(query, **kwargs): def test_bgp_fast_event_uses_later_missing_transition_as_latest_state(tmp_path): toolkit = _toolkit(tmp_path) - scope = toolkit._resolve_pingmesh_time_scope( - 10, - "2026-07-11T00:00:00Z", - "2026-07-11T00:00:30Z", - ) rows = [ { "result": "first_state", @@ -437,7 +432,6 @@ def test_bgp_fast_event_uses_later_missing_transition_as_latest_state(tmp_path): events = toolkit._build_bgp_events_fast( rows, - scope, toolkit._bgp_device_roles(), "leaf1", "10.0.0.1", @@ -481,3 +475,65 @@ def fake_exec(container, args, timeout): assert "Bad Peer AS" in result.data["last_reset"] assert all(call[0].endswith("leaf1") for call in calls) assert all("10.0.0.1" in call[1][-1] or "summary" in call[1][-1] for call in calls) + + +@pytest.mark.parametrize( + "states", + [ + ["ESTABLISHED", "ESTABLISHED"], + ["IDLE", "IDLE"], + ["ESTABLISHED", "IDLE"], + ["IDLE", "ESTABLISHED"], + ["ESTABLISHED", "IDLE", "ESTABLISHED"], + ["IDLE", "ESTABLISHED", "IDLE"], + ], +) +@pytest.mark.parametrize("state_filter", ["all", "established", "non_established"]) +@pytest.mark.parametrize("prior", [None, "ESTABLISHED"]) +def test_snapshot_and_indexed_events_preserve_the_same_session_evidence(states, state_filter, prior): + from netopsbench.platform.toolkit._core.observability.bgp_ops import BgpOpsMixin + + toolkit = BgpOpsMixin() + base = {"source": "leaf1", "neighbor_address": "192.0.2.1"} + times = [f"2026-07-11T00:00:{(index + 1) * 5:02}Z" for index in range(len(states))] + snapshots = [ + {**base, "_measurement": "bgp_neighbors", "_time": timestamp, "session_state": state} + for timestamp, state in zip(times, states, strict=True) + ] + indexed = [ + {**base, "result": "first_state", "_time": times[0], "_value": states[0]}, + {**base, "result": "last_state", "_time": times[-1], "_value": states[-1]}, + {**base, "result": "state_count", "_value": len(states)}, + ] + if prior: + snapshots.insert( + 0, + { + **base, + "_measurement": "bgp_neighbors", + "_time": "2026-07-11T00:00:00Z", + "session_state": prior, + "_scope_prior": True, + }, + ) + indexed.append( + { + **base, + "result": "prior_field", + "_field": "session_state", + "_value": prior, + "_time": "2026-07-11T00:00:00Z", + } + ) + indexed.extend( + {**base, "result": "session_events", "previous_state": before, "latest_state": after, "_time": timestamp} + for before, after, timestamp in zip(states, states[1:], times[1:], strict=False) + ) + snapshots.append({"source": "leaf1", "_measurement": "bgp_collection", "collection_ok": True, "_time": times[-1]}) + indexed.append( + {"source": "leaf1", "result": "collection_last", "_field": "collection_ok", "_value": True, "_time": times[-1]} + ) + roles = {"leaf1": "leaf", "spine1": "spine"} + assert toolkit._build_bgp_events( + snapshots, roles, None, None, None, state_filter + ) == toolkit._build_bgp_events_fast(indexed, roles, None, None, None, state_filter) diff --git a/tests/test_canonical_models.py b/tests/test_canonical_models.py index 70b23d2..35e635b 100644 --- a/tests/test_canonical_models.py +++ b/tests/test_canonical_models.py @@ -137,75 +137,29 @@ def test_topology_manifest_requires_exact_ecmp_policy_for_switch_roles(): def test_agent_projection_preserves_canonical_fat_tree_roles(): - core = Device(name="core1", role="core", mgmt_ip="172.20.20.11", asn=65001) - agg = Device(name="agg1", role="agg", mgmt_ip="172.20.20.12", asn=65101) - edge = Device(name="edge1", role="edge", mgmt_ip="172.20.20.13", asn=65201) - client = Device(name="client1", role="client", attached_switch="edge1", data_ip="192.168.1.2") - manifest = TopologyManifest( - topology_id="fat-demo", - name="fat-demo", - scale="fat-tree-k8", - family="fat-tree", - management=Management(network="clab-fat-demo", ipv4_subnet="172.20.20.0/24"), - collector=Collector(ipv4="172.20.20.200"), - defaults=topology_models.TopologyDefaults(), - facts=topology_models.TopologyFacts( - num_cores=1, - num_aggs=1, - num_edges=1, - num_pods=1, - clients_per_attached_switch=1, - total_clients=1, - total_switches=3, - fat_tree_k=2, - full_density_clients_per_attached_switch=1, - host_density="standard", - ), - routing=topology_models.RoutingMetadata( - core_asn_range="65001-65001", - agg_asn_range="65101-65101", - edge_asn_range="65201-65201", - ecmp_hash_policy_by_role={DeviceRole.CORE: 1, DeviceRole.AGG: 0, DeviceRole.EDGE: 1}, - ), - devices=[core, agg, edge, client], - links=[], - ) + from netopsbench.platform.topology.config import FatTreeConfig + from netopsbench.platform.topology.fat_tree_builder import build_fat_tree_plan + manifest = build_fat_tree_plan(FatTreeConfig(k=2, scale_name="fat-tree-k8", name="fat-demo")).manifest projected = manifest.to_agent_topology() - assert "spines" not in projected["devices"] assert "leafs" not in projected["devices"] - assert [device["name"] for device in projected["devices"]["cores"]] == ["core1"] - assert [device["name"] for device in projected["devices"]["aggs"]] == ["agg1"] - assert [device["name"] for device in projected["devices"]["edges"]] == ["edge1"] - projected_client = projected["devices"]["clients"][0] - assert projected_client["name"] == "client1" - assert projected_client["data_ip"] == "192.168.1.2" - assert projected_client["attached_switch"] == "edge1" - assert projected_client["edge"] == "edge1" - assert "leaf" not in projected_client - assert projected["defaults"] == {"link_mtu": 9232, "sonic_port_mtu": 9100} + for group, prefix, count in [ + ("cores", "core", 1), + ("aggs", "agg", 2), + ("edges", "edge", 2), + ("clients", "client", 2), + ]: + assert [device["name"] for device in projected["devices"][group]] == [ + f"{prefix}{i}" for i in range(1, count + 1) + ] + client = projected["devices"]["clients"][0] + assert client["data_ip"] == "192.168.1.2" + assert client["attached_switch"] == client["edge"] == "edge1" + assert "leaf" not in client assert projected["fat_tree_k"] == 2 - assert projected["scale"] == { - "name": "fat-tree-k8", - "num_core": 1, - "num_agg": 1, - "num_edge": 1, - "num_pods": 1, - "clients_per_edge": 1, - "full_density_clients_per_edge": 1, - "host_density": "standard", - "total_clients": 1, - "total_devices": 3, - } - assert projected["routing"]["core_asn_range"] == "65001-65001" assert projected["routing"]["ecmp_hash_policy_by_role"] == {"core": 1, "agg": 0, "edge": 1} - assert [device["role"] for device in manifest.model_dump(mode="json")["devices"]] == [ - "core", - "agg", - "edge", - "client", - ] + assert projected["pingmesh"]["plan_id"] == manifest.pingmesh_plan.settings.plan_id def test_agent_projection_metadata_cannot_overwrite_canonical_device_fields(): @@ -223,7 +177,12 @@ def test_agent_projection_metadata_cannot_overwrite_canonical_device_fields(): }, ) - projected = _manifest(devices=[spine], links=[]).to_agent_topology()["devices"]["spines"][0] + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import TopologyConfig + + manifest = build_clos_plan(TopologyConfig(scale_name="xs")).manifest + manifest.devices[0] = spine + projected = manifest.to_agent_topology()["devices"]["spines"][0] assert projected["name"] == "spine1" assert projected["mgmt_ip"] == "172.20.20.11" @@ -316,7 +275,7 @@ def test_runtime_identity_normal_constructor_applies_defaults(): mgmt_network="clab-mgmt-lab-direct", ) - assert identity.schema_version == "3" + assert identity.schema_version == "4" assert identity.topology_id == "lab-direct" assert identity.bucket == "network_data_run_direct_1_w02" @@ -339,7 +298,7 @@ def test_runtime_identity_rejects_unknown_schema_version(): assert {error["loc"]: error["type"] for error in exc_info.value.errors()}[("schema_version",)] == "literal_error" -def test_runtime_identity_schema_version_defaults_to_v3(): +def test_runtime_identity_schema_version_defaults_to_v4(): identity = RuntimeIdentity( runtime_id="runtime", worker_id="worker-1", @@ -352,7 +311,7 @@ def test_runtime_identity_schema_version_defaults_to_v3(): mgmt_network="clab-mgmt-lab", ) - assert identity.schema_version == "3" + assert identity.schema_version == "4" @pytest.mark.parametrize( @@ -372,12 +331,11 @@ def test_runtime_identity_schema_version_defaults_to_v3(): ), [ ("xs", "clos", 2, 2, None, 1, 24, None, 250, 1800, 2, 60), - ("small", "clos", 2, 4, None, 2, 24, None, 250, 1800, 2, 60), ("medium", "clos", 4, 8, None, 2, 24, None, 200, 1800, 2, 60), ("large", "clos", 4, 16, None, 4, 24, 16, 100, 2700, 1, 180), - ("xlarge", "clos", 16, 128, None, 1, 23, 16, 100, 3600, 1, 240), + ("xlarge", "clos", 16, 128, None, 2, 23, 16, 50, 3600, 1, 240), ("fat-tree-k8", "fat-tree", None, None, 8, 4, 24, 16, 100, 3600, 1, 240), - ("fat-tree-k12", "fat-tree", None, None, 12, 2, 23, 16, 50, 5400, 1, 300), + ("fat-tree-k12", "fat-tree", None, None, 12, 2, 23, 32, 50, 5400, 1, 300), ], ) def test_scale_profiles_keep_exact_runtime_values( @@ -412,18 +370,18 @@ def test_scale_profiles_keep_exact_runtime_values( def test_scale_profile_registry_is_complete_and_rejects_unknown_scales(): assert supported_scales() == ( "xs", - "small", "medium", "large", "xlarge", "fat-tree-k8", "fat-tree-k12", + "fat-tree-k18", ) with pytest.raises(ValueError, match="Unknown scale"): get_scale_profile("not-a-scale") def test_fat_tree_profiles_use_bounded_containerlab_parallelism(): - assert get_scale_profile("fat-tree-k8").containerlab_max_workers == 1 - assert get_scale_profile("fat-tree-k12").containerlab_max_workers == 1 + assert get_scale_profile("fat-tree-k8").containerlab_max_workers == 16 + assert get_scale_profile("fat-tree-k12").containerlab_max_workers == 16 assert get_scale_profile("xlarge").containerlab_max_workers == 16 diff --git a/tests/test_client_agent_control.py b/tests/test_client_agent_control.py index 733f8d8..3b346ee 100644 --- a/tests/test_client_agent_control.py +++ b/tests/test_client_agent_control.py @@ -50,7 +50,7 @@ def test_request_agent_sends_and_validates_one_json_line(monkeypatch): "payload": {}, "protocol_version": 1, } - assert connection.timeout == 3.0 + assert 0 < connection.timeout <= 3.0 @pytest.mark.parametrize( diff --git a/tests/test_client_agent_deploy.py b/tests/test_client_agent_deploy.py index d6975db..ba568c5 100644 --- a/tests/test_client_agent_deploy.py +++ b/tests/test_client_agent_deploy.py @@ -23,7 +23,7 @@ def _write_topology( (topology_dir / "topology.json").write_text( json.dumps( { - "schema_version": "3", + "schema_version": "4", "topology_id": "demo", "name": "demo", "scale": "test", @@ -52,7 +52,7 @@ def _write_topology( "name": name, "role": "client", "attached_switch": "leaf1", - "data_ip": f"192.168.101.{index + 1}", + "data_ip": f"192.168.1.{index + 1}", "mgmt_ip": f"172.20.20.{100 + index}", "metadata": {"rack": "rack1"}, } @@ -65,6 +65,21 @@ def _write_topology( ), encoding="utf-8", ) + from netopsbench.models.topology import Link, LinkEndpoint, TopologyManifest + from netopsbench.platform.client_agent.config import write_client_agent_config + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + manifest = TopologyManifest.model_validate_json((topology_dir / "topology.json").read_text()) + manifest.links = [ + Link( + kind="access", + endpoints=(LinkEndpoint(device="leaf1", interface=f"eth{i}"), LinkEndpoint(device=name, interface="eth1")), + ) + for i, name in enumerate(client_names) + ] + manifest.pingmesh_plan = compile_pingmesh_plan(manifest) + (topology_dir / "topology.json").write_text(manifest.model_dump_json()) + write_client_agent_config(manifest, topology_dir / "configs" / "client-agent" / "client-agent.json") linux_kind = {"image": "client"} if include_bind: linux_kind["binds"] = [deploy_mod.CLIENT_AGENT_BIND] @@ -145,7 +160,8 @@ def _docker(*args: str, check: bool = True, capture: bool = False, **kwargs): assert "iperf3" not in command assert ". /etc/netopsbench/client-agent.env" in command assert "NETOPSBENCH_INFLUXDB_TOKEN=" not in command - assert "> /dev/null 2>&1" in command + assert ">> /var/log/netopsbench/pingmesh.log 2>&1" in command + assert ">> /var/log/netopsbench/traffic.log 2>&1" in command return subprocess.CompletedProcess( ["docker", *args], 0, @@ -164,6 +180,10 @@ def _docker(*args: str, check: bool = True, capture: bool = False, **kwargs): "status": { "ready": port == deploy_mod.PINGMESH_CONTROL_PORT, "heartbeat_unix_ns": deploy_mod.time.time_ns(), + "config_schema_version": 2, + "plan_id": json.loads((topology_dir / "topology.json").read_text())["pingmesh_plan"]["settings"][ + "plan_id" + ], }, }, ) @@ -179,10 +199,11 @@ def _docker(*args: str, check: bool = True, capture: bool = False, **kwargs): config_path = topology_dir / "configs" / "client-agent" / "client-agent.json" config = json.loads(config_path.read_text(encoding="utf-8")) env_path = config_path.with_name("client-agent.env") - assert config["schema_version"] == 1 + assert config["schema_version"] == 2 assert len(config["clients"]) == len(clients) assert "probes" not in config - assert "NETOPSBENCH_INFLUXDB_URL=http://telegraf:8186" in env_path.read_text() + collector = json.loads((topology_dir / "topology.json").read_text())["collector"]["ipv4"] + assert f"NETOPSBENCH_INFLUXDB_URL=http://{collector}:8186" in env_path.read_text() assert "NETOPSBENCH_INFLUXDB_BUCKET=test-bucket" in env_path.read_text() assert env_path.stat().st_mode & 0o777 == 0o600 assert _RecordingExecutor.max_workers_seen == [7] @@ -237,6 +258,10 @@ def _docker(*args: str, check: bool = True, capture: bool = False, **kwargs): "status": { "ready": port == deploy_mod.PINGMESH_CONTROL_PORT, "heartbeat_unix_ns": deploy_mod.time.time_ns(), + "config_schema_version": 2, + "plan_id": json.loads((topology_dir / "topology.json").read_text())["pingmesh_plan"]["settings"][ + "plan_id" + ], }, }, ) @@ -302,6 +327,8 @@ def _status(_host, port, _operation): "status": { "ready": port == deploy_mod.PINGMESH_CONTROL_PORT, "heartbeat_unix_ns": deploy_mod.time.time_ns(), + "config_schema_version": 2, + "plan_id": "expected-plan", }, } @@ -311,7 +338,7 @@ def _status(_host, port, _operation): _status, ) - deploy_mod._wait_until_ready("172.20.20.101") + deploy_mod._wait_until_ready("172.20.20.101", "expected-plan") assert 10.0 <= clock[0] < deploy_mod.READINESS_TIMEOUT_SECONDS @@ -327,7 +354,7 @@ def test_readiness_failure_is_explicit(monkeypatch): ) with pytest.raises(RuntimeError, match="readiness failed: connection refused"): - deploy_mod._wait_until_ready("172.20.20.101") + deploy_mod._wait_until_ready("172.20.20.101", "expected-plan") def test_custom_image_without_native_bind_is_rejected(tmp_path): diff --git a/tests/test_client_setup_commands.py b/tests/test_client_setup_commands.py new file mode 100644 index 0000000..a65f818 --- /dev/null +++ b/tests/test_client_setup_commands.py @@ -0,0 +1,60 @@ +import json +import os +import shlex +import subprocess +import sys + +import pytest + +from netopsbench.platform.topology.planning import client_commands + + +@pytest.mark.parametrize("fail_at", [0, 1, 2, 3, 4, 5]) +@pytest.mark.parametrize("gateway", ["192.168.1.1", "192.168.1.1; exit 99"]) +def test_client_setup_order_and_fail_fast(tmp_path, fail_at, gateway): + log = tmp_path / "calls.jsonl" + stub = ( + f"#!{sys.executable}\n" + "import json,os,pathlib,sys\n" + "p=pathlib.Path(os.environ['SETUP_TEST_LOG'])\n" + "n=len(p.read_text().splitlines())+1 if p.exists() else 1\n" + "with p.open('a') as f: f.write(json.dumps([pathlib.Path(sys.argv[0]).name,*sys.argv[1:]])+'\\n')\n" + "sys.exit(37 if n==int(os.environ['SETUP_TEST_FAIL']) else 0)\n" + ) + for name in ["ip", "ethtool", "sysctl"]: + p = tmp_path / name + p.write_text(stub) + p.chmod(0o755) + commands = client_commands("192.168.1.2", gateway) + assert len(commands) == 1 + env = {**os.environ, "PATH": str(tmp_path), "SETUP_TEST_LOG": str(log), "SETUP_TEST_FAIL": str(fail_at)} + args = shlex.split(commands[0]) + args[0] = "/bin/sh" + result = subprocess.run(args, env=env, capture_output=True, text=True) + assert result.returncode == (37 if fail_at else 0), result.stderr + expected = [ + ["sysctl", "-w", "net.ipv4.ip_forward=0"], + ["ip", "link", "set", "dev", "eth1", "mtu", "9232"], + ["ip", "addr", "add", "192.168.1.2/30", "dev", "eth1"], + ["ip", "route", "add", "192.168.0.0/16", "via", gateway], + [ + "ethtool", + "-K", + "eth1", + "rx", + "off", + "tx", + "off", + "tso", + "off", + "gso", + "off", + "gro", + "off", + "sg", + "off", + "tx-udp-segmentation", + "off", + ], + ] + assert [json.loads(line) for line in log.read_text().splitlines()] == expected[: fail_at or 5] diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py new file mode 100644 index 0000000..16203a1 --- /dev/null +++ b/tests/test_codex_agent.py @@ -0,0 +1,445 @@ +import asyncio +import json +import socket +import subprocess +from types import SimpleNamespace + +import pytest + +from examples.agents.codex_agent.agent import CodexAgent, CodexEvents, redact, strict_output_schema +from examples.agents.codex_agent.proxy import validate_destination +from examples.agents.codex_agent.runtime import DiagnosticContainer, ensure_image, image_content_identity +from netopsbench.platform.toolkit._core.common import ToolResult +from netopsbench.platform.toolkit.mcp.session_server import session_mcp +from netopsbench.sdk.agents import DiagnosticContext + + +@pytest.fixture +def isolated_agent(monkeypatch, tmp_path): + from contextlib import asynccontextmanager, nullcontext + + import examples.agents.codex_agent.agent as module + + @asynccontextmanager + async def endpoint(*a, **kw): + yield {"url": "http://127.0.0.1:1/mcp", "token": "private-token", "port": 1} + + store = tmp_path / "auth" + store.mkdir() + (store / "auth.json").write_text('{"auth_mode":"chatgpt","tokens":{"access_token":"test-secret"}}') + monkeypatch.setattr(module, "session_mcp", endpoint) + monkeypatch.setattr(module, "openai_proxy", lambda *a: nullcontext(1)) + + def create(container, **kwargs): + monkeypatch.setattr(module, "DiagnosticContainer", container) + agent = CodexAgent(auth_store=store, artifacts_dir=tmp_path / "traces", **kwargs) + agent._image_id = "pinned-image" + return agent + + return create + + +def result_events(): + yield { + "type": "item.completed", + "item": { + "id": "final", + "type": "agent_message", + "text": json.dumps( + { + "verdict": "inconclusive", + "fault_type": None, + "location": {"device": None, "interface": None}, + "evidence": [], + "confidence": 0.2, + "reasoning": "insufficient evidence", + } + ), + }, + } + yield {"type": "turn.completed", "usage": {"input_tokens": 11, "output_tokens": 3, "cached_input_tokens": 5}} + + +def test_native_events_validate_final_and_deduplicate_tool_items(): + events = CodexEvents() + for kind in ("item.started", "item.completed"): + events.accept({"type": kind, "item": {"id": "tool", "type": "mcp_tool_call"}}) + for event in result_events(): + events.accept(event) + assert events.result(0)["verdict"] == "inconclusive" + assert events.counts()["mcp_calls"] == 1 + assert events.usage["total_tokens"] == 14 + assert "llm_call_count" not in events.usage + with pytest.raises(RuntimeError): + events.result(1) + events.accept({"type": "turn.failed", "error": {"message": "failed"}}) + with pytest.raises(RuntimeError, match="failed"): + events.result(0) + + +def test_missing_and_invalid_native_output_fail(): + events = CodexEvents() + events.accept({"type": "turn.completed"}) + with pytest.raises(ValueError, match="structured"): + events.result(0) + events.final = '{"verdict":"invented"}' + with pytest.raises(ValueError): + events.result(0) + + +def test_output_schema_and_cli_do_not_inherit_user_agent_state(): + schema = strict_output_schema() + assert set(schema["required"]) == set(schema["properties"]) + assert schema["additionalProperties"] is False + args = CodexAgent().cli_args({"url": "http://192.0.2.1:1000/mcp"}) + for flag in ("--ephemeral", "--ignore-user-config", "--ignore-rules", "--output-schema"): + assert flag in args + assert 'web_search="disabled"' in args + assert "features.multi_agent=false" in args + assert "features.apps=false" in args + assert "mcp_servers.netopsbench.required=true" in args + assert 'service_tier="default"' in args + assert "features.fast_mode=false" in args + assert "features.ultrafast_mode=false" in args + assert CodexAgent().service_tier == "default" + + +def test_image_content_identity_survives_store_conversion_but_detects_execution_changes(monkeypatch): + image = { + "Id": "manifest-id", + "Architecture": "amd64", + "Os": "linux", + "RootFS": {"Type": "layers", "Layers": ["sha256:layer"]}, + "Config": {"Entrypoint": ["/entrypoint.sh"], "Env": ["PATH=/bin"]}, + } + monkeypatch.setattr("examples.agents.codex_agent.runtime.docker", lambda *args: json.dumps([image])) + expected = image_content_identity("image") + image["Id"] = "config-id" + image["Config"].update(User="", WorkingDir="", StopSignal="", AttachStdin=False) + assert image_content_identity("image") == expected + image["Config"]["Entrypoint"] = ["/other.sh"] + assert image_content_identity("image") != expected + image["Config"]["Entrypoint"] = ["/entrypoint.sh"] + image["RootFS"]["Layers"] = ["sha256:other-layer"] + assert image_content_identity("image") != expected + + +def test_secret_redaction_and_proxy_private_destination_rejection(monkeypatch): + assert redact("secret-token Bearer abc.def", ["secret-token"]) == "[REDACTED] Bearer [REDACTED]" + with pytest.raises(ValueError): + validate_destination("example.com:443") + monkeypatch.setattr( + socket, "getaddrinfo", lambda *a, **kw: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443))] + ) + with pytest.raises(ValueError, match="Non-public"): + validate_destination("chatgpt.com:443") + + +def test_private_credential_values_are_redacted_including_account_identity(tmp_path): + from examples.agents.codex_agent.runtime import credentials + + payload = {"tokens": {"access_token": "private-token", "account_id": "private-account"}} + (tmp_path / "auth.json").write_text(json.dumps(payload)) + values = credentials(tmp_path) + cleaned = redact(payload, values) + assert "private-token" not in cleaned + assert "private-account" not in cleaned + assert (tmp_path / "auth.json").stat().st_mode & 0o777 == 0o600 + + +@pytest.mark.asyncio +async def test_episode_mcp_requires_token_uses_gateway_and_enforces_budget(): + import signal + + import httpx + from fastmcp import Client + + original_handler = signal.getsignal(signal.SIGTERM) + calls = [] + context = DiagnosticContext( + "case-anonymous", + {}, + {}, + tools=SimpleNamespace(get_topology=lambda **kw: calls.append(kw) or ToolResult(True, {"window": "episode"})), + ) + async with session_mcp(context, max_tool_calls=1) as endpoint: + assert signal.getsignal(signal.SIGTERM) == original_handler + async with Client(endpoint["url"], auth=endpoint["token"]) as client: + result = await client.call_tool("get_topology", {}) + assert result.data["data"] == {"window": "episode"} + with pytest.raises(Exception, match="budget"): + await client.call_tool("get_topology", {}) + # Verify the HTTP boundary directly: MCP clients can wrap an HTTP 401 + # in a generic transport error whose wording varies by dependency version. + async with httpx.AsyncClient(trust_env=False) as client: + for headers in ({}, {"Authorization": "Bearer incorrect-token"}): + response = await client.post(endpoint["url"], headers=headers, json={}) + assert response.status_code == 401 + assert calls == [{}] + assert signal.getsignal(signal.SIGTERM) == original_handler + + +@pytest.mark.asyncio +async def test_episode_http_tools_inherit_the_agent_deadline(): + import time + + from fastmcp import Client + + from netopsbench.platform.toolkit._core.control import current_tool_control, tool_deadline_scope + + deadline = time.monotonic() + 20 + context = DiagnosticContext( + "case-anonymous", + {}, + {}, + tools=SimpleNamespace( + get_topology=lambda **kw: ToolResult(True, {"deadline": current_tool_control().deadline}) + ), + ) + with tool_deadline_scope(deadline): + async with session_mcp(context) as endpoint: + async with Client(endpoint["url"], auth=endpoint["token"]) as client: + result = await client.call_tool("get_topology", {}) + assert result.data["data"]["deadline"] == deadline + + +@pytest.mark.real +@pytest.mark.asyncio +async def test_real_diagnostic_container_blocks_host_files_privileges_and_network(tmp_path): + ensure_image() + auth = tmp_path / "auth" + auth.mkdir() + inputs = tmp_path / "inputs" + inputs.mkdir() + inputs.chmod(0o755) + probe = inputs / "probe.py" + probe.write_text("""import json, os, socket, urllib.request +from pathlib import Path +assert not Path('/var/run/docker.sock').exists() +assert not Path('/local/ytyang/NetOpsBench-NetX').exists() +assert os.getuid() != 0 +status = Path('/proc/self/status').read_text() +assert 'CapEff:\\t0000000000000000' in status +assert 'CapBnd:\\t0000000000000000' in status +for destination in [(os.environ['DIAGNOSTIC_GATEWAY'], 22), ('172.31.224.2', 22), ('1.1.1.1', 443)]: + try: + socket.create_connection(destination, timeout=1).close() + except OSError: + continue + raise AssertionError('Forbidden destination was reachable') +url = 'http://' + os.environ['DIAGNOSTIC_GATEWAY'] + ':' + os.environ['DIAGNOSTIC_MCP_PORT'] + '/mcp' +body = json.dumps({'jsonrpc':'2.0','id':1,'method':'tools/call','params':{'name':'get_topology','arguments':{}}}).encode() +request = urllib.request.Request(url, data=body, headers={'Authorization':'Bearer '+os.environ['DIAGNOSTIC_MCP_TOKEN'], + 'Content-Type':'application/json', 'Accept':'application/json,text/event-stream'}) +response = urllib.request.urlopen(request, timeout=10) +assert response.status == 200 and 'isolation-ok' in response.read().decode() +print('isolation and authenticated MCP passed') +""") + probe.chmod(0o644) + context = DiagnosticContext( + "isolation", + {}, + {}, + tools=SimpleNamespace(get_topology=lambda **kw: ToolResult(True, {"probe": "isolation-ok"})), + ) + container = DiagnosticContainer("netopsbench-codex:0.159.2", auth) + await asyncio.to_thread(container.open) + try: + async with session_mcp(context, host=container.gateway) as endpoint: + command = container.command( + inputs, + mcp_port=endpoint["port"], + proxy_port=9, + token=endpoint["token"], + cli_args=["python3", "/input/probe.py"], + ) + process = await asyncio.create_subprocess_exec(*command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + output, errors = await asyncio.wait_for(process.communicate(), 30) + assert process.returncode == 0, errors.decode() + assert b"authenticated MCP passed" in output + finally: + await asyncio.to_thread(container.close) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["nonzero", "invalid", "timeout", "startup_timeout", "cancel"]) +async def test_native_process_failures_always_release_resources(monkeypatch, tmp_path, isolated_agent, failure): + import sys + import time + + import examples.agents.codex_agent.agent as module + + releases = [] + script = ( + "import sys,time; sys.stdin.read(); time.sleep(100)" + if failure in {"timeout", "cancel"} + else ( + 'import sys; sys.stdin.read(); print("{}",flush=True); sys.exit(1)' + if failure == "nonzero" + else 'import sys; sys.stdin.read(); print(\'{"type":"turn.completed"}\',flush=True)' + ) + ) + + class Container: + def __init__(self, image, auth_store): + self.auth_store = auth_store + self.gateway = "127.0.0.1" + + def open(self): + if failure == "startup_timeout": + time.sleep(0.08) + return self + + def command(self, *a, **kw): + return [sys.executable, "-c", script] + + def close(self): + releases.append(True) + + if failure == "startup_timeout": + monkeypatch.setattr( + module.asyncio, + "create_subprocess_exec", + lambda *a, **kw: pytest.fail("Expired startup must not launch CLI"), + ) + agent = isolated_agent(Container, timeout_seconds=0.05) + context = DiagnosticContext("anonymous", {}, {}, tools=None) + task = asyncio.create_task(agent.diagnose(context)) + if failure == "cancel": + await asyncio.sleep(0.03) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + else: + result = await task + assert result.success is False + assert result.metadata["agent_failure_stage"] == "diagnose" + if failure == "startup_timeout": + assert result.metadata["error_type"] == "TimeoutError" + assert releases == [True] + assert not agent._containers + store = tmp_path / "auth" + assert list(store.iterdir()) == [store / "auth.json"] + + +@pytest.mark.asyncio +async def test_cancellation_joins_slow_startup_before_cleanup(isolated_agent): + import threading + + started, release = threading.Event(), threading.Event() + steps = [] + + class Container: + def __init__(self, image, auth_store): + self.auth_store = auth_store + + def open(self): + started.set() + release.wait(3) + steps.append("opened") + + def close(self): + steps.append("closed") + + agent = isolated_agent(Container) + task = asyncio.create_task(agent.diagnose(DiagnosticContext("anonymous", {}, {}, tools=None))) + assert await asyncio.to_thread(started.wait, 3) + task.cancel() + await asyncio.sleep(0.02) + assert steps == [] + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert steps == ["opened", "closed"] + assert not agent._containers + + +@pytest.mark.parametrize("failure", ["timeout", "delete", "already_missing"]) +def test_container_cleanup_checks_absence_and_attempts_network_after_failure(monkeypatch, tmp_path, failure): + import examples.agents.codex_agent.runtime as module + + commands = [] + + def run(command, **kwargs): + commands.append(command) + if command[1:3] == ["rm", "-f"] and failure == "timeout": + raise subprocess.TimeoutExpired(command, 60) + if command[1] == "inspect": + if failure == "delete" and "container" in command: + return subprocess.CompletedProcess(command, 0, stdout="exists", stderr="") + return subprocess.CompletedProcess(command, 1, stdout="", stderr="Error: No such object") + return subprocess.CompletedProcess( + command, 1 if failure == "already_missing" else 0, stdout="", stderr="permission denied" + ) + + monkeypatch.setattr(module.subprocess, "run", run) + container = DiagnosticContainer("image", tmp_path) + if failure == "already_missing": + container.close() + else: + with pytest.raises(RuntimeError, match="cleanup failed"): + container.close() + assert ["docker", "network", "rm", container.network] in commands + + +@pytest.mark.parametrize("host_newer", [True, False]) +def test_private_credentials_follow_newer_host_login_without_losing_case_refresh(monkeypatch, tmp_path, host_newer): + from pathlib import Path + + from examples.agents.codex_agent.runtime import credentials + + host = tmp_path / "host" + (host / ".codex").mkdir(parents=True) + store = tmp_path / "private" + store.mkdir() + earlier, later = "2026-10-11T00:00:00Z", "2026-10-12T00:00:00Z" + (host / ".codex/auth.json").write_text( + json.dumps( + { + "last_refresh": later if host_newer else earlier, + "tokens": {"access_token": "host-token"}, + } + ) + ) + (store / "auth.json").write_text( + json.dumps( + { + "last_refresh": earlier if host_newer else later, + "tokens": {"access_token": "case-token"}, + } + ) + ) + monkeypatch.setattr(Path, "home", lambda: host) + secrets = credentials(store, refresh_from_host=True) + assert secrets == ["host-token" if host_newer else "case-token"] + assert (store / "auth.json").stat().st_mode & 0o777 == 0o600 + + +@pytest.mark.asyncio +async def test_cleanup_failure_is_reported_without_mutating_frozen_result(isolated_agent): + import sys + + class Container: + name, network, gateway = "owned-container", "owned-network", "127.0.0.1" + + def __init__(self, image, auth_store): + self.auth_store = auth_store + + def open(self): + pass + + def command(self, *a, **kw): + events = list(result_events()) + script = "import sys;sys.stdin.read();" + ";".join(f"print({json.dumps(event)!r})" for event in events) + return [sys.executable, "-c", script] + + def close(self): + raise RuntimeError("Docker removal failed") + + agent = isolated_agent(Container) + result = await agent.diagnose(DiagnosticContext("anonymous", {}, {}, tools=None)) + assert result.success is False + assert result.metadata["cleanup_errors"] == ["Docker removal failed"] + assert result.metadata["retained_resources"]["container"] == "owned-container" + assert len(agent._containers) == 1 + assert all(not container.auth_store.exists() for container in agent._containers) diff --git a/tests/test_commands_cli.py b/tests/test_commands_cli.py index a2dc0a1..e9d2aaa 100644 --- a/tests/test_commands_cli.py +++ b/tests/test_commands_cli.py @@ -101,7 +101,7 @@ def test_cli_scenario_validate_and_list(tmp_path, monkeypatch, capsys): scenario_dir.mkdir() scenario_file = scenario_dir / "s1.yaml" scenario_file.write_text( - "scenario_id: s1\nname: Scenario 1\ntopology_scale: xs\nmetadata:\n difficulty: easy\nepisode:\n episode_id: diagnosis\n fault_type: link_down\n target_device: leaf1\n target_interface: Ethernet1\n", + "scenario_id: s1\nname: Scenario 1\ntopology_scale: xs\nmetadata:\n recovery_policy: {version: 3}\n difficulty: easy\nepisode:\n episode_id: diagnosis\n fault_type: link_down\n target_device: leaf1\n target_interface: Ethernet1\n", encoding="utf-8", ) @@ -172,7 +172,9 @@ def test_topology_cli_help_includes_generate(capsys): def test_cli_scenario_generate_uses_existing_default_spec(tmp_path, monkeypatch, capsys): calls = {} - def fake_generate(workspace, *, scale, spec, topology_dir=None, out=None, seed=42): + def fake_generate( + workspace, *, scale, spec, topology_dir=None, out=None, seed=42, scale_registry=None, recovery_mode=None + ): calls.update( workspace=workspace, scale=scale, @@ -210,14 +212,14 @@ def fake_generate(workspace, *, scale, output_dir=None): monkeypatch.setattr("netopsbench.cli.main._generate_topology", fake_generate) monkeypatch.setattr( - "sys.argv", ["netopsbench", "--workspace", str(tmp_path), "topology", "generate", "--scale", "small"] + "sys.argv", ["netopsbench", "--workspace", str(tmp_path), "topology", "generate", "--scale", "medium"] ) assert main() == 0 out = capsys.readouterr().out assert "generated topology" in out assert calls["workspace"].workspace == tmp_path - assert calls["scale"] == "small" + assert calls["scale"] == "medium" assert calls["output_dir"] is None @@ -455,7 +457,9 @@ def fake_generate_topology(workspace, *, scale, output_dir=None): print(f"topology:{scale}") return 0 - def fake_generate_scenarios(workspace, *, scale, spec, topology_dir=None, out=None, seed=42): + def fake_generate_scenarios( + workspace, *, scale, spec, topology_dir=None, out=None, seed=42, scale_registry=None, recovery_mode=None + ): scenario_calls.append((workspace, scale, spec, topology_dir, out, seed)) print(f"scenarios:{scale}") return 0 diff --git a/tests/test_deepagent_mcp_cleanup.py b/tests/test_deepagent_mcp_cleanup.py new file mode 100644 index 0000000..18a5dbe --- /dev/null +++ b/tests/test_deepagent_mcp_cleanup.py @@ -0,0 +1,120 @@ +"""Exercise actual MCP lifecycles without calling a model or starting a lab.""" + +import importlib.metadata +import subprocess +import sys +from pathlib import Path + +import pytest + +_ROOT = Path(__file__).resolve().parents[1] +_SCRIPT = r""" +import asyncio +import json +import socket +import sys +from contextlib import asynccontextmanager +from types import SimpleNamespace +from unittest.mock import patch + +from langchain_core.messages import AIMessage + +import examples.agents.minimal_deepagent.agent as module +from netopsbench.platform.toolkit._core.common import ToolResult +from netopsbench.sdk.agents import DiagnosticContext + +mode = sys.argv[1] +ports, calls = [], [] +original_endpoint = module.session_mcp + +@asynccontextmanager +async def endpoint(*args, **kwargs): + async with original_endpoint(*args, **kwargs) as connection: + ports.append(connection["port"]) + yield connection + +async def exercise(): + started = asyncio.Event() + + def create_graph(**kwargs): + tool = next(tool for tool in kwargs["tools"] if tool.name == "get_topology") + + async def invoke(*args, **kwargs): + assert "healthy" in str(await tool.ainvoke({})) + started.set() + if mode in {"cancel", "timeout"}: + await asyncio.sleep(600) + if mode == "failure": + raise ValueError("model failed") + payload = { + "verdict": "network_healthy", "fault_type": None, + "location": {"device": None, "interface": None}, + "evidence": ["Healthy observation"], "confidence": 0.9, + "reasoning": "Healthy.", + } + return {"messages": [AIMessage(content="```json\n" + json.dumps(payload) + "\n```")]} + + return SimpleNamespace(ainvoke=invoke) + + context = DiagnosticContext( + "anonymous", {}, {}, + metadata={"canonical_observation": {"case_id": "anonymous"}}, + tools=SimpleNamespace(get_topology=lambda **kw: calls.append(kw) or ToolResult(True, {"healthy": True})), + ) + provider = module.get_provider("deepseek") + with ( + patch.object(module, "session_mcp", endpoint), + patch.object(module, "create_deep_agent", create_graph), + patch.object(provider, "build_llm", lambda **kwargs: object()), + ): + agent = module.MinimalDeepAgent( + vendor="deepseek", api_key="offline-test", + diagnosis_timeout_seconds=5 if mode == "timeout" else 20, + ) + task = asyncio.create_task(agent.diagnose(context)) + await asyncio.wait_for(started.wait(), 15) + if mode == "cancel": + task.cancel() + try: + await asyncio.wait_for(task, 15) + except asyncio.CancelledError: + pass + else: + raise AssertionError("Cancellation must propagate") + else: + result = await asyncio.wait_for(task, 15) + if mode == "normal": + assert result.success is True + assert result.verdict == "network_healthy" + else: + assert result.success is False + expected = "timeout" if mode == "timeout" else "model failed" + assert expected in result.reasoning.lower() + assert calls == [{}] + +asyncio.run(exercise()) +assert ports +for port in ports: + with socket.socket() as listener: + listener.settimeout(0.5) + assert listener.connect_ex(("127.0.0.1", port)) != 0, "MCP listener leaked" +""" + + +@pytest.mark.parametrize("mode", ["normal", "failure", "cancel", "timeout"]) +def test_deepagent_closes_real_mcp_session_on_owning_task(mode): + for dependency in ("deepagents", "fastmcp", "langchain-mcp-adapters"): + try: + importlib.metadata.version(dependency) + except importlib.metadata.PackageNotFoundError: + pytest.skip(f"Optional agent dependency unavailable: {dependency}") + # Other example tests stub optional modules in sys.modules; use a fresh + # interpreter so this regression always exercises the real MCP transport. + result = subprocess.run( + [sys.executable, "-c", _SCRIPT, mode], + cwd=_ROOT, + capture_output=True, + text=True, + timeout=40, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/test_device_fault_toolchain.py b/tests/test_device_fault_toolchain.py new file mode 100644 index 0000000..b6f3312 --- /dev/null +++ b/tests/test_device_fault_toolchain.py @@ -0,0 +1,22 @@ +"""Device parking must use the same validated toolchain as deployment.""" + +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from netopsbench.platform.faults.handlers import system + + +@pytest.mark.parametrize("operation", ["stop", "start"]) +def test_device_lifecycle_uses_pinned_toolchain(monkeypatch, operation): + pinned = Path("/validated/runtime-tools") + monkeypatch.setattr(system, "runtime_tools", lambda: pinned) + monkeypatch.setattr(system, "sudo_prefix", lambda: []) + handler = system.SystemHandler(None, None, None, SimpleNamespace(topology_file=Path("/runtime/lab.clab.yaml"))) + + command = handler._containerlab_node_command(operation, "agg46") + + assert command[0] == str(pinned / "containerlab") + assert command[1] == operation + assert command[command.index("--node") + 1] == "agg46" diff --git a/tests/test_diagnostic_boundaries.py b/tests/test_diagnostic_boundaries.py new file mode 100644 index 0000000..180a2cb --- /dev/null +++ b/tests/test_diagnostic_boundaries.py @@ -0,0 +1,267 @@ +"""Public evidence remains useful without runtime injection metadata.""" + +import json +import subprocess +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context + +import pytest + +from netopsbench.platform.incident.context import build_public_symptoms +from netopsbench.platform.toolkit._core.common import ToolResult +from netopsbench.platform.toolkit.mcp.registry import load_tool_specs +from netopsbench.platform.toolkit.public import public_tool_result +from netopsbench.platform.toolkit.toolkit import AgentToolkit +from netopsbench.platform.topology.clos_builder import build_clos_plan +from netopsbench.platform.topology.config import config_for_scale +from netopsbench.platform.utils.measurements import count_operation, measurement_scope + + +@pytest.fixture +def toolkit(): + return AgentToolkit(topology_metadata=build_clos_plan(config_for_scale("xs")).manifest.model_dump(mode="json")) + + +@pytest.mark.parametrize("spec", load_tool_specs(), ids=lambda spec: spec.name) +def test_every_mcp_handler_projects_private_fields_and_errors(monkeypatch, spec): + import inspect + from types import SimpleNamespace + + from netopsbench.platform.toolkit.mcp import context + + evidence = {"state": "down", "mtu": 1400, "config": "neighbor 10.0.0.1 shutdown"} + payload = { + "evidence": [dict(evidence, injection={"corrupt": 20}, recovery_journal={"private": True})], + "collection_errors": [{"error": "/private/campaign/packet_corruption.yml"}], + "service_collection_error": "/private/runtime/packet_corruption", + } + fake = SimpleNamespace(**{spec.name: lambda **kwargs: ToolResult(True, payload)}) + monkeypatch.setattr(context, "_toolkit", fake) + args = { + name: "device" + for name, parameter in inspect.signature(spec.handler).parameters.items() + if parameter.default is inspect.Parameter.empty + } + result = spec.handler(**args) + assert result["evidence"] == [evidence] + assert "private" not in json.dumps(result) + assert "corrupt" not in json.dumps(result) + assert result["collection_errors"][0]["error"] == "Observation unavailable" + + +@pytest.mark.parametrize( + "returncode,stdout,stderr,success", + [ + (1, "", "Error response from daemon: /private/runtime", False), + (126, "OCI runtime exec failed: /private/runtime", "", False), + (1, "5 packets transmitted, 0 received, 100% packet loss", "", True), + (2, "", "ping: local error: message too long, mtu=1400", True), + ], +) +def test_ping_keeps_probe_evidence_but_not_runtime_errors(toolkit, monkeypatch, returncode, stdout, stderr, success): + monkeypatch.setattr( + toolkit, "_docker_exec", lambda *a, **kw: subprocess.CompletedProcess([], returncode, stdout, stderr) + ) + result = toolkit.ping_test("client1", "192.168.1.1") + assert result.success is success + assert "/private" not in json.dumps(public_tool_result(result)) + if success: + assert result.data["output"] == (stdout or stderr) + + +@pytest.mark.parametrize("view", ["raw", "both", "summary", "structured"]) +@pytest.mark.parametrize("device", ["client1", "leaf1"]) +def test_interface_filter_and_qdisc_projection_on_linux_fallback(toolkit, monkeypatch, view, device): + def execute(container, args, timeout): + if args[0] == "bash": + return subprocess.CompletedProcess(args, 1, stdout="", stderr="unavailable") + if args == ["ip", "-j", "-4", "addr", "show"]: + return subprocess.CompletedProcess( + args, + 0, + stdout=json.dumps( + [ + {"ifname": "eth1", "addr_info": [{"local": "192.168.1.1", "prefixlen": 30}]}, + {"ifname": "eth2", "addr_info": [{"local": "192.168.2.1", "prefixlen": 30}]}, + ] + ), + ) + return subprocess.CompletedProcess( + args, + 0, + stdout=( + "2: eth1@if20: mtu 1400 qdisc netem state UP\n" + " RX: bytes packets errors dropped\n 100 10 2 1\n" + "3: eth2: mtu 1500 qdisc noqueue state UP\n" + " RX: bytes packets errors dropped\n 200 20 0 0\n" + ), + ) + + monkeypatch.setattr(toolkit, "_docker_exec", execute) + result = toolkit.get_device_interfaces(device, format=view, interface="Ethernet0") + assert result.success, result.error + serialized = json.dumps(result.data) + assert "netem" not in serialized and "qdisc" not in serialized and "eth2" not in serialized + assert result.data["addresses"] == {"eth1": ["192.168.1.1/30"]} + if view in {"summary", "structured"}: + assert result.data["interfaces"] == [ + { + "name": "eth1", + "mtu": 1400, + "state": "UP", + "admin": "up", + **( + {"rx_errors": 2, "rx_dropped": 1} + if view == "summary" + else {"rx_bytes": 100, "rx_packets": 10, "rx_errors": 2, "rx_dropped": 1} + ), + } + ] + assert not toolkit.get_device_interfaces(device, interface="Ethernet120").success + + +def test_initial_nested_audits_and_semantic_episode_id_are_private(): + result = build_public_symptoms( + episode_result={ + "episode": {"episode_id": "packet_corruption_leaf1", "fault_type": "packet_corruption"}, + "observations": { + "data_source_status": "error: /private/campaign/packet_corruption.yml", + "pingmesh_metrics": { + "summary": {"packet_loss": 20}, + "extra": {"target_device": "leaf1", "effect_audit": {"private": True}}, + }, + }, + }, + pingmesh_query_window={}, + ) + assert result["episode"] == {} + assert result["observations"]["pingmesh_metrics"]["summary"] == {"packet_loss": 20} + assert "leaf1" not in json.dumps(result) + assert result["observations"]["data_source_status"] == "error" + assert "/private" not in json.dumps(result) + + +def test_topology_projects_only_supported_metadata(toolkit): + toolkit.manifest.devices[0].metadata.update(pod=1, injection={"corrupt": 20}, notes="/private/fault.yml") + result = toolkit.get_topology().data + assert "corrupt" not in json.dumps(result) + assert "/private" not in json.dumps(result) + + +@pytest.mark.parametrize("view", ["raw", "both", "summary", "structured"]) +def test_real_non_port_interface_is_not_mistaken_for_missing(toolkit, monkeypatch, view): + def execute(container, args, timeout): + if args[0] == "bash": + output = "Interface Admin Oper\nEthernet0 up up\n" + elif args[:3] == ["ip", "-j", "-4"]: + output = '[{"ifname":"lo", "addr_info":[{"local":"127.0.0.1", "prefixlen":8}]}]' + else: + output = "1: lo: mtu 65536 qdisc noqueue state UNKNOWN\n" + return subprocess.CompletedProcess(args, 0, stdout=output, stderr="") + + monkeypatch.setattr(toolkit, "_docker_exec", execute) + result = toolkit.get_device_interfaces("leaf1", interface="lo", format=view) + assert result.success + assert result.data["addresses"] == {"lo": ["127.0.0.1/8"]} + assert "Ethernet0" not in json.dumps(result.data) + assert "qdisc" not in json.dumps(result.data) + + +def test_failed_tool_does_not_return_internal_exception(): + result = public_tool_result(ToolResult(False, None, "/private/packet_corruption.yaml: corrupt 20%")) + assert result == {"success": False, "data": None, "error": "Observation unavailable"} + + +def test_operation_counts_include_propagated_threads_without_cross_case_leakage(): + first, second = {}, {} + with measurement_scope(first): + count_operation("influx_queries") + with ThreadPoolExecutor(1) as pool: + pool.submit(copy_context().run, count_operation, "docker_commands").result() + with measurement_scope(second): + count_operation("influx_queries") + assert first == {"influx_queries": 1, "docker_commands": 1} + assert second == {"influx_queries": 1} + + +def test_missing_diagnosis_verdict_is_not_healthy(): + from netopsbench.platform.session.scoring import diagnosis_to_agent_output + + assert diagnosis_to_agent_output({"reasoning": "unfinished"}).verdict == "inconclusive" + + +def test_historical_logs_and_metrics_share_episode_and_topology_scope(toolkit, monkeypatch): + from netopsbench.platform.observability.influxdb import FluxQueryResult + + queries = [] + + def query(*args, **kwargs): + queries.append(args[3]) + return FluxQueryResult(status="ok", text="") + + monkeypatch.setattr("netopsbench.platform.toolkit._core.device.log_ops.query_flux", query) + monkeypatch.setattr("netopsbench.platform.toolkit._core.observability.metrics_ops.query_flux", query) + monkeypatch.setattr( + "netopsbench.platform.toolkit._core.device.log_ops.get_device_logs_fallback", lambda *a, **kw: [] + ) + toolkit.set_pingmesh_time_window("2026-11-04T00:00:00Z", "2026-11-04T00:01:00Z") + logs = toolkit.get_device_logs("leaf1") + metrics = toolkit.get_interface_metrics("leaf1", "Ethernet0", view="raw") + assert logs.success and metrics.success + for result in (logs, metrics): + assert result.data["time_scope"]["source"] == "toolkit_default" + for query_text in queries: + assert "2026-11-04T00:00:00Z" in query_text + assert f'r.topology_id == "{toolkit.topology_id}"' in query_text + + +def test_missing_metrics_collect_live_interfaces_only_once(toolkit, monkeypatch): + from netopsbench.platform.observability.influxdb import FluxQueryResult + from netopsbench.platform.toolkit._core.observability import metrics_ops + + monkeypatch.setattr(metrics_ops, "query_flux", lambda *a, **kw: FluxQueryResult(status="ok", text="")) + monkeypatch.setattr(metrics_ops, "get_recent_influx_interface_identities", lambda *a: []) + calls = [] + + def interfaces(*args, **kwargs): + calls.append(args) + return ToolResult( + True, {"interfaces": [{"name": "Ethernet0", "state": "UP", "rx_errors": 3}], "collected_at": "now"} + ) + + monkeypatch.setattr(toolkit, "get_device_interfaces", interfaces) + result = toolkit.get_interface_metrics("leaf1", "Ethernet0") + assert result.success + assert len(calls) == 1 + assert result.data["active_interfaces"] == ["Ethernet0"] + assert result.data["current_snapshot"]["rx_errors"] == 3 + assert result.data["snapshot_collected_at"] == "now" + + +@pytest.mark.parametrize("view", ["raw", "both", "summary", "structured"]) +def test_sonic_tables_filter_alias_and_keep_real_counters(toolkit, monkeypatch, view): + def execute(container, args, timeout): + if args[:3] == ["ip", "-j", "-4"]: + output = json.dumps( + [ + {"ifname": name, "addr_info": [{"local": address, "prefixlen": 30}]} + for name, address in (("Ethernet0", "10.0.0.1"), ("Ethernet4", "10.0.0.5")) + ] + ) + elif "status" in args[-1]: + output = ( + "Interface Admin Oper MTU\nEthernet0 up down 1400\nEthernet4 up up 1500\n" + ) + else: + output = "IFACE RX_ERR TX_DRP\nEthernet0 7 2\nEthernet4 0 0\n" + return subprocess.CompletedProcess(args, 0, stdout=output, stderr="") + + monkeypatch.setattr(toolkit, "_docker_exec", execute) + result = toolkit.get_device_interfaces("leaf1", interface="eth1", format=view) + assert result.success + assert "Ethernet4" not in json.dumps(result.data) + assert result.data["addresses"] == {"Ethernet0": ["10.0.0.1/30"]} + if view in {"summary", "structured"}: + row = result.data["interfaces"][0] + assert row["mtu"] == 1400 and row["rx_err"] == 7 and row["oper"] == "down" + assert not toolkit.get_device_interfaces("leaf1", interface="eth30", format=view).success diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 9e52825..d3d9355 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -12,6 +12,7 @@ import sys import tempfile from pathlib import Path +from types import SimpleNamespace import pytest import yaml @@ -25,8 +26,6 @@ from netopsbench.models.topology import TopologyManifest from netopsbench.platform.client_agent.config import build_client_agent_config from netopsbench.platform.faults.injector import FaultInjector -from netopsbench.platform.faults.specs import create_fault_registry -from netopsbench.platform.scenario.generator import parse_bgp_config, parse_network_interfaces from netopsbench.platform.scenario.parser import parse_scenario_file from netopsbench.platform.scenario.validator import validate_scenario, validate_scenario_topology from netopsbench.platform.session.scoring import score_scenario_episode @@ -35,7 +34,9 @@ # Internal test path: direct toolkit import keeps implementation-level e2e checks fast. from netopsbench.platform.toolkit.toolkit import AgentToolkit, ToolResult +from netopsbench.platform.topology.configdb_payload import interface_names_for_config from netopsbench.platform.topology.generator import generate_topology +from netopsbench.platform.utils.frr import parse_bgp_config from netopsbench.platform.utils.interface_names import are_interfaces_equivalent @@ -168,12 +169,12 @@ def test_generate_xlarge_topology_metadata_and_addressing(self): assert metadata["management"]["ipv4_subnet"] == "172.20.20.0/23" assert metadata["scale"]["num_spines"] == 16 assert metadata["scale"]["num_leafs"] == 128 - assert metadata["scale"]["clients_per_leaf"] == 1 - assert metadata["scale"]["total_clients"] == 128 + assert metadata["scale"]["clients_per_leaf"] == 2 + assert metadata["scale"]["total_clients"] == 256 assert metadata["pingmesh"]["destination_batch_size"] == 16 mgmt_ips = {item["mgmt_ip"] for role in ("spines", "leafs", "clients") for item in devices[role]} - assert len(mgmt_ips) == 16 + 128 + 128 + assert len(mgmt_ips) == 16 + 128 + 256 assert metadata["collector"]["ipv4"] not in mgmt_ips spine16_config = json.loads( @@ -200,12 +201,12 @@ def test_generate_xlarge_topology_metadata_and_addressing(self): assert "eth1:1,2,3,4" in spine16_lanemap assert "eth128:509,510,511,512" in spine16_lanemap assert len([line for line in spine16_lanemap.splitlines() if line.startswith("eth")]) == 128 - assert len([key for key in leaf128_config["INTERFACE"] if "|" not in key]) == 17 + assert len([key for key in leaf128_config["INTERFACE"] if "|" not in key]) == 18 assert leaf128_config["INTERFACE"]["Ethernet60|10.16.128.2/30"] == {} - assert leaf128_config["INTERFACE"]["Ethernet64|192.168.228.1/30"] == {} - assert "network 192.168.228.0/30 route-map RM-ALLOW" in leaf128_frr + assert leaf128_config["INTERFACE"]["Ethernet64|192.168.128.1/30"] == {} + assert "network 192.168.128.0/30 route-map RM-ALLOW" in leaf128_frr leaf128_lanemap = Path(tmpdir, "configs", "sonic", "leaf128", "lanemap.ini").read_text(encoding="utf-8") - assert len([line for line in leaf128_lanemap.splitlines() if line.startswith("eth")]) == 17 + assert len([line for line in leaf128_lanemap.splitlines() if line.startswith("eth")]) == 18 def test_structured_startup_artifacts_drive_scenario_parsers(self): """Scenario parsers should use generated ConfigDB and FRR artifacts as the normal path.""" @@ -214,8 +215,8 @@ def test_structured_startup_artifacts_drive_scenario_parsers(self): spine_cfg = Path(tmpdir, "configs", "sonic", "spine1", "config_db.json") spine_frr = Path(tmpdir, "configs", "frr", "spine1.conf") - assert parse_network_interfaces(spine_cfg) == ["Ethernet0", "Ethernet4"] - bgp_info = parse_bgp_config(spine_frr) + assert interface_names_for_config(spine_cfg) == ["Ethernet0", "Ethernet4"] + bgp_info = parse_bgp_config(spine_frr.read_text()) assert bgp_info["local_as"] == 65001 assert [neighbor["remote_as"] for neighbor in bgp_info["neighbors"]] == [65011, 65012] @@ -223,28 +224,12 @@ def test_structured_startup_artifacts_drive_scenario_parsers(self): class TestAgentToolkit: """Tests for agent toolkit.""" - def test_toolkit_initialization(self): - """Test toolkit initializes correctly.""" - with tempfile.TemporaryDirectory() as tmpdir: - topo = generate_topology("xs", tmpdir) - toolkit = AgentToolkit(topology_metadata=topo["metadata"]) - assert toolkit is not None - assert toolkit.influxdb_url is not None - - def test_tool_registry_specs_complete(self): - """Tool registry specs should define non-empty name/group/handler.""" - specs = load_tool_specs() - assert specs, "tool specs should not be empty" - for spec in specs: - assert spec.name - assert spec.group - assert callable(spec.handler) - def test_get_topology_returns_result(self): """Test get_topology returns a valid result.""" with tempfile.TemporaryDirectory() as tmpdir: topo = generate_topology("xs", tmpdir) toolkit = AgentToolkit(topology_metadata=topo["metadata"]) + assert toolkit.influxdb_url is not None result = toolkit.get_topology() assert isinstance(result, ToolResult) @@ -291,24 +276,21 @@ def test_xlarge_config_is_deterministic_and_bounded(self): second = build_client_agent_config(manifest) assert first == second - assert len(first["clients"]) == 128 - assert len(json.dumps(first).encode()) < 100_000 - assert first["pingmesh_policy"]["destination_batch_size"] == 16 - assert first["pingmesh_policy"]["coverage_epoch_cycles"] == 32 + assert len(first["clients"]) == 256 + assert len(json.dumps(first).encode()) < 150_000 + assert first["pingmesh_plan"]["destination_batch_size"] == 16 + assert first["pingmesh_plan"]["coverage_epoch_cycles"] == 20 class TestFastMCPServer: """Tests for FastMCP server tool wiring.""" - def test_fastmcp_tool_registry_exists(self): - """FastMCP module should expose a non-empty tool registry.""" - assert len(fastmcp_server.EXPOSED_TOOLS) > 0 - - def test_fastmcp_has_all_expected_tools(self): - """FastMCP module should export all MCP tool callables.""" - expected_tools = [ + def test_rl_schemas_and_fastmcp_use_identical_typed_contracts(self): + specs = {spec.name: spec for spec in load_tool_specs()} + expected = { "get_topology", "get_device_interfaces", + "get_device_status", "get_bgp_neighbors", "get_bgp_neighbor", "get_route_table", @@ -322,23 +304,14 @@ def test_fastmcp_has_all_expected_tools(self): "query_bgp_events", "get_pingmesh_summary", "get_pingmesh_hotspots", - ] - - for tool in expected_tools: - assert hasattr(fastmcp_server, tool), f"Tool {tool} callable missing from fastmcp_server" - assert tool in fastmcp_server.EXPOSED_TOOLS, f"Tool {tool} missing from EXPOSED_TOOLS" - - def test_tool_registry_matches_fastmcp_tools(self): - """Tool registry should stay in sync with FastMCP exported tools.""" - tool_names = [spec.name for spec in load_tool_specs()] - - assert len(tool_names) == len(fastmcp_server.EXPOSED_TOOLS), "Tool count mismatch" - for name in tool_names: - assert name in fastmcp_server.EXPOSED_TOOLS, f"Tool {name} in definitions but not in FastMCP" - - def test_rl_schemas_and_fastmcp_use_identical_typed_contracts(self): - schemas = {schema["name"]: schema for schema in tool_schemas()} + } + assert set(specs) == set(fastmcp_server.EXPOSED_TOOLS) == expected + assert len(specs) == len(load_tool_specs()) == len(fastmcp_server.EXPOSED_TOOLS) + assert set(specs) == {spec.name for spec in fastmcp_server._TOOL_SPECS} + assert all(spec.group and callable(spec.handler) for spec in specs.values()) + assert all(callable(getattr(fastmcp_server, name)) for name in expected) specs = {spec.name: spec for spec in fastmcp_server._TOOL_SPECS} + schemas = {schema["name"]: schema for schema in tool_schemas()} assert schemas.keys() == specs.keys() for name, spec in specs.items(): @@ -374,120 +347,6 @@ def test_tool_schema_defaults_are_valid_and_integer_arguments_are_strict(self): class TestFaultInjector: """Tests for fault injection.""" - def test_injector_initialization(self): - """Test fault injector initializes correctly.""" - injector = FaultInjector(topology_metadata=_generated_metadata()) - assert injector is not None - assert injector.container_names["spine1"] == "clab-dcn-spine1" - assert injector.active_faults == [] - - def test_injector_loads_dynamic_topology(self): - """Test injector can load dynamic topology.""" - with tempfile.TemporaryDirectory() as tmpdir: - result = generate_topology("xs", tmpdir) - metadata = result["metadata"] - - injector = FaultInjector(topology_metadata=metadata) - - assert "spine1" in injector.container_names - assert "leaf1" in injector.container_names - - def test_fault_types_defined(self): - """Test all expected fault types are defined.""" - expected_faults = [ - "link_down", - "link_flapping", - "device_down", - "bgp_neighbor_misconfig", - "route_policy_misconfig", - "mtu_mismatch", - "packet_corruption", - "packet_loss", - "high_latency", - "blackhole_route", - "static_route_misconfig", - ] - - defined_faults = [spec.name for spec in create_fault_registry().get_builtin_specs()] - for fault in expected_faults: - assert fault in defined_faults, f"Fault type {fault} not defined" - - def test_inject_high_latency_uses_latency_ms_contract(self): - injector = FaultInjector(topology_metadata=_generated_metadata()) - - class FakeImpairment: - def __init__(self): - self.calls = [] - - def inject_high_latency(self, device, interface, latency_ms=100): - self.calls.append((device, interface, latency_ms)) - return {"success": True, "type": "high_latency", "latency_ms": latency_ms} - - fake = FakeImpairment() - injector._impairment = fake - - result = injector.inject_high_latency("leaf1", "Ethernet0", latency_ms=120) - - assert result["success"] is True - assert fake.calls == [("leaf1", "Ethernet0", 120)] - - def test_inject_mtu_mismatch_uses_mtu_contract(self): - injector = FaultInjector(topology_metadata=_generated_metadata()) - - class FakeImpairment: - def __init__(self): - self.calls = [] - - def inject_mtu_mismatch(self, device, interface, mtu=1400): - self.calls.append((device, interface, mtu)) - return {"success": True, "type": "mtu_mismatch", "mtu": mtu} - - fake = FakeImpairment() - injector._impairment = fake - - result = injector.inject_mtu_mismatch("leaf1", "Ethernet0", mtu=1450) - - assert result["success"] is True - assert fake.calls == [("leaf1", "Ethernet0", 1450)] - - def test_inject_packet_corruption_uses_corruption_pct_contract(self): - injector = FaultInjector(topology_metadata=_generated_metadata()) - - class FakeImpairment: - def __init__(self): - self.calls = [] - - def inject_packet_corruption(self, device, interface, corruption_pct=20): - self.calls.append((device, interface, corruption_pct)) - return {"success": True, "type": "packet_corruption", "corruption_pct": corruption_pct} - - fake = FakeImpairment() - injector._impairment = fake - - result = injector.inject_packet_corruption("leaf1", "Ethernet0", corruption_pct=17) - - assert result["success"] is True - assert fake.calls == [("leaf1", "Ethernet0", 17)] - - def test_inject_packet_loss_uses_loss_pct_contract(self): - injector = FaultInjector(topology_metadata=_generated_metadata()) - - class FakeImpairment: - def __init__(self): - self.calls = [] - - def inject_packet_loss(self, device, interface, loss_pct=10): - self.calls.append((device, interface, loss_pct)) - return {"success": True, "type": "packet_loss", "loss_pct": loss_pct} - - fake = FakeImpairment() - injector._impairment = fake - - result = injector.inject_packet_loss("leaf1", "Ethernet0", loss_pct=11) - - assert result["success"] is True - assert fake.calls == [("leaf1", "Ethernet0", 11)] - def test_injector_interface_alias_resolution_supports_vendor_style(self): injector = FaultInjector(topology_metadata=_generated_metadata()) assert injector._iface.resolve_linux("ethernet-1/2") == "eth2" @@ -497,15 +356,10 @@ def test_injector_interface_alias_resolution_supports_vendor_style(self): class TestEvaluator: """Tests for evaluation system.""" - def test_evaluator_initialization(self): - """Test evaluator initializes correctly.""" - evaluator = Evaluator() - assert evaluator is not None - assert sum(evaluator.weights.values()) == 1.0 - def test_evaluate_correct_answer(self): """Test evaluating a correct agent answer.""" evaluator = Evaluator() + assert sum(evaluator.weights.values()) == 1.0 agent_output = AgentOutput( verdict="fault_detected", @@ -704,19 +558,19 @@ def test_generate_report_device_localization_requires_correct_verdict(self): assert summary["device_accuracy"] == 0.0 assert summary["interface_localization_rate"] == 0.0 - def test_evaluate_route_policy_alias_as_correct_fault_type(self): - """Route-origination style answers should normalize to route_policy_misconfig.""" + def test_evaluate_route_origination_as_correct_fault_type(self): + """The explicit catalog type is scored independently of its mechanism.""" evaluator = Evaluator() agent_output = AgentOutput( verdict="fault_detected", - fault_type="route_origination_missing", + fault_type="route_origination_misconfig", location={"device": "leaf1"}, confidence=0.9, ) ground_truth = { - "fault_type": "route_policy_misconfig", + "fault_type": "route_origination_misconfig", "location": {"device": "leaf1"}, } @@ -795,7 +649,7 @@ def test_topology_guard_rejects_scale_mismatch_by_default(self): scenario = parse_scenario_file(_generated_scenario_path("generated_link_down_xs_001.yaml")) with tempfile.TemporaryDirectory() as tmpdir: - generate_topology("small", tmpdir) + generate_topology("medium", tmpdir) result = validate_scenario_topology( scenario=scenario, @@ -804,7 +658,7 @@ def test_topology_guard_rejects_scale_mismatch_by_default(self): assert result["status"] == "fail" assert result["declared_scale"] == scenario.topology_scale - assert result["actual_scale"] == "small" + assert result["actual_scale"] == "medium" def test_topology_guard_accepts_e_style_interface_aliases(self): """e1-1 style interface labels should map to SONiC Ethernet ports.""" @@ -824,10 +678,10 @@ def test_topology_guard_accepts_e_style_interface_aliases(self): def test_topology_guard_accepts_vendor_style_interface_aliases(self): """Vendor-style ethernet-1/1 labels should also map to SONiC Ethernet ports.""" - scenario = parse_scenario_file(_generated_scenario_path("generated_link_down_small_001.yaml")) + scenario = parse_scenario_file(_generated_scenario_path("generated_link_down_medium_001.yaml")) with tempfile.TemporaryDirectory() as tmpdir: - generate_topology("small", tmpdir) + generate_topology("medium", tmpdir) _write_config_db(tmpdir, "spine1", {"Ethernet0": []}) _write_config_db(tmpdir, "spine2", {"Ethernet4": []}) @@ -842,15 +696,15 @@ def test_topology_guard_accepts_vendor_style_interface_aliases(self): def test_configdb_payload_interfaces_are_used_by_runtime_helpers(self): """Runtime helpers read interface metadata from generated ConfigDB artifacts.""" with tempfile.TemporaryDirectory() as tmpdir: - generate_topology("small", tmpdir) + generate_topology("medium", tmpdir) spine_config = _write_config_db(tmpdir, "spine1", {"Ethernet4": ["10.0.0.2/30"]}) _write_config_db(tmpdir, "leaf1", {"Ethernet4": ["10.0.0.1/30"]}) scenario = ScenarioSpec( scenario_id="configdb_interface_case", name="ConfigDB interface case", - topology_scale="small", - metadata={"difficulty": "easy"}, + topology_scale="medium", + metadata={"recovery_policy": {"version": 3}, "difficulty": "easy"}, episode=EpisodeSpec( episode_id="diagnosis", fault_type="link_down", @@ -860,7 +714,7 @@ def test_configdb_payload_interfaces_are_used_by_runtime_helpers(self): ) result = validate_scenario_topology(scenario=scenario, topology_dir=tmpdir) assert result["status"] == "pass" - assert parse_network_interfaces(spine_config) == ["Ethernet4"] + assert interface_names_for_config(spine_config) == ["Ethernet4"] from netopsbench.platform.session.scoring import build_episode_ground_truth @@ -974,3 +828,29 @@ def test_full_flow_without_containers(self): if __name__ == "__main__": pytest.main([__file__, "-v"]) + + +@pytest.mark.parametrize( + "fault,key,value", + [ + ("high_latency", "latency_ms", 120), + ("mtu_mismatch", "mtu", 1450), + ("packet_corruption", "corruption_pct", 17), + ("packet_loss", "loss_pct", 11), + ], +) +def test_impairment_parameter_forwarding(fault, key, value): + injector = FaultInjector(topology_metadata=_generated_metadata()) + assert injector.container_names["spine1"] == "clab-dcn-spine1" + assert "leaf1" in injector.container_names + assert injector.active_faults == [] + calls = [] + + def inject(device, interface, **kwargs): + calls.append((device, interface, kwargs)) + return {"success": True, "type": fault, **kwargs} + + injector._impairment = SimpleNamespace(**{f"inject_{fault}": inject}) + result = getattr(injector, f"inject_{fault}")("leaf1", "Ethernet0", **{key: value}) + assert result["success"] is True + assert calls == [("leaf1", "Ethernet0", {key: value})] diff --git a/tests/test_episode_runner.py b/tests/test_episode_runner.py index 25e65b8..677b758 100644 --- a/tests/test_episode_runner.py +++ b/tests/test_episode_runner.py @@ -2,10 +2,12 @@ from __future__ import annotations +from datetime import UTC, datetime, timedelta from typing import Any from netopsbench.models.scenario import EpisodeSpec from netopsbench.platform.scenario.episode_runner import observe_episode +from netopsbench.platform.scenario.timing import PhaseTimings _BASELINE = {"start_time": "baseline-start", "end_time": "baseline-end"} @@ -14,11 +16,11 @@ class StubExecutor: def __init__( self, *, - post_recovery_wait_seconds: float = 0, injection_success: bool = True, observe_payload: dict[str, Any] | None = None, ): - self.post_recovery_wait_seconds = post_recovery_wait_seconds + self.timings = PhaseTimings() + self.observation_timeout_seconds = 60 self._injection_success = injection_success self._observe_payload = observe_payload or {"observed": True} self.calls: list[str] = [] @@ -28,25 +30,26 @@ def _inject_fault(self, episode): self.calls.append("inject") return {"success": self._injection_success, "fault_type": episode.fault_type} - def _wait_and_observe(self, seconds, *, baseline_window): - self.calls.append(f"observe:{seconds}") - self.baseline_windows.append(baseline_window) - return {"duration": seconds, **self._observe_payload} - def _capture_observation_window(self, seconds, name): self.calls.append(f"capture:{name}:{seconds}") - return {"name": name, "duration": seconds, **self._observe_payload} + return { + "name": name, + "duration_seconds": seconds, + "start_time": "2026-10-24T00:00:00+00:00", + "end_time": (datetime(2026, 10, 24, tzinfo=UTC) + timedelta(seconds=seconds)).isoformat(), + **self._observe_payload, + } def _merge_observation_windows( self, windows, - *, total_duration_seconds, + *, baseline_window, ): self.calls.append("merge") self.baseline_windows.append(baseline_window) - return {"windows": list(windows), "total": total_duration_seconds} + return {"windows": list(windows), "total": total_duration_seconds, **self._observe_payload} def _episode(**overrides) -> EpisodeSpec: @@ -72,7 +75,8 @@ def test_healthy_episode_is_observed_without_fault_actions(): ) assert result["state"] == "active" - assert executor.calls == ["observe:2"] + assert result["observations"]["observed"] is True + assert executor.calls == ["capture:full:2", "merge"] def test_healthy_episode_promotes_coverage_audit_without_private_observation_key(): @@ -96,7 +100,7 @@ def test_observation_keeps_fault_active_for_incident_engine(): active = observe_episode(executor, episode, baseline_window=_BASELINE) assert active["state"] == "active" - assert executor.calls == ["inject", "capture:steady:2", "merge"] + assert executor.calls == ["inject", "capture:full:2", "merge"] def test_interactive_kernel_uses_explicit_cached_baseline_window(): @@ -123,10 +127,10 @@ def test_observation_defers_detector_analysis_until_all_windows_are_captured(): ) assert result["state"] == "active" - assert executor.calls == ["inject", "capture:early:4", "capture:steady:6", "merge"] + assert executor.calls == ["inject", "capture:full:12", "merge"] -def test_observation_uses_executor_sleep_hook_for_stabilization(): +def test_stabilization_is_a_slice_gap_not_an_additional_wait(): executor = StubExecutor() slept: list[float] = [] executor.sleep = slept.append @@ -137,4 +141,5 @@ def test_observation_uses_executor_sleep_hook_for_stabilization(): baseline_window=_BASELINE, ) - assert slept == [1] + assert slept == [] + assert executor.calls == ["inject", "capture:full:3", "merge"] diff --git a/tests/test_example_agents.py b/tests/test_example_agents.py index cf3ba58..c9c970b 100644 --- a/tests/test_example_agents.py +++ b/tests/test_example_agents.py @@ -1,4 +1,4 @@ -"""Tests for the public example DeepAgent implementation.""" +"""Tests for the public example diagnostic agent implementations.""" import asyncio import json @@ -9,6 +9,21 @@ from unittest.mock import MagicMock from uuid import uuid4 +import pytest + + +@pytest.mark.parametrize("fenced", [True, False]) +def test_bundled_agents_receive_the_actual_output_type_contract(fenced): + from examples.agents.diagnosis import build_user_prompt + + context = SimpleNamespace(metadata={"canonical_observation": {"case_id": "anonymous"}}) + prompt = build_user_prompt(context, fenced_output=fenced) + schema = json.loads(prompt.split("DIAGNOSIS_OUTPUT_SCHEMA: ", 1)[1]) + assert schema["properties"]["evidence"]["type"] == "array" + assert schema["properties"]["evidence"]["items"]["type"] == "string" + assert schema["properties"]["verdict"]["enum"] == ["fault_detected", "network_healthy", "inconclusive"] + + # Stub third-party agent deps so the module can be imported without them. for _mod in [ "deepagents", @@ -193,6 +208,7 @@ def test_minimal_deepagent_reads_minimax_api_key_from_environment(monkeypatch): def test_minimal_deepagent_openai_defaults_and_openai_key(monkeypatch): + monkeypatch.setenv("OPENAI" + "_BASE_URL", "https://example.invalid/v1") monkeypatch.setenv("OPENAI_API_KEY", "openai-shell-key") agent = MinimalDeepAgent(vendor="openai") @@ -202,15 +218,6 @@ def test_minimal_deepagent_openai_defaults_and_openai_key(monkeypatch): assert agent.base_url == "https://api.openai.com/v1" -def test_minimal_deepagent_openai_uses_official_base_url(monkeypatch): - monkeypatch.setenv("OPENAI_API_KEY", "openai-shell-key") - monkeypatch.setenv("OPENAI" + "_BASE_URL", "https://example.invalid/v1") - - agent = MinimalDeepAgent(vendor="openai") - - assert agent.base_url == "https://api.openai.com/v1" - - def test_openai_provider_uses_standard_openai_kwargs(): from examples.agents.minimal_deepagent.providers import openai as openai_provider @@ -230,10 +237,6 @@ def test_openai_provider_uses_standard_openai_kwargs(): assert kwargs["temperature"] == 0.1 -def test_minimal_deepagent_canonical_module_path(): - assert MinimalDeepAgent.__module__ == "examples.agents.minimal_deepagent.agent" - - def test_minimal_deepagent_supports_kimi_vendor(monkeypatch): monkeypatch.setenv("KIMI_API_KEY", "kimi-test-key") @@ -247,12 +250,6 @@ def test_minimal_deepagent_supports_kimi_vendor(monkeypatch): assert agent.api_key == "kimi-test-key" -def test_minimal_deepagent_does_not_expose_legacy_process_method(): - agent = MinimalDeepAgent(api_key="test-key") - - assert not hasattr(agent, "process") - - def test_minimal_deepagent_closes_exit_stack_within_each_diagnose_call(tmp_path, monkeypatch): fake_graph = _FakeRuntime({"messages": [_diagnosis_json_message()]}) agent = MinimalDeepAgent( @@ -525,7 +522,7 @@ def __exit__(self, exc_type, exc, tb): class _FakeAgent: - def __init__(self): + def __init__(self, *, vendor="minimax"): self.closed = False async def aclose(self): @@ -534,11 +531,11 @@ async def aclose(self): def _prepare_basic_repo(tmp_path): repo = tmp_path / "repo" - scenario_root = repo / "scenarios" / "generated" / "xs" + scenario_root = repo / "scenarios" / "generated" / "medium" scenario_root.mkdir(parents=True) - (scenario_root / "generated_link_down_xs_001.yaml").write_text("scenario: link_down\n", encoding="utf-8") - (scenario_root / "generated_packet_loss_xs_001.yaml").write_text("scenario: packet_loss\n", encoding="utf-8") - (scenario_root / "generated_high_latency_xs_001.yaml").write_text("scenario: high_latency\n", encoding="utf-8") + (scenario_root / "generated_link_down_medium_001.yaml").write_text("scenario: link_down\n", encoding="utf-8") + (scenario_root / "generated_packet_loss_medium_001.yaml").write_text("scenario: packet_loss\n", encoding="utf-8") + (scenario_root / "generated_high_latency_medium_001.yaml").write_text("scenario: high_latency\n", encoding="utf-8") # Also create custom fault scenario for 03_custom_faults fault_dir = repo / "examples" / "faults" / "custom_fault_pack" fault_dir.mkdir(parents=True) @@ -546,48 +543,35 @@ def _prepare_basic_repo(tmp_path): return repo -def test_01_run_scenario_main(tmp_path): - import importlib - - mod = importlib.import_module("examples.01_run_scenario") - repo = _prepare_basic_repo(tmp_path) - - result = mod.main(repo_root=repo, bench_cls=_FakeBench, agent_cls=_FakeAgent) - - assert result == 0 - - -def test_02_run_suite_main(tmp_path): - import importlib - - mod = importlib.import_module("examples.02_run_suite") - repo = _prepare_basic_repo(tmp_path) - - result = mod.main(repo_root=repo, bench_cls=_FakeBench, agent_cls=_FakeAgent) - - assert result == 0 - - -def test_03_run_scale_benchmark_main(tmp_path): +@pytest.mark.parametrize( + "scale,override,expected", [("xs", None, 3), ("medium", None, 2), ("fat-tree-k12", None, 1), ("fat-tree-k12", 2, 2)] +) +def test_scale_benchmark_default_workers_respect_topology_size(tmp_path, monkeypatch, scale, override, expected): import importlib + from types import SimpleNamespace mod = importlib.import_module("examples.03_run_scale_benchmark") - repo = _prepare_basic_repo(tmp_path) - - result = mod.main(repo_root=repo, bench_cls=_FakeBench, agent_cls=_FakeAgent) - - assert result == 0 + captured = {} + monkeypatch.setattr(mod, "discover_generated_scenarios", lambda *args: []) + monkeypatch.setattr(mod, "build_wrapped_agent", lambda *args, **kwargs: (object(), object())) + monkeypatch.setattr(mod, "print_agent_banner", lambda *args: None) + monkeypatch.setattr(mod, "wait_and_print_run", lambda *args, **kwargs: 0) + def run_suite(**kwargs): + captured.update(kwargs) -def test_04_custom_faults_main(tmp_path): - import importlib + class Bench: + def __init__(self, **kwargs): + self.sessions = SimpleNamespace(run_suite=run_suite) - mod = importlib.import_module("examples.04_custom_faults") - repo = _prepare_basic_repo(tmp_path) + def __enter__(self): + return self - result = mod.main(repo_root=repo, bench_cls=_FakeBench, agent_cls=_FakeAgent) + def __exit__(self, *args): + pass - assert result == 0 + assert mod.main(repo_root=tmp_path, scale=scale, workers=override, bench_cls=Bench) == 0 + assert captured["workers"] == expected def test_05_manual_runtime_main(tmp_path, capsys): @@ -604,7 +588,7 @@ def test_05_manual_runtime_main(tmp_path, capsys): assert "PYTHONPATH=. netopsbench runtime teardown manual-" in output -def test_example_common_builds_wrapped_agent_with_vendor_fallback(): +def test_example_common_does_not_mask_agent_constructor_errors(): from examples._common import build_wrapped_agent class _NoVendorAgent: @@ -613,15 +597,11 @@ def __init__(self): bench = _FakeBench(workspace=".") - raw, wrapped = build_wrapped_agent(bench, _NoVendorAgent, vendor="minimax") - - assert isinstance(raw, _NoVendorAgent) - assert wrapped is raw + with pytest.raises(TypeError, match="vendor"): + build_wrapped_agent(bench, _NoVendorAgent, vendor="minimax") def test_example_common_require_scenarios_accepts_single_path_and_raises_actionable_error(tmp_path): - import pytest - from examples._common import require_scenarios with pytest.raises(FileNotFoundError) as exc_info: @@ -631,8 +611,6 @@ def test_example_common_require_scenarios_accepts_single_path_and_raises_actiona def test_example_common_require_scenarios_reports_combined_missing_files(tmp_path): - import pytest - from examples._common import require_scenarios (tmp_path / "present.yaml").write_text("scenario: present\n", encoding="utf-8") @@ -746,7 +724,7 @@ async def aclose(self): fake_sdk = types.ModuleType('netopsbench.sdk') fake_sdk.NetOpsBench = NetOpsBench fake_sdk.RunFailedError = RuntimeError -fake_sdk.supported_scales = lambda: ('xs', 'small', 'medium', 'large', 'xlarge', 'fat-tree-k8', 'fat-tree-k12') +fake_sdk.supported_scales = lambda: ('xs', 'medium', 'large', 'xlarge', 'fat-tree-k8', 'fat-tree-k12', 'fat-tree-k18') sys.modules['netopsbench.sdk'] = fake_sdk fake_examples_agents = types.ModuleType('examples.agents') @@ -870,3 +848,11 @@ async def ainvoke(self, payload, config=None): asyncio.run(agent.diagnose(context)) assert captured_config["args"] == ["-m", "netopsbench.platform.toolkit.fastmcp_server"] + + +@pytest.mark.parametrize("example", ["01_run_scenario", "02_run_suite", "03_run_scale_benchmark", "04_custom_faults"]) +def test_example_main(tmp_path, example): + import importlib + + module = importlib.import_module(f"examples.{example}") + assert module.main(repo_root=_prepare_basic_repo(tmp_path), bench_cls=_FakeBench, agent_cls=_FakeAgent) == 0 diff --git a/tests/test_fat_tree_topology.py b/tests/test_fat_tree_topology.py index 2a12a8a..c3810a6 100644 --- a/tests/test_fat_tree_topology.py +++ b/tests/test_fat_tree_topology.py @@ -38,8 +38,8 @@ def test_fat_tree_k12_sparse_generates_valid_non_overlapping_link_networks(tmp_p assert metadata["scale"]["total_clients"] == 144 assert metadata["scale"]["host_density"] == "sparse" assert metadata["scale"]["full_density_clients_per_edge"] == 6 - assert metadata["pingmesh"]["coverage_epoch_cycles"] == 36 - assert metadata["pingmesh"]["coverage_epoch_seconds"] == 108 + assert metadata["pingmesh"]["coverage_epoch_cycles"] == 12 + assert metadata["pingmesh"]["coverage_epoch_seconds"] == 36 assert len(metadata["devices"]["clients"]) == 144 assert manifest.facts.clients_per_attached_switch == 2 assert manifest.facts.host_density == "sparse" diff --git a/tests/test_fault_catalog_v2.py b/tests/test_fault_catalog_v2.py new file mode 100644 index 0000000..5c080ec --- /dev/null +++ b/tests/test_fault_catalog_v2.py @@ -0,0 +1,1019 @@ +"""Configuration ownership, preconditions, and private/public evidence boundaries.""" + +import json +import subprocess + +import pytest + +from netopsbench.models.scenario import EpisodeSpec +from netopsbench.platform.faults.catalog import FAULT_MECHANISMS +from netopsbench.platform.faults.injector import FaultInjector +from netopsbench.platform.faults.services.periodic import PeriodicController +from netopsbench.platform.faults.specs import create_fault_registry +from netopsbench.platform.observability.bgp_collector import BgpTransitionTracker +from netopsbench.platform.scenario.effects import scoped_integrity_errors +from netopsbench.platform.topology.clos_builder import build_clos_plan +from netopsbench.platform.topology.config import config_for_scale + + +@pytest.fixture +def injector(): + return FaultInjector(topology_metadata=build_clos_plan(config_for_scale("medium")).manifest.model_dump(mode="json")) + + +def test_registry_is_the_complete_catalog_and_old_types_are_absent(): + registry = create_fault_registry() + assert set(registry.supported_scenario_faults()) == set(FAULT_MECHANISMS) + for retired in ("bgp_neighbor_misconfig", "route_policy_misconfig", "acl_misconfig", "acl_misconfiguration"): + assert registry.get(retired) is None + + +@pytest.mark.parametrize("fault", ("route_origination_misconfig", "route_filter_misconfig", "ecmp_misconfig")) +def test_mechanism_is_required_in_parameters(fault): + spec = create_fault_registry().get(fault) + episode = EpisodeSpec( + episode_id="a", + fault_type=fault, + target_device="leaf1", + target_prefix="192.168.2.0/30", + metadata={"mechanism": FAULT_MECHANISMS[fault][0]}, + ) + assert any("mechanism" in error for error in spec.validate_episode(episode)) + episode = episode.model_copy( + update={"parameters": {"mechanism": FAULT_MECHANISMS[fault][0], "peer_ip": "10.0.0.1"}} + ) + assert not any("mechanism" in error for error in spec.validate_episode(episode)) + + +def test_malformed_acl_direction_returns_a_validation_error(): + episode = EpisodeSpec( + episode_id="a", + fault_type="acl_l4_port_misconfig", + target_device="leaf1", + target_interface="Ethernet0", + target_prefix="192.168.2.0/30", + parameters={"direction": {"out": True}}, + ) + errors = create_fault_registry().get(episode.fault_type).validate_episode(episode) + assert "ACL direction must be in or out" in errors + + +def test_partial_transaction_compensates_every_attempted_write(injector, monkeypatch): + handler = injector._network + state, attempts = {}, [] + operations = [ + {"kind": "docker", "apply": ["set", "one"], "restore": ["undo", "one"]}, + {"kind": "docker", "apply": ["set", "two"], "restore": ["undo", "two"]}, + ] + monkeypatch.setattr(handler, "_prepare", lambda ep: (operations, {})) + + def run(device, kind, args): + attempts.append(args) + if args[0] == "set": + state[args[1]] = True + if args[1] == "two": + raise RuntimeError("partial write") + else: + state.pop(args[1], None) + return "" + + monkeypatch.setattr(handler, "_run", run) + result = handler.inject(EpisodeSpec(episode_id="a", fault_type="bgp_neighbor_shutdown", target_device="leaf1")) + assert not result["success"] + assert state == {} + assert attempts[-2:] == [["undo", "two"], ["undo", "one"]] + assert not injector.active_faults + + +def test_failed_compensation_tracks_residual_and_keeps_other_cleanup(injector, monkeypatch): + handler = injector._network + called = [] + + def run(device, kind, args): + called.append(args) + if args == ["two"]: + raise RuntimeError("cannot restore two") + + monkeypatch.setattr(handler, "_run", run) + result = handler.recover( + { + "type": "route_filter_misconfig", + "device": "leaf1", + "journal": [{"kind": "docker", "restore": ["one"]}, {"kind": "docker", "restore": ["two"]}], + } + ) + assert not result["recovered"] + assert called == [["two"], ["one"]] + + +def test_policy_is_cloned_and_original_attachment_restored(injector, monkeypatch): + handler = injector._network + monkeypatch.setattr(handler, "_run", lambda *args: "route-map RM-ALLOW permit 10\n set metric 7\n!\n") + monkeypatch.setattr( + handler.routing, + "get_bgp_config_snapshot", + lambda device: { + "neighbors": [{"peer_ip": "10.0.0.1", "route_maps": [{"name": "RM-ALLOW", "direction": "out"}]}] + }, + ) + operations = handler._prefix_policy("leaf1", "192.168.1.0/30", ["10.0.0.1"], "out") + write = "\n".join(operations[0]["apply"]) + assert "route-map RM-ALLOW permit" not in write + assert "set metric 7" in write + assert "deny 1" in write + assert "neighbor 10.0.0.1 route-map RM-ALLOW out" in operations[0]["restore"] + assert not any(command == "no route-map RM-ALLOW" for command in operations[0]["restore"]) + + +def test_ecmp_rejects_single_actual_next_hop_before_mutating(injector, monkeypatch): + handler = injector._network + monkeypatch.setattr(handler, "_run", lambda *args: "") + monkeypatch.setattr(handler, "_json", lambda *args: [{"dst": "192.168.2.0/30", "gateway": "10.0.0.1"}]) + episode = EpisodeSpec( + episode_id="a", + fault_type="ecmp_misconfig", + target_device="leaf1", + target_prefix="192.168.2.0/30", + parameters={"mechanism": "max_paths_limit"}, + ) + with pytest.raises(RuntimeError, match="actual kernel FIB"): + handler._prepare(episode) + assert not injector.active_faults + + +@pytest.mark.parametrize( + "second_path, eligible", + [ + ({}, True), + ({"aspath": {"string": "65033 65067"}}, False), + ({"aspath": {}}, False), + ({"aspath": {"string": ""}}, False), + ({"aspath": {"string": 65034}}, False), + ({"valid": False}, False), + ({"multipath": False}, False), + ({"nexthops": [{"ip": "10.2.1.21", "accessible": False, "used": True}]}, False), + ({"nexthops": [{"ip": "10.2.1.99", "accessible": True, "used": True}]}, False), + ], +) +def test_multipath_relax_requires_distinct_installed_frr_as_paths(injector, monkeypatch, second_path, eligible): + handler = injector._network + reads = [] + + def read_config(device, kind, commands): + reads.append(commands) + assert commands == ["show running-config"] + return "router bgp 65011\n bgp bestpath as-path multipath-relax\n" + + def path(gateway, as_path): + return { + "valid": True, + "multipath": True, + "aspath": {"string": as_path}, + "nexthops": [{"ip": gateway, "accessible": True, "used": True}], + } + + first = path("10.2.1.5", "65033 65067") + second = {**path("10.2.1.21", "65034 65067"), **second_path} + monkeypatch.setattr(handler, "_run", read_config) + monkeypatch.setattr( + handler, + "_json", + lambda *a: [{"nexthops": [{"gateway": "10.2.1.5"}, {"gateway": "10.2.1.21"}]}], + ) + monkeypatch.setattr(handler, "_frr_json", lambda *a: {"paths": [first, second]}) + episode = EpisodeSpec( + episode_id="a", + fault_type="ecmp_misconfig", + target_device="leaf1", + target_prefix="192.168.19.4/30", + parameters={"mechanism": "multipath_relax_disabled"}, + ) + if eligible: + operations, evidence = handler._prepare(episode) + assert "no bgp bestpath as-path multipath-relax" in operations[0]["apply"] + assert "bgp bestpath as-path multipath-relax" in operations[0]["restore"] + assert evidence["healthy_bgp"]["paths"] == [first, second] + else: + with pytest.raises(RuntimeError, match="distinct valid AS_PATHs"): + handler._prepare(episode) + assert reads == [["show running-config"]] + assert not injector.active_faults + + +@pytest.mark.parametrize("received", [1, 2, 14]) +def test_maximum_prefix_uses_healthy_neighbor_count_and_supported_json_command(injector, monkeypatch, received): + handler = injector._network + reads = [] + + def run(device, kind, commands): + reads.append(commands) + if commands == ["show running-config"]: + return "router bgp 65011\n neighbor 10.1.1.1 remote-as 65001\n" + assert commands == ["show ip bgp neighbors 10.1.1.1 json"] + return json.dumps({"10.1.1.1": {"addressFamilyInfo": {"ipv4Unicast": {"acceptedPrefixCounter": received}}}}) + + monkeypatch.setattr(handler, "_run", run) + monkeypatch.setattr(handler, "_neighbor", lambda *a: {"remote_as": 65001}) + episode = EpisodeSpec( + episode_id="a", + fault_type="bgp_max_prefix_misconfig", + target_device="leaf1", + parameters={"peer_ip": "10.1.1.1"}, + ) + if received < 2: + with pytest.raises(RuntimeError, match="at least two healthy"): + handler._prepare(episode) + else: + operations, evidence = handler._prepare(episode) + assert f"neighbor 10.1.1.1 maximum-prefix {received - 1}" in operations[0]["apply"] + assert evidence["healthy_prefix_count"] == received + assert all(command[0].startswith("show ") for command in reads) + + +def test_routing_loop_rejects_an_unhealthy_or_unknown_neighbor_before_mutation(injector, monkeypatch): + handler = injector._network + commands = [] + monkeypatch.setattr(handler, "_run", lambda device, kind, args: commands.append(args) or "") + monkeypatch.setattr(handler.routing, "pick_bgp_neighbor", lambda *a, **kw: None) + episode = EpisodeSpec( + episode_id="a", + fault_type="routing_loop", + target_device="leaf1", + target_interface="Ethernet0", + target_prefix="192.168.2.2/32", + parameters={"next_hop": "192.0.2.1"}, + ) + with pytest.raises(RuntimeError, match="not readable and established"): + handler._prepare(episode) + assert commands == [["show running-config"]] + + +@pytest.mark.parametrize("readable", [True, False]) +def test_bgpd_stop_requires_a_captured_daemon_configuration(injector, monkeypatch, readable): + handler = injector._network + original = "!\nrouter bgp 65011\n neighbor 10.1.1.1 remote-as 65001\n!\nend\n" + commands = [] + + def run(device, kind, args): + commands.append(args) + if args[0] == "supervisorctl": + return "bgpd RUNNING pid 123, uptime 10:00" + return "Building configuration...\n\nCurrent configuration:\n" + original if readable else "% unavailable" + + monkeypatch.setattr(handler, "_run", run) + episode = EpisodeSpec(episode_id="a", fault_type="bgp_process_down", target_device="leaf1") + if not readable: + with pytest.raises(RuntimeError, match="Cannot capture"): + handler._prepare(episode) + else: + operations, evidence = handler._prepare(episode) + assert evidence["original_bgp_config"] == original + assert operations[0]["restore"][-1] == original + assert operations[0]["apply"] == ["supervisorctl", "stop", "bgpd"] + assert commands == [ + ["supervisorctl", "status", "bgpd"], + ["vtysh", "-d", "bgpd", "-c", "show running-config"], + ] + + +@pytest.mark.parametrize("exists", [False, True]) +def test_update_source_uses_an_absent_interface_and_restores_the_original_option(injector, monkeypatch, exists): + handler = injector._network + monkeypatch.setattr(handler, "_neighbor", lambda *a: {"remote_as": 65001}) + monkeypatch.setattr(handler, "_run", lambda *a: "router bgp 65011\n neighbor 10.1.1.1 update-source Ethernet0\n") + monkeypatch.setattr(handler, "_json", lambda *a: [{"ifname": "Loopback999" if exists else "Ethernet0"}]) + episode = EpisodeSpec( + episode_id="a", + fault_type="bgp_update_source_mismatch", + target_device="leaf1", + parameters={"peer_ip": "10.1.1.1"}, + ) + if exists: + with pytest.raises(RuntimeError, match="already exists"): + handler._prepare(episode) + else: + operations, evidence = handler._prepare(episode) + assert "neighbor 10.1.1.1 update-source Loopback999" in operations[0]["apply"] + assert "neighbor 10.1.1.1 update-source Ethernet0" in operations[0]["restore"] + assert evidence["fault_update_source"] == "Loopback999" + + +@pytest.mark.parametrize("running", [True, False]) +def test_bgpd_recovery_reloads_original_configuration_even_if_process_is_running(monkeypatch, running): + from pathlib import Path + + from netopsbench.platform.faults.services import _bgpd_restore + + calls, paths, budgets = [], [], [] + config = "router bgp 65011\n neighbor 10.1.1.1 remote-as 65001\nend\n" + monkeypatch.setattr(_bgpd_restore.sys, "argv", ["restore", config]) + times = iter([0, 1, 2, 3]) + monkeypatch.setattr(_bgpd_restore.time, "monotonic", lambda: next(times)) + + def run(command, **kwargs): + calls.append(command) + budgets.append(kwargs["timeout"]) + if command[:2] == ["supervisorctl", "status"]: + return subprocess.CompletedProcess(command, 0 if running else 3, "RUNNING" if running else "STOPPED", "") + if command[0] == "vtysh": + paths.append(Path(command[-1])) + assert paths[-1].read_text() == config + assert command[:4] == ["vtysh", "-d", "bgpd", "-f"] + return subprocess.CompletedProcess(command, 0, "", "") + + monkeypatch.setattr(_bgpd_restore.subprocess, "run", run) + _bgpd_restore.restore_bgpd() + assert (["supervisorctl", "start", "bgpd"] in calls) is (not running) + assert budgets == sorted(budgets, reverse=True) + assert not paths[0].exists() + + +def test_bgpd_recovery_does_not_start_another_command_after_its_deadline(monkeypatch): + from netopsbench.platform.faults.services import _bgpd_restore + + calls = [] + times = iter([0, 1, 26]) + monkeypatch.setattr(_bgpd_restore.time, "monotonic", lambda: next(times)) + + def run(command, **kwargs): + calls.append(command) + return subprocess.CompletedProcess(command, 3, "STOPPED", "") + + monkeypatch.setattr(_bgpd_restore.subprocess, "run", run) + with pytest.raises(TimeoutError, match="deadline"): + _bgpd_restore.restore_bgpd() + assert calls == [["supervisorctl", "status", "bgpd"]] + + +def test_netem_refuses_unowned_qdisc(injector, monkeypatch): + monkeypatch.setattr( + injector._cmd, "docker_exec", lambda *a, **k: subprocess.CompletedProcess(a, 0, stdout='[{"kind":"htb"}]') + ) + with pytest.raises(RuntimeError, match="Non-default qdisc"): + injector.inject_packet_loss("leaf1", "Ethernet0") + assert not injector.active_faults + + +def test_periodic_controller_stops_and_records_verified_phases(): + import time + + states = [] + controller = PeriodicController( + lambda: states.append("fault"), lambda: states.append("healthy"), down_time=0.01, up_time=0.01 + ) + controller.start() + time.sleep(0.06) + controller.stop_event.set() + controller.thread.join(timeout=1) + assert not controller.thread.is_alive() + assert states[:3] == ["fault", "healthy", "fault"] + assert len(controller.history) >= 3 + + +@pytest.mark.parametrize("failed_phase", ["fault", "healthy"]) +def test_periodic_controller_preserves_errors_and_never_records_a_failed_phase(failed_phase): + calls = [] + + def phase(name): + calls.append(name) + if name == failed_phase and len(calls) > 1: + raise RuntimeError() + + controller = PeriodicController(lambda: phase("fault"), lambda: phase("healthy"), down_time=0.001, up_time=0.001) + controller.start() + controller.thread.join(timeout=1) + assert not controller.thread.is_alive() + assert controller.stop_event.is_set() + assert controller.error == "RuntimeError: " + assert [row["phase"] for row in controller.history] == calls[:-1] + + +def test_prefix_event_does_not_interpret_collection_failure_as_zero(): + tracker = BgpTransitionTracker() + row = {"neighbor": "10.0.0.1", "state": "Established", "prefixes_received": 8} + tracker.process("leaf1", [row], 1, "lab", collection_ok=True) + failure = tracker.process("leaf1", [], 2, "lab", collection_ok=False) + assert not any("bgp_prefix_events" in line for line in failure) + changed = tracker.process("leaf1", [dict(row, prefixes_received=6)], 3, "lab", collection_ok=True) + assert any("prefixes_before=8i,prefixes_after=6i" in line for line in changed) + assert not any("bgp_session_events" in line for line in changed) + + +def test_scoped_outage_requires_complete_remaining_tasks(): + obs = { + "data_source_status": "ok", + "_baseline_coverage": {"coverage_status": "complete"}, + "coverage_status": "incomplete", + } + effect = {"unobservable_clients": ["client1"]} + audit = { + "missing_tasks": [["client1", "client2", 0]], + "invalid_tasks": [], + "observable_pairs": [["client2", "client3"]], + } + assert scoped_integrity_errors(obs, audit, effect) == [] + audit["missing_tasks"].append(["client2", "client3", 0]) + assert scoped_integrity_errors(obs, audit, effect) + + +def test_periodic_outages_include_verified_transition_time_only(): + from netopsbench.platform.scenario.effects import _periodic_client_outages + + phases = [ + {"phase": "fault", "time": "2026-10-12T12:00:00+00:00"}, + {"phase": "healthy", "started_at": "2026-10-12T12:00:20+00:00", "time": "2026-10-12T12:00:21+00:00"}, + {"phase": "fault", "started_at": "2026-10-12T12:00:41+00:00", "time": "2026-10-12T12:00:42+00:00"}, + ] + assert _periodic_client_outages(phases, ["client1"], "2026-10-12T12:00:50Z") == [ + {"client": "client1", "start": "2026-10-12T12:00:00+00:00", "end": "2026-10-12T12:00:21+00:00"}, + {"client": "client1", "start": "2026-10-12T12:00:41+00:00", "end": "2026-10-12T12:00:50+00:00"}, + ] + + +@pytest.mark.parametrize( + "change,missing,valid", + [ + ({}, [], True), + ({"time": "2026-10-12T12:00:21.5Z"}, [], True), + ({"time": "2026-10-12T12:00:24Z"}, [], False), + ({"src": "client2", "dst": "client1"}, [], False), + ({"socket_batch_valid": False}, [], False), + ({"time": ""}, [], False), + ({}, [["client1", "client2", 0]], False), + ({}, [["client2", "client3", 0]], False), + ], +) +def test_periodic_outage_does_not_excuse_missing_tasks_or_errors_in_healthy_phases(change, missing, valid): + obs = {"data_source_status": "ok", "_baseline_coverage": {"coverage_status": "complete"}} + audit = { + "missing_tasks": missing, + "invalid_tasks": [["client1", "client2", 0]], + "invalid_socket_rows": 1, + "invalid_rows": [ + { + "src": "client1", + "dst": "client2", + "time": "2026-10-12T12:00:10Z", + "local_probe_errors": 1, + "socket_batch_valid": True, + **change, + } + ], + "coverage_status": "incomplete", + "observable_pairs": [["client1", "client2"], ["client2", "client3"]], + } + effect = { + "bounded_client_outages": [ + {"client": "client1", "start": "2026-10-12T12:00:00+00:00", "end": "2026-10-12T12:00:21+00:00"} + ], + "probe_cycle_seconds": 1, + } + assert (not scoped_integrity_errors(obs, audit, effect)) is valid + assert audit["coverage_status"] == "incomplete" + assert audit["invalid_socket_rows"] == 1 + + +def test_private_probe_evidence_reuses_rows_and_preserves_local_errors(): + from netopsbench.platform.pingmesh._detector_analysis import probe_pair_evidence + + row = { + "src_name": "client1", + "dst_name": "client2", + "packets_sent": 8, + "packets_lost": 0, + "rtt_avg": 1, + "rtt_max": 2, + "local_probe_errors": 0, + } + fault = {**row, "packets_lost": 3, "rtt_max": 122, "local_probe_errors": 1} + result = probe_pair_evidence( + [row], [fault, {**fault, "src_name": "unrelated"}], [{"src": "client1", "dst": "client2"}] + ) + assert len(result) == 1 + assert result[0]["baseline"]["regular"]["lost"] == 0 + assert result[0]["fault"]["regular"]["lost"] == 3 + assert result[0]["fault"]["rtt_max_ms"] == 122 + assert result[0]["fault"]["local_probe_errors"] == 1 + + +def test_candidate_scope_covers_all_planned_flows_instead_of_only_the_anchor(): + from netopsbench.platform.scenario.candidates import CandidatePaths + + manifest = build_clos_plan(config_for_scale("medium")).manifest + graph = CandidatePaths(manifest) + anchor = {"src": "client12", "dst": "client10"} + pairs = graph.affected_pairs("mtu_mismatch", "leaf6", "spine3", anchor) + assert pairs[0] == anchor + assert {"src": "client11", "dst": "client3"} in pairs + assert len(pairs) == 28 + assert all((pair["src"], pair["dst"]) in graph.pairs for pair in pairs) + assert all( + graph.contains(p["src"], p["dst"], "leaf6", "spine3") or graph.contains(p["dst"], p["src"], "leaf6", "spine3") + for p in pairs + ) + + +def test_effect_audits_scoped_existing_flows_without_changing_case_parameters(monkeypatch): + from types import SimpleNamespace + + from netopsbench.platform.scenario.effects import validate_effect + from netopsbench.platform.toolkit._core.common import ToolResult + + manifest = build_clos_plan(config_for_scale("medium")).manifest + anchor = {"src": "client12", "dst": "client10"} + affected = {"src": "client11", "dst": "client3"} + control = {"src": "client2", "dst": "client4"} + episode = EpisodeSpec( + episode_id="a", + fault_type="mtu_mismatch", + target_device="leaf6", + target_interface="Ethernet8", + parameters={"mtu": 1400, "affected_candidates": [anchor], "control_candidates": [control]}, + ) + toolkit = SimpleNamespace( + get_device_status=lambda device: ToolResult(success=True, data={"running": True, "accessible": True}), + get_device_interfaces=lambda *args, **kwargs: ToolResult(success=True, data={}), + ) + monkeypatch.setattr("netopsbench.platform.scenario.effects.AgentToolkit", lambda **kw: toolkit) + executor = SimpleNamespace( + current_manifest=lambda: manifest, + influxdb_bucket="worker", + topology_id=manifest.topology_id, + injector=SimpleNamespace(_iface=SimpleNamespace(resolve_sonic=lambda interface: interface)), + _case_affected_pairs=[anchor, affected], + ) + probes = [ + { + **pair, + "baseline": {"samples": 20, "df": {"lost": 0, "loss_pct": 0}}, + "fault": {"samples": 20, "df": {"lost": 0, "loss_pct": 0}}, + } + for pair in [anchor, affected, control] + ] + probes[1]["fault"]["df"] = {"lost": 16, "loss_pct": 100} + result = validate_effect( + executor, episode, {"observations": {"_probe_evidence": probes}}, {"nodes": {}}, {"nodes": {}} + ) + assert result["valid"] + assert episode.parameters["affected_candidates"] == [anchor] + + +@pytest.mark.parametrize( + ("df_lost", "mtu_drops", "local_errors", "baseline_loss_pct", "valid"), + [(16, 0, 0, 0, True), (16, 16, 0, 0, False), (16, 0, 1, 0, False), (16, 0, 0, 80, False), (2, 0, 0, 0, False)], +) +def test_acl_effect_accepts_df_path_loss_without_mtu_or_local_errors( + monkeypatch, df_lost, mtu_drops, local_errors, baseline_loss_pct, valid +): + from types import SimpleNamespace + + from netopsbench.platform.scenario.effects import validate_effect + from netopsbench.platform.toolkit._core.common import ToolResult + + manifest = build_clos_plan(config_for_scale("medium")).manifest + pair = {"src": "client1", "dst": "client3"} + toolkit = SimpleNamespace( + get_device_status=lambda device: ToolResult(success=True, data={"running": True, "accessible": True}), + ) + monkeypatch.setattr("netopsbench.platform.scenario.effects.AgentToolkit", lambda **kw: toolkit) + injector = SimpleNamespace( + container_names={"leaf1": "container"}, + _cmd=SimpleNamespace(docker_exec=lambda *args: SimpleNamespace(returncode=0, stdout="36 DROP OWNED")), + ) + executor = SimpleNamespace( + current_manifest=lambda: manifest, + influxdb_bucket="bucket", + topology_id="topology", + injector=injector, + _case_affected_pairs=[pair], + ) + episode = EpisodeSpec(episode_id="a", fault_type="acl_destination_misconfig", target_device="leaf1", parameters={}) + probes = [ + { + **pair, + "baseline": {"samples": 20, "regular": {"loss_pct": 0}, "df": {"loss_pct": baseline_loss_pct}}, + "fault": { + "samples": 20, + "local_probe_errors": local_errors, + "regular": {"lost": 2, "loss_pct": 10}, + "df": {"lost": df_lost, "loss_pct": df_lost * 5, "mtu_drops": mtu_drops}, + }, + } + ] + result = validate_effect( + executor, + episode, + { + "injection": {"evidence": {"acl_name": "OWNED", "rule": ["FORWARD", "-o", "Ethernet0"]}}, + "observations": {"_probe_evidence": probes}, + }, + {"nodes": {}}, + {"nodes": {}}, + ) + assert result["valid"] is valid + assert result["evidence"]["matched_probe_loss_kinds"] == (["df"] if valid else []) + + +def test_periodic_policy_recovery_skips_already_removed_owned_objects(injector, monkeypatch): + handler = injector._network + calls = [] + + def run(device, kind, commands): + calls.append(commands) + return ( + "router bgp 65011\n neighbor 10.0.0.1 route-map RM-ALLOW out\n" + if commands == ["show running-config"] + else "" + ) + + monkeypatch.setattr(handler, "_run", run) + result = handler.recover( + { + "type": "route_flapping", + "device": "leaf1", + "journal": [ + { + "kind": "frr", + "restore": [ + "configure terminal", + "router bgp 65011", + "neighbor 10.0.0.1 route-map RM-ALLOW out", + "no route-map OWNED", + "no ip prefix-list OWNEDL", + "end", + ], + } + ], + } + ) + assert result["recovered"] + assert "no route-map OWNED" not in calls[-1] + assert "no ip prefix-list OWNEDL" not in calls[-1] + assert "neighbor 10.0.0.1 route-map RM-ALLOW out" in calls[-1] + + +def test_validation_outage_keeps_comparison_evidence_without_claiming_unaffected_flow(monkeypatch): + from types import SimpleNamespace + + from netopsbench.platform.scenario.effects import validate_effect + from netopsbench.platform.toolkit._core.common import ToolResult + + manifest = build_clos_plan(config_for_scale("xs")).manifest + toolkit = SimpleNamespace(get_device_status=lambda device: ToolResult(success=True, data={"running": False})) + monkeypatch.setattr("netopsbench.platform.scenario.effects.AgentToolkit", lambda **kw: toolkit) + pair = {"src": "client1", "dst": "client2"} + episode = EpisodeSpec( + episode_id="a", + fault_type="device_down", + target_device="spine1", + parameters={"affected_candidates": [pair], "control_candidates": [pair]}, + ) + observations = { + "_probe_evidence": [{**pair, "baseline": {"samples": 4}, "fault": {"samples": 4}}], + "pingmesh_metrics": {"anomalies": [{"src_name": "client1", "dst_name": "client2"}]}, + } + result = validate_effect( + SimpleNamespace( + current_manifest=lambda: manifest, + influxdb_bucket="worker", + topology_id=manifest.topology_id, + _case_affected_pairs=[pair], + ), + episode, + {"observations": observations}, + {"nodes": {}}, + {"nodes": {}}, + ) + assert result["valid"] + assert result["evidence"]["control_role"] == "comparison" + assert result["evidence"]["probes"] + assert "_probe_evidence" not in observations + + +def test_address_fault_rejects_network_overlap_before_writes(tmp_path, monkeypatch): + from netopsbench.platform.topology.generator import generate_topology + + generate_topology("xs", str(tmp_path)) + injector = FaultInjector(clab_dir=str(tmp_path)) + handler = injector._network + config_path = tmp_path / "configs" / "sonic" / "spine1" / "config_db.json" + config = json.loads(config_path.read_text()) + config["INTERFACE"]["Ethernet0|198.51.100.5/24"] = {} + config_path.write_text(json.dumps(config)) + monkeypatch.setattr( + handler, + "_json", + lambda *args: [{"flags": ["UP"], "addr_info": [{"local": "10.1.1.1", "prefixlen": 30, "scope": "global"}]}], + ) + calls = [] + monkeypatch.setattr(handler, "_run", lambda device, kind, args: calls.append(args) or "1") + with pytest.raises(ValueError, match="non-overlapping"): + handler._prepare( + EpisodeSpec( + episode_id="a", + fault_type="interface_ip_misconfig", + target_device="spine1", + target_interface="Ethernet0", + ) + ) + assert not any(args[0] == "config" for args in calls) + + +def test_address_replacement_and_restore_never_remove_the_last_address(tmp_path, monkeypatch): + from netopsbench.platform.topology.generator import generate_topology + + generate_topology("xs", str(tmp_path)) + injector = FaultInjector(clab_dir=str(tmp_path)) + handler = injector._network + original = "10.1.1.1/30" + wrong = "198.51.100.1/30" + monkeypatch.setattr( + handler, + "_json", + lambda *args: [{"flags": ["UP"], "addr_info": [{"local": "10.1.1.1", "prefixlen": 30, "scope": "global"}]}], + ) + monkeypatch.setattr(handler, "_run", lambda *args: "1") + operations, _ = handler._prepare( + EpisodeSpec( + episode_id="a", fault_type="interface_ip_misconfig", target_device="spine1", target_interface="Ethernet0" + ) + ) + addresses = {original} + for commands in [*[op["apply"] for op in operations], *[op["restore"] for op in reversed(operations)]]: + action, address = commands[3], commands[-1] + if action == "add": + addresses.add(address) + else: + assert len(addresses) > 1 + addresses.remove(address) + assert addresses == {original} + assert operations[0]["apply"][-1] == wrong + + +@pytest.mark.parametrize( + "changes,peer,valid", [([-1, 1], "10.1.1.2", True), ([-1], "10.1.1.2", False), ([-1, 1], "10.9.9.2", False)] +) +def test_route_flapping_requires_actual_changes_at_the_selected_neighbor(injector, monkeypatch, changes, peer, valid): + from types import SimpleNamespace + + from netopsbench.platform.scenario.effects import validate_effect + from netopsbench.platform.toolkit._core.common import ToolResult + + manifest = injector._ctx.manifest + calls = [] + + def events(**kw): + calls.append(kw) + return ToolResult( + success=True, + data={ + "status": "ok", + "events": [ + {"device": "spine1", "peer": peer, "prefixes_before": 4, "prefixes_after": 4 + n} for n in changes + ], + }, + ) + + toolkit = SimpleNamespace( + get_device_status=lambda device: ToolResult(success=True, data={"running": True, "accessible": True}), + get_device_interfaces=lambda *args, **kw: ToolResult( + success=True, data={"addresses": {"Ethernet0": ["10.1.1.2/30"]}} + ), + get_bgp_neighbor=lambda *args: ToolResult(success=True, data={"state": "Established"}), + query_bgp_events=events, + ) + monkeypatch.setattr("netopsbench.platform.scenario.effects.AgentToolkit", lambda **kw: toolkit) + controller = SimpleNamespace( + error=None, + history=[ + {"phase": phase, "time": f"2026-10-12T12:00:{i * 10:02d}Z"} + for i, phase in enumerate(("fault", "healthy", "fault")) + ], + ) + injector._tracker._background_fault_controls["owned"] = {"controller": controller} + episode = EpisodeSpec( + episode_id="a", + fault_type="route_flapping", + target_device="leaf1", + target_interface="Ethernet0", + parameters={"peer_ip": "10.1.1.1"}, + ) + result = validate_effect( + SimpleNamespace( + current_manifest=lambda: manifest, + injector=injector, + _case_affected_pairs=[], + influxdb_bucket="worker", + topology_id=manifest.topology_id, + ), + episode, + { + "injection": {"control_id": "owned"}, + "observations": {"start_time": "2026-10-12T12:00:00Z", "end_time": "2026-10-12T12:00:30Z"}, + }, + {"nodes": {}}, + {"nodes": {}}, + ) + assert result["valid"] is valid + assert calls[0]["device"] == "spine1" and calls[0]["peer"] == "10.1.1.2" + + +def test_loop_evidence_does_not_bind_native_pingmesh_udp_sockets(injector, monkeypatch): + from types import SimpleNamespace + + from netopsbench.platform.scenario.effects import validate_effect + from netopsbench.platform.toolkit._core.common import ToolResult + + manifest = injector._ctx.manifest + toolkit = SimpleNamespace( + get_device_status=lambda device: ToolResult(success=True, data={"running": True, "accessible": True}), + _resolve_container=lambda name: name, + ) + monkeypatch.setattr("netopsbench.platform.scenario.effects.AgentToolkit", lambda **kw: toolkit) + commands = [] + + def trace(args, **kw): + commands.append(args) + return subprocess.CompletedProcess(args, 0, stdout="trace\n1 10.1.1.1\n2 10.1.1.2\n3 10.1.1.1\n4 10.1.1.2\n") + + monkeypatch.setattr("netopsbench.platform.scenario.effects.safe_run", trace) + pair = {"src": "client1", "dst": "client3"} + episode = EpisodeSpec( + episode_id="a", fault_type="routing_loop", target_device="leaf1", parameters={"affected_candidates": [pair]} + ) + result = validate_effect( + SimpleNamespace( + current_manifest=lambda: manifest, + influxdb_bucket="worker", + topology_id=manifest.topology_id, + _case_affected_pairs=[pair], + ), + episode, + {"observations": {"_probe_evidence": [{**pair, "baseline": {"samples": 4}}]}}, + {"nodes": {}}, + {"nodes": {}}, + ) + assert result["valid"] + assert "-I" in commands[0] + assert not any(arg.startswith("--sport") for arg in commands[0]) + + +@pytest.mark.parametrize("output", ["", "% BGP instance not found\n", "Neighbor V AS State/PfxRcd\n"]) +def test_phase_snapshot_distinguishes_unreadable_bgp_from_a_readable_empty_table(injector, monkeypatch, output): + from netopsbench.platform.observability import routes + + payload = {"checks": {"fib": {"returncode": 0, "stdout": "[]"}, "bgp": {"returncode": 0, "stdout": output}}} + monkeypatch.setattr(routes, "safe_run", lambda *a, **kw: subprocess.CompletedProcess(a, 0, json.dumps(payload))) + snapshot = routes.collect_routes(injector._ctx.manifest) + expected = output.startswith("Neighbor") + assert all(row["bgp_collection_ok"] is expected for row in snapshot["nodes"].values()) + assert all(row["bgp"] == [] for row in snapshot["nodes"].values()) + + +@pytest.mark.parametrize("running", [False, None]) +def test_device_fault_does_not_claim_an_already_stopped_or_unreadable_node(injector, monkeypatch, running): + monkeypatch.setattr(injector._cmd, "container_is_running", lambda container: running) + monkeypatch.setattr(injector._cmd, "run_cmd", lambda *args, **kw: pytest.fail("No mutation is authorized")) + result = injector.inject_device_down("spine1") + assert not result["success"] + assert result["original_state"]["container_running"] is running + assert not injector.active_faults + + +@pytest.mark.parametrize("method", ["inject_link_down", "inject_link_flapping"]) +def test_link_fault_preserves_a_preexisting_admin_down_endpoint(injector, monkeypatch, method): + monkeypatch.setattr( + injector._cmd, + "docker_exec", + lambda *args, **kw: subprocess.CompletedProcess(args, 0, stdout="1: eth1: "), + ) + monkeypatch.setattr( + injector._link, "_set_physical_link", lambda *args, **kw: pytest.fail("No link should be changed") + ) + result = getattr(injector, method)("spine1", "Ethernet0") + assert not result["success"] + assert not injector.active_faults + + +@pytest.mark.parametrize("host_route", ["192.168.2.2", "192.168.2.2/32"]) +def test_ttl_counters_need_both_real_exhaustion_and_returning_forwarding(injector, host_route): + from types import SimpleNamespace + + from netopsbench.platform.scenario.effects import _ttl_loop_evidence + + episode = EpisodeSpec( + episode_id="a", + fault_type="routing_loop", + target_device="spine1", + target_interface="Ethernet0", + target_prefix="192.168.2.2/32", + parameters={"next_hop": "10.1.1.2"}, + ) + baseline = { + "nodes": { + "spine1": { + "fib": [{"dst": "10.1.1.0/30", "dev": "Ethernet0", "protocol": "kernel", "prefsrc": "10.1.1.1"}], + "packet_counters": {"icmp_out_time_exceeded": 0}, + }, + "leaf1": {"packet_counters": {"icmp_out_time_exceeded": 0}}, + } + } + current = { + "nodes": { + "spine1": { + "fib": [{"dst": host_route, "gateway": "10.1.1.2"}], + "packet_counters": {"icmp_out_time_exceeded": 0}, + }, + "leaf1": { + "fib": [ + {"dst": "default", "gateway": "172.31.140.1"}, + {"dst": "192.168.2.0/30", "gateway": "10.1.1.1"}, + ], + "packet_counters": {"icmp_out_time_exceeded": 12}, + }, + } + } + executor = SimpleNamespace(injector=injector) + proof = _ttl_loop_evidence(executor, episode, baseline, current) + assert proof["forwarding_cycle"] and proof["ttl_expirations"]["leaf1"]["after"] == 12 + current["nodes"]["leaf1"]["fib"][1]["gateway"] = "10.2.1.1" + assert not _ttl_loop_evidence(executor, episode, baseline, current)["forwarding_cycle"] + + +def test_counter_collection_failure_never_becomes_zero(tmp_path): + from netopsbench.platform.observability._routing_probe import packet_counters + + assert "icmp_out_time_exceeded" not in packet_counters(tmp_path / "missing") + path = tmp_path / "snmp" + path.write_text("Icmp: OutTimeExcds InTimeExcds\nIcmp: 7 3\n") + assert packet_counters(path)["icmp_out_time_exceeded"] == 7 + path.write_text("Icmp: OutTimeExcds\nIcmp: missing\n") + assert "error" in packet_counters(path) + + +@pytest.mark.parametrize("change", ["next_hop", "protocol"]) +def test_recovery_rejects_a_surviving_route_error_with_the_same_path_count(change): + from copy import deepcopy + + from netopsbench.platform.observability.routes import verify_route_recovery + + baseline = { + "nodes": { + "leaf1": {"fib": [{"dst": "192.168.2.0/30", "protocol": "bgp", "gateway": "10.1.1.1", "dev": "Ethernet0"}]} + } + } + recovery = deepcopy(baseline) + route = recovery["nodes"]["leaf1"]["fib"][0] + route["gateway" if change == "next_hop" else "protocol"] = "10.2.1.1" if change == "next_hop" else "static" + assert verify_route_recovery(baseline, recovery) == ["leaf1/192.168.2.0/30: forwarding not restored"] + assert verify_route_recovery(baseline, baseline) == [] + + +def test_effects_preflight_constructs_no_agent(monkeypatch, tmp_path): + from scripts import validate_pingmesh_scales as script + + calls = [] + monkeypatch.setattr(script, "runtime_tools", lambda: calls.append("toolchain")) + monkeypatch.setattr(script.subprocess, "check_output", lambda args, **kw: calls.append(args) or "sha256:image") + monkeypatch.setattr(script, "agent_class", lambda _: pytest.fail("effects must not construct agents")) + assert script.preflight_agents([], "deepseek", tmp_path) == {} + assert len(calls) == 3 + + +def test_failed_preparation_never_removes_another_owned_fault(injector, monkeypatch): + injector._tracker.track({"type": "bgp_neighbor_shutdown", "device": "leaf1", "fault_id": "other-owner"}) + + def fail(episode): + raise RuntimeError("precondition failed before mutation") + + monkeypatch.setattr(injector._network, "_prepare", fail) + result = injector._network.inject( + EpisodeSpec(episode_id="a", fault_type="bgp_neighbor_shutdown", target_device="leaf1") + ) + assert not result["success"] + assert [fault.get("fault_id") for fault in injector.active_faults] == ["other-owner"] + + +def test_recovery_removes_an_owned_neighbor_option_with_its_value(injector, monkeypatch): + handler = injector._network + calls = [] + + def run(device, kind, commands): + calls.append(commands) + return " neighbor 10.0.0.1 password opaque\n" if commands == ["show running-config"] else "" + + monkeypatch.setattr(handler, "_run", run) + result = handler.recover( + { + "type": "bgp_auth_mismatch", + "device": "leaf1", + "journal": [ + { + "kind": "frr", + "restore": ["configure terminal", "router bgp 65011", "no neighbor 10.0.0.1 password", "end"], + } + ], + } + ) + assert result["recovered"] + assert "no neighbor 10.0.0.1 password" in calls[-1] diff --git a/tests/test_fault_generation_contract.py b/tests/test_fault_generation_contract.py new file mode 100644 index 0000000..b8d72bc --- /dev/null +++ b/tests/test_fault_generation_contract.py @@ -0,0 +1,65 @@ +"""Reproducible new cases, with legacy explicit parameters left intact.""" + +import inspect +import ipaddress + +from netopsbench.models.scenario import EpisodeSpec +from netopsbench.platform.faults.builtin.impairment_specs import build_impairment_fault_specs +from netopsbench.platform.faults.defaults import IMPAIRMENT_PARAMETERS +from netopsbench.platform.faults.handlers.impairment import ImpairmentHandler +from netopsbench.platform.faults.injector import FaultInjector +from netopsbench.platform.scenario.generator import generate, load_topology +from netopsbench.platform.scenario.parser import parse_scenario_file +from netopsbench.platform.topology.generator import generate_topology + + +def test_fault_entrypoints_share_defaults_and_explicit_values(): + calls = [] + + class Injector: + def __getattr__(self, name): + return lambda *args, **kwargs: calls.append(kwargs) or {} + + for spec in build_impairment_fault_specs(): + defaults = IMPAIRMENT_PARAMETERS[spec.name] + key, default = next(iter(defaults.items())) + spec.inject_episode( + Injector(), + EpisodeSpec(episode_id="a", fault_type=spec.name, target_device="leaf1", target_interface="Ethernet0"), + ) + assert calls[-1] == defaults + spec.inject_episode( + Injector(), + EpisodeSpec( + episode_id="a", + fault_type=spec.name, + target_device="leaf1", + target_interface="Ethernet0", + parameters={key: 7}, + ), + ) + assert calls[-1] == {key: 7} + assert inspect.signature(getattr(ImpairmentHandler, f"inject_{spec.name}")).parameters[key].default == default + if key != "mtu": + assert inspect.signature(getattr(FaultInjector, f"inject_{spec.name}")).parameters[key].default == default + + +def test_new_generated_values_are_reproducible_and_constrained(tmp_path): + topology = tmp_path / "topology" + generate_topology("medium", str(topology), name="generation-contract") + topo = load_topology("medium", str(topology)) + outputs = [] + for label, seed in (("first", 42), ("same", 42), ("other", 43)): + paths = generate({"fault_catalog_version": 2}, topo, tmp_path / label, seed) + cases = [parse_scenario_file(path) for path in paths] + assert all(case.metadata["generator"] == {"seed": seed, "version": 3} for case in cases) + outputs.append({case.id: case.model_dump(mode="json") for case in cases}) + for case in cases: + p = case.episode.parameters + if case.episode.fault_type == "interface_ip_misconfig": + assert ipaddress.ip_interface(p["fault_address"]).ip in ipaddress.ip_network("198.51.100.0/24") + if case.episode.fault_type == "bgp_update_source_mismatch": + assert p["fault_update_source"].startswith("Loopback") + assert 1 <= int(p["fault_update_source"][8:]) < 4096 + assert outputs[0] == outputs[1] + assert outputs[0] != outputs[2] diff --git a/tests/test_fault_handler_transactions.py b/tests/test_fault_handler_transactions.py index 6e36bb2..e16f94f 100644 --- a/tests/test_fault_handler_transactions.py +++ b/tests/test_fault_handler_transactions.py @@ -14,6 +14,12 @@ from netopsbench.platform.topology.generator import generate_topology +@pytest.fixture(autouse=True) +def mocked_runtime_tools(monkeypatch, tmp_path): + # These transaction tests mock every command; toolchain validation has its own tests. + monkeypatch.setattr("netopsbench.platform.faults.handlers.system.runtime_tools", lambda: tmp_path) + + def _metadata() -> dict: with tempfile.TemporaryDirectory() as tmpdir: return generate_topology("xs", tmpdir)["metadata"] @@ -66,57 +72,14 @@ def is_alive(): assert tracker.stop_background("control") is False -def test_acl_readback_failure_is_compensated(monkeypatch): - injector = FaultInjector(topology_metadata=_metadata()) - calls: list[tuple[str, ...]] = [] - rule_present = False - table_present = False - acl_rule_present = False - - def docker_exec(_container, command, **_kwargs): - nonlocal rule_present, table_present, acl_rule_present - calls.append(tuple(command)) - if command[:2] == ["iptables", "-I"]: - rule_present = True - elif command[:2] == ["iptables", "-D"]: - rule_present = False - elif command[:2] == ["iptables", "-C"]: - return _Result(returncode=0 if rule_present else 1) - elif command[:3] == ["sonic-db-cli", "CONFIG_DB", "hset"]: - if "ACL_TABLE|" in command[3]: - table_present = True - else: - # Simulate a partially applied ACL breadcrumb. - acl_rule_present = False - elif command[:3] == ["sonic-db-cli", "CONFIG_DB", "del"]: - if "ACL_TABLE|" in command[3]: - table_present = False - else: - acl_rule_present = False - elif command[:3] == ["sonic-db-cli", "CONFIG_DB", "exists"]: - present = table_present if "ACL_TABLE|" in command[3] else acl_rule_present - return _Result(stdout="1" if present else "0") - return _Result() - - monkeypatch.setattr(injector._acl._cmd, "docker_exec", docker_exec) - - result = injector.inject_acl_misconfig( - "leaf1", - target_prefix="192.168.102.0/30", - interface="Ethernet0", - ) - - assert result["success"] is False - assert any(command[:2] == ("iptables", "-D") for command in calls) - assert injector.active_faults == [] - - def test_netem_compensation_readback_error_tracks_residual(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) qdisc_reads = 0 def docker_exec(_container, command, **_kwargs): nonlocal qdisc_reads + if command[:4] == ["tc", "-j", "qdisc", "show"]: + return _Result(stdout='[ {"kind": "pfifo_fast"} ]') if command[:4] == ["tc", "qdisc", "replace", "dev"]: return _Result() if command[:4] == ["tc", "qdisc", "del", "dev"]: @@ -161,93 +124,6 @@ def test_mtu_failed_readback_and_compensation_tracks_residual(monkeypatch): _assert_single_residual(injector, "mtu_mismatch") -def test_bgp_unreadable_state_is_compensated(monkeypatch): - injector = FaultInjector(topology_metadata=_metadata()) - commands: list[list[str]] = [] - states = iter([None] * 10 + [True]) - monkeypatch.setattr( - injector._bgp._routing, - "pick_bgp_neighbor", - lambda _device, peer_ip=None: { - "peer_ip": peer_ip or "192.168.11.1", - "local_as": 65101, - "remote_as": 65000, - }, - ) - monkeypatch.setattr( - injector._bgp._routing, - "get_device_asn", - lambda _device: 65101, - ) - monkeypatch.setattr( - injector._bgp._routing, - "normalize_bgp_neighbor_kind", - lambda kind: kind, - ) - monkeypatch.setattr( - injector._bgp._sonic, - "vtysh", - lambda _device, command: commands.append(command) or _Result(), - ) - monkeypatch.setattr( - injector._bgp._sonic, - "bgp_neighbor_state", - lambda _device, _peer: next(states), - ) - monkeypatch.setattr( - "netopsbench.platform.faults.handlers.routing_bgp.time.sleep", - lambda _seconds: None, - ) - - result = injector.inject_bgp_neighbor_misconfig( - "leaf1", - peer_ip="192.168.11.1", - misconfig_kind="peer_as_mismatch", - ) - - assert result["success"] is False - assert any("neighbor 192.168.11.1 remote-as 65000" in command for command in commands) - assert injector.active_faults == [] - - -def test_bgp_failed_compensation_tracks_residual(monkeypatch): - injector = FaultInjector(topology_metadata=_metadata()) - monkeypatch.setattr( - injector._bgp._routing, - "pick_bgp_neighbor", - lambda _device, peer_ip=None: { - "peer_ip": peer_ip or "192.168.11.1", - "local_as": 65101, - "remote_as": 65000, - }, - ) - monkeypatch.setattr(injector._bgp._routing, "get_device_asn", lambda _device: 65101) - monkeypatch.setattr( - injector._bgp._routing, - "normalize_bgp_neighbor_kind", - lambda kind: kind, - ) - monkeypatch.setattr(injector._bgp._sonic, "vtysh", lambda _device, _command: _Result()) - monkeypatch.setattr( - injector._bgp._sonic, - "bgp_neighbor_state", - lambda _device, _peer: None, - ) - monkeypatch.setattr( - "netopsbench.platform.faults.handlers.routing_bgp.time.sleep", - lambda _seconds: None, - ) - - result = injector.inject_bgp_neighbor_misconfig( - "leaf1", - peer_ip="192.168.11.1", - misconfig_kind="peer_as_mismatch", - ) - - assert result["success"] is False - _assert_single_residual(injector, "bgp_neighbor_misconfig") - - def test_blackhole_requires_operational_rib_and_compensates(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) prefix = "192.168.102.2/32" @@ -278,7 +154,7 @@ def vtysh(_device, command): def test_static_route_failed_compensation_tracks_residual(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) target = "192.168.102.2/32" - nexthop = "192.168.101.2" + nexthop = "192.168.1.2" def vtysh(_device, command): if command == ["show running-config"]: @@ -289,6 +165,9 @@ def vtysh(_device, command): monkeypatch.setattr(injector._static_route._sonic, "vtysh", vtysh) + monkeypatch.setattr(injector._static_route, "_running_config_has_route", lambda *_: False) + monkeypatch.setattr(injector._static_route._sonic._cmd, "docker_exec", lambda *_: _Result(stdout="0\n")) + result = injector.inject_static_route_misconfig( "leaf1", target_ip=target, @@ -299,72 +178,9 @@ def vtysh(_device, command): _assert_single_residual(injector, "static_route_misconfig") -def test_route_policy_checks_withdrawal_and_recovery(monkeypatch): - injector = FaultInjector(topology_metadata=_metadata()) - prefix = "192.168.101.0/30" - statement = f"network {prefix}" - configured = True - bgp_reads = 0 - - monkeypatch.setattr( - injector._route_policy._routing, - "normalize_route_policy_kind", - lambda kind: kind, - ) - monkeypatch.setattr( - injector._route_policy._routing, - "pick_advertised_network", - lambda _device, prefix=None: { - "prefix": prefix or "192.168.101.0/30", - "local_as": 65101, - "route_map": None, - }, - ) - monkeypatch.setattr( - injector._route_policy._routing, - "get_device_asn", - lambda _device: 65101, - ) - monkeypatch.setattr( - injector._route_policy._routing, - "format_network_statement", - lambda _prefix, _route_map: statement, - ) - - def vtysh(_device, command): - nonlocal configured, bgp_reads - if command[0] == "configure terminal": - configured = not any(item == f"no {statement}" for item in command) - return _Result() - if command == ["show running-config"]: - return _Result(stdout=f" {statement}\n" if configured else "") - if command == [f"show ip bgp {prefix}"]: - bgp_reads += 1 - if not configured: - return _Result(returncode=1, stderr="BGP RIB unavailable") - return _Result(stdout=f"BGP routing table entry for {prefix}\n") - raise AssertionError(f"unexpected command: {command}") - - monkeypatch.setattr(injector._route_policy._sonic, "vtysh", vtysh) - monkeypatch.setattr( - "netopsbench.platform.faults.handlers.routing_policy.time.sleep", - lambda _seconds: None, - ) - - result = injector.inject_route_policy_misconfig( - "leaf1", - target_prefix=prefix, - misconfig_kind="network_statement_missing", - ) - - assert result["success"] is False - assert configured is True - assert bgp_reads == 11 - assert injector.active_faults == [] - - def test_device_down_unreadable_state_is_terminal_residual(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) + monkeypatch.setattr(injector._system._cmd, "container_is_running", lambda _container: True) monkeypatch.setattr(injector._system._cmd, "run_cmd", lambda *_args, **_kwargs: _Result()) monkeypatch.setattr( injector._system._cmd, @@ -396,6 +212,7 @@ def run_cmd(command, **_kwargs): def test_device_down_running_with_restored_links_is_clean_injection_failure(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) + monkeypatch.setattr(injector._system._cmd, "container_is_running", lambda _container: True) monkeypatch.setattr(injector._system._cmd, "run_cmd", lambda *_args, **_kwargs: _Result()) monkeypatch.setattr(injector._system, "_settled_stop_state", lambda _container: (True, False)) @@ -407,6 +224,7 @@ def test_device_down_running_with_restored_links_is_clean_injection_failure(monk def test_device_down_stopped_without_parking_tracks_terminal_residual(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) + monkeypatch.setattr(injector._system._cmd, "container_is_running", lambda _container: True) monkeypatch.setattr(injector._system._cmd, "run_cmd", lambda *_args, **_kwargs: _Result(returncode=1)) monkeypatch.setattr(injector._system, "_settled_stop_state", lambda _container: (False, False)) @@ -419,6 +237,7 @@ def test_device_down_stopped_without_parking_tracks_terminal_residual(monkeypatc def test_device_down_command_error_is_success_when_stopped_and_parked(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) + monkeypatch.setattr(injector._system._cmd, "container_is_running", lambda _container: True) monkeypatch.setattr( injector._system._cmd, "run_cmd", diff --git a/tests/test_fault_registry.py b/tests/test_fault_registry.py index 9a3c7cd..78d621c 100644 --- a/tests/test_fault_registry.py +++ b/tests/test_fault_registry.py @@ -87,10 +87,3 @@ def test_fault_spec_validate_episode_supports_prefix_and_required_parameters(): def test_fault_registry_shim_module_is_removed(): with pytest.raises(ModuleNotFoundError): importlib.import_module("netopsbench.platform.faults_registry") - - -def test_fault_execution_helpers_are_available_under_faults_subsystem(): - from netopsbench.platform.faults.scenario_execution import inject_fault, recover_fault - - assert callable(inject_fault) - assert callable(recover_fault) diff --git a/tests/test_fault_tools_v2.py b/tests/test_fault_tools_v2.py new file mode 100644 index 0000000..b7e4ff5 --- /dev/null +++ b/tests/test_fault_tools_v2.py @@ -0,0 +1,268 @@ +"""Optional tool views preserve the registry, output scope and transport limits.""" + +import json +import subprocess +import time + +import pytest + +from netopsbench.platform.toolkit._core.control import tool_deadline_scope +from netopsbench.platform.toolkit._core.device.validators import docker_exec +from netopsbench.platform.toolkit.mcp.registry import load_tool_specs, tool_schemas, validate_tool_call +from netopsbench.platform.toolkit.toolkit import AgentToolkit +from netopsbench.platform.topology.clos_builder import build_clos_plan +from netopsbench.platform.topology.config import config_for_scale + + +@pytest.fixture +def toolkit(): + return AgentToolkit(topology_metadata=build_clos_plan(config_for_scale("medium")).manifest.model_dump(mode="json")) + + +def test_only_one_new_tool_and_optional_contracts(): + names = {tool.name for tool in load_tool_specs()} + assert len(names) == 16 + assert "get_device_status" in names + assert "get_pingmesh_flows" not in names + assert validate_tool_call("traceroute", {"src": "client1", "dst_ip": "192.168.2.2", "max_hops": 32}) + assert validate_tool_call("get_route_table", {"device": "leaf1", "view": "kernel"}) + assert validate_tool_call("get_bgp_neighbor", {"device": "leaf1", "peer": "10.0.0.1", "view": "advertised_routes"}) + + +def test_acl_collection_failure_is_not_an_empty_healthy_ruleset(toolkit, monkeypatch): + calls = [] + + def failed(container, args, timeout): + calls.append(args) + return subprocess.CompletedProcess(args, 1, stdout="", stderr="permission denied") + + monkeypatch.setattr(toolkit, "_docker_exec", failed) + result = toolkit.get_device_acl("leaf1") + assert not result.success + assert len(calls) == 3 + assert len(result.data["collection_errors"]) == 3 + assert result.data["collected_at"] + + +def test_interface_schema_does_not_expose_injection_state(): + schema = next(tool for tool in tool_schemas() if tool["name"] == "get_device_interfaces") + assert "include_tc" not in schema["input_schema"]["properties"] + assert validate_tool_call("get_device_interfaces", {"device": "leaf1"}) + assert not validate_tool_call( + "get_device_interfaces", {"device": "leaf1", "interface": "Ethernet0", "include_tc": True} + ) + + +@pytest.mark.parametrize("interface", [None, "Ethernet0"]) +def test_legacy_tc_request_fails_before_device_access(toolkit, monkeypatch, interface): + def unexpected(*args, **kwargs): + pytest.fail("A rejected injection-state query must not access the device") + + monkeypatch.setattr(toolkit, "_docker_exec", unexpected) + with pytest.raises(TypeError, match="include_tc"): + toolkit.get_device_interfaces("leaf1", interface=interface, include_tc=True) + + +@pytest.mark.parametrize("format", ["summary", "structured", "raw", "both"]) +def test_interface_views_preserve_observations_without_tc(toolkit, monkeypatch, format): + def run(container, args, timeout): + if args == ["ip", "-j", "-4", "addr", "show"]: + return subprocess.CompletedProcess( + args, + 0, + stdout=json.dumps([{"ifname": "eth1", "addr_info": [{"local": "192.168.1.2", "prefixlen": 30}]}]), + ) + assert args == ["ip", "-s", "link", "show"] + return subprocess.CompletedProcess( + args, + 0, + stdout="2: eth1: mtu 1500 qdisc netem state UP\n" + " RX: bytes packets errors dropped\n 1000 10 2 1\n", + ) + + monkeypatch.setattr(toolkit, "_docker_exec", run) + result = toolkit.get_device_interfaces("client1", format=format) + assert result.success + assert result.data["addresses"] == {"eth1": ["192.168.1.2/30"]} + assert "qdisc" not in json.dumps(result.data) + assert "netem" not in json.dumps(result.data) + assert result.data["collected_at"] + if format in {"summary", "structured"}: + assert result.data["interfaces"][0]["rx_errors"] == 2 + + +def test_kernel_fib_has_actual_multipath_and_prefix_filter(toolkit, monkeypatch): + calls = [] + + def run(container, args, timeout): + calls.append(args) + return subprocess.CompletedProcess( + args, + 0, + stdout=json.dumps( + [{"dst": "192.168.2.0/30", "nexthops": [{"gateway": "10.0.0.1"}, {"gateway": "10.0.0.2"}]}] + ), + ) + + monkeypatch.setattr(toolkit, "_docker_exec", run) + result = toolkit.get_route_table("leaf1", prefix="192.168.2.0/30", view="kernel") + assert result.success + assert len(result.data["routes"][0]["nexthops"]) == 2 + assert calls == [["ip", "-j", "-4", "route", "show", "exact", "192.168.2.0/30"]] + + +def test_advertised_routes_filtered_locally_with_one_command(toolkit, monkeypatch): + calls = [] + + def run(container, args, timeout): + calls.append(args) + return subprocess.CompletedProcess( + args, 0, stdout=json.dumps({"advertisedRoutes": {"192.168.1.0/30": {}, "192.168.2.0/30": {}}}) + ) + + monkeypatch.setattr(toolkit, "_docker_exec", run) + result = toolkit.get_bgp_neighbor("leaf1", "10.0.0.1", view="advertised_routes", prefix="192.168.2.0/30") + assert result.success + assert set(result.data["advertised_routes"]) == {"192.168.2.0/30"} + assert len(calls) == 1 + + +def test_pingmesh_client_filter_preserves_aggregation_and_window(toolkit, monkeypatch): + calls = [] + monkeypatch.setattr(toolkit, "_query_influx_rows", lambda query, **kw: calls.append(query) or []) + toolkit.set_pingmesh_time_window("2026-10-12T00:00:00Z", "2026-10-12T00:01:00Z") + result = toolkit.get_pingmesh_summary(src_client="client1", dst_client="client2") + assert result.success + assert 'r.src_name == "client1"' in calls[0] + assert 'r.dst_name == "client2"' in calls[0] + assert 'group(columns: ["path_type", "_field"])' in calls[0] + assert "2026-10-12T00:00:00Z" in calls[0] + assert not toolkit.get_pingmesh_summary(src_client="leaf1").success + + +def test_prefix_count_mode_ignores_session_state_filter(toolkit, monkeypatch): + queries = [] + monkeypatch.setattr(toolkit, "_query_influx_rows", lambda query, **kw: queries.append(query) or []) + result = toolkit.query_bgp_events(event_type="prefix_count", state="not_a_session_state") + assert result.success + assert "bgp_prefix_events" in queries[0] + assert "session_state ==" not in queries[0] + assert not toolkit.query_bgp_events(state="not_a_session_state").success + + +def test_traceroute_hop_limit(toolkit, monkeypatch): + calls = [] + + def run(container, args, timeout): + calls.append((args, timeout)) + return subprocess.CompletedProcess(args, 0, stdout="trace") + + monkeypatch.setattr(toolkit, "_docker_exec", run) + assert toolkit.traceroute("client1", "192.168.2.2").success + assert calls[0][0][-2] == "8" and calls[0][1] == 12 + assert toolkit.traceroute("client1", "192.168.2.2", max_hops=32).success + assert not toolkit.traceroute("client1", "192.168.2.2", max_hops=33).success + + +def test_transport_receives_total_session_deadline(monkeypatch): + calls = [] + monkeypatch.setattr( + "netopsbench.platform.toolkit._core.device.validators.safe_run", lambda *a, **kw: calls.append(kw) + ) + deadline = time.monotonic() + 0.2 + with tool_deadline_scope(deadline): + docker_exec("container", ["traceroute"], timeout=36) + assert calls[0]["control"].deadline == deadline + with pytest.raises(TimeoutError): + with tool_deadline_scope(time.monotonic() - 1): + docker_exec("container", ["true"], timeout=30) + + +@pytest.mark.parametrize("view", ["advertised_routes", "advertised-routes", "advertised"]) +def test_bgp_advertised_aliases_use_canonical_output(toolkit, monkeypatch, view): + from netopsbench.platform.toolkit.mcp import inventory + + calls = [] + monkeypatch.setattr(inventory, "get_toolkit", lambda: toolkit) + + def run(container, args, timeout): + calls.append(args) + return subprocess.CompletedProcess( + args, 0, stdout=json.dumps({"advertisedRoutes": {"192.168.2.0/30": {}, "192.168.3.0/30": {}}}) + ) + + monkeypatch.setattr(toolkit, "_docker_exec", run) + result = inventory.get_bgp_neighbor("leaf1", "10.0.0.1", view=view, prefix="192.168.2.0/30") + assert result["view"] == "advertised_routes" + assert result["advertised_routes"] == {"192.168.2.0/30": {}} + assert calls == [["vtysh", "-c", "show bgp ipv4 unicast neighbors 10.0.0.1 advertised-routes json"]] + + +def test_bgp_json_format_is_structured(toolkit, monkeypatch): + monkeypatch.setattr(toolkit, "_docker_exec", lambda *args, **kwargs: subprocess.CompletedProcess([], 0, stdout="")) + assert ( + toolkit.get_bgp_neighbors("leaf1", "json").to_dict() + == toolkit.get_bgp_neighbors("leaf1", "structured").to_dict() + ) + + +@pytest.mark.parametrize("view", ["received-routes", "received_routes", "/private/fault.yml"]) +def test_bgp_invalid_view_has_safe_guidance_without_device_access(toolkit, monkeypatch, view): + from netopsbench.platform.toolkit.mcp import inventory + from netopsbench.platform.toolkit.public import public_tool_result + + monkeypatch.setattr(inventory, "get_toolkit", lambda: toolkit) + monkeypatch.setattr(toolkit, "_resolve_container", lambda *args: pytest.fail("Invalid view accessed device")) + result = public_tool_result(toolkit.get_bgp_neighbor("leaf1", "10.0.0.1", view=view)) + assert not result["success"] + assert "use detail or advertised_routes" in result["error"] + assert "Received routes are not supported" in result["error"] + assert "/private" not in result["error"] + assert inventory.get_bgp_neighbor("leaf1", "10.0.0.1", view=view) == {"error": result["error"]} + assert not validate_tool_call("get_bgp_neighbor", {"device": "leaf1", "peer": "10.0.0.1", "view": view}) + + +def test_bgp_invalid_format_and_collection_error_are_distinct(toolkit, monkeypatch): + from netopsbench.platform.toolkit.mcp import inventory + + monkeypatch.setattr(inventory, "get_toolkit", lambda: toolkit) + monkeypatch.setattr( + toolkit, + "_docker_exec", + lambda *args, **kwargs: subprocess.CompletedProcess([], 1, stdout="", stderr="/private/fault.yml corrupt 20%"), + ) + assert "use structured, raw or both" in inventory.get_bgp_neighbors("leaf1", format="invalid")["error"] + assert inventory.get_bgp_neighbors("leaf1") == {"error": "Observation unavailable"} + assert inventory.get_bgp_neighbor("leaf1", "10.0.0.1", view="advertised") == {"error": "Observation unavailable"} + + +def test_bgp_schema_lists_supported_values(): + schemas = {s["name"]: s for s in tool_schemas()} + assert schemas["get_bgp_neighbor"]["input_schema"]["properties"]["view"]["enum"] == [ + "detail", + "advertised_routes", + "advertised-routes", + "advertised", + ] + assert schemas["get_bgp_neighbors"]["input_schema"]["properties"]["format"]["enum"] == [ + "structured", + "raw", + "both", + "json", + ] + + +@pytest.mark.parametrize("with_gateway", [False, True]) +def test_bgp_fastmcp_schema_matches_registry(with_gateway): + import asyncio + + from netopsbench.platform.toolkit.fastmcp_server import create_server + + server = create_server(gateway=object() if with_gateway else None) + registered = {tool.name: tool for tool in asyncio.run(server.list_tools())} + schemas = {schema["name"]: schema for schema in tool_schemas()} + for name, argument in [("get_bgp_neighbor", "view"), ("get_bgp_neighbors", "format")]: + assert ( + registered[name].parameters["properties"][argument]["enum"] + == schemas[name]["input_schema"]["properties"][argument]["enum"] + ) diff --git a/tests/test_fault_type_judge.py b/tests/test_fault_type_judge.py index bff5fba..f78cb38 100644 --- a/tests/test_fault_type_judge.py +++ b/tests/test_fault_type_judge.py @@ -23,7 +23,7 @@ def judge(self, request): def test_canonicalize_fault_type_preserves_legacy_aliases(): assert canonicalize_fault_type("link failure") == "link_down" assert canonicalize_fault_type("static_route_misconfiguration") == "static_route_misconfig" - assert canonicalize_fault_type("acl_misconfiguration") == "acl_misconfig" + assert canonicalize_fault_type("acl_misconfiguration") == "acl_misconfiguration" def test_exact_canonical_match_uses_fast_path_without_calling_judge(): @@ -52,7 +52,7 @@ def test_exact_canonical_match_uses_fast_path_without_calling_judge(): def test_structured_fault_type_judge_accepts_mapping_results(): def judge_fn(request): return { - "canonical_agent_fault_type": "bgp_neighbor_misconfig", + "canonical_agent_fault_type": "bgp_as_mismatch", "canonical_ground_truth_fault_type": request.canonical_ground_truth_fault_type, "is_match": True, "confidence": 0.92, @@ -62,22 +62,22 @@ def judge_fn(request): judge = StructuredFaultTypeJudge(judge_fn, model="judge-model") request = build_fault_type_judge_request( agent_fault_type="BGP peer AS mismatch", - ground_truth_fault_type="bgp_neighbor_misconfig", + ground_truth_fault_type="bgp_as_mismatch", agent_reasoning="BGP peer has wrong remote AS.", ) result = judge.judge(request) assert result.is_match is True - assert result.canonical_agent_fault_type == "bgp_neighbor_misconfig" + assert result.canonical_agent_fault_type == "bgp_as_mismatch" assert result.judge_model == "judge-model" def test_evaluator_uses_judge_for_semantic_fault_type_match(): judge = RecordingJudge( FaultTypeJudgeResult( - canonical_agent_fault_type="bgp_neighbor_misconfig", - canonical_ground_truth_fault_type="bgp_neighbor_misconfig", + canonical_agent_fault_type="bgp_as_mismatch", + canonical_ground_truth_fault_type="bgp_as_mismatch", is_match=True, confidence=0.93, reasoning="The agent described a BGP peer AS/session configuration issue.", @@ -94,7 +94,7 @@ def test_evaluator_uses_judge_for_semantic_fault_type_match(): reasoning="The BGP peer has the wrong remote AS.", evidence=["BGP session is Idle"], ), - {"fault_type": "bgp_neighbor_misconfig", "location": {"device": "leaf1", "interface": "Ethernet1"}}, + {"fault_type": "bgp_as_mismatch", "location": {"device": "leaf1", "interface": "Ethernet1"}}, "case-1", ) @@ -182,8 +182,8 @@ def test_create_judge_from_env_returns_judge_when_enabled(): def test_public_evaluator_adapter_uses_canonical_scenario_and_report_fields(): judge = RecordingJudge( FaultTypeJudgeResult( - canonical_agent_fault_type="bgp_neighbor_misconfig", - canonical_ground_truth_fault_type="bgp_neighbor_misconfig", + canonical_agent_fault_type="bgp_as_mismatch", + canonical_ground_truth_fault_type="bgp_as_mismatch", is_match=True, confidence=0.9, reasoning="Equivalent BGP peer configuration failure.", @@ -196,7 +196,7 @@ def test_public_evaluator_adapter_uses_canonical_scenario_and_report_fields(): name="BGP case", episode={ "episode_id": "diagnosis", - "fault_type": "bgp_neighbor_misconfig", + "fault_type": "bgp_as_mismatch", "target_device": "leaf1", }, ) diff --git a/tests/test_frr_config.py b/tests/test_frr_config.py new file mode 100644 index 0000000..fcfe5df --- /dev/null +++ b/tests/test_frr_config.py @@ -0,0 +1,56 @@ +"""One BGP config parser serves generated artifacts and live fault snapshots.""" + +from types import SimpleNamespace + +from netopsbench.platform.faults.services.routing_runtime import RoutingRuntime +from netopsbench.platform.utils.frr import parse_bgp_config + +CONFIG = """Building configuration... +Current configuration: +! +router bgp 65001 + neighbor 10.0.0.2 route-map IMPORT in + neighbor 10.0.0.2 remote-as 65002 + neighbor 10.0.0.2 password a-secret + neighbor 10.0.0.2 update-source Ethernet0 + neighbor 10.0.0.2 route-map EXPORT out + address-family ipv4 unicast + neighbor 10.0.0.2 route-map IMPORT in + network 192.168.1.0/30 route-map ORIGIN + network 192.168.1.0/30 route-map ORIGIN + network 192.168.2.0/30 + exit-address-family +! +""" + + +def test_parser_preserves_neighbor_options_and_deduplicates_policies_and_networks(): + parsed = parse_bgp_config(CONFIG) + assert parsed == { + "local_as": 65001, + "neighbors": [ + { + "peer_ip": "10.0.0.2", + "remote_as": 65002, + "password": "a-secret", + "update_source": "Ethernet0", + "route_maps": [{"name": "IMPORT", "direction": "in"}, {"name": "EXPORT", "direction": "out"}], + } + ], + "networks": [ + {"prefix": "192.168.1.0/30", "route_map": "ORIGIN"}, + {"prefix": "192.168.2.0/30", "route_map": None}, + ], + } + + +def test_live_snapshots_share_parser_and_require_the_requested_target(): + response = SimpleNamespace(returncode=0, stdout=CONFIG) + runtime = RoutingRuntime(SimpleNamespace(vtysh=lambda *args: response), SimpleNamespace()) + assert runtime.get_bgp_config_snapshot("leaf1") == parse_bgp_config(CONFIG) + assert runtime.pick_bgp_neighbor("leaf1", "10.0.0.2")["remote_as"] == 65002 + assert runtime.pick_bgp_neighbor("leaf1", "10.0.0.99") is None + assert runtime.pick_advertised_network("leaf1", "192.168.1.0/30")["route_map"] == "ORIGIN" + assert runtime.pick_advertised_network("leaf1", "192.168.99.0/30") is None + response.returncode = 1 + assert runtime.get_bgp_config_snapshot("leaf1") == {"local_as": None, "neighbors": [], "networks": []} diff --git a/tests/test_negative_sample_scenarios.py b/tests/test_negative_sample_scenarios.py index 2392afe..4eeb958 100644 --- a/tests/test_negative_sample_scenarios.py +++ b/tests/test_negative_sample_scenarios.py @@ -3,6 +3,9 @@ from __future__ import annotations import tempfile +from datetime import UTC, datetime, timedelta + +import pytest from netopsbench.evaluator.scorer import AgentOutput, Evaluator from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec @@ -11,6 +14,24 @@ from netopsbench.platform.topology.generator import generate_topology +@pytest.fixture(autouse=True) +def observation_clock(monkeypatch): + # These are diagnosis/scoring contracts; actual waiting is tested separately. + def capture(_runner, duration, **kwargs): + return {**_healthy_observation(duration), "name": kwargs.get("name", "window")} + + monkeypatch.setattr("netopsbench.platform.scenario.observation.capture_observation_window", capture) + # Episode capture uses the executor's imported reference, unlike baseline capture. + monkeypatch.setattr("netopsbench.platform.scenario.executor._capture_observation_window_impl", capture) + monkeypatch.setattr( + ScenarioExecutor, "sleep", lambda *args: pytest.fail("Diagnosis/scoring tests must not wait for real windows") + ) + from netopsbench.platform.scenario.baseline import RuntimeScope + + monkeypatch.setattr(ScenarioExecutor, "_baseline_scope", lambda *a: RuntimeScope({}, {}, {})) + monkeypatch.setattr("netopsbench.platform.observability.routes.collect_routes", lambda *a, **k: {"nodes": {}}) + + def _metadata() -> dict: with tempfile.TemporaryDirectory() as tmpdir: return generate_topology("xs", tmpdir)["metadata"] @@ -18,6 +39,7 @@ def _metadata() -> dict: def _healthy_scenario() -> ScenarioSpec: return ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id="healthy_001", name="healthy", topology_scale="xs", @@ -33,8 +55,8 @@ def _healthy_scenario() -> ScenarioSpec: def _healthy_observation(duration: int) -> dict: return { - "start_time": "2026-01-01T00:00:00Z", - "end_time": "2026-01-01T00:01:00Z", + "start_time": (datetime.now(UTC) - timedelta(seconds=duration)).isoformat(), + "end_time": datetime.now(UTC).isoformat(), "duration_seconds": duration, "pingmesh_metrics": { "summary": { @@ -47,6 +69,11 @@ def _healthy_observation(duration: int) -> dict: "quality": {"current_paths_observed": 2, "local_df_mtu_drops": 0}, "anomalies": [], }, + "_baseline_health": { + "absolute_unreachable_paths": 0, + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, "anomalies_detected": False, "coverage_status": "complete", "data_source_status": "ok", @@ -64,8 +91,8 @@ def test_healthy_scenario_observes_and_diagnoses(monkeypatch): monkeypatch.setattr(runner, "_recover_fault", lambda: []) monkeypatch.setattr( runner, - "_wait_and_observe", - lambda duration, **_kwargs: _healthy_observation(duration), + "_merge_observation_windows", + lambda windows, total_duration_seconds, **_kwargs: _healthy_observation(total_duration_seconds), ) calls = [] @@ -90,8 +117,8 @@ def test_agent_exception_is_zero_outcome_not_infrastructure_failure(monkeypatch) monkeypatch.setattr(runner, "_recover_fault", lambda: []) monkeypatch.setattr( runner, - "_wait_and_observe", - lambda duration, **_kwargs: _healthy_observation(duration), + "_merge_observation_windows", + lambda windows, total_duration_seconds, **_kwargs: _healthy_observation(total_duration_seconds), ) def fail(_payload, **_kwargs): @@ -99,7 +126,8 @@ def fail(_payload, **_kwargs): result = runner.run_scenario(_healthy_scenario(), diagnosis_callback=fail) - assert result["success"] is True + assert result["success"] is False + assert result["case_valid"] is True assert result["episode"]["diagnosis"]["error"] == "agent crashed" assert result["episode"]["execution"]["reward"] == 0.0 assert result["episode"]["execution"]["failure"]["domain"] == "agent" @@ -115,8 +143,8 @@ def test_invalid_diagnosis_schema_is_protocol_outcome_zero(monkeypatch): monkeypatch.setattr(runner, "_recover_fault", lambda: []) monkeypatch.setattr( runner, - "_wait_and_observe", - lambda duration, **_kwargs: _healthy_observation(duration), + "_merge_observation_windows", + lambda windows, total_duration_seconds, **_kwargs: _healthy_observation(total_duration_seconds), ) result = runner.run_scenario( @@ -128,7 +156,7 @@ def test_invalid_diagnosis_schema_is_protocol_outcome_zero(monkeypatch): ) execution = result["episode"]["execution"] - assert result["success"] is True + assert result["success"] is False assert execution["reward"] == 0.0 assert execution["failure"]["domain"] == "protocol" assert execution["termination_reason"] == "protocol_error" diff --git a/tests/test_observability_influxdb.py b/tests/test_observability_influxdb.py index 1d4a253..da0dc62 100644 --- a/tests/test_observability_influxdb.py +++ b/tests/test_observability_influxdb.py @@ -183,3 +183,113 @@ def fake_request(url, token, method="GET", payload=None): assert influxdb.delete_bucket("http://influxdb:8086", "token", "managed") is False assert all(method != "DELETE" for _, method in calls) + + +def test_core_reuses_existing_shared_services_without_recreating_them(monkeypatch): + calls = [] + monkeypatch.setattr(lifecycle, "safe_run", lambda command, **kwargs: calls.append(command)) + monkeypatch.setattr(lifecycle, "wait_for_influxdb_ready", lambda *_args: None) + lifecycle.ensure_observability_core() + assert "--no-recreate" in calls[0] + + +def test_flux_query_concurrency_is_bounded_and_failure_releases_slot(monkeypatch): + import threading + from concurrent.futures import ThreadPoolExecutor + from types import SimpleNamespace + + import requests + + entered = threading.Event() + release = threading.Event() + lock = threading.Lock() + active = peak = calls = 0 + + def post(*args, **kwargs): + nonlocal active, peak, calls + with lock: + active += 1 + calls += 1 + peak = max(peak, active) + if active == 4: + entered.set() + try: + assert release.wait(5) + if kwargs["data"] == "failure": + raise requests.Timeout("test timeout") + return SimpleNamespace(text="fresh data", raise_for_status=lambda: None) + finally: + with lock: + active -= 1 + + monkeypatch.setattr(influxdb.requests, "post", post) + with ThreadPoolExecutor(max_workers=12) as pool: + futures = [ + pool.submit(influxdb.query_flux, "http://test", "token", "org", "failure" if i == 0 else "ok") + for i in range(12) + ] + try: + assert entered.wait(5) + with lock: + assert calls == 4 + finally: + release.set() + results = [f.result(timeout=5) for f in futures] + assert peak == 4 + assert results[0].status == "error" + assert all(r.status == "ok" and r.text == "fresh data" for r in results[1:]) + assert influxdb.query_flux("http://test", "token", "org", "ok").status == "ok" + + +def test_flux_slot_wait_obeys_shared_deadline(monkeypatch): + import threading + import time + + slots = threading.BoundedSemaphore(1) + slots.acquire() + monkeypatch.setattr(influxdb, "_QUERY_SLOTS", slots) + monkeypatch.setattr(influxdb.requests, "post", lambda *a, **kw: pytest.fail("expired query started")) + before = time.monotonic() + result = influxdb.query_flux("http://unused", "token", "org", "query", timeout=30, deadline=before + 0.02) + assert result.status == "error" and "deadline exceeded" in result.error + assert time.monotonic() - before < 0.5 + slots.release() + + +def test_flux_shared_deadline_interrupts_a_slow_streaming_response(): + import threading + import time + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + from netopsbench.platform.observability import influxdb + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + self.send_response(200) + self.send_header("Content-Length", "100") + self.end_headers() + try: + for _ in range(100): + self.wfile.write(b"x") + self.wfile.flush() + time.sleep(0.02) + except (BrokenPipeError, ConnectionResetError): + pass + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=lambda: server.serve_forever(poll_interval=0.01)) + thread.start() + try: + started = time.monotonic() + result = influxdb.query_flux( + f"http://127.0.0.1:{server.server_port}", "token", "org", "query", deadline=started + 0.08 + ) + assert result.status == "error" and "deadline exceeded" in result.error + assert time.monotonic() - started < 0.5 + finally: + server.shutdown() + server.server_close() + thread.join() diff --git a/tests/test_observability_validation.py b/tests/test_observability_validation.py index 4aeb56c..27faca1 100644 --- a/tests/test_observability_validation.py +++ b/tests/test_observability_validation.py @@ -78,3 +78,18 @@ def query_runner(query: str) -> str: assert '_field == "schema_version"' in bgp_query assert 'r.topology_id == "lab-a"' in syslog_query assert "|> limit(n: 1)" in syslog_query + + +def test_individual_observability_check_only_queries_requested_source(): + queries = [] + + def query_runner(query): + queries.append(query) + return ",result,table,_time,_value\n,,0,2026-07-01T18:49:04Z,1\n" + + assert ( + check_observability(query_runner, bucket="test", obs_device="leaf1", syslog_marker="marker", checks={"syslog"}) + == [] + ) + assert len(queries) == 1 + assert '_measurement == "syslog"' in queries[0] diff --git a/tests/test_observation_clock.py b/tests/test_observation_clock.py new file mode 100644 index 0000000..9cfed25 --- /dev/null +++ b/tests/test_observation_clock.py @@ -0,0 +1,56 @@ +from datetime import datetime, timedelta +from types import SimpleNamespace + +import pytest + +from netopsbench.platform.scenario import observation +from netopsbench.platform.utils.control import OperationControl, operation_scope + + +def test_scheduling_overhead_does_not_accumulate_per_second(monkeypatch): + clock = [100.0] + waits = [] + + def sleep(seconds): + waits.append(seconds) + clock[0] += seconds + 0.2 + + monkeypatch.setattr(observation.time, "monotonic", lambda: clock[0]) + runner = SimpleNamespace(sleep=sleep, topology_metadata={"pingmesh_plan": {"settings": {"plan_id": "plan"}}}) + window = observation.capture_observation_window(runner, 42) + start = datetime.fromisoformat(window["start_time"].replace("Z", "+00:00")) + end = datetime.fromisoformat(window["end_time"].replace("Z", "+00:00")) + assert end - start == timedelta(seconds=42) + assert 42 <= window["actual_wait_seconds"] < 42.21 + assert len(waits) < 42 + + +def test_outer_deadline_prevents_starting_an_incomplete_window(monkeypatch): + clock = [100.0] + monkeypatch.setattr(observation.time, "monotonic", lambda: clock[0]) + runner = SimpleNamespace(sleep=lambda _: pytest.fail("insufficient budget started waiting")) + with operation_scope(OperationControl(deadline=110)): + with pytest.raises(TimeoutError, match="Insufficient"): + observation.capture_observation_window(runner, 30) + + +def test_precise_utc_boundary_is_anchored_once(monkeypatch): + from datetime import UTC + + first = datetime(2026, 10, 24, 0, 0, 0, 123456, tzinfo=UTC) + + class WallClock: + @staticmethod + def now(_zone): + return first # The end boundary must be derived, not read again. + + clock = [0.0] + monkeypatch.setattr(observation, "datetime", WallClock) + monkeypatch.setattr(observation.time, "monotonic", lambda: clock[0]) + runner = SimpleNamespace( + sleep=lambda seconds: clock.__setitem__(0, clock[0] + seconds), + topology_metadata={"pingmesh_plan": {"settings": {"plan_id": "plan"}}}, + ) + result = observation.capture_observation_window(runner, 30) + assert result["start_time"] == "2026-10-24T00:00:00.123456Z" + assert result["end_time"] == "2026-10-24T00:00:30.123456Z" diff --git a/tests/test_operation_control.py b/tests/test_operation_control.py new file mode 100644 index 0000000..ddc7862 --- /dev/null +++ b/tests/test_operation_control.py @@ -0,0 +1,77 @@ +"""Cancellation owns only the launched process group; time budgets are shared.""" + +import subprocess +import sys +import threading +import time +from pathlib import Path + +import pytest + +from netopsbench.platform.utils.control import OperationCancelled, OperationControl +from netopsbench.platform.utils.proc import safe_run + + +def test_cancel_before_launch_does_not_run_command(tmp_path): + cancel = threading.Event() + cancel.set() + marker = tmp_path / "created" + with pytest.raises(OperationCancelled): + safe_run([sys.executable, "-c", f"open({str(marker)!r},'w').close()"], control=OperationControl(cancel)) + assert not marker.exists() + + +def test_cancel_reaps_descendant_process_group(tmp_path): + pidfile = tmp_path / "child.pid" + script = ( + "import subprocess,sys,time; " + "child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(90)']); " + f"open({str(pidfile)!r},'w').write(str(child.pid)); time.sleep(90)" + ) + cancel = threading.Event() + + def interrupt(): + deadline = time.monotonic() + 5 + while not pidfile.exists() and time.monotonic() < deadline: + time.sleep(0.01) + cancel.set() + + thread = threading.Thread(target=interrupt) + thread.start() + try: + with pytest.raises(OperationCancelled): + safe_run([sys.executable, "-c", script], control=OperationControl(cancel)) + finally: + thread.join() + child = int(pidfile.read_text()) + status = Path(f"/proc/{child}/stat") + try: + state = status.read_text().split()[2] + except (FileNotFoundError, ProcessLookupError): + # procfs can report ESRCH when the process exits between open and read. + state = "gone" + assert state in {"gone", "Z"} + + +def test_controlled_process_preserves_input_output_and_exit_errors(): + result = safe_run( + [sys.executable, "-c", "import sys; print(sys.stdin.read())"], + input="literal input", + control=OperationControl(deadline=time.monotonic() + 5), + ) + assert result.stdout.strip() == "literal input" + with pytest.raises(subprocess.CalledProcessError) as failure: + safe_run( + [sys.executable, "-c", "import sys;print('details');sys.exit(7)"], check=True, control=OperationControl() + ) + assert failure.value.returncode == 7 and "details" in failure.value.stdout + + +def test_deadline_bounds_process_and_sleep(): + control = OperationControl(deadline=time.monotonic() + 0.03) + started = time.monotonic() + with pytest.raises((TimeoutError, subprocess.TimeoutExpired)): + safe_run([sys.executable, "-c", "import time;time.sleep(90)"], timeout=60, control=control) + assert time.monotonic() - started < 2 + with pytest.raises(TimeoutError): + control.sleep(30) diff --git a/tests/test_pingmesh_acceptance.py b/tests/test_pingmesh_acceptance.py new file mode 100644 index 0000000..fd98335 --- /dev/null +++ b/tests/test_pingmesh_acceptance.py @@ -0,0 +1,912 @@ +"""Acceptance selection and capacity checks must fail before costly deployments.""" + +import hashlib +import json +import sys +from contextlib import nullcontext +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec +from netopsbench.platform.runtime import resources +from netopsbench.platform.scenario.parser import save_scenario_file +from netopsbench.platform.session import acceptance +from netopsbench.platform.topology.config import config_for_scale +from scripts import validate_pingmesh_scales as cli + +BACKEND = {"provider": "upstream", "containerlab_version": "test"} + + +@pytest.fixture +def write_case(tmp_path): + def write(name, filename=None): + return save_scenario_file( + ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, + scenario_id=name, + name=name, + topology_scale="xs", + episode=EpisodeSpec(episode_id="diagnosis", fault_type="none"), + ), + tmp_path / f"{filename or name}.yaml", + ) + + return write + + +@pytest.mark.parametrize( + "change", [None, "imported_image", "content", "source", "agent", "backend", "health", "case", "fingerprint"] +) +def test_codex_qualification_requires_matching_frozen_evidence(tmp_path, change): + identity = { + "model": "gpt-6.1-sol", + "service_tier": "default", + "image_id": "sha256:test", + "image_content_sha256": "same-content", + } + receipt = { + "schema_version": 1, + "status": "passed", + "runtime_disposition": "torn_down", + "final_health": {"status": "passed"}, + "runtime_backend": BACKEND, + "agent_identity": identity, + "source_tree_sha256": "frozen-source", + "cases": [ + { + "id": f"xs-{fault}", + "fault_type": fault, + "status": "completed", + "valid": True, + "diagnosis_complete": True, + "cleanup_failed": False, + "score": 0, + } + for fault in ("none", "link_down", "device_down", "bgp_auth_mismatch") + ], + } + if change == "source": + receipt["source_tree_sha256"] = "other-source" + elif change == "agent": + receipt["agent_identity"] = {**identity, "service_tier": "fast"} + elif change == "content": + receipt["agent_identity"] = {**identity, "image_content_sha256": "other-content"} + elif change == "backend": + receipt["runtime_backend"] = {"provider": "other"} + elif change == "health": + receipt["final_health"] = {"status": "failed"} + elif change == "case": + receipt["cases"][0]["diagnosis_complete"] = False + path = tmp_path / "qualification.json" + path.write_text(json.dumps(receipt)) + args = SimpleNamespace( + codex_smoke_receipt=path, + codex_smoke_receipt_sha256=hashlib.sha256(path.read_bytes()).hexdigest(), + source_tree_sha256="frozen-source", + ) + if change == "fingerprint": + args.codex_smoke_receipt_sha256 = "changed" + current_identity = {**identity, "image_id": "imported-id"} if change == "imported_image" else identity + if change not in {None, "imported_image"}: + with pytest.raises(ValueError, match="Codex qualification"): + acceptance.qualified_codex_smoke(args, {"codex": current_identity}, BACKEND) + else: + # Qualification checks execution and health, never model accuracy. + assert acceptance.qualified_codex_smoke(args, {"codex": current_identity}, BACKEND)["status"] == "passed" + + +@pytest.fixture(autouse=True) +def mock_runtime_backend(monkeypatch): + monkeypatch.setattr(acceptance, "runtime_backend_identity", lambda: dict(BACKEND)) + monkeypatch.setattr(resources, "runtime_backend_identity", lambda: dict(BACKEND)) + + +@pytest.mark.parametrize("agents", [[], ["codex"], ["deepagent", "codex"]]) +def test_acceptance_defaults_to_deepseek_and_requires_explicit_codex(monkeypatch, agents): + arguments = ["acceptance", "--scales", "xs"] + if agents: + arguments.extend(["--agents", *agents]) + monkeypatch.setattr(sys, "argv", arguments) + received = [] + + def run(args, **kwargs): + received.append((args.vendor, args.agents)) + return 0 + + monkeypatch.setattr(cli, "run_acceptance", run) + assert cli.main() == 0 + assert received == [("deepseek", agents or ["deepagent"])] + + +def test_selection_preserves_every_coverage_unit(tmp_path): + from netopsbench.platform.scenario.generator import generate, load_topology + from netopsbench.platform.topology.generator import generate_topology + + root = tmp_path / "topology" + generate_topology("medium", str(root)) + topo = load_topology("medium", str(root)) + paths = generate({"fault_catalog_version": 2}, topo, tmp_path / "cases", 42) + selected = cli.select_cases(paths, True, topo.manifest) + assert len(selected) == 64 + assert all(cli.parse_scenario_file(p).episode.is_healthy for p in selected[:4]) + assert len(cli.select_cases(paths, False, topo.manifest)) == 4 + + +def test_capacity_requires_twenty_percent_margin_and_disk_reserve(monkeypatch): + original_read = Path.read_text + monkeypatch.setattr( + Path, + "read_text", + lambda self, *a, **kw: ( + "MemAvailable: 100000000\n" if str(self) == "/proc/meminfo" else original_read(self, *a, **kw) + ), + ) + free = [1000 * resources.GIB] + monkeypatch.setattr(acceptance.shutil, "disk_usage", lambda _: SimpleNamespace(free=free[0])) + sample = { + "runtime_backend": BACKEND, + "nodes": [ + {"name": "lab-edge1", "data_ports": 18, "memory_bytes": 100 * 1024**2, "writable_bytes": 10 * 1024**2}, + {"name": "lab-client1", "memory_bytes": 2 * 1024**2, "writable_bytes": 1024}, + { + "name": "influxdb", + "role": "observability", + "memory_bytes": 1000 * resources.GIB, + "writable_bytes": 1000 * resources.GIB, + }, + ], + } + result = resources.capacity_check(sample, "fat-tree-k18", Path("/unused")) + assert result["memory_margin"] == 1.2 + assert result["status"] == "passed" + free[0] = 20 * resources.GIB + assert resources.capacity_check(sample, "fat-tree-k18", Path("/unused"))["status"] == "blocked" + + +def test_capacity_uses_peak_of_matching_port_capacity(monkeypatch): + monkeypatch.setattr(Path, "read_text", lambda self: "MemAvailable: 400000000\n") + monkeypatch.setattr(acceptance.shutil, "disk_usage", lambda _: SimpleNamespace(free=1000 * resources.GIB)) + sample = resources.peak_sample( + [ + { + "runtime_backend": BACKEND, + "nodes": [ + { + "name": "lab-leaf1", + "role": "switch", + "data_ports": 18, + "memory_bytes": 100 * 1024**2, + "writable_bytes": 1024, + }, + { + "name": "lab-spine1", + "role": "switch", + "data_ports": 128, + "memory_bytes": 1000 * 1024**2, + "writable_bytes": 1024, + }, + { + "name": "lab-client1", + "role": "client", + "data_ports": 1, + "memory_bytes": 2 * 1024**2, + "writable_bytes": 1024, + }, + ], + }, + { + "runtime_backend": BACKEND, + "nodes": [ + { + "name": "lab-leaf1", + "role": "switch", + "data_ports": 18, + "memory_bytes": 200 * 1024**2, + "writable_bytes": 2048, + } + ], + }, + ] + ) + result = resources.capacity_check(sample, "fat-tree-k18", Path("/unused")) + assert all(cost["sample_ports"] == 18 and not cost["extrapolated"] for cost in result["switch_costs"]) + assert all(cost["sample_memory_bytes"] == 200 * 1024**2 for cost in result["switch_costs"]) + for row in sample["nodes"]: + if row["role"] == "switch": + row["data_ports"] = 8 + assert resources.capacity_check(sample, "fat-tree-k18", Path("/unused"))["status"] == "blocked" + + +@pytest.mark.parametrize("retained", [False, True]) +def test_effects_capacity_excludes_absent_diagnostic_resources_only(monkeypatch, retained): + monkeypatch.setattr(Path, "read_text", lambda self: "MemAvailable: 400000000\n") + monkeypatch.setattr(resources.shutil, "disk_usage", lambda _: SimpleNamespace(free=1000 * resources.GIB)) + sample = { + "runtime_backend": BACKEND, + "nodes": [ + {"name": "lab-core1", "data_ports": 18, "memory_bytes": 500 * 1024**2, "writable_bytes": 1024}, + {"name": "lab-client1", "memory_bytes": 20 * 1024**2, "writable_bytes": 1024}, + ], + } + diagnose = resources.capacity_check(sample, "fat-tree-k18", Path("/unused"), retained) + effects = resources.capacity_check(sample, "fat-tree-k18", Path("/unused"), retained, False) + assert diagnose["diagnostic_memory_reserve_bytes"] == int(2.25 * resources.GIB) + assert effects["diagnostic_memory_reserve_bytes"] == 0 + assert diagnose["estimated_memory_bytes"] - effects["estimated_memory_bytes"] == pytest.approx( + 2.7 * resources.GIB, abs=1 + ) + assert diagnose["estimated_disk_bytes"] == effects["estimated_disk_bytes"] + assert diagnose["switch_costs"] == effects["switch_costs"] + assert effects["memory_margin"] == 1.2 + assert resources.EMERGENCY_MEMORY_BYTES == 12 * resources.GIB + + +def test_docker_memory_units_are_converted(): + assert resources.memory_bytes("195.5MiB") == int(195.5 * 1024**2) + with pytest.raises(ValueError, match="Invalid Docker memory"): + resources.memory_bytes("invalid") + + +def test_resume_retains_valid_low_scores_and_retries_incomplete_cases(): + def report(case, valid, cleanup_failed=False, score=0): + return { + "diagnosis_complete": not cleanup_failed, + "summary": {"average_score": score}, + "scenario_summaries": [{"scenario_id": case, "case_valid": valid, "cleanup_failed": cleanup_failed}], + } + + entry = { + "cases": [ + report("low-score", True), + report("healthy", True, score=1), + report("injection-failed", False), + report("recovery-failed", True, True), + ] + } + assert acceptance.finished_case_ids(entry) == {"low-score", "healthy"} + + +def test_completed_campaign_returns_without_constructing_agent_or_executor(tmp_path, write_case): + path = write_case("low-score") + entry = { + "agents": { + "codex": { + "identity": {}, + "cases": [ + { + "scenario_summaries": [{"scenario_id": path.stem, "case_valid": True, "status": "completed"}], + "summary": {"average_score": 0}, + "diagnosis_complete": True, + } + ], + } + } + } + assert ( + acceptance.run_cases( + None, + None, + [path], + backend="codex", + vendor="deepseek", + entry=entry, + identity={}, + output=tmp_path, + result={}, + cancel=None, + ) + is False + ) + assert entry["agents"]["codex"]["selected_cases"] == [path.stem] + + +@pytest.mark.parametrize("failure_stage", ["agent", "effect_validation"]) +def test_run_cases_records_case_failure_and_continues_without_retry(monkeypatch, tmp_path, write_case, failure_stage): + import threading + + paths = [write_case(name) for name in ("agent-failed", "valid-zero")] + selected = [] + + def execute(**kwargs): + selected.extend(case.id for case in kwargs["scenarios"]) + assert kwargs["control"].stop_on_failure is True + summaries = [] + for case in kwargs["scenarios"]: + failed = case.id == "agent-failed" + summary = { + "scenario_id": case.id, + "case_valid": not (failed and failure_stage == "effect_validation"), + "status": ("invalid" if failure_stage == "effect_validation" else "failed") if failed else "completed", + "cleanup_failed": False, + **({"failure_stage": failure_stage} if failed else {}), + } + raw = { + "episode": { + "diagnosis": {"success": not failed}, + "execution": {"case_valid": True, "termination_reason": "agent_error" if failed else "submitted"}, + }, + "cleanup": {"success": True}, + } + kwargs["control"].on_case(summary, raw, []) + summaries.append(summary) + return SimpleNamespace( + wait=lambda: SimpleNamespace(artifact_paths={"report": "report.json"}, scenario_summaries=summaries) + ) + + monkeypatch.setattr(acceptance.Evaluator, "generate_report", lambda *a, **kw: {"summary": {"average_score": 0}}) + bench = SimpleNamespace( + agents=SimpleNamespace(wrap=lambda raw: SimpleNamespace(name="agent")), + sessions=SimpleNamespace(_executor=SimpleNamespace(_run_with_existing_runtime=execute)), + ) + entry, result = {}, {} + kwargs = dict( + backend="deepagent", + vendor="deepseek", + entry=entry, + identity={}, + output=tmp_path, + result=result, + cancel=threading.Event(), + agent_factory=lambda backend: lambda **kw: object(), + ) + runtime = SimpleNamespace(scale="xs") + assert acceptance.run_cases(bench, runtime, paths, **kwargs) is True + records = entry["agents"]["deepagent"] + assert [r["diagnosis_complete"] for r in records["cases"]] == [False, True] + assert records["cases"][0]["scenario_summaries"][0]["status"] == ( + "invalid" if failure_stage == "effect_validation" else "failed" + ) + assert acceptance.finished_case_ids(records) == {"agent-failed", "valid-zero"} + assert acceptance.run_cases(bench, runtime, paths, **kwargs) is False + assert selected == ["agent-failed", "valid-zero"] + + +@pytest.mark.parametrize( + "stage,valid,diagnosed,cleanup_failed,mode,finished", + [ + pytest.param(None, True, None, False, None, False, id="unknown-execution-failure"), + pytest.param("agent", True, False, False, None, True, id="agent-failed-recovered"), + pytest.param("agent", True, False, True, None, False, id="agent-failed-unrecovered"), + pytest.param("execution", True, False, False, None, False, id="execution-failed"), + pytest.param("effect_validation", False, False, False, None, True, id="invalid-effect-recorded"), + pytest.param("effect_validation", False, False, False, "effects", False, id="effects-requires-validity"), + pytest.param("effect_validation", False, False, True, None, False, id="invalid-effect-unrecovered"), + pytest.param(None, True, True, True, None, True, id="retain-zero-score-despite-cleanup"), + pytest.param(None, True, False, True, None, False, id="incomplete-diagnosis-unrecovered"), + pytest.param(None, True, True, True, "effects", False, id="effects-requires-recovery"), + ], +) +def test_resume_failure_disposition(stage, valid, diagnosed, cleanup_failed, mode, finished): + summary = { + "scenario_id": "case", + "case_valid": valid, + "status": "invalid" if stage == "effect_validation" else "failed", + "cleanup_failed": cleanup_failed, + } + report = {"scenario_summaries": [summary]} + if stage is not None: + summary["failure_stage"] = stage + if diagnosed is not None: + report["diagnosis_complete"] = diagnosed + if diagnosed: + report["summary"] = {"average_score": 0} + if mode is not None: + report["mode"] = mode + before = json.loads(json.dumps(report)) + assert acceptance.finished_case_ids({"cases": [report]}) == ({"case"} if finished else set()) + assert report == before + + +def test_model_inconclusive_without_execution_error_remains_valid(): + diagnosis = {"verdict": "inconclusive", "metadata": {"llm_call_count": 4}} + report = { + "scenario_summaries": [{"scenario_id": "low-score", "case_valid": True, "cleanup_failed": False}], + "diagnosis_complete": True, + "detailed_results": [{"details": {"agent_output": diagnosis}}], + } + assert acceptance.finished_case_ids({"cases": [report]}) == {"low-score"} + + +@pytest.mark.parametrize("mismatch", ["scale", "plan"]) +def test_resume_identity_mismatch_is_rejected_before_health_or_mutation(monkeypatch, tmp_path, mismatch): + entry = {"runtime_backend": BACKEND, "plan": {"plan_id": "original"}} + runtime = SimpleNamespace( + scale="xs" if mismatch == "scale" else "fat-tree-k18", + workers=[SimpleNamespace(topology_dir=tmp_path)], + metadata={"runtime_backend": BACKEND}, + ) + monkeypatch.setattr( + acceptance, + "load_topology_manifest", + lambda _: SimpleNamespace( + require_pingmesh_plan=lambda: SimpleNamespace(settings=SimpleNamespace(plan_id="changed")) + ), + ) + with pytest.raises(ValueError, match="runtime|plan"): + acceptance.validate_resume(entry, runtime, "fat-tree-k18") + + +@pytest.mark.parametrize( + ("allow", "memory_gib", "disk_gib", "extrapolated", "expected"), + [ + (False, 194, 100, False, "Capacity check failed"), + (True, 194, 100, False, "deployment reached"), + (True, 191, 100, False, "Capacity check failed"), + (True, 180, 100, False, "Capacity check failed"), + (True, 194, 20, False, "Capacity check failed"), + (True, 194, 100, True, "Capacity check failed"), + ], +) +def test_explicit_margin_waiver_keeps_memory_disk_and_sample_guards( + monkeypatch, tmp_path, allow, memory_gib, disk_gib, extrapolated, expected +): + sample = tmp_path / "sample.json" + sample.write_text(json.dumps({"runtime_backend": BACKEND, "nodes": []})) + argv = ["acceptance", "--scales", "fat-tree-k18", "--capacity-sample", str(sample), "--output", str(tmp_path)] + if allow: + argv.append("--allow-tight-capacity") + monkeypatch.setattr(sys, "argv", argv) + monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key") + monkeypatch.setattr(cli, "preflight_agents", lambda *a, **kw: {"deepagent": {}}) + monkeypatch.setattr(acceptance.subprocess, "check_output", lambda *a, **kw: str(tmp_path)) + monkeypatch.setattr( + acceptance, + "capacity_check", + lambda *a: { + "status": "blocked", + "available_memory_bytes": memory_gib * resources.GIB, + "estimated_memory_bytes": 218 * resources.GIB, + "docker_disk_free_bytes": disk_gib * resources.GIB, + "estimated_disk_bytes": 28 * resources.GIB, + "switch_costs": [{"extrapolated": extrapolated}], + }, + ) + + def create(**kwargs): + raise RuntimeError("deployment reached") + + monkeypatch.setattr( + cli, "NetOpsBench", lambda **kw: nullcontext(SimpleNamespace(runtimes=SimpleNamespace(create=create))) + ) + with pytest.raises(RuntimeError, match=expected): + cli.main() + + +def test_bgp_acceptance_requires_every_neighbor_to_be_established(monkeypatch, tmp_path): + from netopsbench.platform.topology.clos_builder import build_clos_plan + + manifest = build_clos_plan(config_for_scale("xs")).manifest + switches = {device.name for device in manifest.switches()} + rows = [",result,table,_time,_value,source,neighbor_address"] + for index, link in enumerate(manifest.links): + if all(endpoint.device in switches for endpoint in link.endpoints): + a, b = link.endpoints + rows.extend(f",,0,2026-10-11T00:00:00Z,ESTABLISHED,{src},peer{index}" for src in (a.device, b.device)) + response = SimpleNamespace(status="ok", text="\n".join(rows)) + queries = [] + monkeypatch.setattr(acceptance, "query_flux", lambda *a, **kw: queries.append(a[-1]) or response) + worker = SimpleNamespace(bucket="test", topology_id="test") + assert acceptance.bgp_observation(worker, manifest, tmp_path / "bgp.csv")["established"] == 8 + assert "range(start: -130s)" in queries[-1] + assert 'group(columns: ["source", "neighbor_address"]) |> sort(columns: ["_time"]) |> last()' in queries[-1] + response.text = response.text.replace("ESTABLISHED", "IDLE", 1) + with pytest.raises(RuntimeError, match="Incomplete BGP observations"): + acceptance.bgp_observation(worker, manifest, tmp_path / "bgp.csv") + + +@pytest.mark.parametrize( + "owned,completed,emergency,expected", + [ + (True, False, False, False), + (True, True, False, True), + (False, True, False, False), + (False, False, True, False), + (True, False, True, True), + ], +) +def test_retention_obeys_runtime_ownership(owned, completed, emergency, expected): + calls = [] + runtime = SimpleNamespace(metadata={}, teardown=lambda: calls.append("teardown")) + disposition = acceptance.release_runtime(runtime, owned=owned, completed=completed, emergency=emergency) + assert bool(calls) is expected + assert disposition == ("torn_down" if expected else "retained") + + +def test_quarantined_runtime_is_retained(): + runtime = SimpleNamespace(metadata={"quarantined": True}, teardown=lambda: pytest.fail("must retain")) + assert acceptance.release_runtime(runtime, owned=True, completed=False) == "quarantined" + + +def test_failed_full_health_persists_quarantine_before_raising(monkeypatch): + writes = [] + runtime = SimpleNamespace( + workers=[SimpleNamespace()], + scale_registry=SimpleNamespace(), + metadata={}, + state="warm", + _write_metadata=lambda: writes.append(dict(runtime.metadata)), + ) + runtime.mark_quarantined = lambda reason: ( + runtime.metadata.update(quarantined=True, quarantine_reason=reason), + setattr(runtime, "state", "quarantined"), + runtime._write_metadata(), + ) + monkeypatch.setattr(acceptance, "check_worker_health", lambda *a, **kw: ["BGP not converged"]) + with pytest.raises(RuntimeError, match="BGP not converged"): + acceptance.require_full_health(runtime) + assert runtime.state == "quarantined" + assert writes == [{"quarantined": True, "quarantine_reason": "acceptance_health_failure"}] + + +def test_checkpoint_is_atomic_and_preserves_failed_attempts(tmp_path): + payload = {"status": "failed_retained", "scales": {"xs": {"error": "interrupted", "cases": []}}} + acceptance.checkpoint(tmp_path, payload) + assert json.loads((tmp_path / "acceptance.json").read_text()) == payload + assert len(list(tmp_path.iterdir())) == 1 + + +def test_xs_smoke_has_four_current_validation_cases(tmp_path): + from netopsbench.platform.scenario.generator import generate, load_topology + from netopsbench.platform.topology.generator import generate_topology + + root = tmp_path / "topology" + generate_topology("xs", str(root)) + topo = load_topology("xs", str(root)) + paths = generate({"fault_catalog_version": 2}, topo, tmp_path / "cases", 42) + selected = cli.smoke_cases(paths, topo.manifest) + cases = {cli.parse_scenario_file(path).episode.fault_type: cli.parse_scenario_file(path) for path in selected} + assert set(cases) == {"none", "link_down", "device_down", "bgp_auth_mismatch"} + assert topo.manifest.device(cases["device_down"].episode.target_device).role.value == "spine" + assert cases["link_down"].metadata["coverage_unit"].endswith("leaf-spine") + + +def test_owned_failed_partial_deployment_is_retained_and_quarantined(tmp_path): + calls = [] + runtime = SimpleNamespace( + stage_results={"deploy": SimpleNamespace(status="failed")}, + root_dir=tmp_path, + name="partial", + metadata={}, + state="created", + _write_metadata=lambda: calls.append("write"), + describe=lambda: {"state": "created"}, + teardown=lambda: calls.append("teardown"), + ) + runtime.mark_quarantined = lambda reason: ( + runtime.metadata.update(quarantined=True, quarantine_reason=reason), + setattr(runtime, "state", "quarantined"), + runtime._write_metadata(), + ) + assert not acceptance.quarantine_partial_deployment(runtime, {"runtime_owned": False}, tmp_path) + entry = {"runtime_owned": True} + assert acceptance.quarantine_partial_deployment(runtime, entry, tmp_path) + assert calls == ["write"] + assert runtime.state == "quarantined" + assert runtime.metadata["quarantined"] + assert entry["partial_deployment"] == {"state": "created"} + runtime.stage_results["deploy"].status = "completed" + runtime.mark_quarantined = lambda reason: ( + runtime.metadata.update(quarantined=True, quarantine_reason=reason), + setattr(runtime, "state", "quarantined"), + runtime._write_metadata(), + ) + assert not acceptance.quarantine_partial_deployment(runtime, entry, tmp_path) + + +def test_explicit_rebuild_can_validate_an_incomplete_owned_runtime_without_a_plan(tmp_path): + runtime = SimpleNamespace( + scale="xs", workers=[SimpleNamespace(topology_dir=tmp_path)], metadata={"runtime_backend": BACKEND} + ) + assert acceptance.validate_resume({"runtime_backend": BACKEND}, runtime, "xs", allow_unplanned=True) is None + with pytest.raises((FileNotFoundError, ValueError)): + acceptance.validate_resume({"runtime_backend": BACKEND}, runtime, "xs") + + +def test_retained_lab_capacity_does_not_charge_for_another_deployment(monkeypatch): + monkeypatch.setattr(Path, "read_text", lambda *a: "MemAvailable: 110000000\n") + monkeypatch.setattr(acceptance.shutil, "disk_usage", lambda _: SimpleNamespace(free=1000 * resources.GIB)) + sample = { + "runtime_backend": BACKEND, + "nodes": [ + { + "name": "lab-core1", + "role": "switch", + "data_ports": 18, + "memory_bytes": 500 * 1024**2, + "writable_bytes": 1024, + }, + {"name": "lab-client1", "role": "client", "memory_bytes": 20 * 1024**2, "writable_bytes": 1024}, + ], + } + fresh = resources.capacity_check(sample, "fat-tree-k18", Path("/unused")) + retained = resources.capacity_check(sample, "fat-tree-k18", Path("/unused"), True) + assert fresh["status"] == "blocked" + assert retained["status"] == "passed" + assert retained["mode"] == "retained_runtime" + assert retained["estimated_memory_bytes"] < retained["full_runtime_estimated_memory_bytes"] + + +@pytest.mark.parametrize("change", ["add", "remove", "replace", "content"]) +def test_case_set_and_contents_are_immutable_on_resume(write_case, change): + original = [write_case("one", "filename-is-not-id"), write_case("two")] + records = {} + acceptance.freeze_cases(records, original) + assert records["selected_cases"] == ["one", "two"] + before = json.loads(json.dumps(records)) + changed = list(original) + if change == "add": + changed.append(write_case("three")) + elif change == "remove": + changed.pop() + elif change == "replace": + changed[-1] = write_case("three") + else: + original[0].write_text(original[0].read_text() + "\n# changed\n") + with pytest.raises(ValueError, match="scenario"): + acceptance.freeze_cases(records, changed) + assert records == before + + +def test_preflight_interrupt_prevents_runtime_creation(monkeypatch, tmp_path): + import signal + + monkeypatch.setattr(sys, "argv", ["acceptance", "--scales", "xs", "--agents", "codex", "--output", str(tmp_path)]) + monkeypatch.setattr(acceptance.subprocess, "check_output", lambda *a, **kw: str(tmp_path)) + + def preflight(*args, **kwargs): + signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) + return {"codex": {}} + + monkeypatch.setattr(cli, "preflight_agents", preflight) + created = [] + monkeypatch.setattr( + cli, + "NetOpsBench", + lambda **kw: nullcontext( + SimpleNamespace( + runtimes=SimpleNamespace(create=lambda **kw: created.append(kw)), + ) + ), + ) + with pytest.raises(RuntimeError, match="cancelled"): + cli.main() + assert created == [] + checkpoint = json.loads((tmp_path / "acceptance.json").read_text()) + assert checkpoint["status"] == "failed_retained" + assert checkpoint["memory_samples"] + + +def test_resumed_campaign_exposes_current_resource_state_before_deployment(monkeypatch, tmp_path): + from netopsbench.platform.runtime.manager import RuntimePool + from netopsbench.sdk import NetOpsBench + + workspace = tmp_path / "workspace" + output = tmp_path / "campaign" + output.mkdir() + runtime_dir = workspace / ".netopsbench" / "runtimes" / "historical" + recorded = { + "runtime_backend": BACKEND, + "vendor": "deepseek", + "mode": "effects", + "fault_catalog_version": 2, + "status": "failed_retained", + "finished": "2026-10-12T00:00:00Z", + "scales": { + "xs": { + "runtime": str(runtime_dir), + "runtime_owned": True, + "runtime_disposition": "quarantined", + "resource_samples": [], + } + }, + } + acceptance.checkpoint(output, recorded) + sample = tmp_path / "capacity.json" + sample.write_text(json.dumps({"runtime_backend": BACKEND, "nodes": []})) + args = SimpleNamespace( + mode="effects", + agents=[], + scales="xs", + vendor="deepseek", + output=output, + resume_runtime=runtime_dir, + rebuild_runtime=False, + capacity_sample=sample, + allow_tight_capacity=False, + ) + monkeypatch.setattr(acceptance.subprocess, "check_output", lambda *a, **kw: str(tmp_path)) + monkeypatch.setattr(acceptance, "capacity_check", lambda *a: {"status": "passed"}) + monkeypatch.setattr(acceptance, "validate_campaign_cases", lambda *a: None) + monkeypatch.setattr(resources.ResourceMonitor, "watch", lambda *a: None) + + def deploy(runtime): + current = json.loads((output / "acceptance.json").read_text()) + assert current["status"] == "running" + assert "finished" not in current + assert current["scales"]["xs"]["runtime_disposition"] == "active" + assert current["resumptions"][-1]["previous_finished"] == recorded["finished"] + raise RuntimeError("deployment reached") + + monkeypatch.setattr(RuntimePool, "deploy", deploy) + with pytest.raises(RuntimeError, match="deployment reached"): + acceptance.run_acceptance( + args, + bench_factory=lambda **kw: NetOpsBench(workspace=str(workspace)), + agent_factory=None, + preflight=lambda *a, **kw: {}, + select_cases=cli.select_cases, + smoke_cases=cli.smoke_cases, + ) + + +def test_prepared_identity_is_durable_before_the_first_case(monkeypatch, tmp_path): + from netopsbench.models.profiles import default_scale_registry + from netopsbench.platform.topology.generator import generate_topology + + output, topology = tmp_path / "campaign", tmp_path / "runtime" / "worker-1" + generated = generate_topology("xs", str(topology), name="checkpoint-xs") + worker = SimpleNamespace( + lab_name="checkpoint-xs", topology_dir=topology, mgmt_subnet="172.31.100.0/24", mgmt_network="checkpoint-mgmt" + ) + runtime = SimpleNamespace( + state="warm", + root_dir=topology.parent, + workers=[worker], + scale_registry=default_scale_registry(), + metadata={}, + stage_results={}, + describe=lambda: {}, + ) + bench = SimpleNamespace(runtimes=SimpleNamespace(create=lambda **kw: SimpleNamespace(_runtime=runtime))) + sample = tmp_path / "capacity.json" + sample.write_text(json.dumps({"runtime_backend": BACKEND, "nodes": []})) + args = SimpleNamespace( + mode="effects", + agents=[], + scales="xs", + vendor="deepseek", + output=output, + resume_runtime=None, + rebuild_runtime=False, + capacity_sample=sample, + allow_tight_capacity=False, + ) + monkeypatch.setattr( + acceptance.subprocess, "check_output", lambda cmd, **kw: "sha256:test" if "inspect" in cmd else str(tmp_path) + ) + monkeypatch.setattr(resources.ResourceMonitor, "start", lambda *a: None) + monkeypatch.setattr(resources.ResourceMonitor, "watch", lambda *a: None) + monkeypatch.setattr(acceptance, "require_full_health", lambda *a: {"status": "passed"}) + monkeypatch.setattr(acceptance, "capacity_check", lambda *a: {"status": "passed"}) + monkeypatch.setattr(acceptance, "ingestion_latency", lambda *a: {"query_visible_seconds": 0.1}) + monkeypatch.setattr(acceptance, "bgp_observation", lambda *a, **kw: {"established": 8}) + monkeypatch.setattr(acceptance, "storage_snapshot", lambda: {}) + + def first_case(*a, **kw): + saved = json.loads((output / "acceptance.json").read_text())["scales"]["xs"] + assert saved["plan"]["plan_id"] == generated["metadata"]["pingmesh_plan"]["settings"]["plan_id"] + assert saved["client_images"] == ["sha256:test"] + assert saved["start_health"]["status"] == "passed" + assert saved["ingestion_latency"]["query_visible_seconds"] == 0.1 + raise RuntimeError("first case interrupted") + + monkeypatch.setattr(acceptance, "run_cases", first_case) + with pytest.raises(RuntimeError, match="first case interrupted"): + acceptance.run_acceptance( + args, + bench_factory=lambda **kw: nullcontext(bench), + agent_factory=None, + preflight=lambda *a, **kw: {}, + select_cases=cli.select_cases, + smoke_cases=cli.smoke_cases, + ) + assert json.loads((output / "acceptance.json").read_text())["status"] == "failed_retained" + + +def test_checkpoint_remains_parseable_during_resource_sampling(tmp_path): + import threading + + from netopsbench.platform.runtime.resources import ResourceMonitor + + result = {"scales": {}} + cancel, emergency = threading.Event(), threading.Event() + monitor = ResourceMonitor(result, cancel, emergency, acceptance._CHECKPOINT_LOCK) + monitor.start() + try: + for _ in range(10): + acceptance.checkpoint(tmp_path, result) + assert json.loads((tmp_path / "acceptance.json").read_text())["memory_samples"] + finally: + monitor.close() + assert not cancel.is_set() + + +@pytest.mark.parametrize("mismatch", ["model", "image_id", "service_tier"]) +def test_codex_resume_identity_checked_before_credentials_or_container_preflight(monkeypatch, tmp_path, mismatch): + agent = SimpleNamespace( + cli_version="0.159.2", + model="gpt-6.1-sol", + reasoning_effort="xhigh", + service_tier="default", + timeout_seconds=600, + max_tool_calls=40, + image="codex-image", + preflight=lambda: pytest.fail("identity mismatch must not create credentials or containers"), + ) + expected = { + "cli_version": agent.cli_version, + "model": agent.model, + "reasoning_effort": agent.reasoning_effort, + "service_tier": agent.service_tier, + "timeout_seconds": agent.timeout_seconds, + "max_mcp_calls": agent.max_tool_calls, + "image_id": "image-digest", + "image_content_sha256": "image-content", + } + expected[mismatch] = "changed" + monkeypatch.setattr(cli, "runtime_tools", lambda: tmp_path) + monkeypatch.setattr(cli, "agent_class", lambda backend: lambda **kwargs: agent) + monkeypatch.setattr(cli.subprocess, "check_output", lambda *args, **kwargs: "image-digest\n") + monkeypatch.setattr("examples.agents.codex_agent.runtime.image_content_identity", lambda image: "image-content") + with pytest.raises(ValueError, match="configuration"): + cli.preflight_agents(["codex"], "deepseek", tmp_path, expected={"codex": expected}) + + +def test_resume_does_not_infer_missing_diagnosis_state_from_archived_raw_results(tmp_path): + raw = tmp_path / "case.json" + raw.write_text(json.dumps({"episode": {"diagnosis": {"success": True}}})) + report = { + "scenario_summaries": [ + {"scenario_id": "old", "case_valid": True, "status": "completed", "raw_result_path": str(raw)} + ], + } + original = raw.read_bytes() + assert acceptance.finished_case_ids({"cases": [report]}) == set() + assert raw.read_bytes() == original + + +def test_effects_resume_requires_valid_completed_and_recovered_case(): + reports = [ + {"mode": "effects", "scenario_summaries": [{"scenario_id": name, **summary}]} + for name, summary in ( + ("completed", {"case_valid": True, "status": "completed", "cleanup_failed": False}), + ("invalid", {"case_valid": False, "status": "completed"}), + ("incomplete", {"case_valid": True, "status": "failed"}), + ("unrecovered", {"case_valid": True, "status": "completed", "cleanup_failed": True}), + ) + ] + assert acceptance.finished_case_ids({"cases": reports}) == {"completed"} + + +def test_legacy_campaign_rejected_before_provider_or_docker(monkeypatch, tmp_path): + from types import SimpleNamespace + + from netopsbench.platform.session import acceptance + + output = tmp_path / "campaign" + output.mkdir() + (output / "acceptance.json").write_text( + json.dumps({"mode": "effects", "fault_catalog_version": 2, "runtime_backend": {"provider": "custom"}}) + ) + monkeypatch.setattr(acceptance, "runtime_backend_identity", lambda: {"provider": "upstream"}) + monkeypatch.setattr(acceptance.subprocess, "check_output", lambda *a, **kw: pytest.fail("Docker called")) + args = SimpleNamespace( + mode="effects", + agents=[], + scales="xs", + vendor="deepseek", + output=output, + resume_runtime=tmp_path / "runtime", + rebuild_runtime=False, + ) + with pytest.raises(ValueError, match="Campaign runtime backend changed"): + acceptance.run_acceptance( + args, + bench_factory=None, + agent_factory=None, + preflight=lambda *a: pytest.fail("provider called"), + select_cases=None, + smoke_cases=None, + ) diff --git a/tests/test_pingmesh_detector_query.py b/tests/test_pingmesh_detector_query.py index 9deee5b..ee00167 100644 --- a/tests/test_pingmesh_detector_query.py +++ b/tests/test_pingmesh_detector_query.py @@ -1,9 +1,13 @@ from __future__ import annotations import re +import threading +import time from concurrent.futures import ThreadPoolExecutor as RealThreadPoolExecutor from types import SimpleNamespace +import pytest + from netopsbench.platform.pingmesh import _detector_query from netopsbench.platform.pingmesh._detector_query import DetectorQueryMixin, SnapshotQueryResult @@ -15,28 +19,30 @@ def __init__(self, clients: list[str]): self.token = "token" self.org = "org" self.topology_id = "runtime-topology" + self.plan_id = "current-plan" self._pingmesh_clients = clients self.client_to_leaf: dict[str, str] = {} -def test_topology_mapping_uses_canonical_attached_switch_for_fat_tree(): - detector = _Detector(["client1"]) - - detector._load_topology_metadata( - { - "devices": { - "clients": [ - { - "name": "client1", - "attached_switch": "edge1", - "edge": "edge1", - } - ] - } - } - ) +@pytest.mark.parametrize("scale", ["xs", "fat-tree-k8"]) +def test_topology_mapping_uses_canonical_attached_switch(tmp_path, scale): + from netopsbench.platform.pingmesh.detector import AnomalyDetector + from netopsbench.platform.topology.generator import generate_topology - assert detector.client_to_leaf == {"client1": "edge1"} + metadata = generate_topology(scale, str(tmp_path))["metadata"] + detector = AnomalyDetector("http://influxdb", "token", "org", "bucket", topology_metadata=metadata) + clients = [device for device in metadata["devices"] if device["role"] == "client"] + assert detector.client_to_leaf == {client["name"]: client["attached_switch"] for client in clients} + assert detector.client_to_leaf + if scale == "fat-tree-k8": + roles = {device["name"]: device["role"] for device in metadata["devices"]} + assert {roles[switch] for switch in detector.client_to_leaf.values()} == {"edge"} + from netopsbench.platform.toolkit.toolkit import AgentToolkit + + toolkit = AgentToolkit(topology_metadata=metadata) + assert toolkit._bgp_device_roles() == { + device["name"]: device["role"] for device in metadata["devices"] if device["role"] != "client" + } def test_snapshot_query_uses_bounded_pushdown_source_shards(monkeypatch): @@ -63,9 +69,47 @@ def executor_factory(*, max_workers): assert result.status == "ok" assert len(queries) == 5 assert worker_counts == [4] + assert all('r.plan_id == "current-plan"' in query for query in queries) assert all("contains(" not in query for query in queries) assert all('r.topology_id == "runtime-topology"' in query for query in queries) assert sorted(len(re.findall(r'r\.src_name == "client\d+"', query)) for query in queries) == [1, 16, 16, 16, 16] + assert result.request_count == 5 + + +def test_k18_two_closed_windows_require_42_first_pass_requests(monkeypatch): + from netopsbench.platform.pingmesh._detector_ingestion import DetectorIngestionMixin + + class ClosedDetector(DetectorIngestionMixin, _Detector): + _pingmesh_plan = SimpleNamespace(settings=SimpleNamespace(coverage_epoch_seconds=36)) + + def _boundary_padding_seconds(self): + return 6 + + def _slice_rows(self, rows, start, end): + return rows + + def summarize_coverage(self, rows): + return {"coverage_status": "complete"} + + def audit_ingestion(self, *args): + return {"status": "ready"} + + requests = [] + + def query(*args, **kwargs): + requests.append(args[3]) + return SimpleNamespace(status="ok", text="", error=None) + + monkeypatch.setattr(_detector_query, "query_flux", query) + detector = ClosedDetector([f"client{i}" for i in range(1, 325)]) + for start, end in [ + ("2026-01-01T00:00:00Z", "2026-01-01T00:00:42Z"), + ("2026-01-01T00:01:00Z", "2026-01-01T00:01:42Z"), + ]: + snapshot, coverage = detector._query_covered_snapshot(start, end) + assert snapshot.status == "ok" + assert coverage["ingestion"]["query_requests"] == 21 + assert len(requests) == 42 def test_snapshot_query_merges_every_shard_in_stable_order(monkeypatch): @@ -108,3 +152,121 @@ def query_shard(_start, _end, sources): assert result.status == "error" assert result.rows == [] assert result.error == "snapshot shard 2/2 failed: influx timeout" + + +def test_baseline_and_current_reads_overlap_and_remain_fresh(monkeypatch, tmp_path): + import threading + + from netopsbench.platform.pingmesh.detector import AnomalyDetector + from netopsbench.platform.topology.generator import generate_topology + + metadata = generate_topology("xs", str(tmp_path))["metadata"] + detector = AnomalyDetector("http://test", "token", "org", "bucket", topology_metadata=metadata) + barrier = threading.Barrier(2) + reads = [] + + def query(start, end): + reads.append((start, end)) + barrier.wait(timeout=5) + return SnapshotQueryResult(status="error", rows=[], error="test incomplete"), {} + + monkeypatch.setattr(detector, "_query_covered_snapshot", query) + for _ in range(2): + report = detector.generate_windowed_anomaly_report( + baseline_start="b1", baseline_end="b2", current_start="c1", current_end="c2", windows=[] + ) + assert report["query_status"]["ok"] is False + assert reads.count(("b1", "b2")) == 2 + assert reads.count(("c1", "c2")) == 2 + + +@pytest.mark.parametrize("client_count", [1, 128]) +def test_expired_snapshot_budget_never_starts_http(monkeypatch, client_count): + def unexpected(*_args, **_kwargs): + pytest.fail("expired snapshot started an HTTP request") + + monkeypatch.setattr(_detector_query, "query_flux", unexpected) + result = _Detector([f"client{i}" for i in range(client_count)])._query_snapshot( + "start", "end", deadline=time.monotonic() - 1 + ) + assert result.status == "error" + assert result.rows == [] + assert "deadline exceeded" in result.error + + +def test_queued_snapshot_shards_share_deadline_and_stop_http(monkeypatch): + calls = [] + ready = threading.Barrier(4) + deadline = time.monotonic() + 0.08 + + def query_flux(*_args, timeout, deadline): + calls.append(deadline) + ready.wait(timeout=1) + time.sleep(max(0, deadline - time.monotonic())) + return SimpleNamespace(status="error", text="", error="query deadline exceeded") + + monkeypatch.setattr(_detector_query, "query_flux", query_flux) + started = time.monotonic() + result = _Detector([f"client{i}" for i in range(128)])._query_snapshot("start", "end", deadline=deadline) + assert result.status == "error" + assert result.rows == [] + assert calls == [deadline] * 4 + assert time.monotonic() - started < 0.5 + + +def test_parallel_baseline_and_current_queries_receive_same_deadline(monkeypatch): + from netopsbench.platform.pingmesh.detector import AnomalyDetector + from netopsbench.platform.utils.measurements import count_operation, measurement_scope + + detector = object.__new__(AnomalyDetector) + budgets = [] + + def query(_start, _end, *, deadline): + budgets.append(deadline) + count_operation("influx_queries") + return SnapshotQueryResult(status="error", rows=[], error="deadline exceeded"), {} + + monkeypatch.setattr(detector, "_query_covered_snapshot", query) + monkeypatch.setattr(detector, "_build_report", lambda **kwargs: kwargs) + deadline = time.monotonic() + 1 + counts = {} + with measurement_scope(counts): + report = detector.generate_windowed_anomaly_report( + baseline_start="b1", baseline_end="b2", current_start="c1", current_end="c2", windows=[], deadline=deadline + ) + assert report["query_status"]["ok"] is False + assert budgets == [deadline, deadline] + assert counts == {"influx_queries": 2} + + +def test_snapshot_shards_preserve_phase_counts_and_control(monkeypatch): + from netopsbench.platform.utils.control import OperationControl, current_operation_control, operation_scope + from netopsbench.platform.utils.measurements import count_operation, measurement_scope + + control = OperationControl(deadline=time.monotonic() + 10) + + def query(*_args, **_kwargs): + assert current_operation_control() == control + count_operation("influx_queries") + return SimpleNamespace(status="ok", text="", error=None) + + monkeypatch.setattr(_detector_query, "query_flux", query) + counts = {} + with operation_scope(control), measurement_scope(counts): + result = _Detector([f"client{i}" for i in range(64)])._query_snapshot("start", "end") + assert result.status == "ok" and result.request_count > 1 + assert counts == {"influx_queries": result.request_count} + + +def test_snapshot_csv_honors_reordered_table_headers(): + text = ( + ",result,table,_time,src_name,dst_name,probe_cycle,port_batch_index\n" + ",_result,0,2026-10-24T00:00:00Z,client1,client2,6,0\n" + ",result,table,_time,port_batch_index,probe_cycle,dst_name,src_name\n" + ",_result,1,2026-10-24T00:00:01Z,1,7,client3,client1\n" + ) + rows = _Detector([])._parse_snapshot_csv(text) + assert [(r["src_name"], r["dst_name"], r["probe_cycle"], r["port_batch_index"]) for r in rows] == [ + ("client1", "client2", 6, 0), + ("client1", "client3", 7, 1), + ] diff --git a/tests/test_pingmesh_ingestion.py b/tests/test_pingmesh_ingestion.py new file mode 100644 index 0000000..c992bd6 --- /dev/null +++ b/tests/test_pingmesh_ingestion.py @@ -0,0 +1,277 @@ +"""Closed-window readiness must include repeated tasks at the window tail.""" + +import json +from copy import deepcopy +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest + +from netopsbench.platform.pingmesh._detector_query import _SNAPSHOT_FIELDS, SnapshotQueryResult +from netopsbench.platform.pingmesh.detector import AnomalyDetector +from netopsbench.platform.topology.generator import generate_topology + +START = datetime(2026, 1, 1, 0, 0, 1, tzinfo=UTC) +END = START + timedelta(seconds=4) + + +def rows_for(detector, cycles=range(7)): + rows = [] + for source in detector._pingmesh_clients: + for cycle in cycles: + destination_batch, port_batch, targets = detector._expected_frames[ + source, cycle % detector._pingmesh_plan.settings.coverage_epoch_cycles + ] + for target in sorted(targets): + row = dict.fromkeys(_SNAPSHOT_FIELDS, 0) + row.update( + _time=(START + timedelta(seconds=cycle - 1)).isoformat(), + plan_id=detector.plan_id, + src_name=source, + dst_name=target, + src_ip=detector._client_addresses[source], + dst_ip=detector._client_addresses[target], + probe_cycle=cycle, + destination_batch_index=destination_batch, + port_batch_index=port_batch, + rtt_ports_active=len(detector._pingmesh_plan.settings.port_batches[port_batch]), + rtt_ports_total=16, + packets_sent=4, + df_packets_sent=1, + ) + rows.append(row) + return rows + + +@pytest.fixture +def detector(tmp_path): + manifest = generate_topology("xs", str(tmp_path))["metadata"] + return AnomalyDetector("http://test", "token", "org", "bucket", topology_metadata=manifest) + + +def audit(detector, progress, snapshot=None): + if snapshot is None: + snapshot = detector._slice_rows(progress, START.isoformat(), END.isoformat()) + return detector.audit_ingestion(progress, snapshot, START.isoformat(), END.isoformat()) + + +def test_coverage_complete_does_not_prove_tail_arrival(detector): + progress = rows_for(detector) + current = detector._slice_rows(progress, START.isoformat(), END.isoformat()) + partial = [r for r in current if not (r["src_name"] == "client1" and r["probe_cycle"] == 4)] + assert detector.summarize_coverage(partial)["coverage_status"] == "complete" + assert audit(detector, progress, partial)["status"] == "pending" + assert audit(detector, progress, current)["status"] == "ready" + + +@pytest.mark.parametrize("damage", ["whole_round", "field", "progress_field", "following", "preceding"]) +def test_missing_data_or_boundary_cannot_close_window(detector, damage): + progress = rows_for(detector) + current = detector._slice_rows(progress, START.isoformat(), END.isoformat()) + if damage == "whole_round": + progress = [r for r in progress if r["probe_cycle"] != 3] + current = [r for r in current if r["probe_cycle"] != 3] + elif damage == "field": + current[0] = {k: v for k, v in current[0].items() if k != "df_packets_lost"} + elif damage == "progress_field": + progress[1] = {k: v for k, v in progress[1].items() if k != "port_batch_index"} + elif damage == "following": + progress = [r for r in progress if r["probe_cycle"] < 5] + else: + progress = [r for r in progress if r["probe_cycle"] > 0] + assert audit(detector, progress, current)["status"] == "pending" + + +@pytest.mark.parametrize("damage", ["restart", "clock", "peer", "port", "address"]) +def test_conflicting_identity_is_invalid(detector, damage): + progress = rows_for(detector) + row = progress[3] + if damage == "restart": + progress.append({**row, "_time": (START + timedelta(seconds=2.5)).isoformat()}) + elif damage == "clock": + row["_time"] = (START - timedelta(seconds=2)).isoformat() + elif damage == "peer": + row["dst_name"] = "wrong" + elif damage == "port": + row["port_batch_index"] = 9 + else: + row["src_ip"] = "192.0.2.99" + assert audit(detector, progress)["status"] == "invalid" + + +def test_loss_and_local_errors_are_ingested_but_remain_invalid_coverage(detector): + progress = rows_for(detector) + for row in progress: + row.update(packets_lost=4, df_packets_lost=1, local_probe_errors=1) + current = detector._slice_rows(progress, START.isoformat(), END.isoformat()) + assert audit(detector, progress, current)["status"] == "ready" + assert detector.summarize_coverage(current)["coverage_status"] == "incomplete" + + +def test_out_of_order_identical_retries_are_idempotent(detector): + progress = rows_for(detector) + assert audit(detector, [*reversed(progress), deepcopy(progress[3])])["status"] == "ready" + + +def test_empty_frames_are_inferred_from_plan(detector): + for frame in detector._pingmesh_plan.clients[0].frames[1::2]: + frame.target_indices.clear() + detector._compile_coverage_expectations() + progress = rows_for(detector) + assert audit(detector, progress)["status"] == "ready" + assert detector._boundary_padding_seconds() == 3 + + +def test_query_waits_for_late_tail_and_keeps_query_interval(detector, monkeypatch): + progress = rows_for(detector) + current = detector._slice_rows(progress, START.isoformat(), END.isoformat()) + clock = [0.0] + from netopsbench.platform.pingmesh import _detector_ingestion as module + + monkeypatch.setattr(module.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr( + module.OperationControl, "sleep", lambda self, seconds: clock.__setitem__(0, clock[0] + seconds) + ) + calls = [] + + def query(start, end, *, deadline, fields=None): + calls.append((start, end, deadline, fields)) + rows = progress + if clock[0] == 0: + rows = [r for r in rows if not (r["src_name"] == "client1" and r["probe_cycle"] == 4)] + return SnapshotQueryResult(status="ok", rows=rows, request_count=1) + + monkeypatch.setattr(detector, "_query_snapshot", query) + result, coverage = detector._query_covered_snapshot(START.isoformat(), END.isoformat(), deadline=5) + assert result.status == "ok" + assert coverage["ingestion"]["status"] == "ready" + assert coverage["query_retries"] == 1 + assert result.rows == current + assert all(datetime.fromisoformat(a) < START and datetime.fromisoformat(b) > END for a, b, _, _ in calls) + assert all(fields is None for _, _, _, fields in calls) + assert len(calls) == coverage["ingestion"]["query_requests"] == 2 + assert {limit for _, _, limit, _ in calls} == {5} + + +def test_missing_rows_exhaust_one_shared_deadline(detector, monkeypatch): + from netopsbench.platform.pingmesh import _detector_ingestion as module + + clock = [0.0] + monkeypatch.setattr(module.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr( + module.OperationControl, "sleep", lambda self, seconds: clock.__setitem__(0, clock[0] + seconds) + ) + calls = [] + monkeypatch.setattr(detector, "_query_snapshot", lambda *a, **kw: calls.append(kw) or SnapshotQueryResult("ok", [])) + snapshot, coverage = detector._query_covered_snapshot(START.isoformat(), END.isoformat(), deadline=2) + assert snapshot.status == "error" + assert coverage["ingestion"]["status"] == "not_ready" + assert len(calls) == 2 + + +def test_failed_query_time_is_still_reported(detector, monkeypatch): + from netopsbench.platform.pingmesh import _detector_ingestion as module + + clock = [0.0] + monkeypatch.setattr(module.time, "monotonic", lambda: clock[0]) + + def fail(*args, **kwargs): + clock[0] += 0.25 + return SnapshotQueryResult("error", [], "connection failed") + + monkeypatch.setattr(detector, "_query_snapshot", fail) + snapshot, coverage = detector._query_covered_snapshot(START.isoformat(), END.isoformat(), deadline=2) + assert snapshot.status == "error" + assert coverage["ingestion"]["query_seconds"] == 0.25 + assert coverage["ingestion"]["wait_seconds"] == 0 + + +def test_combined_read_keeps_boundary_metrics_outside_statistics(detector, monkeypatch): + context = rows_for(detector) + expected = detector._slice_rows(context, START.isoformat(), END.isoformat()) + for row in context: + if not START <= datetime.fromisoformat(row["_time"]) < END: + row.update(packets_lost=4, df_packets_lost=1, rtt_avg=100000) + reads = [] + + def query(start, end, **kwargs): + reads.append((start, end, kwargs)) + return SnapshotQueryResult("ok", context, request_count=1) + + monkeypatch.setattr(detector, "_query_snapshot", query) + result, coverage = detector._query_covered_snapshot(START.isoformat(), END.isoformat()) + assert result.rows == expected + assert coverage["ingestion"]["status"] == "ready" + assert detector.analyze_snapshot_rows(result.rows, result.rows).anomalies == [] + assert len(reads) == coverage["ingestion"]["query_requests"] == 1 + + +def test_completed_audit_after_deadline_cannot_return_ready(detector, monkeypatch): + from netopsbench.platform.pingmesh import _detector_ingestion as module + + clock = [0.0] + monkeypatch.setattr(module.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr( + detector, "_query_snapshot", lambda *a, **kw: SnapshotQueryResult("ok", rows_for(detector), request_count=1) + ) + audit = detector.audit_ingestion + + def slow_audit(*args): + result = audit(*args) + assert result["status"] == "ready" + clock[0] = 6 + return result + + monkeypatch.setattr(detector, "audit_ingestion", slow_audit) + result, coverage = detector._query_covered_snapshot(START.isoformat(), END.isoformat(), deadline=5) + assert result.status == "error" + assert coverage["ingestion"]["status"] == "not_ready" + assert coverage["ingestion"]["query_requests"] == 1 + + +def test_boundary_round_can_straddle_window(tmp_path): + manifest = generate_topology("medium", str(tmp_path))["metadata"] + detector = AnomalyDetector("http://test", "token", "org", "bucket", topology_metadata=manifest) + progress = rows_for(detector) + row = next(r for r in progress if r["src_name"] == "client1" and r["probe_cycle"] == 0) + row["_time"] = (START + timedelta(microseconds=1)).isoformat() + for following in progress: + if following["src_name"] == "client1" and following["probe_cycle"] == 1: + following["_time"] = (START + timedelta(milliseconds=1)).isoformat() + assert audit(detector, progress)["status"] == "ready" + partial = [r for r in progress if r is not row] + assert audit(detector, partial)["status"] == "pending" + + +def test_later_partial_frame_does_not_block_a_closed_window(detector): + progress = rows_for(detector) + partial = deepcopy(progress[-1]) + partial.pop("port_batch_index") + assert audit(detector, [*progress, partial])["status"] == "ready" + + +def test_archived_k8_four_to_five_samples_cannot_pass_early(tmp_path): + trace = json.loads((Path(__file__).parent / "fixtures" / "pingmesh_late_tail.json").read_text()) + manifest = generate_topology("fat-tree-k8", str(tmp_path))["metadata"] + detector = AnomalyDetector("http://test", "token", "org", "bucket", topology_metadata=manifest) + detector._pingmesh_clients = ["client31"] + progress = rows_for(detector, range(1068, 1084)) + origin = datetime.fromisoformat(trace["current"][0]["_time"].replace("Z", "+00:00")) + original = {int(row["probe_cycle"]): row for row in trace["current"]} + for row in progress: + row["_time"] = (origin + timedelta(seconds=3 * (row["probe_cycle"] - 1069))).isoformat() + if row["dst_name"] == "client115": + row.update(original[row["probe_cycle"]]) + row["plan_id"] = detector.plan_id # Bind the archived trace to this generated test topology. + start, end = trace["provenance"]["start"], trace["provenance"]["end"] + current = detector._slice_rows(progress, start, end) + partial = [r for r in current if not (r["dst_name"] == "client115" and r["probe_cycle"] == 1081)] + first_audit = detector.audit_ingestion(progress, partial, start, end) + assert first_audit["status"] == "pending", first_audit + assert detector.audit_ingestion(progress, current, start, end)["status"] == "ready" + early = detector.analyze_snapshot_rows(trace["baseline"], trace["current"][:-1]).anomalies + final = detector.analyze_snapshot_rows(trace["baseline"], trace["current"]).anomalies + assert next(a.value for a in early if a.type == "packet_loss") == 75 + assert next(a.value for a in final if a.type == "packet_loss") == 80 + assert any(a.type == "mtu_or_fragmentation_suspect" for a in early) + assert not any(a.type == "mtu_or_fragmentation_suspect" for a in final) diff --git a/tests/test_pingmesh_plan.py b/tests/test_pingmesh_plan.py new file mode 100644 index 0000000..0449f36 --- /dev/null +++ b/tests/test_pingmesh_plan.py @@ -0,0 +1,128 @@ +"""Contracts for the single offline compiler and its exact observation audit.""" + +from collections import Counter + +import pytest + +from netopsbench.platform.pingmesh.detector import AnomalyDetector +from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan +from netopsbench.platform.topology.clos_builder import build_clos_plan +from netopsbench.platform.topology.config import TopologyConfig, config_for_scale +from netopsbench.platform.topology.fat_tree_builder import build_fat_tree_plan +from netopsbench.platform.topology.topology_utils import coerce_topology_manifest + + +@pytest.fixture(scope="module") +def manifests(): + result = {} + for scale in ("xs", "medium", "large", "xlarge", "fat-tree-k8", "fat-tree-k12", "fat-tree-k18"): + config = config_for_scale(scale) + builder = build_clos_plan if isinstance(config, TopologyConfig) else build_fat_tree_plan + result[scale] = builder(config).manifest + return result + + +@pytest.mark.parametrize( + "scale,pairs,epoch,window", + [ + ("xs", 2, 2, 7), + ("medium", 128, 3, 8), + ("large", 1152, 24, 30), + ("xlarge", 16512, 60, 66), + ("fat-tree-k8", 4352, 36, 42), + ("fat-tree-k12", 10368, 36, 42), + ("fat-tree-k18", 26406, 36, 42), + ], +) +def test_fixed_plans_cover_all_links_and_ports(manifests, scale, pairs, epoch, window): + manifest = manifests[scale] + plan = manifest.require_pingmesh_plan() + assert plan.directed_pair_count == pairs + assert plan.settings.coverage_epoch_seconds == epoch + assert plan.settings.complete_window_seconds == window + assert len(plan.coverage.directed_links) == 2 * len(manifest.links) + assert set(plan.coverage.covered_switches) == {device.name for device in manifest.switches()} + assert plan.coverage.minimum_witnesses >= (2 if scale in {"xlarge", "fat-tree-k18"} else 1) + planned_pairs = {(client.name, destination) for client in plan.clients for destination in client.targets} + assert all((destination, source) in planned_pairs for source, destination in planned_pairs) + for client in plan.clients: + assert len(client.frames) == plan.settings.coverage_epoch_cycles + combinations = Counter() + for frame in client.frames: + combinations.update((client.targets[index], frame.port_batch_index) for index in frame.target_indices) + socket_count = len(plan.settings.port_batches[frame.port_batch_index]) + assert len(frame.probes) == len(frame.target_indices) * (socket_count + 1) + for target in range(len(frame.target_indices)): + assert {socket for kind, index, socket in frame.probes if kind == "rtt" and index == target} == set( + range(socket_count) + ) + assert sum(kind == "df" and index == target for kind, index, _ in frame.probes) == 1 + assert len(combinations) == len(client.targets) * len(plan.settings.port_batches) + assert set(combinations.values()) == {1} + if scale in {"xlarge", "fat-tree-k18"}: + degrees = [len(client.targets) for client in plan.clients] + assert max(degrees) - min(degrees) == 1 + + +def test_compilation_is_deterministic_and_old_or_stale_artifacts_fail(manifests): + manifest = manifests["medium"] + assert compile_pingmesh_plan(manifest) == manifest.pingmesh_plan + payload = manifest.model_dump(mode="json") + payload["schema_version"] = "3" + with pytest.raises(ValueError, match="Regenerate"): + coerce_topology_manifest(payload) + payload["schema_version"] = "4" + payload["pingmesh_plan"]["clients"][0]["targets"].reverse() + with pytest.raises(ValueError, match="fingerprint"): + coerce_topology_manifest(payload) + + +def observation_rows(plan): + rows = [] + for client in plan.clients: + for cycle, frame in enumerate(client.frames): + for index in frame.target_indices: + rows.append( + { + "plan_id": plan.settings.plan_id, + "probe_cycle": cycle, + "src_name": client.name, + "dst_name": client.targets[index], + "destination_batch_index": frame.destination_batch_index, + "port_batch_index": frame.port_batch_index, + "rtt_ports_total": len(plan.settings.source_ports), + "rtt_ports_active": len(plan.settings.port_batches[frame.port_batch_index]), + "local_probe_errors": 0, + } + ) + return rows + + +def test_audit_requires_exact_peers_frames_and_current_plan(manifests): + manifest = manifests["medium"] + detector = AnomalyDetector("http://localhost", "token", "org", "bucket", topology_metadata=manifest) + rows = observation_rows(manifest.require_pingmesh_plan()) + assert detector.summarize_coverage(rows)["coverage_status"] == "complete" + assert detector.summarize_coverage(rows[1:])["missing_pair_port_combinations"] == 1 + for replacement in ({"dst_name": "unknown"}, {"plan_id": "old"}, {"probe_cycle": 1}, {"local_probe_errors": 1}): + altered = [dict(row) for row in rows] + altered[0].update(replacement) + assert detector.summarize_coverage(altered)["coverage_status"] == "incomplete" + lossy = [dict(row, packets_sent=8, packets_lost=8, packet_loss=100) for row in rows] + assert detector.summarize_coverage(lossy)["coverage_status"] == "complete" + + +def test_k18_addresses_asns_neighbors_and_management_capacity(manifests): + manifest = manifests["fat-tree-k18"] + assert len(manifest.switches()) == 405 + assert len(manifest.clients()) == 324 + assert len(manifest.links) == 3240 + assert len({device.asn for device in manifest.switches()}) == 405 + assert manifest.routing.core_asn_range == "65001-65081" + assert manifest.routing.agg_asn_range == "65082-65243" + assert manifest.routing.edge_asn_range == "65244-65405" + assert manifest.clients()[-1].data_ip == "192.168.162.6" + assert manifest.device("edge162").metadata["client_subnet"] == "192.168.162.0/24" + config = config_for_scale("fat-tree-k18") + fabric = build_fat_tree_plan(config) + assert sum(len(device.bgp_neighbors) for device in fabric.device_plans) == 5832 diff --git a/tests/test_pingmesh_time_scope.py b/tests/test_pingmesh_time_scope.py index cbe567c..74c329b 100644 --- a/tests/test_pingmesh_time_scope.py +++ b/tests/test_pingmesh_time_scope.py @@ -1,12 +1,16 @@ import inspect import json import tempfile -from types import SimpleNamespace +import time + +import pytest from netopsbench.models.topology import ( Collector, Device, DeviceRole, + Link, + LinkEndpoint, Management, PingmeshPolicy, RoutingMetadata, @@ -17,7 +21,7 @@ from netopsbench.platform.pingmesh._detector_analysis import DetectorAnalysisMixin from netopsbench.platform.pingmesh._detector_query import SnapshotQueryResult from netopsbench.platform.pingmesh.detector import Anomaly, AnomalyDetector -from netopsbench.platform.scenario.observation import wait_and_observe +from netopsbench.platform.scenario.observation import analyze_observation_windows, capture_observation_window from netopsbench.platform.toolkit._core.common import ToolResult from netopsbench.platform.toolkit.mcp import context as mcp_context from netopsbench.platform.toolkit.mcp import observability as fastmcp_server @@ -59,7 +63,16 @@ def _coverage_detector(client_count=144, *, rtt_ports_per_cycle=4): total_switches=1, ), devices=[Device(name="leaf1", role=DeviceRole.LEAF), *clients], - links=[], + links=[ + Link( + kind="access", + endpoints=( + LinkEndpoint(device="leaf1", interface=f"eth{i}"), + LinkEndpoint(device=client.name, interface="eth1"), + ), + ) + for i, client in enumerate(clients) + ], routing=RoutingMetadata(ecmp_hash_policy_by_role={DeviceRole.LEAF: 1}), pingmesh=PingmeshPolicy( destination_batch_size=16, @@ -68,6 +81,9 @@ def _coverage_detector(client_count=144, *, rtt_ports_per_cycle=4): cycle_interval_seconds=2, ), ) + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + topology.pingmesh_plan = compile_pingmesh_plan(topology) return AnomalyDetector( "http://influxdb:8086", "token", @@ -108,9 +124,10 @@ def _snapshot_sequence(monkeypatch, detector, responses): def query(start_time, end_time): calls.append((start_time, end_time)) - return SnapshotQueryResult(status="ok", rows=next(pending)) + rows = next(pending) + return SnapshotQueryResult(status="ok", rows=rows), detector.summarize_coverage(rows) - monkeypatch.setattr(detector, "_query_snapshot", query) + monkeypatch.setattr(detector, "_query_covered_snapshot", query) return calls @@ -315,7 +332,7 @@ def test_df_only_loss_is_mtu_suspect(): assert analysis.quality["absolute_network_mtu_paths"] == 1 -def test_df_loss_with_any_counted_small_probe_loss_is_not_mtu(): +def test_df_loss_with_any_counted_medium_probe_loss_is_not_mtu(): detector = _coverage_detector(client_count=2) analysis = detector.analyze_snapshot_rows( @@ -462,6 +479,81 @@ def test_generate_report_queries_each_snapshot_once(monkeypatch): ] +def test_equal_snapshot_window_reuses_analysis_and_keeps_anomaly_labels(monkeypatch): + detector = _coverage_detector(client_count=2) + _snapshot_sequence(monkeypatch, detector, [_rtt_rows([1]), _rtt_rows([100])]) + monkeypatch.setattr(detector, "summarize_coverage", lambda rows: {"coverage_status": "complete"}) + original = detector.analyze_snapshot_rows + calls = [] + + def analyze(baseline, current): + calls.append(len(current)) + return original(baseline, current) + + monkeypatch.setattr(detector, "analyze_snapshot_rows", analyze) + report = detector.generate_windowed_anomaly_report( + baseline_start="2025-12-31T23:59:00Z", + baseline_end="2026-01-01T00:00:00Z", + current_start="2026-01-01T00:00:00Z", + current_end="2026-01-01T00:00:01Z", + windows=[{"name": "steady", "start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:00:01Z"}], + ) + assert calls == [1] + assert report["summary"]["latency_spikes"] == 1 + assert report["anomalies"][0]["windows_observed"] == ["full", "steady"] + assert report["anomalies"][0]["persistence"] == "steady_only" + + +def test_window_analysis_does_not_reuse_rows_excluded_by_slice(monkeypatch): + detector = _coverage_detector(client_count=2) + current = _rtt_rows([100, 1]) + [{"_time": "invalid", "rtt_avg": 100}] + _snapshot_sequence(monkeypatch, detector, [_rtt_rows([1]), current]) + monkeypatch.setattr(detector, "summarize_coverage", lambda rows: {"coverage_status": "complete"}) + original = detector.analyze_snapshot_rows + calls = [] + + def analyze(baseline, rows): + calls.append(len(rows)) + return original(baseline, rows) + + monkeypatch.setattr(detector, "analyze_snapshot_rows", analyze) + detector.generate_windowed_anomaly_report( + baseline_start="2025-12-31T23:59:00Z", + baseline_end="2026-01-01T00:00:00Z", + current_start="2026-01-01T00:00:00Z", + current_end="2026-01-01T00:00:02Z", + windows=[ + {"name": "steady", "start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:00:02Z"}, + {"name": "early", "start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:00:01Z"}, + ], + ) + assert calls == [3, 2, 1] + + +def test_analysis_groups_each_snapshot_once_without_modifying_rows(monkeypatch): + from copy import deepcopy + + from netopsbench.platform.pingmesh import _detector_analysis as module + + counts = {"_group_by_path": 0, "_group_by_path_port_batch": 0} + + def wrap(name, original): + def grouped(rows): + counts[name] += 1 + return original(rows) + + return grouped + + for name in counts: + monkeypatch.setattr(module, name, wrap(name, getattr(module, name))) + baseline, current = [_probe_sample()], [_probe_sample(lost=4, df_lost=4)] + before = deepcopy((baseline, current)) + analysis = _coverage_detector(client_count=2).analyze_snapshot_rows(baseline, current) + assert counts == {"_group_by_path": 2, "_group_by_path_port_batch": 2} + assert (baseline, current) == before + assert analysis.quality["absolute_unreachable_paths"] == 1 + + def test_generate_report_keeps_baseline_coverage_separate_from_current(monkeypatch): detector = _coverage_detector(client_count=2) _snapshot_sequence(monkeypatch, detector, [[_probe_sample()], [_probe_sample()]]) @@ -490,8 +582,11 @@ def test_snapshot_query_failure_is_not_reported_as_healthy(monkeypatch): detector = _coverage_detector(client_count=2) monkeypatch.setattr( detector, - "_query_snapshot", - lambda _start, _end: SnapshotQueryResult(status="error", rows=[], error="influx unavailable"), + "_query_covered_snapshot", + lambda _start, _end: ( + SnapshotQueryResult(status="error", rows=[], error="influx unavailable"), + {"coverage_status": "error"}, + ), ) report = detector.generate_windowed_anomaly_report( @@ -510,8 +605,8 @@ def test_snapshot_query_failure_without_error_text_is_still_an_error(monkeypatch detector = _coverage_detector(client_count=2) monkeypatch.setattr( detector, - "_query_snapshot", - lambda _start, _end: SnapshotQueryResult(status="error", rows=[]), + "_query_covered_snapshot", + lambda _start, _end: (SnapshotQueryResult(status="error", rows=[]), {"coverage_status": "error"}), ) report = detector.generate_windowed_anomaly_report( @@ -611,37 +706,6 @@ def test_snapshot_csv_parser_accepts_pivoted_rows(): ] -def test_pingmesh_coverage_summary_reports_complete_epoch(): - detector = _coverage_detector() - rows = [] - for source in range(1, 145): - for offset in range(1, 144): - destination_batch = (offset - 1) // 16 - for port_batch in range(4): - cycle = destination_batch + port_batch * 9 - rows.append( - { - "probe_cycle": float(cycle), - "destination_batch_index": float(destination_batch), - "port_batch_index": float(port_batch), - "src_name": f"client{source}", - "dst_name": f"client{((source + offset - 1) % 144) + 1}", - "rtt_ports_active": 4, - "rtt_ports_total": 16, - "local_probe_errors": 0, - } - ) - audit = detector.summarize_coverage(rows) - - assert audit["coverage_status"] == "complete" - assert audit["expected_epoch_cycles"] == 36 - assert audit["min_source_cycle_span"] == 36 - assert audit["destination_batches_observed"] == list(range(9)) - assert audit["port_batches_observed"] == list(range(4)) - assert audit["pair_port_combinations_observed"] == 20_592 * 4 - assert audit["missing_pair_port_combinations"] == 0 - - def test_detector_projects_canonical_manifest_before_loading_coverage_policy(tmp_path): from netopsbench.platform.topology.generator import generate_topology from netopsbench.platform.topology.topology_utils import load_topology_manifest @@ -658,44 +722,16 @@ def test_detector_projects_canonical_manifest_before_loading_coverage_policy(tmp topology_id=manifest.topology_id, ) - assert detector._pingmesh_policy["destination_batch_count"] == 8 - assert detector._pingmesh_policy["port_batch_count"] == 4 - assert detector._pingmesh_policy["coverage_epoch_cycles"] == 32 - - -def test_xlarge_and_k8_coverage_counts_all_pairs_and_port_batches(): - client_count = 128 - rows = [] - for source in range(1, client_count + 1): - for offset in range(1, client_count): - destination_batch = (offset - 1) // 16 - destination = ((source + offset - 1) % client_count) + 1 - for port_batch in range(4): - rows.append( - { - "probe_cycle": float(destination_batch + port_batch * 8), - "destination_batch_index": float(destination_batch), - "port_batch_index": float(port_batch), - "src_name": f"client{source}", - "dst_name": f"client{destination}", - "rtt_ports_active": 4, - "rtt_ports_total": 16, - "local_probe_errors": 0, - } - ) - - audit = _coverage_detector(client_count).summarize_coverage(rows) - - assert audit["coverage_status"] == "complete" - assert audit["expected_epoch_cycles"] == 32 - assert audit["destination_pairs_observed"] == 16_256 - assert audit["pair_port_combinations_observed"] == 65_024 + assert len(detector._pingmesh_plan.settings.port_batches) == 4 + assert detector._pingmesh_plan.settings.coverage_epoch_cycles == 20 + assert detector._pingmesh_plan.directed_pair_count == 16512 def test_coverage_rejects_incomplete_socket_pool(): detector = _coverage_detector(2) rows = [ { + "plan_id": detector.plan_id, "probe_cycle": float(port_batch), "destination_batch_index": 0.0, "port_batch_index": float(port_batch), @@ -713,12 +749,15 @@ def test_coverage_rejects_incomplete_socket_pool(): assert audit["coverage_status"] == "incomplete" assert audit["invalid_socket_rows"] == 1 + assert audit["invalid_rows"][0]["local_probe_errors"] == 0 + assert audit["invalid_rows"][0]["socket_batch_valid"] is False def test_coverage_accepts_smaller_final_port_batch(): detector = _coverage_detector(2, rtt_ports_per_cycle=6) rows = [ { + "plan_id": detector.plan_id, "probe_cycle": float(port_batch), "destination_batch_index": 0.0, "port_batch_index": float(port_batch), @@ -741,6 +780,7 @@ def test_coverage_accepts_smaller_final_port_batch(): def _coverage_row(source: str, destination: str, port_batch: int, *, probe_cycle: int | None = None) -> dict: return { + "plan_id": _coverage_detector(2).plan_id, "probe_cycle": float(port_batch if probe_cycle is None else probe_cycle), "destination_batch_index": 0.0, "port_batch_index": float(port_batch), @@ -773,140 +813,8 @@ def test_coverage_rejects_local_probe_errors(): assert audit["coverage_status"] == "incomplete" assert audit["invalid_socket_rows"] == 1 - - -def test_coverage_accepts_df_send_error_explained_by_strong_rtt_loss(): - detector = _coverage_detector(2) - rows = _complete_coverage_rows( - { - ("client1", 0): { - "packets_lost": 3, - "df_mtu_drops": 15, - "local_probe_errors": 15, - } - } - ) - - audit = detector.summarize_coverage(rows) - - assert audit["coverage_status"] == "complete" - assert audit["invalid_socket_rows"] == 0 - - -def test_coverage_accepts_transition_df_error_with_full_window_socket_batch_loss(): - detector = _coverage_detector(2) - rows = _complete_coverage_rows( - { - ("client1", 0): { - "packets_lost": 1, - "df_mtu_drops": 15, - "local_probe_errors": 15, - } - } - ) - followup = _coverage_row("client1", "client2", 0, probe_cycle=4) - followup["packets_lost"] = 2 - rows.append(followup) - - audit = detector.summarize_coverage(rows) - - assert audit["coverage_status"] == "complete" - assert audit["invalid_socket_rows"] == 0 - - -def test_coverage_does_not_use_loss_from_another_socket_batch_to_explain_df_error(): - detector = _coverage_detector(2) - rows = _complete_coverage_rows( - { - ("client1", 0): { - "packets_lost": 1, - "df_mtu_drops": 15, - "local_probe_errors": 15, - }, - ("client1", 1): {"packets_lost": 4}, - } - ) - - audit = detector.summarize_coverage(rows) - - assert audit["coverage_status"] == "incomplete" - assert audit["invalid_socket_rows"] == 1 - - -def test_coverage_rejects_df_send_error_without_strong_rtt_loss(): - detector = _coverage_detector(2) - - def audit_for(*, lost: int, local_errors: int, df_mtu_drops: int) -> dict: - rows = _complete_coverage_rows( - { - ("client1", 0): { - "packets_lost": lost, - "df_mtu_drops": df_mtu_drops, - "local_probe_errors": local_errors, - } - } - ) - return detector.summarize_coverage(rows) - - for audit in ( - audit_for(lost=2, local_errors=15, df_mtu_drops=15), - audit_for(lost=0, local_errors=15, df_mtu_drops=15), - audit_for(lost=3, local_errors=16, df_mtu_drops=15), - ): - assert audit["coverage_status"] == "incomplete" - assert audit["invalid_socket_rows"] == 1 - - -def test_pingmesh_coverage_summary_reports_missing_batches(): - detector = _coverage_detector() - rows = [ - { - "probe_cycle": float(index), - "destination_batch_index": float(index % 8), - "port_batch_index": float(index % 3), - "src_name": "client1", - "dst_name": "client2", - } - for index in range(10) - ] - audit = detector.summarize_coverage(rows) - - assert audit["coverage_status"] == "incomplete" - assert audit["missing_destination_batches"] == [8] - assert audit["missing_port_batches"] == [3] - assert audit["missing_source_clients"] == 143 - - -def test_pingmesh_time_scope_uses_explicit_window_first(monkeypatch): - toolkit, captured = _toolkit_with_captured_queries(monkeypatch) - toolkit.set_pingmesh_time_window("2026-01-01T00:00:00Z", "2026-01-01T00:01:00Z") - - result = toolkit.get_pingmesh_summary( - time_range_minutes=10, - start_time="2026-01-02T00:00:00Z", - end_time="2026-01-02T00:01:00Z", - ) - - assert result.success is True - assert result.data["time_scope"]["source"] == "explicit" - assert 'range(start: time(v: "2026-01-02T00:00:00Z")' in captured["query"] - - -def test_pingmesh_time_scope_uses_toolkit_default_before_context_file(monkeypatch, tmp_path): - context_file = tmp_path / "pingmesh-window.json" - context_file.write_text( - json.dumps({"start_time": "2026-01-03T00:00:00Z", "end_time": "2026-01-03T00:01:00Z"}), - encoding="utf-8", - ) - monkeypatch.setenv("NETOPSBENCH_PINGMESH_CONTEXT_FILE", str(context_file)) - toolkit, captured = _toolkit_with_captured_queries(monkeypatch) - toolkit.set_pingmesh_time_window("2026-01-02T00:00:00Z", "2026-01-02T00:01:00Z") - - result = toolkit.get_pingmesh_hotspots() - - assert result.success is True - assert result.data["time_scope"]["source"] == "toolkit_default" - assert 'range(start: time(v: "2026-01-02T00:00:00Z")' in captured["query"] + assert audit["invalid_rows"][0]["local_probe_errors"] == 1 + assert audit["invalid_rows"][0]["socket_batch_valid"] is True def test_pingmesh_hotspots_applies_global_loss_first_limit(monkeypatch): @@ -950,50 +858,6 @@ def test_pingmesh_hotspots_queries_only_raw_leaf_pair_data(monkeypatch): assert "pingmesh_leaf_pair_30s" not in captured["query"] -def test_pingmesh_time_scope_uses_context_file_before_env(monkeypatch, tmp_path): - context_file = tmp_path / "pingmesh-window.json" - context_file.write_text( - json.dumps({"start_time": "2026-01-03T00:00:00Z", "end_time": "2026-01-03T00:01:00Z"}), - encoding="utf-8", - ) - monkeypatch.setenv("NETOPSBENCH_PINGMESH_CONTEXT_FILE", str(context_file)) - monkeypatch.setenv("NETOPSBENCH_PINGMESH_START_TIME", "2026-01-04T00:00:00Z") - monkeypatch.setenv("NETOPSBENCH_PINGMESH_END_TIME", "2026-01-04T00:01:00Z") - toolkit, captured = _toolkit_with_captured_queries(monkeypatch) - - result = toolkit.get_pingmesh_summary() - - assert result.success is True - assert result.data["time_scope"]["source"] == "context_file" - assert 'range(start: time(v: "2026-01-03T00:00:00Z")' in captured["query"] - - -def test_pingmesh_time_scope_uses_env_before_rolling(monkeypatch): - monkeypatch.setenv("NETOPSBENCH_PINGMESH_START_TIME", "2026-01-04T00:00:00Z") - monkeypatch.setenv("NETOPSBENCH_PINGMESH_END_TIME", "2026-01-04T00:01:00Z") - toolkit, captured = _toolkit_with_captured_queries(monkeypatch) - - result = toolkit.get_pingmesh_summary() - - assert result.success is True - assert result.data["time_scope"]["source"] == "env" - assert 'range(start: time(v: "2026-01-04T00:00:00Z")' in captured["query"] - - -def test_pingmesh_time_scope_falls_back_to_rolling(monkeypatch): - toolkit, captured = _toolkit_with_captured_queries(monkeypatch) - - result = toolkit.get_pingmesh_summary(time_range_minutes=7) - - assert result.success is True - assert result.data["time_scope"] == { - "mode": "rolling", - "source": "time_range_minutes", - "time_range_minutes": 7, - } - assert "|> range(start: -7m)" in captured["query"] - - def test_fastmcp_pingmesh_tools_pass_absolute_window(monkeypatch): calls = {} @@ -1008,15 +872,21 @@ def get_pingmesh_hotspots(self, **kwargs): monkeypatch.setattr(mcp_context, "_toolkit", FakeToolkit()) - assert fastmcp_server.get_pingmesh_summary( - start_time="2026-01-01T00:00:00Z", - end_time="2026-01-01T00:01:00Z", - ) == {"ok": "summary"} - assert fastmcp_server.get_pingmesh_hotspots( - limit=3, - start_time="2026-01-01T00:00:00Z", - end_time="2026-01-01T00:01:00Z", - ) == {"ok": "hotspots"} + assert ( + fastmcp_server.get_pingmesh_summary( + start_time="2026-01-01T00:00:00Z", + end_time="2026-01-01T00:01:00Z", + )["ok"] + == "summary" + ) + assert ( + fastmcp_server.get_pingmesh_hotspots( + limit=3, + start_time="2026-01-01T00:00:00Z", + end_time="2026-01-01T00:01:00Z", + )["ok"] + == "hotspots" + ) assert calls["summary"]["start_time"] == "2026-01-01T00:00:00Z" assert calls["summary"]["end_time"] == "2026-01-01T00:01:00Z" assert calls["hotspots"]["limit"] == 3 @@ -1066,6 +936,7 @@ def __init__(self, **kwargs): captured.update(kwargs) def generate_windowed_anomaly_report(self, **_kwargs): + captured["query_deadline"] = _kwargs.get("deadline") return { "summary": {"total_anomalies": 0}, "query_status": {"ok": True, "error": None}, @@ -1074,7 +945,10 @@ def generate_windowed_anomaly_report(self, **_kwargs): } monkeypatch.setattr("netopsbench.platform.pingmesh.detector.AnomalyDetector", FakeDetector) - runner = SimpleNamespace( + from netopsbench.platform.scenario.executor import ScenarioExecutor + + runner = ScenarioExecutor( + topology_dir=str(tmpdir), influxdb_url="http://influxdb:8086", influxdb_token="token", influxdb_org="org", @@ -1083,11 +957,77 @@ def generate_windowed_anomaly_report(self, **_kwargs): topology_metadata=topology, ) - observations = wait_and_observe( + deadline = time.monotonic() + 10 + observations = analyze_observation_windows( runner, - duration=0, + [capture_observation_window(runner, 0, name="steady", deadline=deadline)], + total_duration_seconds=0, baseline_window={"start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:01:00Z"}, + deadline=deadline, ) assert observations["data_source_status"] == "ok" - assert captured["topology_metadata"] == topology + assert captured["topology_metadata"] is runner.manifest + assert captured["query_deadline"] == deadline + + +@pytest.mark.parametrize( + "lost,local_errors,extra", + [ + pytest.param(3, 15, None, id="strong-rtt-loss"), + pytest.param(1, 15, "later", id="later-valid-sample"), + pytest.param(1, 15, "other-batch", id="other-socket-batch"), + pytest.param(2, 15, None, id="weak-rtt-loss"), + pytest.param(0, 15, None, id="no-rtt-loss"), + pytest.param(3, 16, None, id="additional-local-error"), + ], +) +def test_df_local_errors_remain_incomplete(lost, local_errors, extra): + detector = _coverage_detector(2) + overrides = {("client1", 0): {"packets_lost": lost, "df_mtu_drops": 15, "local_probe_errors": local_errors}} + if extra == "other-batch": + overrides[("client1", 1)] = {"packets_lost": 4} + rows = _complete_coverage_rows(overrides) + if extra == "later": + rows.append({**_coverage_row("client1", "client2", 0, probe_cycle=4), "packets_lost": 2}) + audit = detector.summarize_coverage(rows) + assert audit["coverage_status"] == "incomplete" + assert audit["invalid_socket_rows"] == 1 + + +@pytest.mark.parametrize( + "source,day", + [ + ("explicit", 1), + ("toolkit_default", 2), + ("context_file", 3), + ("env", 4), + ("time_range_minutes", 5), + ], +) +def test_pingmesh_window_precedence(monkeypatch, tmp_path, source, day): + toolkit, captured = _toolkit_with_captured_queries(monkeypatch) + + def window(day): + return {"start_time": f"2026-01-0{day}T00:00:00Z", "end_time": f"2026-01-0{day}T00:01:00Z"} + + for name in ("CONTEXT_FILE", "START_TIME", "END_TIME"): + monkeypatch.delenv(f"NETOPSBENCH_PINGMESH_{name}", raising=False) + if day <= 4: + for key, value in window(4).items(): + monkeypatch.setenv(f"NETOPSBENCH_PINGMESH_{key.upper()}", value) + if day <= 3: + context = tmp_path / "window.json" + context.write_text(json.dumps(window(3))) + monkeypatch.setenv("NETOPSBENCH_PINGMESH_CONTEXT_FILE", str(context)) + if day <= 2: + toolkit.set_pingmesh_time_window(**window(2)) + query = toolkit.get_pingmesh_hotspots if source == "toolkit_default" else toolkit.get_pingmesh_summary + result = query(time_range_minutes=7, **(window(1) if source == "explicit" else {})) + assert result.success is True + assert result.data["time_scope"]["source"] == source + if day < 5: + assert f'range(start: time(v: "{window(day)["start_time"]}")' in captured["query"] + else: + assert result.data["time_scope"] == {"mode": "rolling", "source": source, "time_range_minutes": 7} + assert "|> range(start: -7m)" in captured["query"] diff --git a/tests/test_platform_fault_active_faults.py b/tests/test_platform_fault_active_faults.py index d016f57..ac21615 100644 --- a/tests/test_platform_fault_active_faults.py +++ b/tests/test_platform_fault_active_faults.py @@ -3,13 +3,22 @@ import json import tempfile import time +from types import SimpleNamespace from unittest.mock import patch +import pytest + from netopsbench.platform.faults.injector import FaultInjector from netopsbench.platform.faults.models import ActiveFault from netopsbench.platform.topology.generator import generate_topology +@pytest.fixture(autouse=True) +def mocked_runtime_tools(monkeypatch, tmp_path): + # These transaction tests mock every command; toolchain validation has its own tests. + monkeypatch.setattr("netopsbench.platform.faults.handlers.system.runtime_tools", lambda: tmp_path) + + def _metadata() -> dict: with tempfile.TemporaryDirectory() as tmpdir: return generate_topology("xs", tmpdir)["metadata"] @@ -92,8 +101,9 @@ def test_link_flapping_uses_python_background_control_metadata(): states, _commands = _stub_link_state(injector) - fault = injector.inject_link_flapping(device="spine1", interface="Ethernet0", iterations=1, down_time=0, up_time=0) - time.sleep(0.01) + fault = injector.inject_link_flapping(device="spine1", interface="Ethernet0", down_time=0.01, up_time=0.01) + time.sleep(0.015) + injector.recover_all() assert fault["type"] == "link_flapping" assert fault["orchestration"] == "python" @@ -104,6 +114,44 @@ def test_link_flapping_uses_python_background_control_metadata(): assert states[("clab-dcn-leaf1", "eth1")] == "up" +@pytest.mark.parametrize("enabled", [False, True]) +@pytest.mark.parametrize("converges", [False, True]) +def test_link_admin_readback_waits_for_async_sonic_state_with_a_deadline(monkeypatch, enabled, converges): + from netopsbench.platform.faults.handlers import link + + injector = FaultInjector(topology_metadata=_metadata()) + clock, reads, mutations = [0.0], [], [] + + def sleep(delay): + clock[0] += delay + + def configure(device, commands): + mutations.append(commands) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + def read(container, commands, *, timeout): + assert commands == ["ip", "-o", "link", "show", "dev", "eth1"] + assert clock[0] < 3 + assert 0 < timeout <= 3 - clock[0] + reads.append(timeout) + applied = enabled if converges and len(reads) >= 3 else not enabled + flags = "BROADCAST,MULTICAST,UP" if applied else "BROADCAST,MULTICAST" + return SimpleNamespace(returncode=0, stdout=f"1: eth1: <{flags}>", stderr="") + + monkeypatch.setattr(link, "time", SimpleNamespace(monotonic=lambda: clock[0], sleep=sleep)) + monkeypatch.setattr(injector._sonic, "config_cmd", configure) + monkeypatch.setattr(injector._cmd, "docker_exec", read) + result = injector._link._set_link_admin_state("spine1", "clab-dcn-spine1", "Ethernet0", "eth1", enabled=enabled) + assert result["success"] is converges + assert mutations == [["interface", "startup" if enabled else "shutdown", "Ethernet0"]] + if converges: + assert len(reads) == 3 + assert clock[0] < 3 + else: + assert clock[0] == 3 + assert result["error"] + + def test_link_flapping_recovery_verifies_both_physical_endpoints(): injector = FaultInjector(topology_metadata=_metadata()) states, _commands = _stub_link_state(injector) @@ -111,7 +159,6 @@ def test_link_flapping_recovery_verifies_both_physical_endpoints(): injector.inject_link_flapping( device="spine1", interface="Ethernet0", - iterations=10, down_time=10, up_time=10, ) @@ -123,6 +170,7 @@ def test_link_flapping_recovery_verifies_both_physical_endpoints(): "device": "spine1", "interface": "Ethernet0", "recovered": True, + "readback_verified": True, "error": None, } ] @@ -249,6 +297,7 @@ def docker_exec(container, command, **kwargs): def test_device_down_uses_containerlab_node_stop(): injector = FaultInjector(topology_metadata=_metadata()) + injector._system._cmd.container_is_running = lambda _container: True calls = [] result = type("R", (), {"returncode": 0, "stderr": "", "stdout": "spine1"})() injector._system._cmd.run_cmd = lambda command, **_kwargs: calls.append(command) or result diff --git a/tests/test_platform_toolkit_fastmcp.py b/tests/test_platform_toolkit_fastmcp.py index b883b98..105aa40 100644 --- a/tests/test_platform_toolkit_fastmcp.py +++ b/tests/test_platform_toolkit_fastmcp.py @@ -20,8 +20,8 @@ def get_topology(self): first = server.get_topology() second = server.get_topology() - assert first == {"ok": True} - assert second == {"ok": True} + assert first["ok"] is True and first["collected_at"] + assert second["ok"] is True and second["collected_at"] assert FakeToolkit.init_count == 1 diff --git a/tests/test_private_impairment_audit.py b/tests/test_private_impairment_audit.py new file mode 100644 index 0000000..73f7fc9 --- /dev/null +++ b/tests/test_private_impairment_audit.py @@ -0,0 +1,76 @@ +"""Impairment configuration stays in private validation, outside agent tools.""" + +import json +import subprocess +from types import SimpleNamespace + +import pytest + +from netopsbench.models.scenario import EpisodeSpec +from netopsbench.platform.scenario.effects import validate_effect +from netopsbench.platform.toolkit._core.common import ToolResult +from netopsbench.platform.topology.clos_builder import build_clos_plan +from netopsbench.platform.topology.config import config_for_scale + + +@pytest.mark.parametrize("fault", ["packet_loss", "packet_corruption", "high_latency"]) +@pytest.mark.parametrize("collection", ["ok", "failed", "invalid_json"]) +def test_impairment_effect_uses_private_qdisc_collection(monkeypatch, fault, collection): + manifest = build_clos_plan(config_for_scale("medium")).manifest + pair = {"src": "client1", "dst": "client3"} + episode = EpisodeSpec( + episode_id="audit", + fault_type=fault, + target_device="leaf1", + target_interface="Ethernet0", + parameters={"affected_candidates": [pair]}, + ) + calls = [] + + def interfaces(device, interface): + # No include_tc keyword is accepted, even for internal validation. + assert device == "leaf1" and interface == "Ethernet0" + return ToolResult(success=True, data={"interfaces": []}) + + def run(container, args): + calls.append((container, args)) + return subprocess.CompletedProcess( + args, + 1 if collection == "failed" else 0, + stdout="invalid" if collection == "invalid_json" else json.dumps([{"kind": "netem"}]), + stderr="unavailable" if collection == "failed" else "", + ) + + toolkit = SimpleNamespace( + get_device_status=lambda device: ToolResult(success=True, data={"running": True, "accessible": True}), + get_device_interfaces=interfaces, + ) + monkeypatch.setattr("netopsbench.platform.scenario.effects.AgentToolkit", lambda **kw: toolkit) + executor = SimpleNamespace( + current_manifest=lambda: manifest, + influxdb_bucket="worker", + topology_id=manifest.topology_id, + injector=SimpleNamespace( + _iface=SimpleNamespace(resolve_sonic=lambda name: name, resolve_linux=lambda name: "eth1"), + _cmd=SimpleNamespace(docker_exec=run), + container_names={"leaf1": "worker-leaf1"}, + ), + _case_affected_pairs=[pair], + ) + probes = [ + { + **pair, + "baseline": {"samples": 20, "regular": {"lost": 0, "loss_pct": 0}, "rtt_max_ms": 1}, + "fault": {"samples": 20, "regular": {"lost": 5, "loss_pct": 25}, "rtt_max_ms": 150}, + } + ] + result = validate_effect( + executor, episode, {"observations": {"_probe_evidence": probes}}, {"nodes": {}}, {"nodes": {}} + ) + assert calls == [("worker-leaf1", ["tc", "-s", "-j", "qdisc", "show", "dev", "eth1"])] + assert result["valid"] is (collection == "ok") + assert "qdisc" not in result["evidence"]["interface"]["data"] + if collection == "ok": + assert result["evidence"]["qdisc"]["rows"] == [{"kind": "netem"}] + else: + assert any("Private qdisc collection failed" in error for error in result["errors"]) diff --git a/tests/test_recovery_migration.py b/tests/test_recovery_migration.py new file mode 100644 index 0000000..27b306b --- /dev/null +++ b/tests/test_recovery_migration.py @@ -0,0 +1,91 @@ +"""Recovery v3 is explicit and cannot rewrite frozen source campaigns.""" + +import json +from types import SimpleNamespace + +import pytest + +from netopsbench.models.recovery import RecoveryPolicy +from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec +from netopsbench.platform.scenario.migration import migrate_recovery +from netopsbench.platform.scenario.parser import parse_scenario_file, save_scenario_file +from netopsbench.platform.session.orchestrator import SessionOrchestrator + + +def legacy(): + return ScenarioSpec( + scenario_id="original", + name="original", + topology_scale="xs", + episode=EpisodeSpec(episode_id="diagnosis", fault_type="none"), + metadata={"negative_sample": True, "experiment": {"observation_seconds": 30}}, + ) + + +@pytest.mark.parametrize("source_version", [None, 2]) +def test_migration_preserves_case_and_source_and_changes_identity(tmp_path, source_version): + source = tmp_path / "frozen" + case = legacy() + if source_version is not None: + case.metadata["recovery_policy"] = { + "version": source_version, + "baseline_max_cases": 10, + "baseline_max_age_seconds": 600, + } + path = save_scenario_file(case, source / "healthy.yaml") + original = path.read_bytes() + output = migrate_recovery(source, tmp_path / "new") + migrated = parse_scenario_file(output / "healthy.yaml") + assert path.read_bytes() == original + assert migrated.id == case.id and migrated.episode == case.episode + assert migrated.metadata["experiment"] == case.metadata["experiment"] + assert migrated.digest != case.digest + assert RecoveryPolicy.from_metadata(migrated.metadata) == RecoveryPolicy() + receipt = json.loads((output / "migration.json").read_text()) + assert receipt["sources"][0]["scenario_digest"] == case.digest + assert migrated.metadata["recovery_migration"]["campaign_id"] == receipt["campaign_id"] + with pytest.raises(ValueError, match="new output"): + migrate_recovery(source, output) + with pytest.raises(ValueError, match="outside"): + migrate_recovery(source, source / "nested") + + +@pytest.mark.parametrize( + "policy", + [ + None, + {"version": 1}, + {"version": 2}, + {"version": 2, "baseline_max_age_seconds": 600}, + {"mode": "full_window"}, + {"version": 3, "baseline_max_age_seconds": 600}, + ], +) +def test_old_policy_rejected_before_deployment(tmp_path, monkeypatch, policy): + session = SessionOrchestrator(workspace=str(tmp_path)) + case = legacy() + if policy is not None: + case.metadata["recovery_policy"] = policy + monkeypatch.setattr(session, "_provision_runtime", lambda **kw: pytest.fail("must validate before provisioning")) + with pytest.raises(ValueError): + session.run_scenario(scenario=case, agent=SimpleNamespace()) + + +def test_failed_migration_does_not_create_destination(tmp_path): + source = tmp_path / "source" + save_scenario_file(legacy(), source / "good.yaml") + (source / "bad.yaml").write_text("invalid: true") + with pytest.raises(ValueError): + migrate_recovery(source, tmp_path / "new") + assert not (tmp_path / "new").exists() + + +def test_cli_migration_writes_a_new_campaign(tmp_path, monkeypatch): + from netopsbench.cli.main import main + + save_scenario_file(legacy(), tmp_path / "old.yaml") + monkeypatch.setattr( + "sys.argv", ["netopsbench", "--workspace", str(tmp_path), "scenario", "migrate", "old.yaml", "--out", "new"] + ) + assert main() == 0 + assert RecoveryPolicy.from_metadata(parse_scenario_file(tmp_path / "new" / "old.yaml").metadata).version == 3 diff --git a/tests/test_recovery_reporting.py b/tests/test_recovery_reporting.py new file mode 100644 index 0000000..77bc32f --- /dev/null +++ b/tests/test_recovery_reporting.py @@ -0,0 +1,54 @@ +import csv +from datetime import UTC, datetime +from pathlib import Path +from types import SimpleNamespace + +from netopsbench.models.profiles import default_scale_registry +from netopsbench.platform.session.reporting import create_run_report + + +def test_nested_recovery_timings_preserve_phase_csv_and_export_steps(tmp_path): + step = { + "status": "completed", + "actual_seconds": 10, + "calls": 1, + "failed_calls": 0, + "ingestion": {"baseline": {"query_requests": 21}, "current": {"query_requests": 21}}, + } + phase = { + "status": "completed", + "actual_seconds": 80, + "timeout_seconds": 600, + "steps": {"window_query": step}, + } + runtime = SimpleNamespace(id="runtime", scale="medium", scale_registry=default_scale_registry()) + now = datetime.now(UTC) + report = create_run_report( + run_id="test", + mode="effects", + started_at=now, + completed_at=now, + runtime=runtime, + runtime_owner="external", + teardown="never", + scenarios=[], + agent=None, + worker_summaries=[], + scenario_summaries=[{"scenario_id": "case", "scale": "medium", "phase_timings": {"recovery": phase}}], + aggregate_report={}, + artifact_dir=tmp_path, + raw_dir=tmp_path / "raw", + report_path=tmp_path / "report.json", + metadata_path=tmp_path / "metadata.json", + ) + with Path(report["artifact_paths"]["phase_timings"]).open() as handle: + phases = list(csv.DictReader(handle)) + assert len(phases) == 1 + assert phases[0]["phase"] == "recovery" + assert phases[0]["actual_seconds"] == "80" + assert "steps" not in phases[0] + with Path(report["artifact_paths"]["recovery_steps"]).open() as handle: + steps = list(csv.DictReader(handle)) + assert len(steps) == 1 + assert steps[0]["actual_seconds"] == "10" + assert steps[0]["baseline_query_requests"] == steps[0]["current_query_requests"] == "21" diff --git a/tests/test_route_parser_and_static_route.py b/tests/test_route_parser_and_static_route.py index 8be8a9a..33e9265 100644 --- a/tests/test_route_parser_and_static_route.py +++ b/tests/test_route_parser_and_static_route.py @@ -1,4 +1,3 @@ -import random import subprocess import tempfile from datetime import UTC, datetime, timedelta @@ -8,7 +7,6 @@ from netopsbench.platform.faults.injector import FaultInjector from netopsbench.platform.observability.bgp_parser import parse_bgp_summary from netopsbench.platform.observability.influxdb import FluxQueryResult -from netopsbench.platform.scenario import generator as _generate_scenarios_mod from netopsbench.platform.toolkit._core.device.route_parsers import parse_route_table from netopsbench.platform.toolkit._core.device.telemetry_parsers import ( parse_influx_metric_rows, @@ -115,30 +113,6 @@ def test_parse_route_table_preserves_blackhole_discard_kind(): assert routes[0]["discard_interface"] == "blackhole" -def test_build_fault_instance_static_route_targets_remote_client(tmp_path): - gs = _generate_scenarios_mod - topology_dir = tmp_path / "topology" - generate_topology("xs", str(topology_dir)) - topo = gs.load_topology("xs", str(topology_dir)) - template = {"name": "static_route_misconfig", "device_role": "leaf", "severity": "medium"} - defaults = {"seed": 42} - - scenario = gs.build_fault_instance( - "static_route_misconfig", - "hard", - topo, - random.Random(1), - defaults, - template, - 1, - ) - - episode = scenario["episode"] - assert episode["target_device"] == "leaf1" - assert episode["metadata"]["target_ip"] == "192.168.102.2/32" - assert episode["metadata"]["wrong_nexthop"] == "auto" - - def test_recover_static_route_misconfig_prefers_specific_nexthop(monkeypatch): injector = FaultInjector(topology_metadata=_metadata()) injector.active_faults = [ @@ -193,34 +167,36 @@ def test_inject_static_route_misconfig_auto_uses_topology_clients(monkeypatch): class Result: returncode = 0 stderr = "" - stdout = "ip route 192.168.102.2/32 192.168.101.2\n" + stdout = "ip route 192.168.2.2/32 192.168.1.2\n" captured = [] def fake_vtysh(device, commands): if commands == ["show running-config"]: return Result() - if commands == ["show ip route 192.168.102.2/32"]: + if commands == ["show ip route 192.168.2.2/32"]: return Result() captured.append((device, commands)) return Result() monkeypatch.setattr(injector._static_route._sonic, "vtysh", fake_vtysh) + monkeypatch.setattr(injector._static_route, "_running_config_has_route", lambda *args: False) + monkeypatch.setattr(injector._cmd, "docker_exec", lambda *a, **k: subprocess.CompletedProcess(a, 0, stdout="0")) result = injector.inject_static_route_misconfig( device="leaf1", - target_ip="192.168.102.2/32", + target_ip="192.168.2.2/32", wrong_nexthop="auto", ) assert result["success"] is True - assert result["wrong_nexthop"] == "192.168.101.2" + assert result["wrong_nexthop"] == "192.168.1.2" assert captured == [ ( "leaf1", [ "configure terminal", - "ip route 192.168.102.2/32 192.168.101.2", + "ip route 192.168.2.2/32 192.168.1.2", "end", "write memory", ], @@ -322,6 +298,7 @@ def fake_docker_exec(_container, command, timeout=30): monkeypatch.setattr(injector._impairment._cmd, "docker_exec", fake_docker_exec) + monkeypatch.setattr(injector._impairment, "_require_default_qdisc", lambda *args: None) result = injector.inject_packet_loss("spine1", "Ethernet0", loss_pct=10.0) assert result["success"] is True diff --git a/tests/test_runtime_agent_input_contract.py b/tests/test_runtime_agent_input_contract.py index 23fd732..18ce18d 100644 --- a/tests/test_runtime_agent_input_contract.py +++ b/tests/test_runtime_agent_input_contract.py @@ -1,3 +1,5 @@ +import pytest + from netopsbench.platform.incident.context import ( build_canonical_observation, build_public_case_id, @@ -115,7 +117,7 @@ def test_build_public_symptoms_strips_fault_injection_labels(): ) episode = payload["episode"] - assert episode["episode_id"] == "ep002_fault" + assert "episode_id" not in episode assert episode["duration_seconds"] == 30 assert episode["stabilization_time"] == 5 assert "fault_type" not in episode @@ -123,6 +125,158 @@ def test_build_public_symptoms_strips_fault_injection_labels(): assert "target_interface" not in episode +@pytest.mark.parametrize("total_anomalies", [0, 3]) +def test_initial_context_only_exposes_pingmesh_and_window_metadata(total_anomalies): + from copy import deepcopy + + public = { + "start_time": "2026-01-01T00:00:00Z", + "end_time": "2026-01-01T00:00:30Z", + "duration_seconds": 30, + "pingmesh_metrics": {"summary": {"total_anomalies": total_anomalies}}, + "anomalies_detected": bool(total_anomalies), + "coverage_status": "complete", + "data_source_status": "ok", + "observation_windows": [{"name": "steady", "duration_seconds": 20}], + } + observations = { + **public, + "route_observations": {"changes": [{"device": "core4", "route_type": "blackhole"}]}, + "bgp_observations": {"device": "agg16", "state": "Idle"}, + "device_status": {"spine4": {"running": False}}, + "interface_observations": {"leaf2": {"Ethernet0": "down"}}, + "acl_observations": {"device": "edge1", "hits": 10}, + "future_device_summary": {"root": "answer"}, + "_probe_evidence": [{"root": "answer"}], + } + original = deepcopy(observations) + window = {"start_time": public["start_time"], "end_time": public["end_time"]} + symptoms = build_public_symptoms(episode_result={"observations": observations}, pingmesh_query_window=window) + assert symptoms["observations"] == public + assert symptoms["pingmesh_query_window"] == window + + # The canonical helper is also public: callers can bypass build_public_symptoms. + canonical = build_canonical_observation( + case_id="case-anonymous", + topology={}, + symptoms={"observations": observations, "pingmesh_query_window": window}, + ) + assert canonical["symptoms"]["observations"] == public + assert observations == original + symptoms["observations"]["pingmesh_metrics"]["summary"]["total_anomalies"] = 99 + assert observations == original + + +@pytest.mark.parametrize("fault_type", ["none", "blackhole_route", "ecmp_misconfig"]) +def test_incident_keeps_route_validation_private_and_supports_explicit_route_queries(monkeypatch, fault_type): + from types import SimpleNamespace + + from netopsbench.models.scenario import EpisodeSpec + from netopsbench.platform.incident.contracts import ToolAction + from netopsbench.platform.scenario import effects, incident_backend + from netopsbench.platform.scenario.timing import PhaseTimings + from netopsbench.platform.toolkit._core.common import ToolResult + + baseline = {"nodes": {"core4": {"fib": [{"dst": "192.168.49.0/30", "gateway": "10.0.0.1"}]}}} + current = {"nodes": {"core4": {"fib": [{"dst": "192.168.49.2/32", "type": "blackhole"}]}}} + snapshots = iter([baseline, current]) + monkeypatch.setattr("netopsbench.platform.observability.routes.collect_routes", lambda *a, **kw: next(snapshots)) + manifest = SimpleNamespace( + require_pingmesh_plan=lambda: SimpleNamespace(settings=SimpleNamespace(complete_window_seconds=30)) + ) + episode = EpisodeSpec(episode_id="diagnosis", fault_type=fault_type, target_device="core4") + observations = {"pingmesh_metrics": {"summary": {"total_anomalies": 0}}} + result = {"episode": episode.model_dump(), "observations": observations} + monkeypatch.setattr(incident_backend, "observe_episode", lambda *a, **kw: result) + audit = {"valid": True, "errors": []} + + def validate(executor, ep, episode_result, before, after): + assert before is baseline and after is current + assert episode_result["route_evidence"] == {"baseline": baseline, "fault": current} + return audit + + monkeypatch.setattr(effects, "validate_effect", validate) + monkeypatch.setattr(effects, "scoped_integrity_errors", lambda *a: []) + + class Toolkit: + def __init__(self, **kwargs): + pass + + def get_topology(self): + return ToolResult(True, {"devices": {"cores": [{"name": "core4"}]}}) + + def set_pingmesh_time_window(self, start, end): + pass + + def get_route_table(self, device, *, view): + assert view == "kernel" + return ToolResult(True, current["nodes"][device]["fib"]) + + monkeypatch.setattr(incident_backend, "AgentToolkit", Toolkit) + from netopsbench.models.recovery import RecoveryPolicy + from netopsbench.platform.scenario.baseline import BaselineHandoff + + executor = SimpleNamespace( + recovery_policy=RecoveryPolicy(), + topology_dir="unused", + _traffic_config=None, + _cancel_event=None, + _baseline_handoff=BaselineHandoff(), + _baseline_scope=lambda scenario: None, + topology_metadata={}, + injector=SimpleNamespace(active_faults=[]), + traffic_controller=SimpleNamespace(active_flows={"flow": 1}, verify_active_flows=lambda: True), + runtime_worker=None, + minimum_baseline_seconds=30, + observation_timeout_seconds=60, + _capture_baseline_window=lambda: {"duration_seconds": 30}, + _merge_observation_windows=lambda *a, **kw: { + "start_time": "2026-07-11T00:00:00Z", + "end_time": "2026-07-11T00:00:30Z", + "duration_seconds": 30, + }, + current_manifest=lambda: manifest, + timings=PhaseTimings(), + scale_registry=SimpleNamespace(get=lambda scale: SimpleNamespace(health_timeout_seconds=60)), + influxdb_bucket="bucket", + topology_id="topology", + ) + from datetime import UTC, datetime, timedelta + + from netopsbench.platform.scenario.baseline import RuntimeScope + + scope = RuntimeScope({}, {}, {}) + executor._baseline_scope = lambda _: scope + executor.calibrate = lambda case, reason: executor._baseline_handoff.publish( + { + "start_time": (datetime.now(UTC) - timedelta(seconds=30)).isoformat(), + "end_time": datetime.now(UTC).isoformat(), + "duration_seconds": 30, + }, + scope, + case.id, + 30, + verified=True, + ) + backend = incident_backend.ExecutorIncidentBackend(executor) + canonical = backend.prepare( + SimpleNamespace( + id="private-case", + scale="medium", + episode=episode, + metadata={"fault_catalog_version": 2, "recovery_policy": {"version": 3}}, + ) + ) + assert backend.symptoms["observations"] == observations + assert canonical["symptoms"]["observations"] == observations + assert result["route_evidence"] == {"baseline": baseline, "fault": current} + assert result["effect_audit"] is audit + assert "route_observations" not in result["observations"] + queried = backend.call_tool(ToolAction(name="get_route_table", arguments={"device": "core4", "view": "kernel"})) + assert queried["success"] + assert queried["data"] == current["nodes"]["core4"]["fib"] + + def test_build_public_case_id_is_non_semantic_and_stable(): episode_result = {"episode": {"episode_id": "ep002_fault"}} @@ -192,3 +346,77 @@ def test_canonical_observation_compacts_without_changing_public_symptoms(): assert compacted["truncated"] is True assert "aggregated_anomalies" not in compacted assert len(symptoms["observations"]["pingmesh_metrics"]["anomalies"]) == 20 + + +def test_agent_success_false_survives_runtime_callback(tmp_path): + from types import SimpleNamespace + + from netopsbench.platform.session.diagnosis import build_runtime_diagnosis_callback + from netopsbench.sdk.agents import DiagnosisResult + + async def diagnose(context): + return DiagnosisResult("provider", "inconclusive", success=False, reasoning="provider unavailable") + + callback = build_runtime_diagnosis_callback( + SimpleNamespace(diagnose=diagnose, name="provider"), str(tmp_path), "case" + ) + result = callback( + {}, + diagnostic_session=SimpleNamespace(config=SimpleNamespace(max_agent_seconds=600)), + diagnostic_payload={"case_id": "anonymous", "topology": {}, "symptoms": {}, "canonical_observation": {}}, + ) + assert result["success"] is False + assert result["error"] == "provider unavailable" + + +def test_agent_cancellation_waits_for_resource_cleanup(): + import asyncio + import threading + from types import SimpleNamespace + + import pytest + + from netopsbench.platform.session.diagnosis import run_agent_diagnose + + cleaned = [] + cancelled = threading.Event() + + async def diagnose(context): + try: + cancelled.set() + await asyncio.sleep(100) + finally: + cleaned.append(True) + + with pytest.raises(RuntimeError, match="cancelled"): + run_agent_diagnose(SimpleNamespace(diagnose=diagnose), None, cancelled) + assert cleaned == [True] + + +def test_scenario_cancellation_prevents_injection_and_allows_recovery_sleep(monkeypatch): + import threading + + import pytest + + from netopsbench.platform.scenario.executor import ScenarioExecutor + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import config_for_scale + + slept = [] + runner = ScenarioExecutor( + topology_metadata=build_clos_plan(config_for_scale("xs")).manifest, + sleep_fn=lambda seconds: slept.append(seconds), + ) + runner._cancel_event = threading.Event() + runner._cancel_event.set() + monkeypatch.setattr( + "netopsbench.platform.scenario.executor._inject_fault_impl", + lambda *a: pytest.fail("cancelled scenario must not inject"), + ) + with pytest.raises(RuntimeError, match="cancelled"): + runner._inject_fault(None) + with pytest.raises(RuntimeError, match="cancelled"): + runner.sleep(1) + runner._recovering = True + runner.sleep(1) + assert slept == [1] diff --git a/tests/test_runtime_audit_driver.py b/tests/test_runtime_audit_driver.py new file mode 100644 index 0000000..1dc0405 --- /dev/null +++ b/tests/test_runtime_audit_driver.py @@ -0,0 +1,54 @@ +"""Audit instrumentation must not leak counters between fresh runtime batches.""" + +import sys +from types import ModuleType + +from scripts.validate_runtime_refactor import CommandCounts, influxdb + + +def test_lazy_query_alias_is_restored_after_batch(monkeypatch): + original = influxdb.query_flux + with CommandCounts(): + late = ModuleType("netopsbench.audit_test_alias") + late.query = influxdb.query_flux + monkeypatch.setitem(sys.modules, late.__name__, late) + assert late.query is not original + assert late.query is original + assert influxdb.query_flux is original + + +def test_shadow_preserves_production_baseline_on_success_and_failure(): + from types import SimpleNamespace + + import pytest + + from netopsbench.platform.scenario.baseline import BaselineHandoff + from scripts.validate_runtime_refactor import verify_shadow + + for failed in (False, True): + baseline = BaselineHandoff(window={"end_time": "original"}, uses=9, ready=True) + runner = SimpleNamespace( + _baseline_handoff=baseline, + _last_calibration={"success": True, "reason": "original"}, + _calibration_current=False, + ) + + def calibrate(case, reason, runner=runner, failed=failed): + runner._baseline_handoff.window = {"end_time": "new"} + runner._baseline_handoff.uses = 0 + runner._calibration_current = True + runner._last_calibration = {"success": not failed, "reason": reason} + if failed: + raise RuntimeError("shadow failed") + + runner.calibrate = calibrate + if failed: + with pytest.raises(RuntimeError, match="shadow failed"): + verify_shadow(runner, None) + else: + assert verify_shadow(runner, None)["reason"] == "shadow_validation" + assert runner._baseline_handoff.window == {"end_time": "original"} + assert runner._baseline_handoff.uses == 9 + assert runner._baseline_handoff.ready + assert runner._last_calibration == {"success": True, "reason": "original"} + assert not runner._calibration_current diff --git a/tests/test_runtime_config_consistency.py b/tests/test_runtime_config_consistency.py index 88db10a..26024fe 100644 --- a/tests/test_runtime_config_consistency.py +++ b/tests/test_runtime_config_consistency.py @@ -62,7 +62,7 @@ def test_update_telegraf_config_rejects_legacy_grouped_topology(tmp_path): encoding="utf-8", ) - with pytest.raises(ValueError, match="schema_version.*3.*Regenerate"): + with pytest.raises(ValueError, match="schema_version.*4.*Regenerate"): telegraf_mod.update_telegraf_config(str(topo_path), output_file=str(tmp_path / "telegraf.conf")) @@ -106,7 +106,7 @@ def test_update_telegraf_config_isolates_gnmi_subscriptions_per_role(tmp_path): assert '"172.20.20.27:50051"' in leaf_block assert '"172.20.20.11:50051"' not in leaf_block assert 'path = "COUNTERS/Ethernet64"' in leaf_block - assert 'path = "COUNTERS/Ethernet68"' not in leaf_block + assert 'path = "COUNTERS/Ethernet68"' in leaf_block assert 'subscription_mode = "sample"' in rendered assert 'sample_interval = "10s"' in rendered assert 'username = "admin"' in rendered @@ -317,7 +317,7 @@ def test_native_client_image_has_no_python_or_iperf_runtime(): assert "python" not in runtime_stage.lower() assert "iperf" not in runtime_stage.lower() assert "/usr/local/bin/netopsbench-client-agent" in runtime_stage - assert DEFAULT_CLIENT_IMAGE.startswith("docker.io/yyyyyt123/netopsbench-client@sha256:") + assert DEFAULT_CLIENT_IMAGE == "netopsbench-client:pingmesh-v2" assert ":latest" not in DEFAULT_CLIENT_IMAGE assert DEFAULT_SONIC_VS_IMAGE.startswith("yyyyyt123/netopsbench-sonic-vs-202505-telemetry@sha256:") diff --git a/tests/test_runtime_refactor_audit.py b/tests/test_runtime_refactor_audit.py new file mode 100644 index 0000000..fcbb556 --- /dev/null +++ b/tests/test_runtime_refactor_audit.py @@ -0,0 +1,49 @@ +"""The deterministic audit records real execution rather than predicted diagnoses.""" + +import subprocess +from types import SimpleNamespace + +import pytest + +from scripts import validate_runtime_refactor as audit + + +def test_scripted_diagnosis_uses_same_tools_without_reading_truth(): + calls = [] + + class Session: + def call_tool(self, action): + calls.append(action) + return SimpleNamespace(model_dump=lambda **_: {"observation": {"success": True}}) + + result = audit.deterministic_diagnosis( + None, + diagnostic_session=Session(), + diagnostic_payload={"topology": {"devices": {"leafs": [{"name": "leaf1"}], "clients": [{"name": "client1"}]}}}, + ) + assert result["verdict"] == "inconclusive" + assert [call.name for call in calls] == [ + "get_topology", + "get_pingmesh_summary", + "get_device_interfaces", + "get_bgp_neighbors", + "get_route_table", + "get_device_acl", + ] + assert len(result["metadata"]["scripted_observations"]) == 6 + + +def test_counter_restores_process_api_even_after_failure(): + original = subprocess.Popen + with pytest.raises(RuntimeError), audit.CommandCounts() as counts: + subprocess.run(["true"], check=True) + assert counts.snapshot() == {"subprocess": 1, "docker": 0, "influx_queries": 0} + raise RuntimeError("failed audit") + assert subprocess.Popen is original + + +def test_selection_rejects_unsupported_fault_instead_of_silent_skip(monkeypatch): + healthy = SimpleNamespace(id="healthy", episode=SimpleNamespace(is_healthy=True, fault_type="none")) + monkeypatch.setattr(audit, "parse_scenario_file", lambda _: healthy) + with pytest.raises(ValueError, match="No generated case"): + audit.select_cases(["case"], ["packet_loss"]) diff --git a/tests/test_runtime_toolchain.py b/tests/test_runtime_toolchain.py new file mode 100644 index 0000000..48279fd --- /dev/null +++ b/tests/test_runtime_toolchain.py @@ -0,0 +1,209 @@ +"""Official distribution integrity and backend identity are checked before allocation.""" + +import hashlib +import io +import json +import tarfile +from pathlib import Path + +import pytest + +from netopsbench.platform.runtime import build_tools, resources, toolchain + + +@pytest.fixture +def release(tmp_path, monkeypatch): + data = b'#!/bin/sh\nprintf \'{"version":"0.77.0"}\\n\'\n' + archive = tmp_path / "official.tar.gz" + with tarfile.open(archive, "w:gz") as tar: + member = tarfile.TarInfo("containerlab") + member.size = len(data) + tar.addfile(member, io.BytesIO(data)) + spec = dict( + provider="upstream", + version="0.77.0", + architecture="amd64", + archive_url="https://example.invalid", + archive_sha256=hashlib.sha256(archive.read_bytes()).hexdigest(), + binary_sha256=hashlib.sha256(data).hexdigest(), + ) + monkeypatch.setattr(toolchain, "release_spec", lambda: dict(spec)) + monkeypatch.setattr(build_tools, "release_spec", lambda: dict(spec)) + output = tmp_path / "private-tools" + monkeypatch.setenv("NETOPSBENCH_RUNTIME_TOOLS", str(output)) + return archive, output, spec + + +def test_install_and_resolve_official_release(release): + archive, output, spec = release + build_tools.install_release(archive, output) + assert toolchain.runtime_tools() == output + assert toolchain.containerlab_command() == [str(output / "containerlab")] + assert json.loads((output / "manifest.json").read_text()) == spec + assert sorted(p.name for p in output.iterdir()) == ["containerlab", "manifest.json"] + + +@pytest.mark.parametrize("tamper", ["archive", "executable", "manifest", "version", "permissions"]) +def test_reject_corruption_before_use(release, monkeypatch, tamper): + archive, output, _ = release + if tamper == "archive": + archive.write_bytes(b"not an archive") + with pytest.raises(RuntimeError, match="archive checksum"): + build_tools.install_release(archive, output) + assert not output.exists() + return + build_tools.install_release(archive, output) + if tamper == "executable": + (output / "containerlab").write_bytes(b"corrupted") + elif tamper == "manifest": + (output / "manifest.json").write_text('{"provider":"custom"}') + elif tamper == "version": + monkeypatch.setattr(toolchain, "binary_version", lambda _: "0.76.0") + else: + (output / "containerlab").chmod(0o644) + with pytest.raises(RuntimeError, match="official runtime"): + toolchain.runtime_tools() + + +def test_missing_tools_have_no_global_fallback(release): + with pytest.raises(RuntimeError, match="Prepare the official runtime"): + toolchain.runtime_tools() + + +def test_reject_wrong_binary_even_with_valid_archive(release): + archive, output, spec = release + spec["binary_sha256"] = "0" * 64 + with pytest.raises(RuntimeError, match="executable checksum"): + build_tools.install_release(archive, output) + assert not output.exists() + + +def test_backend_identity_hashes_executable_and_startup_script(release, monkeypatch, tmp_path): + from netopsbench.platform.topology import config + + archive, output, spec = release + build_tools.install_release(archive, output) + wrapper = tmp_path / "start.sh" + wrapper.write_text("first") + monkeypatch.setattr(config, "SONIC_START_WRAPPER_SOURCE", wrapper) + identity = toolchain.runtime_backend_identity() + assert identity["containerlab_sha256"] == spec["binary_sha256"] + assert identity["containerlab_version"] == "0.77.0" + wrapper.write_text("changed") + assert identity["sonic_start_sha256"] != toolchain.runtime_backend_identity()["sonic_start_sha256"] + + +@pytest.mark.parametrize("architecture", ["x86_64", "aarch64"]) +def test_lock_selects_official_release_architecture(monkeypatch, architecture): + monkeypatch.setattr(toolchain.platform, "system", lambda: "Linux") + monkeypatch.setattr(toolchain.platform, "machine", lambda: architecture) + spec = toolchain.release_spec() + assert spec["provider"] == "upstream" + assert spec["version"] == "0.77.0" + assert spec["archive_url"].startswith("https://github.com/srl-labs/containerlab/releases/download/v0.77.0/") + assert len(spec["binary_sha256"]) == 64 + + +def test_capacity_rejects_old_or_mixed_backend_before_host_queries(monkeypatch): + monkeypatch.setattr(resources, "runtime_backend_identity", lambda: {"provider": "upstream"}) + with pytest.raises(ValueError, match="measure the current runtime"): + resources.capacity_check({"nodes": []}, "medium", Path("/nonexistent")) + with pytest.raises(ValueError, match="same recorded runtime backend"): + resources.peak_sample([{"nodes": []}, {"runtime_backend": {"provider": "upstream"}, "nodes": []}]) + + +def test_runtime_records_identity_before_deploy_and_checks_cached_stage(monkeypatch, tmp_path): + from netopsbench.platform.runtime import manager + + identity = { + "provider": "upstream", + "containerlab_version": "0.77.0", + "containerlab_sha256": "a", + "sonic_start_sha256": "b", + } + monkeypatch.setattr(manager, "runtime_backend_identity", lambda: dict(identity)) + runtime = manager.RuntimeManager(workspace=tmp_path).create(scale="xs", workers=1, name="identity") + calls = [] + + def deploy(_self, stage, pool): + saved = json.loads((pool.root_dir / "runtime.json").read_text()) + assert saved["metadata"]["runtime_backend"] == identity + calls.append(stage) + from datetime import UTC, datetime + + from netopsbench.platform.runtime.lifecycle import LifecycleStageResult + + return LifecycleStageResult( + stage=stage, + status="completed", + started_at=datetime.now(UTC), + ended_at=datetime.now(UTC), + duration_seconds=0, + ) + + monkeypatch.setattr(manager.RuntimeLifecycle, "run", deploy) + runtime.deploy().deploy() + assert calls == ["deploy"] + identity["sonic_start_sha256"] = "changed" + with pytest.raises(ValueError, match="backend changed"): + runtime.deploy() + assert calls == ["deploy"] + + +def test_cancelled_deploy_does_not_resolve_tools_or_create_topology(monkeypatch, tmp_path): + import threading + + from netopsbench.models.runtime import RuntimeIdentity + from netopsbench.platform.runtime import deployment + from netopsbench.platform.utils.control import OperationCancelled, OperationControl + + worker = RuntimeIdentity.create( + runtime_id="cancel", + worker_id="worker-1", + worker_index=1, + lab_name="cancel", + topology_dir=tmp_path / "absent", + mgmt_subnet="172.31.1.0/24", + mgmt_network="cancel", + ) + cancel = threading.Event() + cancel.set() + monkeypatch.setattr(deployment, "containerlab_command", lambda: pytest.fail("resolved tools after cancellation")) + with pytest.raises(OperationCancelled): + deployment.deploy_worker_lab(worker, "xs", control=OperationControl(cancel)) + assert not worker.topology_dir.exists() + + +def test_failed_destroy_is_reported_after_remaining_cleanup(monkeypatch, tmp_path): + import subprocess + + from netopsbench.models.runtime import RuntimeIdentity + from netopsbench.platform.runtime import deployment + + worker = RuntimeIdentity.create( + runtime_id="cleanup", + worker_id="worker-1", + worker_index=1, + lab_name="cleanup", + topology_dir=tmp_path, + mgmt_subnet="172.31.1.0/24", + mgmt_network="owned", + ) + calls = [] + + def run(command, **kwargs): + calls.append(command) + return subprocess.CompletedProcess(command, 1 if command[0] == "official" else 0, "", "namespace failed") + + monkeypatch.setattr(deployment, "containerlab_command", lambda: ["official"]) + monkeypatch.setattr(deployment, "safe_run", run) + monkeypatch.setattr(deployment, "sudo_prefix", lambda: []) + monkeypatch.setattr(deployment, "docker_prefix", lambda: []) + monkeypatch.setattr(deployment, "_stop_collector", lambda *a: None) + monkeypatch.setattr(deployment, "_lab_container_names", lambda *a: []) + monkeypatch.setattr(deployment, "_container_exists", lambda *a: False) + monkeypatch.setattr(deployment, "_network_exists", lambda *a: False) + with pytest.raises(RuntimeError, match="namespace failed"): + deployment.teardown_worker_lab(worker) + assert ["docker", "network", "rm", "owned"] in calls + assert len([c for c in calls if c[0] == "official"]) == 2 diff --git a/tests/test_scale_registry.py b/tests/test_scale_registry.py index a795ef2..f6c584b 100644 --- a/tests/test_scale_registry.py +++ b/tests/test_scale_registry.py @@ -15,7 +15,7 @@ def _write_profile(path: Path, *, name: str = "clos-lab", override: bool = False, leafs: int = 3) -> Path: path.write_text( - f"""schema_version: \"1\" + f"""schema_version: \"2\" override: {str(override).lower()} profiles: - name: {name} @@ -46,12 +46,12 @@ def test_custom_same_family_scale_generates_without_code_changes(tmp_path: Path) def test_profile_override_must_be_explicit(tmp_path: Path): - profile_file = _write_profile(tmp_path / "scale.yaml", name="small") + profile_file = _write_profile(tmp_path / "scale.yaml", name="medium") with pytest.raises(ValueError, match="override: true"): ScaleRegistry.with_builtins([profile_file]) - registry = ScaleRegistry.with_builtins([_write_profile(profile_file, name="small", override=True, leafs=5)]) - assert registry.get("small").num_leafs == 5 + registry = ScaleRegistry.with_builtins([_write_profile(profile_file, name="medium", override=True, leafs=5)]) + assert registry.get("medium").num_leafs == 5 def test_registry_digest_is_stable_and_changes_with_profile(tmp_path: Path): @@ -88,3 +88,31 @@ def test_large_limits_containerlab_deploy_parallelism(): profile = ScaleRegistry.with_builtins().get("large") assert profile.containerlab_max_workers == 16 + + +def test_k8_uses_official_containerlab_parallelism(): + profile = ScaleRegistry.with_builtins().get("fat-tree-k8") + + assert profile.containerlab_max_workers == 16 + assert profile.worker_deploy_parallelism == 1 + + +def test_k12_defaults_select_the_validated_fast_combination(): + from netopsbench.models.profiles import default_scale_registry + from netopsbench.models.topology import PingmeshPolicy + + profile = default_scale_registry().get("fat-tree-k12") + assert profile.containerlab_max_workers == 16 + policy = PingmeshPolicy.model_validate(profile.pingmesh.model_dump()) + assert policy.destination_batch_size == 32 + assert policy.cycle_interval_seconds == 3 + assert policy.rtt_ports_per_cycle == 4 + from netopsbench.platform.topology.config import config_for_scale + from netopsbench.platform.topology.fat_tree_builder import build_fat_tree_plan + + assert ( + build_fat_tree_plan(config_for_scale("fat-tree-k12")) + .manifest.require_pingmesh_plan() + .settings.complete_window_seconds + == 42 + ) diff --git a/tests/test_scenario_artifacts.py b/tests/test_scenario_artifacts.py new file mode 100644 index 0000000..6d4831e --- /dev/null +++ b/tests/test_scenario_artifacts.py @@ -0,0 +1,72 @@ +"""Large private snapshots remain complete without inflating primary result JSON.""" + +import gzip +import hashlib +import json +from pathlib import Path + +import pytest + +from netopsbench.platform.scenario.artifacts import persist_result + + +def test_private_snapshots_are_lossless_and_do_not_mutate_execution_or_scores(tmp_path): + snapshot = { + "collected_at": "2026-10-12T12:00:00Z", + "nodes": { + "edge1": { + "fib": [{"dst": "192.168.1.0/30", "nexthops": [{"gateway": "10.0.0.1", "dev": "Ethernet0"}]}] * 1000 + } + }, + } + diagnosis = {"success": True, "fault_type": "ecmp_misconfig"} + result = { + "case_valid": True, + "episode": {"diagnosis": diagnosis, "route_evidence": {"baseline": snapshot, "fault": snapshot}}, + "cleanup": {"success": True, "route_recovery": snapshot}, + } + path = tmp_path / "case.json" + persist_result(path, result) + saved = json.loads(path.read_text()) + assert saved["episode"]["diagnosis"] == diagnosis + assert saved["case_valid"] is True and saved["cleanup"]["success"] is True + assert result["episode"]["route_evidence"]["baseline"] is snapshot + assert result["cleanup"]["route_recovery"] is snapshot + refs = [*saved["episode"]["route_evidence"].values(), saved["cleanup"]["route_recovery"]] + for ref in refs: + artifact = Path(ref["path"]) + data = artifact.read_bytes() + assert artifact.is_relative_to(tmp_path) + assert ref["encoding"] == "gzip+json" + assert hashlib.sha256(data).hexdigest() == ref["sha256"] + assert json.loads(gzip.decompress(data)) == snapshot + assert ref["compressed_bytes"] < ref["uncompressed_bytes"] / 10 + assert path.stat().st_size < 3000 + + +def test_evidence_write_failure_keeps_primary_result_and_leaves_no_partial_file(tmp_path, monkeypatch): + from netopsbench.platform.utils import files + + path = tmp_path / "case.json" + path.write_text('{"original": true}') + original = files.os.replace + + def fail_evidence(source, target): + if str(target).endswith(".json.gz"): + raise OSError("storage failure") + original(source, target) + + monkeypatch.setattr(files.os, "replace", fail_evidence) + with pytest.raises(OSError, match="storage failure"): + persist_result(path, {"episode": {"route_evidence": {"baseline": {"nodes": {}}}}}) + assert json.loads(path.read_text()) == {"original": True} + assert not list(tmp_path.rglob("*.tmp")) + assert not list(tmp_path.rglob("*.json.gz")) + + +def test_result_without_route_snapshots_keeps_the_same_json_contract(tmp_path): + result = {"success": True, "episode": {"diagnosis": {"verdict": "network_healthy"}}} + path = tmp_path / "case.json" + persist_result(path, result) + assert json.loads(path.read_text()) == result + assert not (tmp_path / "evidence").exists() diff --git a/tests/test_scenario_cleanup.py b/tests/test_scenario_cleanup.py index 2b4a2d7..f8fe834 100644 --- a/tests/test_scenario_cleanup.py +++ b/tests/test_scenario_cleanup.py @@ -1,12 +1,22 @@ from types import SimpleNamespace +import pytest + import netopsbench.platform.scenario.executor as executor_module from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec from netopsbench.platform.scenario.executor import ScenarioExecutor +@pytest.fixture(autouse=True) +def shared_recovery_clock(monkeypatch): + from netopsbench.platform.utils import control + + monkeypatch.setattr(control.time, "monotonic", lambda: executor_module.monotonic()) + + def _scenario() -> ScenarioSpec: return ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id="cleanup-case", name="cleanup-case", description="cleanup boundary test", @@ -22,8 +32,37 @@ def _scenario() -> ScenarioSpec: def _runner(*, active_faults, timeout_seconds=10): runner = object.__new__(ScenarioExecutor) + from netopsbench.models.recovery import RecoveryPolicy + + runner.recovery_policy = RecoveryPolicy() + runner.begin_case() + runner.traffic_controller = None + runner.runtime_worker = None + runner._baseline_handoff = executor_module.BaselineHandoff() + runner._recovering = True runner.injector = SimpleNamespace(active_faults=list(active_faults)) - runner.scale_registry = SimpleNamespace(get=lambda _scale: SimpleNamespace(health_timeout_seconds=timeout_seconds)) + runner.scale_registry = SimpleNamespace( + get=lambda _scale: SimpleNamespace( + health_timeout_seconds=timeout_seconds, experiment=SimpleNamespace(recovery_timeout_seconds=timeout_seconds) + ) + ) + runner._cancel_event = None + runner._baseline_scope = lambda _: None + runner.minimum_baseline_seconds = 4 + runner._capture_baseline_window = lambda: executor_module._capture_observation_window_impl( + runner, runner.minimum_baseline_seconds, name="baseline" + ) + runner._merge_observation_windows = lambda windows, *a, **k: { + "data_source_status": "ok", + "coverage_status": "complete", + "_baseline_coverage": {"coverage_status": "complete"}, + "_baseline_health": { + "absolute_unreachable_paths": 0, + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, + "pingmesh_metrics": {"quality": {"current_paths_observed": 1}}, + } return runner @@ -45,11 +84,35 @@ def test_clean_scenario_boundary_does_not_retry_or_sleep(monkeypatch): "attempts": 1, "duration_seconds": 0.0, "errors": [], + "validation_level": "full_window", + "full_validation_reason": "custom_callback", + "state_validation": {}, + "recovery_policy": runner.recovery_policy.model_dump(mode="json"), "recovery": [{"type": "link_down", "recovered": True}], } assert calls == [] +def test_explicit_sdk_baseline_can_recover_without_a_handoff_identity(monkeypatch): + runner = _runner(active_faults=[{"type": "link_down"}]) + runner.runtime_worker = SimpleNamespace() + runner.sleep = lambda _: None + runner._baseline_scope = lambda _: None + monkeypatch.setattr(executor_module, "monotonic", lambda: 0.0) + monkeypatch.setattr(executor_module, "check_worker_health", lambda *a, **k: []) + + def recover(): + runner.injector.active_faults.clear() + return [{"type": "link_down", "recovered": True, "readback_verified": True}] + + runner._recover_fault = recover + result = runner._cleanup_after_scenario(_scenario(), None, baseline_window={"duration_seconds": 30}) + assert result["success"] is True + assert result["validation_level"] == "state_checked" + assert "validated_baseline" not in result + assert "validated_baseline_scope" not in result + + def test_failed_episode_recovery_is_retried_once_and_can_continue(monkeypatch): runner = _runner(active_faults=[{"type": "link_down"}]) calls = [] @@ -135,7 +198,7 @@ def test_cleanup_requires_shared_post_recovery_health(monkeypatch): runner.runtime_worker = object() runner.traffic_controller = SimpleNamespace( active_flows={"flow": object()}, - verify_active_flows=lambda: True, + verify_active_flows=lambda **kw: True, ) runner.sleep = lambda seconds: clock.__setitem__(0, clock[0] + seconds) @@ -165,7 +228,7 @@ def test_cleanup_retries_background_traffic_until_scale_deadline(monkeypatch): clock = [0.0] checks = 0 - def verify(): + def verify(**kwargs): nonlocal checks checks += 1 return checks >= 2 @@ -192,3 +255,140 @@ def test_executor_close_stops_suite_owned_traffic_once(): runner.close() assert calls == ["stop"] + + +def test_recovery_health_cannot_start_window_larger_than_remaining_budget(monkeypatch): + from netopsbench.platform.utils import control + + runner = _runner(active_faults=[{"type": "link_down"}], timeout_seconds=10) + runner.runtime_worker = object() + clock = [100.0] + sleeps = [] + runner.sleep = lambda seconds: sleeps.append(seconds) + + def recover(): + runner.injector.active_faults.clear() + return [{"type": "link_down", "recovered": True}] + + def check_health(_worker, *, deadline, **_kwargs): + assert deadline == 110 + clock[0] = 108 + return [] + + runner._recover_fault = recover + monkeypatch.setattr(executor_module, "monotonic", lambda: clock[0]) + monkeypatch.setattr(control.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(executor_module, "check_worker_health", check_health) + cleanup = runner._cleanup_after_scenario(_scenario(), None, baseline_window={"duration_seconds": 4}) + + assert cleanup["success"] is False + assert cleanup["status"] == "recovery_timeout" + assert cleanup["duration_seconds"] == 8 + assert "complete observation window" in cleanup["errors"][-1] + assert not sleeps + assert not runner.injector.active_faults + + +def test_observation_that_reaches_deadline_is_not_published_as_healthy(monkeypatch): + runner = _runner(active_faults=[{"type": "link_down"}], timeout_seconds=10) + clock = [100.0] + + def recover(): + runner.injector.active_faults.clear() + return [{"type": "link_down", "recovered": True}] + + def observe(_duration, *, baseline_window, deadline): + assert deadline == 110 + clock[0] = deadline + return {"data_source_status": "ok", "coverage_status": "complete"} + + runner._recover_fault = recover + runner.calibrate = lambda scenario, reason, deadline: ( + observe(runner.minimum_baseline_seconds, baseline_window={}, deadline=deadline), + setattr(runner._baseline_handoff, "window", {"duration_seconds": runner.minimum_baseline_seconds}), + ) + monkeypatch.setattr(executor_module, "monotonic", lambda: clock[0]) + cleanup = runner._cleanup_after_scenario(_scenario(), None, baseline_window={"duration_seconds": 1}) + assert cleanup["success"] is False + assert cleanup["status"] == "recovery_timeout" + assert "validated_baseline" not in cleanup + + +def test_observation_stops_after_a_sleep_exhausts_its_budget(monkeypatch): + from netopsbench.platform.scenario.observation import capture_observation_window + from netopsbench.platform.utils import control + + clock = [100.0] + sleeps = [] + + def sleep(seconds): + sleeps.append(seconds) + clock[0] += seconds + 2 # Scheduling delay after a requested one-second sleep. + + runner = SimpleNamespace(sleep=sleep) + monkeypatch.setattr(control.time, "monotonic", lambda: clock[0]) + with pytest.raises(TimeoutError, match="deadline exceeded"): + capture_observation_window(runner, 2, deadline=102.5) + assert sleeps == [1] + + +def test_recovery_budget_is_explicit_and_not_derived_from_baseline(monkeypatch): + runner = _runner(active_faults=[{"type": "link_down"}], timeout_seconds=120) + runner.minimum_baseline_seconds = 60 + clock = [100.0] + + def recover(): + runner.injector.active_faults.clear() + clock[0] += 8 + return [{"type": "link_down", "recovered": True}] + + def observe(duration, *, baseline_window, deadline): + assert duration == 60 + assert deadline == 220 + clock[0] += duration + return { + "data_source_status": "ok", + "coverage_status": "complete", + "_baseline_coverage": {"coverage_status": "complete"}, + "pingmesh_metrics": {"quality": {"current_paths_observed": 1}}, + "start_time": "2026-01-01T00:00:00Z", + "end_time": "2026-01-01T00:01:00Z", + "duration_seconds": duration, + } + + runner._recover_fault = recover + runner.calibrate = lambda scenario, reason, deadline: ( + observe(runner.minimum_baseline_seconds, baseline_window={}, deadline=deadline), + setattr(runner._baseline_handoff, "window", {"duration_seconds": runner.minimum_baseline_seconds}), + ) + monkeypatch.setattr(executor_module, "monotonic", lambda: clock[0]) + cleanup = runner._cleanup_after_scenario(_scenario(), None, baseline_window={"duration_seconds": 60}) + assert cleanup["success"] is True + assert cleanup["duration_seconds"] == 68 + assert cleanup["validated_baseline"]["duration_seconds"] == 60 + + +@pytest.mark.parametrize("verified", [True, False]) +def test_state_checked_readback_avoids_window_custom_callback_requires_calibration(verified): + from netopsbench.models.recovery import RecoveryPolicy + + runner = _runner(active_faults=[{"type": "link_down"}], timeout_seconds=60) + runner.recovery_policy = RecoveryPolicy() + runner._baseline_scope = lambda scenario: None + calls = [] + window = {"start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:00:30Z", "duration_seconds": 30} + + def recover(): + runner.injector.active_faults.clear() + return [{"recovered": True, "readback_verified": verified}] + + def calibrate(scenario, reason, **kwargs): + calls.append(reason) + runner._baseline_handoff.window = dict(window) + + runner._recover_fault = recover + runner.calibrate = calibrate + result = runner._cleanup_after_scenario(_scenario(), {}, baseline_window=window) + assert result["success"] + assert result["validation_level"] == ("state_checked" if verified else "full_window") + assert calls == ([] if verified else ["custom_callback"]) diff --git a/tests/test_scenario_generator_placements.py b/tests/test_scenario_generator_placements.py index 7e139fd..bccff8f 100644 --- a/tests/test_scenario_generator_placements.py +++ b/tests/test_scenario_generator_placements.py @@ -1,250 +1,114 @@ -"""Placement coverage for the default large-topology scenario campaign.""" +"""Catalog coverage is stable across scale, with auditable planned witnesses.""" -from __future__ import annotations - -from collections import Counter, defaultdict -from pathlib import Path +import json +from collections import Counter import pytest import yaml -from netopsbench.platform.scenario import generator as scenario_generator +from netopsbench.models.profiles import supported_scales +from netopsbench.platform.faults.catalog import FAULT_MECHANISMS, coverage_units +from netopsbench.platform.scenario.generator import _CandidateIndex, generate, load_topology +from netopsbench.platform.scenario.parser import parse_scenario_file +from netopsbench.platform.scenario.validator import validate_scenario from netopsbench.platform.topology.generator import generate_topology -EXPANDED_FAULTS = { - "bgp_neighbor_misconfig", - "blackhole_route", - "device_down", - "high_latency", - "link_down", - "link_flapping", - "mtu_mismatch", - "packet_corruption", - "packet_loss", -} -ACCESS_SCOPED_FAULTS = { - "acl_misconfig", - "route_policy_misconfig", - "static_route_misconfig", -} - - -def _load_generated(paths: list[Path]) -> list[dict]: - return [yaml.safe_load(path.read_text(encoding="utf-8")) for path in paths] - - -def _generate_default(scale: str, root: Path, *, reverse_templates: bool = False): - topology_dir = root / f"topology-{scale}" - if not topology_dir.exists(): - generate_topology(scale, str(topology_dir)) - topo = scenario_generator.load_topology(scale, str(topology_dir)) - spec = scenario_generator.load_yaml(scenario_generator.default_campaign_spec()) - if reverse_templates: - spec["fault_templates"] = list(reversed(spec["fault_templates"])) - paths = scenario_generator.generate(spec, topo, root / "scenarios", seed=42) - return topo, _load_generated(paths) - - -def _role_counts(rows: list[dict], roles: dict[str, str], fault_type: str) -> Counter: - return Counter(roles[row["episode"]["target_device"]] for row in rows if row["episode"]["fault_type"] == fault_type) - - -def test_large_campaign_uses_complete_pingmesh_window(tmp_path): - _topology, rows = _generate_default("large", tmp_path) - - assert len(rows) == 52 - assert {row["episode"]["duration_seconds"] for row in rows} == {54} - - -@pytest.mark.parametrize("scale", ["xlarge", "fat-tree-k8", "fat-tree-k12"]) -def test_default_large_campaign_has_balanced_tier_placements(tmp_path, scale): - topo, rows = _generate_default(scale, tmp_path) - fault_counts = Counter(row["episode"]["fault_type"] for row in rows) - - assert len(rows) == 70 - assert len({row["scenario_id"] for row in rows}) == 70 - assert all(fault_counts[fault] == 6 for fault in EXPANDED_FAULTS) - assert all(fault_counts[fault] == 4 for fault in ACCESS_SCOPED_FAULTS) - assert fault_counts["none"] == 4 - assert { - row["episode"]["metadata"]["loss_pct"] for row in rows if row["episode"]["fault_type"] == "packet_loss" - } == {30} - - indices_by_fault: dict[str, list[int]] = defaultdict(list) - for row in rows: - indices_by_fault[row["episode"]["fault_type"]].append(int(row["scenario_id"].rsplit("_", 1)[1])) - for fault_type, indices in indices_by_fault.items(): - assert sorted(indices) == list(range(1, fault_counts[fault_type] + 1)) - - roles = {device.name: device.role.value for device in topo.manifest.devices} - if scale == "xlarge": - assert _role_counts(rows, roles, "link_down") == {"leaf": 4, "spine": 2} - assert _role_counts(rows, roles, "device_down") == {"leaf": 3, "spine": 3} - for fault in EXPANDED_FAULTS - {"device_down", "link_down"}: - assert _role_counts(rows, roles, fault) == {"leaf": 3, "spine": 3} - else: - assert _role_counts(rows, roles, "link_down") == {"edge": 3, "agg": 2, "core": 1} - for fault in {"device_down", "mtu_mismatch", "bgp_neighbor_misconfig", "blackhole_route"}: - assert _role_counts(rows, roles, fault) == {"edge": 2, "agg": 2, "core": 2} - for fault in {"high_latency", "packet_loss", "packet_corruption", "link_flapping"}: - assert _role_counts(rows, roles, fault) == {"edge": 2, "agg": 3, "core": 1} - - by_template: dict[str, list[dict]] = defaultdict(list) - for row in rows: - by_template[row["metadata"]["generator"]["template"]].append(row) - for template_rows in by_template.values(): - devices = [row["episode"].get("target_device") for row in template_rows] - devices = [device for device in devices if device is not None] - assert len(devices) == len(set(devices)) - - pods = { - int(next(device for device in topo.manifest.devices if device.name == name).metadata["pod"]) - for name in devices - if roles[name] in {"edge", "agg"} - } - if len(devices) > 1 and all(roles[name] in {"edge", "agg"} for name in devices): - assert len(pods) == len(devices) - - -def _normalize_interface(name: str) -> str: - if name.startswith("eth") and name[3:].isdigit(): - return f"Ethernet{(int(name[3:]) - 1) * 4}" - return name - -def test_fat_tree_templates_select_the_requested_link_and_bgp_roles(tmp_path): - topo, rows = _generate_default("fat-tree-k8", tmp_path) - roles = {device.name: device.role.value for device in topo.manifest.devices} - peers: dict[tuple[str, str], str] = {} - for link in topo.manifest.links: - left, right = link.endpoints - peers[(left.device, _normalize_interface(left.interface))] = right.device - peers[(right.device, _normalize_interface(right.interface))] = left.device - - expected_peer_role = { - "link_down_access": "client", - "link_down_leaf_fabric": "agg", - "link_down_agg_edge": "edge", - "link_down_agg_core": "core", - "link_down_core_agg": "agg", - "packet_loss_leaf": "agg", - "packet_loss_spine": "agg", - "packet_loss_agg_edge": "edge", - "packet_loss_agg_core": "core", - } - for row in rows: - template = row["metadata"]["generator"]["template"] - if template not in expected_peer_role: - continue +@pytest.mark.parametrize("scale", supported_scales()) +def test_catalog_has_one_case_per_necessary_unit(tmp_path, scale): + root = tmp_path / "topology" + generate_topology(scale, str(root)) + topo = load_topology(scale, str(root)) + out = tmp_path / "cases" + paths = generate({"fault_catalog_version": 2}, topo, out, 42) + expected = 4 if scale == "xs" else 108 if topo.manifest.family == "fat-tree" else 64 + assert len(paths) == expected + rows = [yaml.safe_load(p.read_text()) for p in paths] + matrix = json.loads((out / "coverage.json").read_text()) + units = coverage_units(topo.manifest.family, validation=scale == "xs") + assert {r["unit"] for r in matrix["coverage_units"]} == {unit.id for unit in units} + assert len(matrix["coverage_units"]) == len(units) + assert matrix["negative_cases"] == (1 if scale == "xs" else 4) + if scale != "xs": + assert set(r["episode"]["fault_type"] for r in rows) == set(FAULT_MECHANISMS) | {"none"} + index = _CandidateIndex(topo, 42) + planned = set(index.pairs) + for row, path in zip(rows, paths, strict=True): + case = parse_scenario_file(path) + assert validate_scenario(case) == [] episode = row["episode"] - peer = peers[(episode["target_device"], episode["target_interface"])] - assert roles[peer] == expected_peer_role[template] - - bgp_by_template = { - row["metadata"]["generator"]["template"]: row - for row in rows - if row["episode"]["fault_type"] == "bgp_neighbor_misconfig" - } - for template, expected_role in ( - ("bgp_neighbor_misconfig_agg_edge", "downlink"), - ("bgp_neighbor_misconfig_agg_core", "uplink"), - ): - episode = bgp_by_template[template]["episode"] - peer_ip = episode["metadata"]["peer_ip"] - neighbor = next(item for item in topo.bgp_neighbors[episode["target_device"]] if item["peer_ip"] == peer_ip) - assert neighbor["interface_role"] == expected_role - - -def test_xlarge_link_down_templates_select_the_requested_peer_roles(tmp_path): - topo, rows = _generate_default("xlarge", tmp_path) - roles = {device.name: device.role.value for device in topo.manifest.devices} - peers: dict[tuple[str, str], str] = {} - for link in topo.manifest.links: - left, right = link.endpoints - peers[(left.device, _normalize_interface(left.interface))] = right.device - peers[(right.device, _normalize_interface(right.interface))] = left.device - - expected_peer_role = { - "link_down_access": "client", - "link_down_leaf_fabric": "spine", - "link_down_spine_fabric": "leaf", - "packet_loss_leaf": "spine", - "packet_loss_spine": "leaf", - } - for row in rows: - template = row["metadata"]["generator"]["template"] - if template not in expected_peer_role: + assert episode["duration_seconds"] >= topo.manifest.require_pingmesh_plan().settings.complete_window_seconds + assert episode["duration_seconds"] == max( + 30, topo.manifest.require_pingmesh_plan().settings.complete_window_seconds + ) + assert episode["stabilization_time"] == 0 + if episode["fault_type"] == "none": continue - episode = row["episode"] - peer = peers[(episode["target_device"], episode["target_interface"])] - assert roles[peer] == expected_peer_role[template] - - -def test_template_rng_is_stable_when_campaign_order_changes(tmp_path): - topology_root = tmp_path / "shared" - topo, forward = _generate_default("fat-tree-k8", topology_root) - del topo - _, reverse = _generate_default("fat-tree-k8", topology_root / "reverse", reverse_templates=True) - - def signatures(rows): - grouped = defaultdict(list) - for row in rows: - episode = row["episode"] - grouped[row["metadata"]["generator"]["template"]].append( - ( - episode.get("target_device"), - episode.get("target_interface"), - episode.get("target_prefix"), - episode.get("metadata", {}).get("peer_ip"), - episode.get("metadata", {}).get("target_ip"), - ) + assert "misconfig_kind" not in episode.get("parameters", {}) + assert "mtu" not in episode + p = episode["parameters"] + assert all((pair["src"], pair["dst"]) in planned for pair in p["affected_candidates"] + p["control_candidates"]) + if episode["fault_type"] in {"link_flapping", "route_flapping"}: + assert (p["down_time"], p["up_time"]) == (10, 10) + if len(FAULT_MECHANISMS[episode["fault_type"]]) > 1: + assert p["mechanism"] in FAULT_MECHANISMS[episode["fault_type"]] + if episode["fault_type"] == "ecmp_misconfig": + assert all( + not index.contains(pair["src"], pair["dst"], episode["target_device"]) + for pair in p["control_candidates"] ) - return {name: sorted(values, key=str) for name, values in grouped.items()} - - assert signatures(forward) == signatures(reverse) - - -def test_link_down_without_interface_role_defaults_to_access_link(tmp_path): - topology_dir = tmp_path / "topology" - generate_topology("small", str(topology_dir)) - topo = scenario_generator.load_topology("small", str(topology_dir)) - spec = { - "defaults": {"count_per_fault": 1}, - "fault_templates": [{"name": "default_access_link_down", "fault_type": "link_down", "device_role": "leaf"}], - } - rows = _load_generated(scenario_generator.generate(spec, topo, tmp_path / "scenarios", seed=7)) - episode = rows[0]["episode"] - - link = next( - link - for link in topo.manifest.links - if any( - endpoint.device == episode["target_device"] - and _normalize_interface(endpoint.interface) == episode["target_interface"] - for endpoint in link.endpoints - ) - ) - peer = next(endpoint.device for endpoint in link.endpoints if endpoint.device != episode["target_device"]) - roles = {device.name: device.role.value for device in topo.manifest.devices} - assert roles[peer] == "client" - - -def test_static_route_template_remains_access_scoped(tmp_path): - topology_dir = tmp_path / "topology" - generate_topology("fat-tree-k8", str(topology_dir)) - topo = scenario_generator.load_topology("fat-tree-k8", str(topology_dir)) - spec = { - "defaults": {"count_per_fault": 1}, - "fault_templates": [ - { - "name": "static_route_must_remain_at_origin", - "fault_type": "static_route_misconfig", - "device_role": "agg", - } - ], - } - rows = _load_generated(scenario_generator.generate(spec, topo, tmp_path / "scenarios", seed=7)) - target = rows[0]["episode"]["target_device"] - roles = {device.name: device.role.value for device in topo.manifest.devices} - - assert roles[target] == "edge" + if topo.manifest.family == "fat-tree": + for role in ("edge", "agg"): + assert {r["pod"] for r in matrix["coverage_units"] if r["role"] == role} == set( + range(1, topo.manifest.facts.num_pods + 1) + ) + if scale == "fat-tree-k18": + for role in ("edge", "agg"): + assert any(int(r["root"][len(role) :]) > 155 for r in matrix["coverage_units"] if r["role"] == role) + assert any(int(r["root"][4:]) > 60 for r in matrix["coverage_units"] if r["role"] == "core") + else: + assert not any(r["mechanism"] == "multipath_relax_disabled" for r in matrix["coverage_units"]) + first = {p.name: p.read_bytes() for p in paths} + second = generate({"fault_catalog_version": 2}, topo, out, 42) + assert first == {p.name: p.read_bytes() for p in second} + + +def test_catalog_totals_and_mechanisms(): + assert len(FAULT_MECHANISMS) == 24 + assert sum(map(len, FAULT_MECHANISMS.values())) == 27 + assert len(coverage_units("clos")) == 60 + assert len(coverage_units("fat-tree")) == 104 + assert 3 * 64 + 3 * 108 == 516 + assert Counter(u.fault_type for u in coverage_units("fat-tree"))["route_filter_misconfig"] == 9 + + +@pytest.mark.parametrize("fault", ["packet_loss", "acl_source_misconfig", "acl_l4_port_misconfig"]) +def test_core_dataplane_effect_audits_use_all_matching_existing_pairs(tmp_path, fault): + root = tmp_path / "topology" + generate_topology("fat-tree-k8", str(root)) + index = _CandidateIndex(load_topology("fat-tree-k8", str(root)), 42) + unit = next(u for u in coverage_units("fat-tree") if u.fault_type == fault and u.role == "core") + placement = index.place(unit) + source = placement.witnesses[0]["src"] + expected = set() + for src, dst in index.pairs: + forward = index.contains(src, dst, placement.device, placement.peer) + backward = index.contains(dst, src, placement.device, placement.peer) + if fault == "acl_source_misconfig": + matching = src == source and forward or dst == source and backward + elif fault == "acl_l4_port_misconfig": + matching = forward + else: + matching = forward or backward + if matching: + expected.add((src, dst)) + actual = {(pair["src"], pair["dst"]) for pair in placement.witnesses} + assert actual == expected + assert len(actual) > (1 if fault == "acl_source_misconfig" else 8) + + +def test_old_campaign_is_rejected(tmp_path): + root = tmp_path / "topology" + generate_topology("xs", str(root)) + with pytest.raises(ValueError, match="Obsolete campaign"): + generate({"fault_templates": []}, load_topology("xs", str(root)), tmp_path / "cases", 1) diff --git a/tests/test_scenario_schema.py b/tests/test_scenario_schema.py index de8dec6..887f1ed 100644 --- a/tests/test_scenario_schema.py +++ b/tests/test_scenario_schema.py @@ -1,16 +1,14 @@ """Schema regression tests for normalized scenario parameters.""" -import ipaddress import json -import random import pytest import yaml from netopsbench.models import topology as topology_models -from netopsbench.models.profiles import default_scale_registry +from netopsbench.models.profiles import get_scale_profile from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec -from netopsbench.models.topology import Collector, Device, DeviceRole, Management, TopologyManifest +from netopsbench.models.topology import TopologyManifest from netopsbench.platform.faults.specs import FaultSpec, create_fault_registry from netopsbench.platform.scenario import generator as scenario_generator from netopsbench.platform.scenario.executor import ScenarioExecutor @@ -20,120 +18,74 @@ def _minimal_canonical_topology() -> dict: - manifest = TopologyManifest( - topology_id="dcn", - name="dcn", - scale="xs", - family="clos", - management=Management(network="clab-dcn", ipv4_subnet="172.20.20.0/24"), - collector=Collector(ipv4="172.20.20.200"), - defaults=topology_models.TopologyDefaults(), - facts=topology_models.TopologyFacts( - num_spines=1, - num_leafs=1, - clients_per_attached_switch=1, - total_clients=0, - total_switches=2, - ), - routing=topology_models.RoutingMetadata(ecmp_hash_policy_by_role={DeviceRole.SPINE: 1, DeviceRole.LEAF: 1}), - devices=[ - Device(name="spine1", role=DeviceRole.SPINE), - Device(name="leaf1", role=DeviceRole.LEAF), - ], - links=[], - ) - return manifest.model_dump(mode="json") + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import TopologyConfig + + return build_clos_plan(TopologyConfig(scale_name="xs")).manifest.model_dump(mode="json") def test_all_diagnostic_observation_durations_use_complete_pingmesh_window(): - k12 = topology_models.PingmeshPolicy( - destination_batch_size=16, - rtt_port_pool_size=16, - rtt_ports_per_cycle=4, - cycle_interval_seconds=3, - ) - manifest = TopologyManifest.model_validate( - { - **_minimal_canonical_topology(), - "facts": { - "clients_per_attached_switch": 2, - "total_clients": 144, - "total_switches": 180, - }, - "pingmesh": k12.model_dump(), - } - ) + from netopsbench.platform.topology.config import config_for_scale + from netopsbench.platform.topology.fat_tree_builder import build_fat_tree_plan - assert scenario_generator.diagnostic_observation_duration(20, manifest) == 114 - assert scenario_generator.diagnostic_observation_duration(30, manifest) == 114 - assert scenario_generator.diagnostic_observation_duration(90, manifest) == 114 - assert scenario_generator.diagnostic_observation_duration(120, manifest) == 120 - - xlarge = manifest.model_copy( - update={ - "facts": manifest.facts.model_copy(update={"total_clients": 128}), - "pingmesh": topology_models.PingmeshPolicy( - destination_batch_size=16, - rtt_port_pool_size=16, - rtt_ports_per_cycle=4, - cycle_interval_seconds=3, - ), - } - ) - assert scenario_generator.diagnostic_observation_duration(30, xlarge) == 102 + manifest = build_fat_tree_plan(config_for_scale("fat-tree-k12")).manifest + profile = get_scale_profile("fat-tree-k12").experiment + complete = manifest.require_pingmesh_plan().settings.complete_window_seconds + for requested, expected in ((20, 42), (30, 42), (90, 90)): + assert profile.model_copy(update={"observation_seconds": requested}).window_seconds(complete) == expected @pytest.mark.parametrize( - ("scale", "expected_window"), + "scale,expected_window", [ ("xs", 7), - ("small", 7), ("medium", 8), - ("large", 54), - ("xlarge", 102), - ("fat-tree-k8", 102), - ("fat-tree-k12", 114), + ("large", 30), + ("xlarge", 66), + ("fat-tree-k8", 42), + ("fat-tree-k12", 42), + ("fat-tree-k18", 42), ], ) def test_builtin_scale_complete_windows_are_topology_derived(scale, expected_window): - profile = default_scale_registry().get(scale) - policy = topology_models.PingmeshPolicy( - destination_batch_size=profile.pingmesh_destination_batch_size, - rtt_port_pool_size=profile.pingmesh_rtt_port_pool_size, - rtt_ports_per_cycle=profile.pingmesh_rtt_ports_per_cycle, - cycle_interval_seconds=profile.pingmesh_cycle_interval_seconds, - ) + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import TopologyConfig, config_for_scale + from netopsbench.platform.topology.fat_tree_builder import build_fat_tree_plan - assert policy.complete_window_seconds(profile.total_clients) == expected_window - assert max(30, policy.complete_window_seconds(profile.total_clients)) == ( - expected_window if scale in {"large", "xlarge", "fat-tree-k8", "fat-tree-k12"} else 30 - ) + config = config_for_scale(scale) + manifest = (build_clos_plan if isinstance(config, TopologyConfig) else build_fat_tree_plan)(config).manifest + assert manifest.require_pingmesh_plan().settings.complete_window_seconds == expected_window + assert get_scale_profile(scale).experiment.window_seconds(expected_window) == max(30, expected_window) def test_custom_pingmesh_policy_derives_complete_window_without_scale_name(): + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import TopologyConfig + policy = topology_models.PingmeshPolicy( - destination_batch_size=10, - rtt_port_pool_size=12, - rtt_ports_per_cycle=3, - cycle_interval_seconds=3, + destination_batch_size=10, rtt_port_pool_size=12, rtt_ports_per_cycle=3, cycle_interval_seconds=3 ) - - assert policy.coverage_epoch_seconds(41) == 48 - assert policy.coverage_grace_seconds() == 6 - assert policy.complete_window_seconds(41) == 54 + manifest = build_clos_plan(TopologyConfig(num_leafs=42, scale_name="xs", pingmesh_policy=policy)).manifest + assert manifest.require_pingmesh_plan().settings.coverage_epoch_seconds == 60 + assert manifest.require_pingmesh_plan().settings.complete_window_seconds == 66 -def test_executor_recovery_wait_covers_one_pingmesh_cycle(tmp_path): +def test_executor_uses_v3_without_fixed_recovery_wait(tmp_path): metadata = _minimal_canonical_topology() metadata["pingmesh"]["cycle_interval_seconds"] = 3 + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + manifest = TopologyManifest.model_validate(metadata) + manifest.pingmesh_plan = compile_pingmesh_plan(manifest) + metadata = manifest.model_dump(mode="json") runner = ScenarioExecutor( topology_dir=str(tmp_path), topology_metadata=metadata, - post_recovery_wait_seconds=1, ) - assert runner.post_recovery_wait_seconds == 3 + assert runner.recovery_policy.version == 3 + assert not hasattr(runner, "post_recovery_wait_seconds") def test_parse_scenario_allows_none_episode_without_target_device(tmp_path): @@ -141,6 +93,7 @@ def test_parse_scenario_allows_none_episode_without_target_device(tmp_path): scenario_path.write_text( yaml.safe_dump( { + "metadata": {"recovery_policy": {"version": 3}}, "scenario_id": "baseline_only", "name": "Baseline Only", "description": "No fault episode", @@ -169,6 +122,7 @@ def test_validate_scenario_accepts_xlarge_scale(tmp_path): scenario_path.write_text( yaml.safe_dump( { + "metadata": {"recovery_policy": {"version": 3}}, "scenario_id": "generated_healthy_network_xlarge_001", "name": "XLarge healthy case", "description": "No fault episode", @@ -215,7 +169,7 @@ def test_parse_scenario_preserves_episode_parameters(tmp_path): "description": "parameter parsing", "topology_scale": "xs", "traffic_profile": "standard", - "metadata": {"difficulty": "medium"}, + "metadata": {"recovery_policy": {"version": 3}, "difficulty": "medium"}, "episode": { "episode_id": "diagnosis", "description": "fault", @@ -224,7 +178,7 @@ def test_parse_scenario_preserves_episode_parameters(tmp_path): "duration_seconds": 10, "stabilization_time": 1, "parameters": { - "target_ip": "192.168.102.2/32", + "target_ip": "192.168.2.2/32", "wrong_nexthop": "auto", }, }, @@ -237,7 +191,7 @@ def test_parse_scenario_preserves_episode_parameters(tmp_path): assert scenario.episode.fault_type == "static_route_misconfig" assert scenario.episode.parameters == { - "target_ip": "192.168.102.2/32", + "target_ip": "192.168.2.2/32", "wrong_nexthop": "auto", } assert validate_scenario(scenario) == [] @@ -253,7 +207,7 @@ def test_validate_scenario_rejects_blackhole_route_without_target_prefix(tmp_pat "description": "missing required prefix", "topology_scale": "xs", "traffic_profile": "standard", - "metadata": {"difficulty": "medium"}, + "metadata": {"recovery_policy": {"version": 3}, "difficulty": "medium"}, "episode": { "episode_id": "diagnosis", "description": "fault", @@ -270,7 +224,7 @@ def test_validate_scenario_rejects_blackhole_route_without_target_prefix(tmp_pat scenario = parse_scenario_file(str(scenario_path)) errors = validate_scenario(scenario) - assert any("blackhole_route requires target_prefix" in error for error in errors) + assert "Episode 0: blackhole_route requires target_prefix" in errors def test_validate_scenario_accepts_runtime_registered_fault(): @@ -280,7 +234,7 @@ def test_validate_scenario_accepts_runtime_registered_fault(): scenario_id="synthetic", name="Synthetic", topology_scale="xs", - metadata={"difficulty": "easy"}, + metadata={"recovery_policy": {"version": 3}, "difficulty": "easy"}, episode=EpisodeSpec( episode_id="diagnosis", fault_type="synthetic_schema_fault", @@ -290,24 +244,6 @@ def test_validate_scenario_accepts_runtime_registered_fault(): assert validate_scenario(scenario, fault_registry=registry) == [] -def test_validate_scenario_enforces_blackhole_route_target_prefix(): - scenario = ScenarioSpec( - scenario_id="blackhole_case", - name="Blackhole case", - topology_scale="xs", - metadata={"difficulty": "easy"}, - episode=EpisodeSpec( - episode_id="diagnosis", - fault_type="blackhole_route", - target_device="leaf1", - ), - ) - - errors = validate_scenario(scenario) - - assert "Episode 0: blackhole_route requires target_prefix" in errors - - def test_validate_scenario_runs_custom_fault_spec_validator(): def validate_episode(episode): if getattr(episode, "target_device", None) != "leaf1": @@ -320,7 +256,7 @@ def validate_episode(episode): scenario_id="synthetic_validator", name="Synthetic Validator", topology_scale="xs", - metadata={"difficulty": "easy"}, + metadata={"recovery_policy": {"version": 3}, "difficulty": "easy"}, episode=EpisodeSpec( episode_id="diagnosis", fault_type="synthetic_validated_fault", @@ -340,7 +276,7 @@ def test_validate_scenario_topology_accepts_fat_tree_agg_target(tmp_path): scenario_id="fat_tree_agg_fault", name="Fat-tree aggregation fault", topology_scale="fat-tree-k8", - metadata={"difficulty": "easy"}, + metadata={"recovery_policy": {"version": 3}, "difficulty": "easy"}, episode=EpisodeSpec( episode_id="diagnosis", fault_type="link_down", @@ -361,6 +297,7 @@ def test_validate_scenario_topology_rejects_window_shorter_than_manifest_require topology_dir = tmp_path / "generated_topology_xs" generate_topology("xs", str(topology_dir), name="xs-window") scenario = ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id="short-window", name="Short observation window", topology_scale="xs", @@ -391,124 +328,32 @@ def test_validate_scenario_topology_rejects_legacy_grouped_topology(tmp_path): encoding="utf-8", ) scenario = ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id="legacy_schema", name="Legacy schema", topology_scale="xs", episode=EpisodeSpec(episode_id="diagnosis", fault_type="none"), ) - with pytest.raises(ValueError, match="schema_version.*3.*Regenerate"): + with pytest.raises(ValueError, match="schema_version.*4.*Regenerate"): validate_scenario_topology(scenario, str(topology_dir)) -def test_scenario_generator_supports_fat_tree_roles_with_structured_artifacts(tmp_path): - topology_dir = tmp_path / "topology" - generate_topology("fat-tree-k8", str(topology_dir)) - topo = scenario_generator.load_topology("fat-tree-k8", str(topology_dir)) - - assert topo.cores[0] == "core1" - assert topo.aggs[0] == "agg1" - assert topo.edges[0] == "edge1" - assert "Ethernet0" in topo.device_interfaces["agg1"] - - spec = { - "defaults": {"count_per_fault": 1, "seed": 1}, - "fault_templates": [ - { - "name": "link_flapping_agg", - "fault_type": "link_flapping", - "device_role": "agg", - "interface_role": "uplink", - } - ], - } - generated = scenario_generator.generate(spec, topo, tmp_path / "scenarios", seed=1) - - scenario = parse_scenario_file(str(generated[0])) - assert scenario.topology_scale == "fat-tree-k8" - assert scenario.episode.target_device.startswith("agg") - assert validate_scenario(scenario) == [] - - -@pytest.mark.parametrize("location", ["defaults", "template"]) -def test_scenario_generator_rejects_nonstandard_traffic_profile(tmp_path, location): - topology_dir = tmp_path / "topology" - generate_topology("xs", str(topology_dir)) - topo = scenario_generator.load_topology("xs", str(topology_dir)) - spec = { - "defaults": {"count_per_fault": 1}, - "fault_templates": [{"name": "healthy", "fault_type": "none"}], - } - if location == "defaults": - spec["defaults"]["traffic_profile"] = "stress" - else: - spec["fault_templates"][0]["traffic_profile"] = "light" - - with pytest.raises(ValueError, match="Only the standard traffic profile is supported"): - scenario_generator.generate(spec, topo, tmp_path / "scenarios", seed=1) - - -def _xlarge_topology_context(tmp_path): +def test_scenario_generator_rejects_nonstandard_traffic_profile(tmp_path): topology_dir = tmp_path / "topology" - generate_topology("xlarge", str(topology_dir)) - return scenario_generator.load_topology("xlarge", str(topology_dir)) - - -def _pingmesh_destination_names(topo, src_leaf: str) -> set[str]: - clients = topo.manifest.clients() - sources = [client for client in clients if client.attached_switch == src_leaf] - return {destination.name for source in sources for destination in clients if destination.name != source.name} - - -def _client_for_prefix(topo, prefix: str) -> dict: - network = ipaddress.ip_network(prefix, strict=False) - return next(client for client in topo.clients if ipaddress.ip_address(client["data_ip"]) in network) - - -def _client_for_host_route(topo, host_route: str) -> dict: - host_ip = host_route.split("/", 1)[0] - return next(client for client in topo.clients if client["data_ip"] == host_ip) - - -def test_xlarge_blackhole_route_targets_pingmesh_observable_destination(tmp_path): - topo = _xlarge_topology_context(tmp_path) - - scenario = scenario_generator.build_fault_instance( - "blackhole_route", - "medium", - topo, - random.Random(1), - {"seed": 1}, - {"name": "blackhole_route_leaf", "fault_type": "blackhole_route", "device_role": "leaf"}, - 1, - ) - - fault = scenario["episode"] - target_client = _client_for_prefix(topo, fault["target_prefix"]) - - assert target_client["name"] in _pingmesh_destination_names(topo, fault["target_device"]) - - -def test_xlarge_static_route_targets_pingmesh_observable_destination(tmp_path): - topo = _xlarge_topology_context(tmp_path) - - scenario = scenario_generator.build_fault_instance( - "static_route_misconfig", - "medium", - topo, - random.Random(1), - {"seed": 1}, - {"name": "static_route_misconfig", "fault_type": "static_route_misconfig", "device_role": "leaf"}, - 1, - ) - - fault = scenario["episode"] - target_client = _client_for_host_route(topo, fault["metadata"]["target_ip"]) - - assert target_client["name"] in _pingmesh_destination_names(topo, fault["target_device"]) + generate_topology("medium", str(topology_dir)) + topo = scenario_generator.load_topology("medium", str(topology_dir)) + with pytest.raises(ValueError, match="Only standard traffic"): + scenario_generator.generate( + {"fault_catalog_version": 2, "defaults": {"traffic_profile": "stress"}}, + topo, + tmp_path / "scenarios", + seed=1, + ) -def test_scenario_runner_prefers_parameters_over_metadata(monkeypatch): +@pytest.mark.parametrize("parameters", [{"target_ip": "new", "wrong_nexthop": "new-hop"}, {}]) +def test_builtin_faults_read_only_parameters_not_descriptive_metadata(monkeypatch, parameters): runner = ScenarioExecutor( topology_dir="lab-topology", topology_metadata=_minimal_canonical_topology(), @@ -529,7 +374,7 @@ def fake_inject(device, target_ip, wrong_nexthop): fault_type="static_route_misconfig", target_device="leaf1", metadata={"target_ip": "old", "wrong_nexthop": "old-hop"}, - parameters={"target_ip": "new", "wrong_nexthop": "new-hop"}, + parameters=parameters, ) result = runner._inject_fault(episode) @@ -537,11 +382,30 @@ def fake_inject(device, target_ip, wrong_nexthop): assert result["success"] is True assert captured == { "device": "leaf1", - "target_ip": "new", - "wrong_nexthop": "new-hop", + "target_ip": parameters.get("target_ip"), + "wrong_nexthop": parameters.get("wrong_nexthop"), } +def test_mtu_injection_reads_the_canonical_episode_parameters(monkeypatch): + runner = ScenarioExecutor(topology_dir="lab-topology", topology_metadata=_minimal_canonical_topology()) + captured = [] + monkeypatch.setattr( + runner.injector, "inject_mtu_mismatch", lambda device, interface, mtu: captured.append(mtu) or {"success": True} + ) + result = runner._inject_fault( + EpisodeSpec( + episode_id="mtu", + fault_type="mtu_mismatch", + target_device="leaf1", + target_interface="Ethernet0", + parameters={"mtu": 1450}, + ) + ) + assert result["success"] + assert captured == [1450] + + def test_scenario_executor_returns_result_for_session_persistence(monkeypatch): events = [] runner = ScenarioExecutor( @@ -555,29 +419,30 @@ def setup_traffic(scale, profile): events.append("traffic_ready") return {"scale": scale, "profile": profile} - baseline = {"start_time": "baseline-start", "end_time": "baseline-end", "duration_seconds": 7} + from datetime import UTC, datetime, timedelta + + from netopsbench.platform.scenario.baseline import RuntimeScope + + baseline = { + "start_time": (datetime.now(UTC) - timedelta(seconds=7)).isoformat(), + "end_time": datetime.now(UTC).isoformat(), + "duration_seconds": 7, + } + monkeypatch.setattr(runner, "_baseline_scope", lambda _: RuntimeScope({}, {}, {})) + monkeypatch.setattr("netopsbench.platform.observability.routes.collect_routes", lambda *a, **k: {"nodes": {}}) def capture_baseline(): events.append("baseline_captured") return baseline - def observe(duration, *, baseline_window): + def observe(windows, total_duration_seconds, *, baseline_window): is_validation = len([event for event in events if event.endswith("_observed")]) == 0 events.append("validation_observed" if is_validation else "current_observed") - assert baseline_window == ( - baseline - if is_validation - else { - "name": "baseline", - "start_time": "current-start", - "end_time": "current-end", - "duration_seconds": 7, - } - ) + assert baseline_window == baseline return { - "start_time": "current-start", - "end_time": "current-end", - "duration_seconds": duration, + "start_time": "2026-01-01T00:00:00Z", + "end_time": "2026-01-01T00:00:07Z", + "duration_seconds": total_duration_seconds, "pingmesh_metrics": { "summary": { "total_anomalies": 0, @@ -589,6 +454,11 @@ def observe(duration, *, baseline_window): "quality": {"current_paths_observed": 2, "local_df_mtu_drops": 0}, "anomalies": [], }, + "_baseline_health": { + "absolute_unreachable_paths": 0, + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, "anomalies_detected": False, "coverage_status": "complete", "data_source_status": "ok", @@ -598,11 +468,21 @@ def observe(duration, *, baseline_window): monkeypatch.setattr(runner, "_setup_traffic", setup_traffic) monkeypatch.setattr(runner, "_capture_baseline_window", capture_baseline) - monkeypatch.setattr(runner, "_wait_and_observe", observe) + monkeypatch.setattr( + runner, + "_capture_observation_window", + lambda duration, name: { + "start_time": "2026-01-01T00:00:00Z", + "end_time": "2026-01-01T00:00:15Z", + "duration_seconds": duration, + }, + ) + monkeypatch.setattr(runner, "_merge_observation_windows", observe) monkeypatch.setattr(runner, "_stop_traffic", lambda: None) monkeypatch.setattr(runner, "_recover_fault", lambda: {"success": True}) scenario = ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id="no-persist", name="No Persist", description="test", @@ -625,6 +505,11 @@ def test_fault_observation_stabilization_is_inside_total_duration_budget(): calls = [] class Executor: + from netopsbench.platform.scenario.timing import PhaseTimings + + timings = PhaseTimings() + observation_timeout_seconds = 60 + def _inject_fault(self, _episode): return {"success": True} @@ -632,8 +517,8 @@ def _capture_observation_window(self, duration, name): calls.append((name, duration)) return { "name": name, - "start_time": f"{name}-start", - "end_time": f"{name}-end", + "start_time": "2026-10-24T00:00:00Z", + "end_time": "2026-10-24T00:01:54Z", "duration_seconds": duration, } @@ -676,8 +561,6 @@ def _merge_observation_windows( ) assert calls == [ - ("early", 20), - ("stabilization", 5), - ("steady", 89), + ("full", 114), ("merge", 114, 2), ] diff --git a/tests/test_session_dispatch.py b/tests/test_session_dispatch.py index 1751b3d..50ab2f3 100644 --- a/tests/test_session_dispatch.py +++ b/tests/test_session_dispatch.py @@ -27,6 +27,9 @@ def run_scenario(self, scenario, diagnosis_callback=None): "episode": {}, } + def final_calibration(self, scenario, **kwargs): + return {"success": True} + def close(self): type(self).closed += 1 @@ -52,6 +55,7 @@ def generate_report(self, results, agent_name="unknown", topology_scale="unknown def _scenario(scenario_id: str) -> ScenarioSpec: return ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id=scenario_id, name=scenario_id, description="test", @@ -87,7 +91,89 @@ def test_worker_context_uses_lab_name_for_observability_topology_id(tmp_path): context = build_worker_execution_context(worker, Path(worker.topology_dir)) assert context.topology_id == "lab-1" - assert "NETOPSBENCH_TOPOLOGY_ID" not in context.as_env() + assert context.topology_dir == worker.topology_dir + assert context.influxdb_bucket == worker.bucket + + +@pytest.mark.parametrize( + ("domain", "phase", "cleanup", "valid", "cancelled", "cleanup_errors", "continues"), + [ + ("agent", "diagnosis", True, True, False, [], True), + ("agent", "limits", True, True, False, [], True), + ("protocol", "diagnosis", True, True, False, [], True), + ("infrastructure", "observation", True, False, False, [], False), + ("agent", "diagnosis", False, True, False, [], False), + ("agent", "diagnosis", None, True, False, [], False), + ("agent", "diagnosis", True, True, True, [], False), + ("agent", "diagnosis", True, True, False, ["container cleanup failed"], False), + ("agent", "observation", True, True, False, [], False), + ], +) +def test_acceptance_continues_only_after_recovered_agent_failure( + tmp_path, monkeypatch, domain, phase, cleanup, valid, cancelled, cleanup_errors, continues +): + import threading + + import netopsbench.platform.session.dispatch as dispatch + + cancel = threading.Event() + executed, checkpoints, built, closed, quarantined = [], [], [], [], [] + + class Runner: + evaluator = None + + def run_scenario(self, scenario, diagnosis_callback=None): + executed.append(scenario.id) + if scenario.id == "first": + if cancelled: + cancel.set() + return { + "success": False, + "case_valid": valid, + "cleanup": {} if cleanup is None else {"success": cleanup}, + "episode": { + "execution": {"failure": {"domain": domain, "phase": phase}}, + "diagnosis": {"metadata": {"cleanup_errors": cleanup_errors}}, + }, + } + return {"success": True, "case_valid": True, "cleanup": {"success": True}, "episode": {}} + + def final_calibration(self, scenario, **kwargs): + return {"success": True} + + def close(self): + closed.append(True) + + def build(*args, **kwargs): + built.append(True) + return Runner() + + monkeypatch.setattr(dispatch, "_build_scenario_executor", build) + monkeypatch.setattr(dispatch, "build_worker_execution_context", lambda *a: SimpleNamespace(topology_dir=tmp_path)) + monkeypatch.setattr(dispatch, "require_scenario_topology", lambda *a: None) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *a, **kw: None) + runtime = SimpleNamespace(id="runtime", mark_quarantined=lambda *a: quarantined.append(a)) + result = dispatch._run_worker( + runtime=runtime, + agent=None, + raw_dir=tmp_path, + trace_writer=None, + fault_registry=None, + minimum_baseline_seconds=None, + scale_registry=None, + worker=SimpleNamespace(worker_id="worker-1", lab_name="lab", topology_dir=tmp_path), + scenarios=[_scenario("first"), _scenario("second")], + control=dispatch.ExecutionControl( + on_case=lambda summary, *args: checkpoints.append(summary), stop_on_failure=True, cancel_event=cancel + ), + ) + assert executed == (["first", "second"] if continues else ["first"]) + assert len(built) == len(closed) == 1 + assert len(checkpoints) == len(executed) + assert dispatch.is_recovered_case_failure(checkpoints[0]) is continues + assert bool(quarantined) is (cleanup is False) + assert result[2]["success"] is False + assert result[0] == [] # Failed agent execution must not create a score. def test_worker_context_uses_explicit_identity_topology_id(tmp_path): @@ -99,6 +185,59 @@ def test_worker_context_uses_explicit_identity_topology_id(tmp_path): assert context.topology_id == "runtime-observability-id" +@pytest.mark.parametrize( + ("recovery_verified", "effects_only", "continues"), + [(True, False, True), (False, False, False), (True, True, False)], +) +def test_invalid_effect_continues_only_after_verified_health( + tmp_path, monkeypatch, recovery_verified, effects_only, continues +): + import netopsbench.platform.session.dispatch as dispatch + + class Runner(_FakeRunner): + def run_scenario(self, scenario, diagnosis_callback=None): + if scenario.id == "invalid": + return { + "success": False, + "case_valid": False, + "error": "Owned ACL rule has no verified hits", + "episode": {"effect_audit": {"valid": False}}, + "cleanup": { + "success": True, + **({"validated_baseline": {"duration_seconds": 42}} if recovery_verified else {}), + }, + } + return {"success": True, "case_valid": True, "cleanup": {"success": True}, "episode": {}} + + runtime = RuntimePool( + id="runtime-1", + name="runtime-1", + scale="xs", + root_dir=tmp_path / "runtime", + workers=[_worker(tmp_path, 1)], + state="warm", + ) + monkeypatch.setattr(dispatch, "ScenarioExecutor", Runner) + monkeypatch.setattr(dispatch, "_create_evaluator", _FakeEvaluator) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *a, **kw: None) + monkeypatch.setattr(dispatch, "load_topology_metadata", lambda *a: None) + monkeypatch.setattr(dispatch, "require_scenario_topology", lambda *a: None) + result = execute_on_runtime_pool( + runtime=runtime, + scenarios=[_scenario("invalid"), _scenario("next")], + agent=None, + raw_dir=tmp_path / "raw", + control=dispatch.ExecutionControl(stop_on_failure=True, effects_only=effects_only), + ) + first = result.scenarios[0] + assert first["status"] == "invalid" and first["case_valid"] is False + assert dispatch.is_recovered_case_failure(first) is continues + assert result.workers[0]["executed_count"] == (2 if continues else 1) + assert result.scenarios[1]["status"] == ("completed" if continues else "skipped_execution_failure") + assert result.evaluations == [] + assert runtime.state == "warm" + + def test_worker_context_rejects_topology_directory_mismatch(tmp_path): worker = _worker(tmp_path, 1) @@ -127,7 +266,7 @@ def score_episode(_scenario, scenario_result, evaluator, **_kwargs): monkeypatch.setattr(dispatch, "ScenarioExecutor", _FakeRunner) monkeypatch.setattr(dispatch, "_create_evaluator", _FakeEvaluator) monkeypatch.setattr(dispatch, "score_scenario_episode", score_episode) - monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *_args: lambda _payload: {}) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *_args, **_kwargs: lambda _payload: {}) monkeypatch.setattr( dispatch, "build_worker_execution_context", @@ -165,7 +304,7 @@ def test_execute_on_runtime_pool_rejects_scenario_scale_mismatch(tmp_path): runtime = RuntimePool( id="runtime-1", name="runtime-1", - scale="small", + scale="medium", root_dir=tmp_path / "runtime", workers=[_worker(tmp_path, 1)], state="warm", @@ -240,7 +379,7 @@ def run_scenario(self, scenario, diagnosis_callback=None): "score_scenario_episode", lambda _scenario, _result, evaluator, **_kwargs: [SimpleNamespace(score=1.0, evaluator_id=evaluator.id)], ) - monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *_args: lambda _payload: {}) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *_args, **_kwargs: lambda _payload: {}) monkeypatch.setattr( dispatch, "build_worker_execution_context", @@ -285,6 +424,7 @@ def run_scenario(self, scenario, diagnosis_callback=None): "executed_count": 2, "skipped_count": 0, "success": True, + "final_calibration": {"success": True}, }, ] assert runtime.metadata["quarantined"] is True @@ -319,7 +459,7 @@ def run_scenario(self, scenario, diagnosis_callback=None): ) monkeypatch.setattr(dispatch, "ScenarioExecutor", InvalidCleanupRunner) monkeypatch.setattr(dispatch, "_create_evaluator", _FakeEvaluator) - monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *_args: lambda _payload: {}) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *_args, **_kwargs: lambda _payload: {}) monkeypatch.setattr( dispatch, "build_worker_execution_context", @@ -346,3 +486,52 @@ def run_scenario(self, scenario, diagnosis_callback=None): assert result.evaluations == [] assert runtime.state == "quarantined" assert runtime.metadata["quarantined_workers"] == ["worker-1"] + + +@pytest.mark.parametrize("failed", [False, True]) +def test_final_calibration_is_reported_and_failure_quarantines_without_rescoring(tmp_path, monkeypatch, failed): + import netopsbench.platform.session.dispatch as dispatch + from netopsbench.models.recovery import RecoveryPolicy + + calls, quarantined = [], [] + score = object() + + class Runner: + evaluator = object() + + def run_scenario(self, scenario, diagnosis_callback=None): + return {"success": True, "case_valid": True, "cleanup": {"success": True}, "episode": {}} + + def final_calibration(self, scenario, **kwargs): + calls.append("calibration") + if failed: + raise RuntimeError("late loss") + return {"success": True} + + def close(self): + calls.append("close") + + monkeypatch.setattr(dispatch, "_build_scenario_executor", lambda *a, **k: Runner()) + monkeypatch.setattr(dispatch, "build_worker_execution_context", lambda *a: SimpleNamespace(topology_dir=tmp_path)) + monkeypatch.setattr(dispatch, "require_scenario_topology", lambda *a: None) + monkeypatch.setattr(dispatch, "build_runtime_diagnosis_callback", lambda *a, **k: None) + monkeypatch.setattr(dispatch, "score_scenario_episode", lambda *a, **k: calls.append("score") or [score]) + case = _scenario("one") + case.metadata["recovery_policy"] = RecoveryPolicy().model_dump() + evaluations, summaries, worker = dispatch._run_worker( + runtime=SimpleNamespace(id="runtime", mark_quarantined=lambda *a: quarantined.append(a)), + agent=None, + raw_dir=tmp_path, + trace_writer=None, + fault_registry=None, + minimum_baseline_seconds=None, + scale_registry=None, + worker=SimpleNamespace(worker_id="worker-1", lab_name="lab", topology_dir=tmp_path), + scenarios=[case], + ) + assert evaluations == [score] + assert calls == ["score", "calibration", "close"] + assert worker["success"] is (not failed) + assert bool(quarantined) is failed + assert summaries[0]["status"] == "completed" + assert (tmp_path / "worker-1" / "final_calibration.json").exists() diff --git a/tests/test_session_reporting.py b/tests/test_session_reporting.py index 71961d0..ee6aceb 100644 --- a/tests/test_session_reporting.py +++ b/tests/test_session_reporting.py @@ -36,7 +36,7 @@ def test_session_runtime_loader_preserves_canonical_topology_schema(tmp_path: Pa metadata = load_topology_metadata(topology_dir) - assert metadata["schema_version"] == "3" + assert metadata["schema_version"] == "4" assert isinstance(metadata["devices"], list) assert {device["role"] for device in metadata["devices"]} == {"spine", "leaf", "client"} @@ -49,18 +49,19 @@ def test_session_runtime_loader_requires_canonical_topology(tmp_path: Path): load_topology_metadata(missing) -def test_create_run_report_preserves_topology_scale_and_agent_name(tmp_path: Path): +@pytest.mark.parametrize("mode", ["suite", "effects"]) +def test_create_run_report_preserves_topology_scale_and_agent_name(tmp_path: Path, mode): runtime = SimpleNamespace( id="run-0001-runtime", - scale="small", + scale="medium", scale_registry=default_scale_registry(), ) agent = SimpleNamespace(name="agent-x") - scenario = SimpleNamespace(id="generated_link_down_small_001", scale="small") + scenario = SimpleNamespace(id="generated_link_down_medium_001", scale="medium") report = create_run_report( run_id="run-0001", - mode="suite", + mode=mode, started_at=datetime(2026, 4, 29, 1, 0, tzinfo=UTC), completed_at=datetime(2026, 4, 29, 2, 0, tzinfo=UTC), runtime=runtime, @@ -72,7 +73,7 @@ def test_create_run_report_preserves_topology_scale_and_agent_name(tmp_path: Pat scenario_summaries=[], aggregate_report={ "agent_name": "agent-x", - "topology_scale": "small", + "topology_scale": "medium", "summary": {"total_cases": 1, "overall_accuracy": 1.0}, "detailed_results": [], }, @@ -85,18 +86,25 @@ def test_create_run_report_preserves_topology_scale_and_agent_name(tmp_path: Pat ) assert report["agent_name"] == "agent-x" - assert report["topology_scale"] == "small" + assert report["topology_scale"] == "medium" assert report["summary"]["agent_name"] == "agent-x" - assert report["summary"]["topology_scale"] == "small" - assert report["raw"]["topology_scale"] == "small" + assert report["summary"]["topology_scale"] == "medium" + assert report["raw"]["topology_scale"] == "medium" assert report["scale_registry_sha256"] == runtime.scale_registry.digest - assert report["scale_profile_sha256"] == runtime.scale_registry.get("small").digest - assert report["resolved_scale_profile"]["name"] == "small" + assert report["scale_profile_sha256"] == runtime.scale_registry.get("medium").digest + assert report["resolved_scale_profile"]["name"] == "medium" assert report["artifact_paths"]["traces_dir"] == str(tmp_path / "traces") assert report["artifact_paths"]["trace_index"] == str(tmp_path / "traces" / "index.jsonl") + from netopsbench.sdk.sessions import _benchmark_report_from_payload + public = _benchmark_report_from_payload(report).to_dict() + assert public["summary"]["fault_catalog_version"] == 2 + assert public["summary"]["included_in_benchmark"] is (mode != "effects") + assert public["raw"]["purpose"] == "benchmark" -def test_session_report_keeps_execution_and_cleanup_failures_separate(tmp_path: Path, monkeypatch): + +@pytest.mark.parametrize("execution_error", [ValueError, KeyboardInterrupt]) +def test_session_report_keeps_execution_and_cleanup_failures_separate(tmp_path: Path, monkeypatch, execution_error): class FailingRuntime: id = "runtime-1" scale = "xs" @@ -109,12 +117,12 @@ def teardown(self): monkeypatch.setattr(orchestrator, "_provision_runtime", lambda **_kwargs: FailingRuntime()) def fail_execution(**_kwargs): - raise ValueError("execution exploded") + raise execution_error("execution exploded") monkeypatch.setattr(orchestrator, "_execute_on_runtime_pool", fail_execution) - scenario = SimpleNamespace(id="scenario-1", scale="xs") + scenario = SimpleNamespace(id="scenario-1", scale="xs", metadata={"recovery_policy": {"version": 3}}) - with pytest.raises(ValueError, match="execution exploded") as raised: + with pytest.raises(execution_error, match="execution exploded") as raised: orchestrator._run_with_platform_runtime( mode="scenario", scenarios=[scenario], @@ -133,7 +141,7 @@ def fail_execution(**_kwargs): report = json.loads(reports[0].read_text()) assert report["status"] == "failed" assert report["raw"]["teardown"] == "failed" - assert report["raw"]["execution_failure"] == {"type": "ValueError", "message": "execution exploded"} + assert report["raw"]["execution_failure"] == {"type": execution_error.__name__, "message": "execution exploded"} assert report["raw"]["cleanup_failure"] == {"type": "OSError", "message": "cleanup exploded"} @@ -165,7 +173,7 @@ def execute(**kwargs): return SimpleNamespace(refresh=lambda: None) monkeypatch.setattr(orchestrator, "_execute_on_runtime_pool", execute) - scenario = SimpleNamespace(id="scenario-1", scale="xs") + scenario = SimpleNamespace(id="scenario-1", scale="xs", metadata={"recovery_policy": {"version": 3}}) orchestrator._run_with_platform_runtime( mode="scenario", scenarios=[scenario], diff --git a/tests/test_session_scoring.py b/tests/test_session_scoring.py new file mode 100644 index 0000000..d6ae0cf --- /dev/null +++ b/tests/test_session_scoring.py @@ -0,0 +1,81 @@ +"""Persisted incident grades skip independent ground-truth reconstruction.""" + +from types import SimpleNamespace + +from netopsbench.evaluator.scorer import EvaluationResult +from netopsbench.platform.session import scoring + + +def test_persisted_grade_does_not_rebuild_truth_or_call_evaluator(monkeypatch): + def unexpected(*args, **kwargs): + raise AssertionError("Persisted scores must not query topology or evaluate again") + + monkeypatch.setattr(scoring, "build_episode_ground_truth", unexpected) + grade = EvaluationResult("opaque-incident", True, True, False, True, 0.5) + result = scoring.score_scenario_episode( + SimpleNamespace(scenario_id="scenario", metadata={}), + { + "episode": { + "episode": {"episode_id": "case", "fault_type": "link_down"}, + "evaluation_result": grade.to_dict(), + } + }, + SimpleNamespace(evaluate=unexpected), + ) + assert len(result) == 1 and result[0].score == 0.5 + assert result[0].testcase_id == "opaque-incident" + assert result[0].details["episode_id"] == "case" + + +def test_independent_evaluation_still_builds_truth_when_grade_is_absent(monkeypatch): + truth = {"device": "leaf1"} + calls = [] + monkeypatch.setattr( + scoring, "build_episode_ground_truth", lambda episode, directory: calls.append(directory) or truth + ) + + def evaluate(agent, ground_truth, testcase_id): + assert ground_truth is truth + assert agent.verdict == "inconclusive" + return EvaluationResult(testcase_id, False, False, False, False, 0) + + result = scoring.score_scenario_episode( + SimpleNamespace(scenario_id="scenario", metadata={}), + {"episode": {"episode": {"episode_id": "case", "fault_type": "link_down"}}}, + SimpleNamespace(evaluate=evaluate), + topology_dir="topology", + ) + assert calls == ["topology"] + assert result[0].score == 0 + + +def test_diagnosis_entrypoint_precedence_is_preserved(): + from netopsbench.agents.base import DiagnosisResult + from netopsbench.evaluator.scorer import AgentOutput + + diagnosis = DiagnosisResult( + agent_name="custom", + verdict="fault_detected", + findings={ + "location": {"device": "leaf1"}, + "device": "leaf2", + "interface": "Ethernet0", + "tool_calls": [{"tool": "findings"}], + }, + metadata={"evidence": ["metadata evidence"], "fault_type": "link_down", "time_taken_seconds": 9}, + ) + sdk = AgentOutput.from_diagnosis(diagnosis) + runtime = AgentOutput.from_diagnosis( + diagnosis, + merge_location_fields=True, + metadata_evidence=False, + findings_tool_calls=False, + time_taken_seconds=2, + ) + assert sdk.location == {"device": "leaf1"} + assert runtime.location == {"device": "leaf1", "interface": "Ethernet0"} + assert sdk.evidence == ["metadata evidence"] and runtime.evidence == [] + assert sdk.tool_calls == [{"tool": "findings"}] and runtime.tool_calls == [] + assert sdk.time_taken_seconds == 9 and runtime.time_taken_seconds == 2 + assert sdk.fault_type == runtime.fault_type == "link_down" + assert diagnosis.findings["location"] == {"device": "leaf1"} diff --git a/tests/test_session_tracing.py b/tests/test_session_tracing.py index 760dd88..2c7dcca 100644 --- a/tests/test_session_tracing.py +++ b/tests/test_session_tracing.py @@ -148,7 +148,7 @@ def test_trace_writer_persists_atif_and_index_with_redaction(tmp_path): worker="worker-1", topology_id="topo-1", runtime_id="runtime-1", - topology_scale="small", + topology_scale="medium", agent=SimpleNamespace(name="agent-x"), diagnostic_context=context, diagnosis=diagnosis, @@ -173,13 +173,13 @@ def test_trace_writer_persists_atif_and_index_with_redaction(tmp_path): assert atif["steps"][2]["message"].startswith("Final diagnosis:") assert atif["extra"]["final_diagnosis"]["metadata"]["OPENAI_API_KEY"] == "" assert atif["extra"]["final_diagnosis"]["metadata"]["worker_env"]["NETOPSBENCH_TOKEN"] == "" - assert atif["extra"]["topology_scale"] == "small" + assert atif["extra"]["topology_scale"] == "medium" assert atif["final_metrics"]["total_prompt_tokens"] == 10 assert index[0]["case_id"] == "case-123" assert index[0]["status"] == "completed" assert index[0]["provider"] == "openai" assert index[0]["model"] == "gpt-test" - assert index[0]["topology_scale"] == "small" + assert index[0]["topology_scale"] == "medium" assert index[0]["started_at"] == "2026-01-01T00:00:00+00:00" assert index[0]["duration_seconds"] == 2.0 @@ -197,7 +197,7 @@ def test_trace_writer_falls_back_to_agent_display_metadata_on_early_failure(tmp_ worker="worker-1", topology_id="topo-1", runtime_id="runtime-1", - topology_scale="small", + topology_scale="medium", agent=agent, diagnostic_context=context, diagnosis=diagnosis, @@ -212,7 +212,7 @@ def test_trace_writer_falls_back_to_agent_display_metadata_on_early_failure(tmp_ assert index[0]["provider"] == "deepseek" assert index[0]["model"] == "deepseek-v4-pro" - assert index[0]["topology_scale"] == "small" + assert index[0]["topology_scale"] == "medium" assert atif["agent"]["model_name"] == "deepseek-v4-pro" assert atif["agent"]["extra"]["provider"] == "deepseek" @@ -274,7 +274,7 @@ def test_export_traces_writes_harbor_jobs_directory(tmp_path): worker="worker-1", topology_id="topo", runtime_id="runtime", - topology_scale="small", + topology_scale="medium", agent=SimpleNamespace(name="agent"), diagnostic_context=context, diagnosis=diagnosis, @@ -329,12 +329,12 @@ def test_export_traces_writes_harbor_jobs_directory(tmp_path): eval_stats = next(iter(job_result["stats"]["evals"].values())) assert eval_stats["metrics"][0]["reward"] == 1.0 assert eval_stats["metrics"][0]["score"] == 1.0 - assert job_config["datasets"][0]["name"] == "netopsbench-small" + assert job_config["datasets"][0]["name"] == "netopsbench-medium" assert job_config["agents"][0]["name"] == "agent" assert job_config["agents"][0]["model_name"] == "openai/gpt-test" assert trial_result["task_name"] == "scenario-1" - assert trial_result["source"] == "netopsbench-small" - assert trial_result["config"]["task"]["source"] == "netopsbench-small" + assert trial_result["source"] == "netopsbench-medium" + assert trial_result["config"]["task"]["source"] == "netopsbench-medium" assert trial_result["agent_info"]["model_info"]["provider"] == "openai" assert trial_result["agent_result"]["n_input_tokens"] == 5 assert verifier["reward"] == 1.0 diff --git a/tests/test_simulator_runtime.py b/tests/test_simulator_runtime.py index b17d24d..0db2252 100644 --- a/tests/test_simulator_runtime.py +++ b/tests/test_simulator_runtime.py @@ -31,12 +31,12 @@ ToolAction, ) from netopsbench.platform.simulator.runtime import RuntimeEpisodeBackend, RuntimeLeasePool, WarmRuntime -from netopsbench.platform.topology.generator import generate_topology from netopsbench.sdk.simulators import SimulatorManager def _scenario(*, healthy: bool = False) -> ScenarioSpec: return ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, scenario_id="scenario-1", name="scenario-1", topology_scale="xs", @@ -543,248 +543,54 @@ def test_observation_integrity_does_not_reject_real_network_anomalies(): assert observation_integrity_errors(observation) == [] -def test_simulator_builds_reference_and_validation_once_then_reuses_latest_window(tmp_path): - topology_dir = tmp_path / "xs-topology" - generate_topology("xs", str(topology_dir), name="sim-baseline") - reference = { - "name": "baseline", - "start_time": "2026-01-01T00:00:00Z", - "end_time": "2026-01-01T00:01:00Z", - "duration_seconds": 60, - } - calls = [] - - class BaselineRunner: - def __init__(self): - self.topology_dir = topology_dir - self.traffic_controller = object() - - def _capture_baseline_window(self): - calls.append("reference") - return reference - - def _wait_and_observe(self, duration, *, baseline_window): - calls.append(("validation", duration, baseline_window)) - return _baseline_observation() - - runner = BaselineRunner() - record = WarmRuntime(runtime=FakeRuntime("xs"), runner=runner) - backend = RuntimeEpisodeBackend(SimpleNamespace(), default_scale_registry()) - backend.record = record - - backend._ensure_baseline(_scenario(healthy=True)) - backend._ensure_baseline(_scenario(healthy=True)) - - assert calls == ["reference", ("validation", 60, reference)] - assert record.baseline == { - "name": "baseline", - "start_time": "2026-01-01T00:01:00Z", - "end_time": "2026-01-01T00:02:00Z", - "duration_seconds": 60, - } - - runner.traffic_controller = object() - backend._ensure_baseline(_scenario(healthy=True)) - assert calls.count("reference") == 2 - - -def test_simulator_rebuilds_missing_traffic_once_and_invalidates_baseline(monkeypatch): +@pytest.mark.parametrize("failure", [None, "Background traffic matrix incomplete", "Healthy baseline is unavailable"]) +def test_simulator_delegates_preparation_and_quarantines_failed_preparation(monkeypatch, failure): events = [] - - class StaleTraffic: - active_flows = {"flow": object()} - - @staticmethod - def verify_active_flows(): - events.append("verify") - return False - - class FreshTraffic: - active_flows = {"fresh": object()} - - class Runner: - topology_dir = "unused" - post_recovery_wait_seconds = 0 - - def __init__(self): - self.traffic_controller = StaleTraffic() - - @staticmethod - def _recover_fault(): - return [] - - def _stop_traffic(self): - events.append("stop") - self.traffic_controller = None - - def _setup_traffic(self, scale, profile): - events.append(("setup", scale, profile)) - self.traffic_controller = FreshTraffic() - - worker = SimpleNamespace(topology_dir="unused", bucket="bucket", topology_id="topology") - record = WarmRuntime( - runtime=SimpleNamespace(workers=[worker]), - runner=Runner(), - baseline_signature="old-signature", - baseline={"name": "old"}, - ) - - class Leases: - @staticmethod - def acquire(_scale): - return record - - @staticmethod - def release(_record): - events.append("release") - - @staticmethod - def quarantine(_record): - events.append("quarantine") - - class Delegate: - def __init__(self, *args, **kwargs): - pass - - @staticmethod - def prepare(_scenario): - return {"case_id": "case-test"} - - @staticmethod - def finish(*, broken=False): - events.append(("finish", broken)) - - backend = RuntimeEpisodeBackend(Leases(), default_scale_registry()) - monkeypatch.setattr(backend, "_health_errors", lambda *args, **kwargs: []) - - def ensure_baseline(_scenario): - assert record.baseline_signature is None - assert record.baseline is None - events.append("baseline") - - monkeypatch.setattr(backend, "_ensure_baseline", ensure_baseline) - monkeypatch.setattr(simulator_runtime_module, "ExecutorIncidentBackend", Delegate) - validated = [] - monkeypatch.setattr( - simulator_runtime_module, - "require_scenario_topology", - lambda scenario, topology_dir: validated.append((scenario.id, topology_dir)), - ) - - result = backend.prepare(_scenario(healthy=True)) - - assert result == {"case_id": "case-test"} - assert events[:4] == ["verify", "stop", ("setup", "xs", "standard"), "baseline"] - assert validated == [("scenario-1", "unused")] - - -def test_simulator_rebuilds_baseline_after_recovering_lingering_fault(monkeypatch): - class Traffic: - active_flows = {"flow": object()} - - @staticmethod - def verify_active_flows(): - return True - runner = SimpleNamespace( - traffic_controller=Traffic(), - topology_dir="unused", - post_recovery_wait_seconds=0, - sleep=lambda _seconds: None, - _recover_fault=lambda: [{"type": "link_down", "recovered": True}], + topology_dir="unused", begin_case=lambda: None, _baseline_handoff=SimpleNamespace(clear=lambda reason: None) ) worker = SimpleNamespace(topology_dir="unused", bucket="bucket", topology_id="topology") - record = WarmRuntime( - runtime=SimpleNamespace(workers=[worker]), - runner=runner, - baseline_signature="stale", - baseline={"name": "stale"}, + record = WarmRuntime(runtime=SimpleNamespace(workers=[worker]), runner=runner) + leases = SimpleNamespace( + acquire=lambda scale: record, + release=lambda record: events.append("release"), + quarantine=lambda record: events.append("quarantine"), ) - class Leases: - @staticmethod - def acquire(_scale): - return record - class Delegate: - def __init__(self, *args, **kwargs): - pass - - @staticmethod - def prepare(_scenario): + def __init__(self, executor, **kwargs): + assert executor is runner + assert kwargs == {"influxdb_bucket": "bucket", "topology_id": "topology"} + + def prepare(self, scenario): + events.append("shared_prepare") + if failure: + raise RuntimeError(failure) return {"case_id": "case-test"} - backend = RuntimeEpisodeBackend(Leases(), default_scale_registry()) - monkeypatch.setattr(backend, "_health_errors", lambda *args, **kwargs: []) - monkeypatch.setattr( - backend, - "_ensure_baseline", - lambda _scenario: (record.baseline_signature is None and record.baseline is None) - or pytest.fail("lingering-fault recovery must invalidate the cached baseline"), - ) - monkeypatch.setattr(simulator_runtime_module, "ExecutorIncidentBackend", Delegate) - monkeypatch.setattr( - simulator_runtime_module, - "require_scenario_topology", - lambda _scenario, _topology_dir: None, - ) - - assert backend.prepare(_scenario(healthy=True)) == {"case_id": "case-test"} - - -def test_simulator_quarantines_when_traffic_rebuild_is_incomplete(monkeypatch): - events = [] - - class StaleTraffic: - active_flows = {"flow": object()} - - @staticmethod - def verify_active_flows(): - return False - - runner = SimpleNamespace( - traffic_controller=StaleTraffic(), - topology_dir="unused", - post_recovery_wait_seconds=0, - _recover_fault=lambda: [], - _stop_traffic=lambda: events.append("stop"), - _setup_traffic=lambda _scale, _profile: (_ for _ in ()).throw( - RuntimeError("Background traffic matrix incomplete") - ), - ) - worker = SimpleNamespace(topology_dir="unused", bucket="bucket", topology_id="topology") - record = WarmRuntime(runtime=SimpleNamespace(workers=[worker]), runner=runner) - - class Leases: - @staticmethod - def acquire(_scale): - return record - - @staticmethod - def quarantine(_record): - events.append("quarantine") - - from netopsbench.platform.incident.engine import IncidentEngine, IncidentState - - backend = RuntimeEpisodeBackend(Leases(), default_scale_registry()) - monkeypatch.setattr(backend, "_health_errors", lambda *args, **kwargs: []) - monkeypatch.setattr( - simulator_runtime_module, - "require_scenario_topology", - lambda _scenario, _topology_dir: None, - ) + def finish(self, *, broken=False): + events.append(("shared_finish", broken)) + monkeypatch.setattr(simulator_runtime_module, "ExecutorIncidentBackend", Delegate) + monkeypatch.setattr(simulator_runtime_module, "require_scenario_topology", lambda *args: None) + backend = RuntimeEpisodeBackend(leases, default_scale_registry()) incident = IncidentEngine(lambda: backend).prepare(_scenario(healthy=True)) - - assert events == ["stop", "quarantine"] - assert incident.state is IncidentState.BROKEN - assert incident.failure is not None - assert incident.failure.message == "Background traffic matrix incomplete" + if failure: + assert incident.state is IncidentState.BROKEN + assert incident.failure.message == failure + assert events == ["shared_prepare", ("shared_finish", True), "quarantine"] + else: + assert incident.observation == {"case_id": "case-test"} + incident.close() + incident.close() + assert events == ["shared_prepare", ("shared_finish", False), "release"] def test_simulator_invalid_topology_releases_lease_without_quarantine(monkeypatch): events = [] - runner = SimpleNamespace(topology_dir="unused") + runner = SimpleNamespace( + topology_dir="unused", begin_case=lambda: None, _baseline_handoff=SimpleNamespace(clear=lambda reason: None) + ) worker = SimpleNamespace(topology_dir="unused", bucket="bucket", topology_id="topology") record = WarmRuntime(runtime=SimpleNamespace(workers=[worker]), runner=runner) @@ -815,3 +621,153 @@ def quarantine(_record): assert incident.failure is not None assert incident.failure.message == "invalid scenario" assert events == ["acquire", "release"] + + +def test_slow_provision_does_not_block_release_or_refresh(monkeypatch): + pool, _ = _pool(monkeypatch) + pool.config = SimulatorConfig(max_active_runtimes=2) + first = pool.acquire("xs") + entered, proceed = threading.Event(), threading.Event() + results = [] + + def slow(scale): + entered.set() + assert proceed.wait(2) + return WarmRuntime(runtime=FakeRuntime(scale), runner=FakeRunner()) + + monkeypatch.setattr(pool, "_provision", slow) + thread = threading.Thread(target=lambda: results.append(pool.acquire("medium"))) + thread.start() + assert entered.wait(1) + try: + done = threading.Event() + + def update(): + pool.refresh(first) + pool.release(first) + done.set() + + updater = threading.Thread(target=update) + updater.start() + assert done.wait(1), "provisioning held the lease lock" + updater.join(1) + assert pool._pending == 1 + assert pool.acquire("xs") is first + finally: + proceed.set() + thread.join(2) + assert len(results) == 1 + assert pool._runtime_count() == 2 and pool._pending == 0 + + +def test_failed_provision_releases_reserved_capacity(monkeypatch): + pool, _ = _pool(monkeypatch) + original = pool._provision + monkeypatch.setattr(pool, "_provision", lambda scale: (_ for _ in ()).throw(RuntimeError("deploy failed"))) + with pytest.raises(RuntimeError, match="deploy failed"): + pool.acquire("xs") + assert pool._pending == 0 + monkeypatch.setattr(pool, "_provision", original) + assert pool.acquire("xs").in_use + + +def test_slow_teardown_does_not_block_other_lease(monkeypatch): + pool, _ = _pool(monkeypatch) + pool.config = SimulatorConfig(max_active_runtimes=2) + first, second = pool.acquire("xs"), pool.acquire("xs") + entered, proceed, updated = threading.Event(), threading.Event(), threading.Event() + + def teardown(): + entered.set() + assert proceed.wait(2) + + first.runtime.teardown = teardown + thread = threading.Thread(target=lambda: pool.quarantine(first)) + thread.start() + assert entered.wait(1) + try: + + def release(): + pool.release(second) + updated.set() + + updater = threading.Thread(target=release) + updater.start() + assert updated.wait(1) + updater.join(1) + assert pool.acquire("xs") is second + finally: + proceed.set() + thread.join(2) + assert first not in pool._runtimes["xs"] + + +def test_incident_close_waits_for_inflight_tool_before_recovery(): + entered, proceed, closing, finished = (threading.Event() for _ in range(4)) + + class Backend(FakeBackend): + def call_tool(self, action): + entered.set() + assert proceed.wait(2) + assert not finished.is_set() + return {"success": True, "data": {}} + + def finish(self, *, broken=False): + finished.set() + + incident = IncidentEngine(Backend).prepare(_scenario()) + tool = threading.Thread(target=lambda: incident.call_tool(ToolAction(name="get_topology"))) + + def close(): + closing.set() + incident.close() + + closer = threading.Thread(target=close) + tool.start() + assert entered.wait(1) + closer.start() + assert closing.wait(1) + try: + assert not finished.wait(0.05) + finally: + proceed.set() + tool.join(2) + closer.join(2) + assert finished.is_set() + + +def test_failed_provision_cleanup_occupies_capacity_until_drain(): + from netopsbench.platform.runtime.manager import RuntimeProvisionError + + runtime = FakeRuntime("xs") + + class Manager: + def provision(self, **kwargs): + raise RuntimeProvisionError(runtime, "deployment and cleanup failed") + + pool = RuntimeLeasePool(Manager(), default_scale_registry(), SimulatorConfig(max_active_runtimes=1)) + with pytest.raises(RuntimeProvisionError): + pool.acquire("xs") + assert pool._pending == 0 + assert pool._runtime_count() == 1 + record = pool._runtimes["xs"][0] + assert record.quarantined and record.runner is None + pool.drain() + assert runtime.teardowns == 1 + assert pool._runtime_count() == 0 + + +def test_public_step_required_flags_and_transition_serialization_are_preserved(): + from pydantic import ValidationError + + from netopsbench.platform.incident.engine import SessionTransition + from netopsbench.platform.simulator.environment import StepResult + + transition = SessionTransition(state=SessionState.ACTIVE) + with pytest.raises(ValidationError): + StepResult(state=SessionState.ACTIVE) + result = StepResult.model_validate(transition.model_dump()) + assert result.model_dump() == transition.model_dump() + assert set(StepResult.model_json_schema()["required"]) == {"valid", "case_valid", "state"} + with pytest.raises(ValidationError): + result.valid = False diff --git a/tests/test_simulator_service.py b/tests/test_simulator_service.py deleted file mode 100644 index 18ec2a4..0000000 --- a/tests/test_simulator_service.py +++ /dev/null @@ -1,266 +0,0 @@ -"""Generic HTTP simulator boundary tests.""" - -from __future__ import annotations - -import json - -import pytest - -pytest.importorskip("fastapi") -from fastapi.testclient import TestClient - -from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec -from netopsbench.platform.simulator import service as service_module -from netopsbench.platform.simulator.service import SimulatorService, create_app, scenario_case_id - - -class Result: - def __init__(self, payload): - self.payload = payload - - def model_dump(self, mode="python"): - return dict(self.payload) - - -class FakeEnvironment: - def __init__(self, case_id): - self.case_id = case_id - self.closed = False - - def reset(self): - return Result( - { - "valid": True, - "case_valid": True, - "state": "active", - "case_id": self.case_id, - "observation": {}, - "tools": [], - "cleanup_status": "not_started", - } - ) - - def step(self, action): - terminal = action.type == "submit_diagnosis" - return Result( - { - "valid": True, - "case_valid": True, - "state": "terminal" if terminal else "active", - "reward": 1.0 if terminal else None, - "observation": {} if terminal else {"tool": action.name}, - "reward_components": {"outcome": 1.0} if terminal else {}, - "metrics": {}, - "termination_reason": "submitted" if terminal else None, - "cleanup_status": "succeeded" if terminal else "not_started", - } - ) - - def terminate_protocol(self, message): - return Result( - { - "valid": True, - "case_valid": True, - "state": "terminal", - "reward": 0.0, - "reward_components": {"outcome": 0.0}, - "metrics": {}, - "termination_reason": "protocol_error", - "failure": { - "domain": "protocol", - "phase": "diagnosis", - "message": message, - "error_type": None, - }, - "cleanup_status": "succeeded", - "error": message, - } - ) - - def close(self): - self.closed = True - - -class FakeManager: - def __init__(self): - self.closed = False - - def create(self, *, scenario, config): - return FakeEnvironment(scenario_case_id(scenario)) - - def close(self): - self.closed = True - - -def _scenario(): - return ScenarioSpec( - scenario_id="scenario-1", - name="scenario-1", - episode=EpisodeSpec(episode_id="diagnosis", fault_type="none"), - ) - - -def test_http_service_uses_opaque_case_ids_and_generic_actions(tmp_path): - manager = FakeManager() - scenario = _scenario() - case_id = scenario_case_id(scenario) - event_log = tmp_path / "events.jsonl" - service = SimulatorService(manager, [scenario], event_log=event_log) - - with TestClient(create_app(service)) as client: - assert client.get("/v1/cases").json() == {"case_ids": [case_id]} - created = client.post("/v1/environments", json={"case_id": case_id}).json() - environment_id = created["environment_id"] - tool = client.post( - f"/v1/environments/{environment_id}/actions", - json={"action": {"type": "tool", "name": "get_topology", "arguments": {}}}, - ) - terminal = client.post( - f"/v1/environments/{environment_id}/actions", - json={ - "action": { - "type": "submit_diagnosis", - "diagnosis": {"verdict": "network_healthy"}, - } - }, - ) - deleted = client.delete(f"/v1/environments/{environment_id}") - - assert created["reset"]["case_id"] == case_id - assert tool.status_code == 200 and tool.json()["state"] == "active" - assert terminal.status_code == 200 and terminal.json()["reward"] == 1.0 - assert deleted.json() == {"deleted": True} - assert manager.closed is True - events = [json.loads(line) for line in event_log.read_text(encoding="utf-8").splitlines()] - assert [event["event"] for event in events] == ["create", "step", "step", "delete"] - assert all("task_id" not in event and "split" not in event for event in events) - - -def test_http_service_rejects_unknown_case_and_group_fields(): - service = SimulatorService(FakeManager(), [_scenario()]) - with TestClient(create_app(service)) as client: - missing = client.post("/v1/environments", json={"case_id": "case-missing"}) - grouped = client.post( - "/v1/environments", - json={"case_id": scenario_case_id(_scenario()), "group_id": "rl-group"}, - ) - assert missing.status_code == 404 - assert grouped.status_code == 422 - - -def test_http_service_maps_illegal_diagnosis_to_protocol_outcome_zero(): - service = SimulatorService(FakeManager(), [_scenario()]) - with TestClient(create_app(service)) as client: - created = client.post( - "/v1/environments", - json={"case_id": scenario_case_id(_scenario())}, - ).json() - result = client.post( - f"/v1/environments/{created['environment_id']}/actions", - json={ - "action": { - "type": "submit_diagnosis", - "diagnosis": {"verdict": "not-a-verdict"}, - } - }, - ) - - assert result.status_code == 200 - assert result.json()["case_valid"] is True - assert result.json()["reward"] == 0.0 - assert result.json()["termination_reason"] == "protocol_error" - assert result.json()["failure"]["domain"] == "protocol" - - -def test_http_service_returns_conflict_after_terminal_action(): - service = SimulatorService(FakeManager(), [_scenario()]) - with TestClient(create_app(service)) as client: - created = client.post( - "/v1/environments", - json={"case_id": scenario_case_id(_scenario())}, - ).json() - path = f"/v1/environments/{created['environment_id']}/actions" - first = client.post( - path, - json={ - "action": { - "type": "submit_diagnosis", - "diagnosis": {"verdict": "network_healthy"}, - } - }, - ) - repeated = client.post( - path, - json={"action": {"type": "tool", "name": "get_topology", "arguments": {}}}, - ) - assert service.environments[created["environment_id"]].environment is None - - assert first.status_code == 200 - assert repeated.status_code == 409 - assert repeated.json()["detail"] == "Simulator environment is terminal" - - -def test_terminal_tombstone_expires_from_conflict_to_not_found(monkeypatch): - clock = [100.0] - monkeypatch.setattr(service_module.time, "monotonic", lambda: clock[0]) - service = SimulatorService(FakeManager(), [_scenario()]) - with TestClient(create_app(service)) as client: - created = client.post( - "/v1/environments", - json={"case_id": scenario_case_id(_scenario())}, - ).json() - path = f"/v1/environments/{created['environment_id']}/actions" - client.post( - path, - json={ - "action": { - "type": "submit_diagnosis", - "diagnosis": {"verdict": "network_healthy"}, - } - }, - ) - assert ( - client.post( - path, - json={"action": {"type": "tool", "name": "get_topology", "arguments": {}}}, - ).status_code - == 409 - ) - clock[0] += 3_600.0 - assert ( - client.post( - path, - json={"action": {"type": "tool", "name": "get_topology", "arguments": {}}}, - ).status_code - == 404 - ) - - -def test_terminal_tombstones_are_bounded(monkeypatch): - monkeypatch.setattr(service_module, "_MAX_TERMINAL_TOMBSTONES", 2) - service = SimulatorService(FakeManager(), [_scenario()]) - case_id = scenario_case_id(_scenario()) - for _ in range(3): - created = service.create(case_id) - service.step( - created["environment_id"], - { - "type": "submit_diagnosis", - "diagnosis": {"verdict": "network_healthy"}, - }, - ) - - assert len(service.environments) == 2 - - -def test_event_log_rotates_and_omits_full_observation(monkeypatch, tmp_path): - monkeypatch.setattr(service_module, "_EVENT_LOG_MAX_BYTES", 300) - event_log = tmp_path / "events.jsonl" - service = SimulatorService(FakeManager(), [_scenario()], event_log=event_log) - result = {"state": "active", "observation": {"large": "x" * 1_000}} - - for _ in range(5): - service._record_event({"event": "step", "result": service._summarize_result(result)}) - - assert event_log.with_name("events.jsonl.1").exists() - assert "observation" not in event_log.read_text(encoding="utf-8") diff --git a/tests/test_sonic_runtime_config_permissions.py b/tests/test_sonic_runtime_config_permissions.py new file mode 100644 index 0000000..f56c909 --- /dev/null +++ b/tests/test_sonic_runtime_config_permissions.py @@ -0,0 +1,43 @@ +"""Saved FRR configuration remains readable for runtime baseline identity.""" + +import subprocess +from types import SimpleNamespace + +import pytest + +from netopsbench.platform.faults.services.sonic_runtime import SonicRuntime + + +@pytest.mark.parametrize("save", [True, False]) +def test_saved_config_keeps_host_readability_without_changing_read_commands(tmp_path, save): + config = tmp_path / "frr.conf" + config.write_text("router bgp 65001\n") + config.chmod(0o640) + + def docker_exec(container, command): + assert container == "clab-test-edge160" + if command[0] == "chmod": + subprocess.run([*command[:2], str(config)], check=True) + return subprocess.CompletedProcess(command, 0, "ok", "") + + runtime = SonicRuntime( + SimpleNamespace(docker_exec=docker_exec), SimpleNamespace(container_names={"edge160": "clab-test-edge160"}) + ) + result = runtime.vtysh("edge160", ["write memory"] if save else ["show ip bgp summary"]) + + assert result.returncode == 0 + assert bool(config.stat().st_mode & 0o004) is save + assert config.read_text() == "router bgp 65001\n" + + +def test_saved_config_permission_failure_is_reported(): + def docker_exec(container, command): + return subprocess.CompletedProcess(command, 1 if command[0] == "chmod" else 0, "", "read-only mount") + + runtime = SonicRuntime( + SimpleNamespace(docker_exec=docker_exec), SimpleNamespace(container_names={"edge160": "clab-test-edge160"}) + ) + result = runtime.vtysh("edge160", ["write memory"]) + + assert result.returncode == 1 + assert result.stderr == "read-only mount" diff --git a/tests/test_sonic_startup.py b/tests/test_sonic_startup.py new file mode 100644 index 0000000..8d4fb6c --- /dev/null +++ b/tests/test_sonic_startup.py @@ -0,0 +1,54 @@ +"""The retained wrapper preserves sequential upstream startup and optional service handling.""" + +import subprocess + +import pytest + +from netopsbench.platform.topology.config import SONIC_START_WRAPPER_SOURCE +from netopsbench.platform.topology.generator import generate_topology +from netopsbench.platform.topology.topology_utils import load_topology_manifest + + +def test_sonic_service_order_and_renderer_have_no_parallel_helper(tmp_path): + subprocess.run(["bash", "-n", str(SONIC_START_WRAPPER_SOURCE)], check=True) + script = SONIC_START_WRAPPER_SOURCE.read_text() + starts = [ + line.removeprefix("supervisorctl start ") + for line in script.splitlines() + if line.startswith("supervisorctl start ") + ] + assert starts[starts.index("syncd") : starts.index("syncd") + 3] == ["syncd", "portsyncd", "orchagent"] + for prerequisite, dependent in [ + ("teamsyncd", "teammgrd"), + ("fpmsyncd", "zebra"), + ("zebra", "staticd"), + ("natmgrd", "natsyncd"), + ]: + assert starts.index(prerequisite) < starts.index(dependent) + assert "nb-start-group" not in script + generate_topology("xs", str(tmp_path)) + # Do not advertise fast failure detection that the generated FRR config does not enable. + assert load_topology_manifest(tmp_path).routing.bfd is False + assert not (tmp_path / "configs/sonic/start_group.py").exists() + assert "start_group" not in next(tmp_path.glob("*.clab.yaml")).read_text() + + +@pytest.mark.parametrize("status", [0, 3, 1]) +def test_optional_service_absence_is_distinct_from_failure(tmp_path, status): + script = SONIC_START_WRAPPER_SOURCE.read_text() + block = script[script.index("if python3 - <<'CHECK_REBOOTBACKEND'") : script.index("# Start arp_update")] + (tmp_path / "python3").write_text(f"#!/bin/sh\nexit {status}\n") + (tmp_path / "supervisorctl").write_text("#!/bin/sh\necho started\n") + for file in tmp_path.iterdir(): + file.chmod(0o755) + import os + + result = subprocess.run( + ["bash", "-e", "-c", block], + env={**os.environ, "PATH": f"{tmp_path}:/usr/bin:/bin"}, + capture_output=True, + text=True, + ) + assert result.returncode == (1 if status == 1 else 0) + assert ("started" in result.stdout) == (status == 0) + assert ("optional rebootbackend is absent" in result.stdout) == (status == 3) diff --git a/tests/test_state_checked_recovery.py b/tests/test_state_checked_recovery.py new file mode 100644 index 0000000..123c08e --- /dev/null +++ b/tests/test_state_checked_recovery.py @@ -0,0 +1,213 @@ +"""Recovery cannot trade missing state evidence for a healthy ping result.""" + +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +import pytest + +from netopsbench.models.recovery import RecoveryPolicy +from netopsbench.platform.scenario.baseline import BaselineHandoff, RuntimeScope + + +def window(age=0): + end = datetime.now(UTC) - timedelta(seconds=age) + return { + "name": "baseline", + "start_time": (end - timedelta(seconds=30)).isoformat(), + "end_time": end.isoformat(), + "duration_seconds": 30, + } + + +def test_policy_does_not_rewrite_legacy_metadata(): + metadata = {"experiment": {"observation_seconds": 30}} + with pytest.raises(ValueError, match="migrate"): + RecoveryPolicy.from_metadata(metadata) + assert "recovery_policy" not in metadata + assert RecoveryPolicy().version == 3 + assert RecoveryPolicy().baseline_max_cases == 10 + with pytest.raises(ValueError): + RecoveryPolicy(version=1) + + +def test_baseline_ten_uses_and_interrupted_consumer(): + h = BaselineHandoff(max_cases=10) + scope = RuntimeScope({}, {}, {}) + w = window() + assert h.publish(w, scope, "initial", 30, verified=True) + for i in range(10): + assert h.take(scope, 30)[0] == w + assert h.uses == i + 1 + assert h.take(scope, 30) == (None, "previous_case_not_verified") + h.ready = True # Only a successful recovery grants this permission. + assert h.take(scope, 30) == (None, "case_limit") + assert h.window == w + + +@pytest.mark.parametrize("age", [599, 600, 601, 7200]) +def test_old_verified_window_remains_reusable_without_refresh(age): + h = BaselineHandoff() + scope = RuntimeScope({}, {}, {}) + original = window(age) + assert h.publish(original, scope, "initial", 30, verified=True) + assert h.take(scope, 30)[0] == original + assert h.uses == 1 + + +def test_identity_change_and_failure_invalidate_reuse(): + h = BaselineHandoff() + h.publish(window(), RuntimeScope({"generation": 1}, {}, {}), "initial", 30, verified=True) + assert h.take(RuntimeScope({"generation": 2}, {}, {}), 30)[1] == "scope_changed" + h.clear("recovery_failed") + assert h.take(None, 30) == (None, "recovery_failed") + + +def test_elapsed_time_does_not_expire_a_valid_window(monkeypatch): + from netopsbench.platform.scenario import baseline + + now = datetime.now(UTC) + + class FrozenDatetime(datetime): + @classmethod + def now(cls, tz=None): + return now + + monkeypatch.setattr(baseline, "datetime", FrozenDatetime) + end = now - timedelta(seconds=600) + w = { + "start_time": (end - timedelta(seconds=30)).isoformat(), + "end_time": end.isoformat(), + "duration_seconds": 30, + } + assert baseline.window_error(w, 30) is None + now += timedelta(microseconds=1) + assert baseline.window_error(w, 30) is None + + +@pytest.mark.parametrize("wrong_neighbor,flap", [(False, False), (True, False), (False, True)]) +def test_state_health_uses_identities_and_final_full_pass(monkeypatch, wrong_neighbor, flap): + import time + + from netopsbench.platform.runtime import health + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import config_for_scale + from netopsbench.platform.utils.control import OperationControl + from netopsbench.platform.utils.interface_names import to_sonic_interface + + topo = build_clos_plan(config_for_scale("xs")).manifest + worker = SimpleNamespace(lab_name=topo.name, topology_id=topo.topology_id, topology_dir="unused", bucket="test") + counts = health.expected_network_counts(topo) + calls = {} + expected = {"nodes": {}} + for device in topo.routing_devices(): + expected["nodes"][device.name] = { + "fib": [], + "bgp_collection_ok": True, + "bgp": [ + {"neighbor": f"10.1.1.{i + 1}", "asn": 65001, "state": "Established"} + for i in range(counts[device.name]["bgp_neighbors"]) + ], + } + + def routing(container, control=None, route_snapshot=None): + device = container.removeprefix(f"clab-{topo.name}-") + calls[device] = calls.get(device, 0) + 1 + route_snapshot.update(fib=[], bgp_collection_ok=True) + prefix = "10.9.9" if wrong_neighbor or (flap and calls[device] == 2) else "10.1.1" + bgp = "Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down State/PfxRcd\n" + "\n".join( + f"{prefix}.{i + 1} 4 65001 1 1 0 0 0 00:10 2" for i in range(counts[device]["bgp_neighbors"]) + ) + interfaces = "\n".join( + to_sonic_interface(e.interface) for link in topo.links for e in link.endpoints if e.device == device + ) + return bgp, interfaces + + def run(args, **kwargs): + if "inspect" in args: + names = [f"clab-{topo.name}-{d.name}" for d in topo.devices] + return SimpleNamespace(returncode=0, stdout="\n".join(f"/{n} true false" for n in names)) + return SimpleNamespace(returncode=0, stdout=f"telegraf-{topo.name}") + + monkeypatch.setattr(health, "_routing_state", routing) + monkeypatch.setattr(health, "_parse_active_interfaces", lambda output: set(output.splitlines())) + monkeypatch.setattr(health, "_running_container_count", lambda *a, **k: len(topo.devices)) + monkeypatch.setattr(health, "safe_run", run) + commands = [] + monkeypatch.setattr(health, "_docker_exec", lambda *a, **k: commands.append(a) or SimpleNamespace(returncode=0)) + monkeypatch.setattr( + health, + "request_agent", + lambda *a, **k: { + "ok": True, + "status": { + "ready": True, + "heartbeat_unix_ns": time.time_ns(), + "plan_id": topo.require_pingmesh_plan().settings.plan_id, + "config_schema_version": 2, + }, + }, + ) + audit = {"network_rounds": 3} # Preserve rounds from an earlier bounded recovery attempt. + errors = health._check_worker_health( + worker, + health_retries=2, + health_delay=0, + all_routing_devices=True, + topology=topo, + control=OperationControl(deadline=time.monotonic() + 10), + route_snapshot={"nodes": {}}, + expected_routes=expected, + state_only=True, + recovery_audit=audit, + ) + assert bool(errors) == (wrong_neighbor or flap) + assert set(calls.values()) == {2} + assert not any("logger" in str(command) for command in commands) + if not errors: + assert audit["network_rounds"] == 5 and audit["collected_at"] > 0 + + +@pytest.mark.parametrize("resource", ["acl", "frr"]) +def test_recovery_exit_zero_does_not_hide_resource_drift(monkeypatch, resource): + from netopsbench.platform.faults.handlers.network import NetworkFaultHandler + from netopsbench.platform.scenario.baseline import normalized_frr + + handler = NetworkFaultHandler( + None, None, None, None, SimpleNamespace(remove_faults=lambda f: pytest.fail("removed")), None + ) + if resource == "acl": + fault_type = "acl_l4_port_misconfig" + evidence = {"original_iptables": "-P FORWARD ACCEPT", "acl_name": "owned"} + actual = "-P FORWARD ACCEPT\n-A FORWARD -j DROP" + else: + fault_type = "bgp_auth_mismatch" + evidence = {"original_frr_digest": normalized_frr("router bgp 65001\n")} + actual = "router bgp 65001\n neighbor 10.1.1.1 password wrong\n" + fault = { + "type": fault_type, + "device": "leaf1", + "fault_id": "owned", + "journal": [{"kind": "docker", "restore": ["true"]}], + "evidence": evidence, + } + monkeypatch.setattr(handler, "_run", lambda *args: actual) + result = handler.recover(fault) + assert not result["recovered"] and not result["readback_verified"] + if resource == "acl": + assert "Actual ACL rules" in result["error"] + + +def test_terminal_destroy_skips_window_but_never_accepts_active_faults(): + from netopsbench.platform.scenario.executor import ScenarioExecutor + + runner = object.__new__(ScenarioExecutor) + runner.injector = SimpleNamespace(active_faults=[]) + runner.calibrate = lambda *a, **k: pytest.fail("destroy path must not collect a window") + assert runner.final_calibration(None, destroy_after_run=True) == { + "status": "skipped", + "reason": "runtime_will_be_destroyed", + "validation_level": "state_checked", + } + runner.injector.active_faults.append({"residual": True}) + with pytest.raises(RuntimeError, match="unresolved"): + runner.final_calibration(None, destroy_after_run=True) diff --git a/tests/test_toolkit_output_shape.py b/tests/test_toolkit_output_shape.py index e0c5b6e..7207dfc 100644 --- a/tests/test_toolkit_output_shape.py +++ b/tests/test_toolkit_output_shape.py @@ -17,7 +17,7 @@ def _toolkit() -> AgentToolkit: def test_toolkit_keeps_canonical_state_and_projects_public_topology(monkeypatch): toolkit = _toolkit() - assert toolkit.topology_metadata["schema_version"] == "3" + assert toolkit.topology_metadata["schema_version"] == "4" assert isinstance(toolkit.topology_metadata["devices"], list) public_topology = toolkit.get_topology() @@ -110,7 +110,9 @@ def test_get_device_interfaces_summary_keeps_diagnostic_fields(monkeypatch): def fake_exec(container, cmd_args, timeout): command = " ".join(cmd_args) - if "status" in command: + if cmd_args[:3] == ["ip", "-j", "-4"]: + stdout = '[{"ifname":"Ethernet0", "addr_info":[{"local":"10.0.0.1", "prefixlen":30}]}]' + elif "status" in command: stdout = "Interface Admin Oper Speed\nEthernet0 up up 100G\nEthernet4 up down 100G\n" else: stdout = "IFACE RX_ERR TX_ERR RX_DRP TX_DRP\nEthernet0 0 0 0 0\nEthernet4 5 0 2 0\n" @@ -153,6 +155,24 @@ def test_get_device_config_truncates_with_metadata(monkeypatch): assert result.data["total_lines"] == 5 +def test_config_section_filter_preserves_nested_frr_blocks_without_unsupported_pipe(monkeypatch): + toolkit = _toolkit() + monkeypatch.setattr(toolkit, "_resolve_container", lambda device: "clab-dcn-leaf1") + config = "interface Ethernet0\n ip address 10.0.0.1/31\n!\nrouter bgp 65001\n neighbor 10.0.0.0 remote-as 65002\n !\n address-family ipv4 unicast\n exit-address-family\n!\nroute-map ALLOW permit 10\n!\n" + + def execute(container, cmd_args, timeout): + assert cmd_args == ["vtysh", "-c", "show running-config"] + return subprocess.CompletedProcess(cmd_args, 0, config, "") + + monkeypatch.setattr(toolkit, "_docker_exec", execute) + result = toolkit.get_device_config("leaf1", section="router bgp") + assert result.success + assert "remote-as 65002" in result.data["config"] + assert "address-family ipv4" in result.data["config"] + assert "interface Ethernet0" not in result.data["config"] + assert "route-map ALLOW" not in result.data["config"] + + def test_get_device_acl_respects_view(monkeypatch): toolkit = _toolkit() diff --git a/tests/test_topology_fail_fast.py b/tests/test_topology_fail_fast.py index a93f27b..480ec9f 100644 --- a/tests/test_topology_fail_fast.py +++ b/tests/test_topology_fail_fast.py @@ -22,7 +22,7 @@ def test_toolkit_uses_only_the_explicit_topology_directory(tmp_path): selected_dir = tmp_path / "selected" unrelated_dir = tmp_path / "newer" generate_topology("xs", str(selected_dir), name="selected-lab") - generate_topology("small", str(unrelated_dir), name="unrelated-lab") + generate_topology("medium", str(unrelated_dir), name="unrelated-lab") toolkit = AgentToolkit(topology_dir=selected_dir) diff --git a/tests/test_topology_generation_v3.py b/tests/test_topology_generation_v4.py similarity index 91% rename from tests/test_topology_generation_v3.py rename to tests/test_topology_generation_v4.py index 9039416..be3c7b6 100644 --- a/tests/test_topology_generation_v3.py +++ b/tests/test_topology_generation_v4.py @@ -24,7 +24,7 @@ @pytest.mark.parametrize( "scale", - ["xs", "small", "medium", "large", "xlarge", "fat-tree-k8", "fat-tree-k12"], + ["xs", "medium", "medium", "large", "xlarge", "fat-tree-k8", "fat-tree-k12"], ) def test_every_builtin_scale_uses_terminable_sonic_pid1(tmp_path, scale): result = generate_topology(scale, str(tmp_path / scale)) @@ -37,17 +37,17 @@ def test_every_builtin_scale_uses_terminable_sonic_pid1(tmp_path, scale): ("scale", "roles", "clients", "links"), [ ("xs", {"spine": 2, "leaf": 2}, 2, 6), - ("xlarge", {"spine": 16, "leaf": 128}, 128, 2176), + ("xlarge", {"spine": 16, "leaf": 128}, 256, 2304), ("fat-tree-k8", {"core": 16, "agg": 32, "edge": 32}, 128, 384), ("fat-tree-k12", {"core": 36, "agg": 72, "edge": 72}, 144, 1008), ], ) -def test_renderer_persists_only_canonical_schema_v3_devices(tmp_path, scale, roles, clients, links): +def test_renderer_persists_only_canonical_schema_v4_devices(tmp_path, scale, roles, clients, links): result = generate_topology(scale, str(tmp_path / scale)) persisted = json.loads(Path(result["metadata_file"]).read_text(encoding="utf-8")) manifest = TopologyManifest.model_validate(persisted) - assert persisted["schema_version"] == "3" + assert persisted["schema_version"] == "4" assert isinstance(persisted["devices"], list) assert len(manifest.links) == links assert all(link.mtu == 9232 for link in manifest.links) @@ -66,7 +66,7 @@ def test_renderer_persists_only_canonical_schema_v3_devices(tmp_path, scale, rol def test_renderer_atomically_removes_stale_device_artifacts(tmp_path): output = tmp_path / "topology" - generate_topology("small", str(output)) + generate_topology("medium", str(output)) assert (output / "configs" / "sonic" / "leaf4").is_dir() generate_topology("xs", str(output)) @@ -90,7 +90,7 @@ def test_clos_builder_returns_complete_fabric_plan_without_writing(tmp_path): assert spine1.configdb_interface_cidrs["Ethernet0"] == ("10.1.1.1/30",) assert spine1.bgp_neighbors[0].peer_ip == "10.1.1.2" assert leaf1.required_ports == 3 - assert leaf1.bgp_networks == ("192.168.101.0/30",) + assert leaf1.bgp_networks == ("192.168.1.0/30",) assert plan.manifest.links[0].endpoints[0].interface == "eth1" @@ -101,24 +101,24 @@ def test_rendered_clos_artifacts_keep_preseed_and_addressing_contract(tmp_path): nodes = rendered["topology"]["nodes"] links = rendered["topology"]["links"] - assert len(nodes) == 16 + 128 + 128 - assert len(links) == (16 * 128) + 128 + assert len(nodes) == 16 + 128 + 256 + assert len(links) == (16 * 128) + 256 assert manifest.routing.ecmp_hash_policy_by_role == {DeviceRole.SPINE: 1, DeviceRole.LEAF: 1} assert nodes["spine16"]["mgmt-ipv4"] == "172.20.20.26" assert nodes["leaf128"]["mgmt-ipv4"] == "172.20.20.154" assert nodes["client128"]["mgmt-ipv4"] == "172.20.21.26" assert links[0] == {"endpoints": ["spine1:eth1", "leaf1:eth1"], "mtu": 9232} assert links[2047] == {"endpoints": ["spine16:eth128", "leaf128:eth16"], "mtu": 9232} - assert links[-1] == {"endpoints": ["leaf128:eth17", "client128:eth1"], "mtu": 9232} + assert links[-1] == {"endpoints": ["leaf128:eth18", "client256:eth1"], "mtu": 9232} assert (tmp_path / "configs" / "sonic" / "start.sh").is_file() assert (tmp_path / "configs" / "client-agent" / "client-agent.json").is_file() spine = json.loads((tmp_path / "configs" / "sonic" / "spine16" / "config_db.json").read_text()) leaf = json.loads((tmp_path / "configs" / "sonic" / "leaf128" / "config_db.json").read_text()) assert len([name for name in spine["PORT"]]) == 128 - assert len([name for name in leaf["PORT"]]) == 17 + assert len([name for name in leaf["PORT"]]) == 18 assert "Ethernet508|10.16.128.1/30" in spine["INTERFACE"] - assert "Ethernet64|192.168.228.1/30" in leaf["INTERFACE"] + assert "Ethernet64|192.168.128.1/30" in leaf["INTERFACE"] @pytest.mark.parametrize( @@ -179,9 +179,9 @@ def test_topology_helpers_require_v3_and_manifest_owns_role_queries(tmp_path): legacy = tmp_path / "legacy" legacy.mkdir() (legacy / "topology.json").write_text(json.dumps({"name": "legacy", "devices": {}}), encoding="utf-8") - with pytest.raises(ValueError, match="schema_version.*3"): + with pytest.raises(ValueError, match="schema_version.*4"): load_topology_manifest(legacy) - with pytest.raises(ValueError, match="schema_version.*3"): + with pytest.raises(ValueError, match="schema_version.*4"): coerce_topology_manifest({"name": "legacy", "devices": {}}) diff --git a/tests/test_traffic_controller.py b/tests/test_traffic_controller.py index f6c531d..9d02a41 100644 --- a/tests/test_traffic_controller.py +++ b/tests/test_traffic_controller.py @@ -10,7 +10,6 @@ TrafficController, TrafficFlow, _client_plans, - _parse_bandwidth_bps, _plan_digest, ) @@ -148,7 +147,9 @@ def test_compact_plan_preserves_existing_flow_contract(): }, ] assert _plan_digest(plans["client1"]) == _plan_digest(plans["client1"]) - assert _parse_bandwidth_bps("1G") == 1_000_000_000 + from netopsbench.platform.traffic.estimator import bandwidth_to_bps + + assert int(bandwidth_to_bps("1G")) == 1_000_000_000 def test_synthetic_1024_client_plan_has_4096_flows(): @@ -382,3 +383,14 @@ def start_matrix(self, flows): assert len(result["matrix_digest"]) == 64 assert "flows" not in result assert "estimated_switch_pps" not in result["stats"] + + +@pytest.mark.parametrize("text,expected", [("1G", 1e9), (" 2.5m ", 2.5e6), ("12.9", 12.9), ("0", 0)]) +def test_bandwidth_estimation_and_agent_plan_share_units(text, expected): + from netopsbench.platform.traffic.controller import TrafficFlow, _client_plans + from netopsbench.platform.traffic.estimator import bandwidth_to_bps + + assert bandwidth_to_bps(text) == expected + flow = TrafficFlow(src="a", dst="b", dst_ip="192.0.2.2", bandwidth=text) + plans = _client_plans({"a": "192.0.2.1", "b": "192.0.2.2"}, [flow]) + assert plans["a"]["flows"][0]["bandwidth_bps"] == int(expected) diff --git a/tests/test_traffic_generator.py b/tests/test_traffic_generator.py index 3d8588e..b0bb39e 100644 --- a/tests/test_traffic_generator.py +++ b/tests/test_traffic_generator.py @@ -16,7 +16,7 @@ def _canonical_traffic_topology( scale: str, family: str = "clos", spines: int = 2, - leafs: int = 1, + leafs: int = 2, clients_per_leaf: int = 2, ) -> dict: devices = [ @@ -53,8 +53,32 @@ def _canonical_traffic_topology( ecmp_hash_policy_by_role={device.role: 1 for device in devices if device.role is not DeviceRole.CLIENT} ), devices=devices, - links=[], + links=[ + topology_models.Link( + kind="access", + endpoints=( + topology_models.LinkEndpoint(device=client.attached_switch, interface=f"eth{i}"), + topology_models.LinkEndpoint(device=client.name, interface="eth1"), + ), + ) + for i, client in enumerate(devices) + if client.role is DeviceRole.CLIENT + ], + ) + manifest.links.extend( + topology_models.Link( + kind="fabric", + endpoints=( + topology_models.LinkEndpoint(device=f"spine{i}", interface=f"eth{j}"), + topology_models.LinkEndpoint(device=f"leaf{j}", interface=f"eth{i}"), + ), + ) + for i in range(1, spines + 1) + for j in range(1, leafs + 1) ) + from netopsbench.platform.pingmesh.planner import compile_pingmesh_plan + + manifest.pingmesh_plan = compile_pingmesh_plan(manifest) return manifest.model_dump(mode="json") @@ -80,8 +104,7 @@ def test_large_standard_profile_respects_switch_budget(tmp_path): ) assert config["stats"]["total_flows"] == 256 - assert config["stats"]["estimated_max_pps_per_client"] == pytest.approx(353.64) - assert config["stats"]["estimated_switch_pps"]["max_switch_pps"] == pytest.approx(4229.69) + assert config["stats"]["estimated_max_pps_per_client"] <= get_scale_profile("large").traffic_max_pps_per_client assert config["stats"]["estimated_switch_pps"]["max_leaf_pps"] <= DEFAULT_SWITCH_PPS_LIMIT assert config["stats"]["estimated_switch_pps"]["max_spine_pps"] <= DEFAULT_SWITCH_PPS_LIMIT assert traffic_generator.validate_traffic_config(config, "large") is True @@ -97,11 +120,22 @@ def test_xlarge_standard_profile_respects_switch_budget(tmp_path): ) assert config["stats"]["total_flows"] > 0 + assert config["stats"]["estimated_max_pps_per_client"] <= 50 assert config["stats"]["estimated_switch_pps"]["max_leaf_pps"] <= DEFAULT_SWITCH_PPS_LIMIT assert config["stats"]["estimated_switch_pps"]["max_spine_pps"] <= DEFAULT_SWITCH_PPS_LIMIT assert traffic_generator.validate_traffic_config(config, "xlarge") is True +@pytest.mark.parametrize("scale", ["xlarge", "fat-tree-k18"]) +@pytest.mark.parametrize("switch_budget", [None, 1000, 5000, 10000]) +def test_switch_budget_cannot_raise_profile_client_limit(scale, switch_budget): + assert traffic_generator._max_pps_per_client(scale, switch_budget) == 50 + + +def test_smaller_switch_budget_reduces_client_limit(): + assert traffic_generator._max_pps_per_client("xlarge", 500) == 25 + + def test_fat_tree_profiles_are_bounded(tmp_path): from netopsbench.platform.topology.generator import generate_topology @@ -138,10 +172,9 @@ def test_fat_tree_profiles_are_bounded(tmp_path): ("scale", "expected_flows", "expected_incoming"), [ ("xs", 2, 1), - ("small", 32, 4), ("medium", 64, 4), ("large", 256, 4), - ("xlarge", 512, 4), + ("xlarge", 1024, 4), ("fat-tree-k8", 512, 4), ("fat-tree-k12", 576, 4), ], @@ -206,7 +239,7 @@ def test_standard_matrix_is_deterministic(tmp_path): def test_traffic_generator_rejects_legacy_grouped_topology(): - with pytest.raises(ValueError, match="schema_version.*3"): + with pytest.raises(ValueError, match="schema_version.*4"): traffic_generator.generate_traffic_config_from_topology( {"devices": {"clients": [], "leafs": [], "spines": []}}, "xs", diff --git a/tests/test_unified_experiment_timing.py b/tests/test_unified_experiment_timing.py new file mode 100644 index 0000000..c8406bc --- /dev/null +++ b/tests/test_unified_experiment_timing.py @@ -0,0 +1,502 @@ +"""Behavioral regression for frozen policies, short windows and shared budgets.""" + +import asyncio +from copy import deepcopy +from types import SimpleNamespace + +import pytest + +from netopsbench.models.profiles import ScaleProfileDocument, get_scale_profile +from netopsbench.models.scenario import EpisodeSpec, ScenarioSpec +from netopsbench.platform.observability.routes import verify_route_recovery +from netopsbench.platform.scenario.effects import scoped_integrity_errors +from netopsbench.platform.scenario.episode_runner import observe_episode +from netopsbench.platform.scenario.executor import ScenarioExecutor +from netopsbench.platform.scenario.timing import PhaseTimings, agent_cleanup_timing +from netopsbench.platform.session.diagnosis import run_agent_diagnose + + +def test_experiment_defaults_are_resolved_once_and_fingerprinted(): + original = get_scale_profile("medium") + defaults = original.experiment.model_dump() + raw = original.model_dump(exclude={"experiment"}) + document = ScaleProfileDocument.model_validate( + { + "experiment_defaults": {**defaults, "observation_seconds": 40}, + "profiles": [raw, {**raw, "name": "custom", "experiment": {"diagnosis_timeout_seconds": 90}}], + } + ) + first, second = document.profiles + assert first.experiment.observation_seconds == second.experiment.observation_seconds == 40 + assert second.experiment.diagnosis_timeout_seconds == 90 + assert first.digest != original.digest + with pytest.raises(ValueError): + first.experiment.observation_seconds = 50 + + +def test_observation_is_one_capture_with_analysis_slices(): + captures = [] + analyzed = [] + runner = SimpleNamespace( + timings=PhaseTimings(), + observation_timeout_seconds=60, + _inject_fault=lambda _: {"success": True}, + ) + runner._capture_observation_window = lambda duration, name: ( + captures.append((duration, name)) + or {"start_time": "2026-10-24T00:00:00Z", "end_time": "2026-10-24T00:00:30Z", "duration_seconds": duration} + ) + runner._merge_observation_windows = lambda windows, **kw: ( + analyzed.extend(windows) or {"duration_seconds": kw["total_duration_seconds"]} + ) + observe_episode( + runner, + EpisodeSpec(episode_id="a", fault_type="link_flapping", duration_seconds=30, stabilization_time=0), + baseline_window={}, + ) + assert captures == [(30, "full")] + assert [(w["name"], w["duration_seconds"]) for w in analyzed] == [("early", 10), ("steady", 20)] + assert analyzed[0]["end_time"] == analyzed[1]["start_time"] + + +@pytest.mark.parametrize( + "broken_batch,missing_peer,valid", [(False, False, True), (True, False, False), (False, True, False)] +) +def test_short_outage_requires_actual_correctly_scheduled_failure(broken_batch, missing_peer, valid): + obs = {"data_source_status": "ok", "_baseline_coverage": {"coverage_status": "complete"}} + task = ["client1", "client3" if missing_peer else "client2", 0] + audit = { + "missing_tasks": [task], + "invalid_tasks": [["client1", "client2", 0]], + "invalid_socket_rows": 1, + "invalid_rows": [ + { + "src": "client1", + "dst": "client2", + "port_batch_index": 0, + "time": "2026-10-24T00:00:05Z", + "local_probe_errors": 1, + "socket_batch_valid": not broken_batch, + } + ], + "observable_pairs": [["client2", "client3"]], + "coverage_status": "incomplete", + } + effect = { + "probe_cycle_seconds": 1, + "bounded_client_outages": [ + {"client": "client1", "start": "2026-10-24T00:00:00+00:00", "end": "2026-10-24T00:00:10+00:00"} + ], + } + assert (not scoped_integrity_errors(obs, audit, effect)) is valid + assert audit["coverage_status"] == "incomplete" + + +def test_down_destination_does_not_excuse_incorrect_source_port_pool(): + obs = {"data_source_status": "ok", "_baseline_coverage": {"coverage_status": "complete"}} + audit = { + "missing_tasks": [], + "invalid_tasks": [["client1", "client7", 0]], + "invalid_socket_rows": 1, + "invalid_rows": [{"src": "client1", "dst": "client7", "socket_batch_valid": False}], + "observable_pairs": [["client1", "client2"]], + } + assert scoped_integrity_errors(obs, audit, {"unobservable_clients": ["client7"]}) + + +def test_restored_bgp_route_does_not_hide_residual_more_specific_static(): + before = { + "nodes": { + "leaf1": {"fib": [{"dst": "192.168.2.0/30", "protocol": "bgp", "gateway": "10.0.0.1", "dev": "Ethernet0"}]} + } + } + after = deepcopy(before) + after["nodes"]["leaf1"]["fib"].append( + {"dst": "192.168.2.2", "protocol": "static", "gateway": "10.0.0.9", "dev": "Ethernet4"} + ) + assert "residual" in verify_route_recovery(before, after)[0] + assert not verify_route_recovery(after, deepcopy(after)) + + +def test_late_recovery_cannot_be_published_as_clean(monkeypatch): + import netopsbench.platform.scenario.executor as module + from netopsbench.platform.utils import control + + clock = [0.0] + runner = object.__new__(ScenarioExecutor) + from netopsbench.models.recovery import RecoveryPolicy + + runner.recovery_policy = RecoveryPolicy() + runner.begin_case() + runner.traffic_controller = None + runner.runtime_worker = None + runner.injector = SimpleNamespace(active_faults=[{"type": "link_down"}]) + runner.scale_registry = SimpleNamespace( + get=lambda _: SimpleNamespace(experiment=SimpleNamespace(recovery_timeout_seconds=1)) + ) + runner.sleep = lambda _: None + + def recover(): + runner.injector.active_faults.clear() + clock[0] += 5 + return [{"recovered": True}] + + runner._recover_fault = recover + monkeypatch.setattr(module, "monotonic", lambda: clock[0]) + monkeypatch.setattr(control.time, "monotonic", lambda: clock[0]) + result = runner._cleanup_after_scenario( + ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, + scenario_id="late", + name="late", + episode=EpisodeSpec(episode_id="a", fault_type="link_down"), + ), + None, + ) + assert result["success"] is False + assert result["status"] == "recovery_timeout" + + +def test_recovery_steps_accumulate_retries_without_resetting_budget(monkeypatch): + import netopsbench.platform.scenario.timing as module + from netopsbench.platform.utils import control + from netopsbench.platform.utils.control import current_operation_control + + clock = [0.0] + monkeypatch.setattr(module, "monotonic", lambda: clock[0]) + monkeypatch.setattr(control.time, "monotonic", lambda: clock[0]) + timings = PhaseTimings() + with timings.measure("recovery", timeout_seconds=120): + deadline = current_operation_control().deadline + with pytest.raises(RuntimeError), timings.measure_step("recovery", "health_check"): + clock[0] += 3 + raise RuntimeError("not yet healthy") + with timings.measure_step("recovery", "health_check"): + assert current_operation_control().deadline == deadline + clock[0] += 5 + with timings.measure_step("recovery", "window_wait"): + clock[0] += 42 + with timings.measure_step("recovery", "window_query") as query: + query["ingestion"] = {"baseline": {"query_seconds": 9}, "current": {"query_seconds": 8}} + clock[0] += 10 + recovery = timings.phases["recovery"] + assert recovery["actual_seconds"] == 60 + assert recovery["steps"]["health_check"] == { + "status": "completed", + "actual_seconds": 8, + "calls": 2, + "failed_calls": 1, + "operations": {}, + } + assert recovery["steps"]["window_query"]["actual_seconds"] == 10 + assert sum(step["actual_seconds"] for step in recovery["steps"].values()) == recovery["actual_seconds"] + + +def test_recovery_window_and_ingestion_timings_are_separate(monkeypatch): + from netopsbench.platform.scenario import observation, timing + + clock = [0.0] + monkeypatch.setattr(timing, "monotonic", lambda: clock[0]) + timings = PhaseTimings() + reference = {"start_time": "2026-01-01T00:00:00Z", "end_time": "2026-01-01T00:00:42Z"} + + def capture(*args, **kwargs): + clock[0] += 42 + return reference + + def analyze(*args, **kwargs): + clock[0] += 10 + return { + "_baseline_health": { + "absolute_unreachable_paths": 0, + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, + "_baseline_coverage": {"ingestion": {"query_requests": 21}}, + "_coverage_audit": {"ingestion": {"query_requests": 21}}, + } + + from netopsbench.models.profiles import default_scale_registry + from netopsbench.platform.scenario.baseline import BaselineHandoff + from netopsbench.platform.scenario.executor import ScenarioExecutor + + runner = object.__new__(ScenarioExecutor) + runner.timings = timings + runner.injector = SimpleNamespace(active_faults=[]) + runner._recovering = True + runner.runtime_worker = None + runner.manifest = SimpleNamespace(scale="xs") + runner.scale_registry = default_scale_registry() + runner.experiment = runner.scale_registry.get("xs").experiment + runner.minimum_baseline_seconds = 42 + runner._baseline_handoff = BaselineHandoff() + runner._baseline_scope = lambda _: None + runner._capture_baseline_window = capture + runner._merge_observation_windows = analyze + reference["duration_seconds"] = 42 + monkeypatch.setattr(observation, "baseline_gate_errors", lambda _: []) + runner.calibrate(SimpleNamespace(id="case"), "test") + steps = timings.phases["calibration"]["steps"] + assert steps["window_wait"]["actual_seconds"] == 42 + assert steps["window_query"]["actual_seconds"] == 10 + assert steps["window_query"]["ingestion"] == {"baseline": {"query_requests": 21}, "current": {"query_requests": 21}} + + +def test_total_diagnosis_timeout_cancels_and_measures_cleanup(): + events = [] + + class Agent: + async def diagnose(self, context): + try: + events.append("started") + await asyncio.sleep(10) + finally: + with agent_cleanup_timing(): + await asyncio.sleep(0.01) + events.append("cleaned") + + timings = PhaseTimings() + with pytest.raises(TimeoutError): + run_agent_diagnose(Agent(), None, timeout_seconds=0.02, timings=timings) + assert events == ["started", "cleaned"] + assert timings.phases["agent_cleanup"]["actual_seconds"] >= 0.01 + + +def test_completed_diagnosis_cleanup_does_not_consume_the_work_budget(): + from netopsbench.platform.toolkit._core.control import diagnosis_budget_scope + + expected = object() + + class Agent: + async def diagnose(self, context): + # A bundled adapter and the SDK share the same earlier deadline. + async with diagnosis_budget_scope(10): + try: + await asyncio.sleep(0) + return expected + finally: + with agent_cleanup_timing(): + await asyncio.sleep(0.05) + + timings = PhaseTimings() + assert run_agent_diagnose(Agent(), None, timeout_seconds=0.02, timings=timings) is expected + assert timings.phases["agent_cleanup"]["actual_seconds"] >= 0.05 + + +def test_session_budget_excludes_recorded_cleanup_but_preserves_wall_time_metrics(): + from netopsbench.platform.incident.engine import DiagnosticSession + + session = object.__new__(DiagnosticSession) + session.config = SimpleNamespace(max_agent_seconds=0.02, max_tool_calls=10) + session.tool_calls = 0 + session.phase_timings = PhaseTimings() + session.phase_timings.phases["agent_cleanup"] = {"status": "completed", "actual_seconds": 0.05} + assert session._limit_transition(0.06) is None + assert session._metrics(0.06)["elapsed_seconds"] == 0.06 + assert session._limit_transition(0.08).error == "max_agent_seconds exceeded" + + +def test_user_cancellation_still_interrupts_post_diagnosis_cleanup(): + from netopsbench.platform.toolkit._core.control import diagnosis_budget_scope + from netopsbench.platform.utils.control import finish_cleanup + + async def run(): + entered = asyncio.Event() + cleaned = [] + + async def agent(): + async with diagnosis_budget_scope(10): + with agent_cleanup_timing(): + entered.set() + + async def cleanup(): + await asyncio.sleep(0.01) + cleaned.append(True) + + _, cancelled = await finish_cleanup(cleanup()) + if cancelled: + raise asyncio.CancelledError + + task = asyncio.create_task(agent()) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert cleaned == [True] + + asyncio.run(run()) + + +def test_recovery_stops_an_inflight_periodic_command(): + from threading import Event + + from netopsbench.platform.faults.services.periodic import PeriodicController + from netopsbench.platform.utils.control import current_operation_control + + entered = Event() + + def healthy(): + control = current_operation_control() + assert control is not None + entered.set() + control.sleep(30) + + controller = PeriodicController(lambda: None, healthy, down_time=0.001, up_time=0.001) + controller.start() + try: + assert entered.wait(1) + finally: + controller.stop_event.set() + controller.thread.join(timeout=1) + assert not controller.thread.is_alive() + assert controller.error is None + assert [row["phase"] for row in controller.history] == ["fault"] + + +@pytest.mark.parametrize("unhealthy", [False, True]) +def test_fresh_baseline_is_one_capture_and_checks_absolute_health(tmp_path, monkeypatch, unhealthy): + from netopsbench.platform.topology.generator import generate_topology + + metadata = generate_topology("xs", str(tmp_path), name="single-baseline")["metadata"] + sleeps = [] + clock = [0.0] + + def advance(seconds): + sleeps.append(seconds) + clock[0] += seconds + + from datetime import UTC, datetime, timedelta + + epoch = datetime.now(UTC) + + class ClockDatetime(datetime): + @classmethod + def now(cls, tz=None): + return epoch + timedelta(seconds=clock[0]) + + monkeypatch.setattr("netopsbench.platform.scenario.baseline.datetime", ClockDatetime) + monkeypatch.setattr("netopsbench.platform.scenario.observation.datetime", ClockDatetime) + monkeypatch.setattr("netopsbench.platform.scenario.observation.time.monotonic", lambda: clock[0]) + monkeypatch.setattr("netopsbench.platform.scenario.timing.monotonic", lambda: clock[0]) + runner = ScenarioExecutor(topology_dir=str(tmp_path), topology_metadata=metadata, sleep_fn=advance) + monkeypatch.setattr(runner, "_setup_traffic", lambda *_: {}) + monkeypatch.setattr(runner, "_stop_traffic", lambda: None) + reads = [] + + def analyze(windows, total_duration_seconds, **kwargs): + reads.append(windows) + return { + "start_time": "2026-10-24T00:00:00Z", + "end_time": "2026-10-24T00:00:30Z", + "duration_seconds": total_duration_seconds, + "data_source_status": "ok", + "coverage_status": "complete", + "_baseline_coverage": {"coverage_status": "complete"}, + "_baseline_health": { + "absolute_unreachable_paths": int(unhealthy), + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, + "pingmesh_metrics": {"summary": {"total_anomalies": 0}, "quality": {"current_paths_observed": 2}}, + } + + from netopsbench.platform.scenario.baseline import RuntimeScope + + monkeypatch.setattr(runner, "_baseline_scope", lambda _: RuntimeScope({}, {}, {})) + monkeypatch.setattr("netopsbench.platform.observability.routes.collect_routes", lambda *a, **k: {"nodes": {}}) + monkeypatch.setattr(runner, "_merge_observation_windows", analyze) + case = ScenarioSpec( + metadata={"recovery_policy": {"version": 3}}, + scenario_id="healthy", + name="healthy", + topology_scale="xs", + episode=EpisodeSpec(episode_id="a", fault_type="none", duration_seconds=30, stabilization_time=0), + ) + result = runner.run_scenario(case) + assert result["success"] is not unhealthy, result.get("error", result.get("episode")) + assert len(sleeps) == (30 if unhealthy else 60) + assert sum(w[0]["name"] == "baseline" for w in reads) == 1 + if unhealthy: + assert "absolute_unreachable_paths=1" in result["error"] + else: + assert result["phase_timings"]["calibration"]["steps"]["window_wait"]["actual_seconds"] == 30 + assert result["phase_timings"]["diagnosis"]["status"] == "skipped" + + +def test_periodic_effect_cannot_borrow_transitions_outside_window(): + from netopsbench.platform.scenario.effects import _observed_periodic_phases + + history = [ + {"phase": phase, "time": f"2026-10-24T00:00:{i * 10:02d}Z"} + for i, phase in enumerate(("fault", "healthy", "fault", "healthy", "fault")) + ] + assert [p["phase"] for p in _observed_periodic_phases(history, "2026-10-24T00:00:25Z", "2026-10-24T00:00:29Z")] == [ + "fault" + ] + assert [p["phase"] for p in _observed_periodic_phases(history, "2026-10-24T00:00:00Z", "2026-10-24T00:00:30Z")] == [ + "fault", + "healthy", + "fault", + "healthy", + ] + + +def test_fresh_health_snapshot_is_read_once_without_losing_absolute_health(monkeypatch): + from netopsbench.platform.pingmesh._detector_query import SnapshotQueryResult + from netopsbench.platform.pingmesh.detector import AnomalyDetector + + detector = object.__new__(AnomalyDetector) + detector.plan_id = "fixed" + calls = [] + + def query(start, end, **kwargs): + calls.append((start, end)) + return SnapshotQueryResult(status="ok", rows=[]), {"coverage_status": "complete"} + + monkeypatch.setattr(detector, "_query_covered_snapshot", query) + monkeypatch.setattr( + detector, + "analyze_snapshot_rows", + lambda *_: SimpleNamespace( + anomalies=[], + quality={ + "current_paths_observed": 1, + "absolute_unreachable_paths": 1, + "absolute_packet_loss_paths": 0, + "absolute_network_mtu_paths": 0, + }, + ), + ) + report = detector.generate_windowed_anomaly_report( + baseline_start="start", + baseline_end="end", + current_start="start", + current_end="end", + windows=[], + include_internal_health=True, + ) + assert calls == [("start", "end")] + assert report["_baseline_health"]["absolute_unreachable_paths"] == 1 + + +def test_healthy_and_fault_cases_share_the_same_public_window_shape(): + shapes = [] + for fault in ("none", "link_down"): + runner = SimpleNamespace( + timings=PhaseTimings(), + observation_timeout_seconds=60, + _inject_fault=lambda _: {"success": True}, + ) + runner._capture_observation_window = lambda duration, name: { + "start_time": "2026-10-24T00:00:00Z", + "end_time": "2026-10-24T00:00:30Z", + "duration_seconds": duration, + } + runner._merge_observation_windows = lambda windows, **kwargs: {"observation_windows": windows} + result = observe_episode( + runner, + EpisodeSpec(episode_id="diagnosis", fault_type=fault, duration_seconds=30, stabilization_time=0), + baseline_window={}, + ) + shapes.append(result["observations"]) + assert shapes[0] == shapes[1] diff --git a/tests/test_wheel_smoke.py b/tests/test_wheel_smoke.py index 8f15e8b..a509a6b 100644 --- a/tests/test_wheel_smoke.py +++ b/tests/test_wheel_smoke.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import shutil import subprocess import sys import venv @@ -12,11 +13,17 @@ def test_installed_wheel_generates_topology_without_source_checkout(tmp_path): repo = Path(__file__).resolve().parents[1] + source = tmp_path / "source" + source.mkdir() + shutil.copytree(repo / "netopsbench", source / "netopsbench", ignore=shutil.ignore_patterns("__pycache__", "_bin")) + for name in ("pyproject.toml", "README.md", "LICENSE"): + if (repo / name).exists(): + shutil.copy2(repo / name, source / name) wheel_dir = tmp_path / "wheel" wheel_dir.mkdir() subprocess.run( [sys.executable, "-m", "pip", "wheel", ".", "--no-deps", "--wheel-dir", str(wheel_dir)], - cwd=repo, + cwd=source, check=True, capture_output=True, text=True, @@ -32,6 +39,8 @@ def test_installed_wheel_generates_topology_without_source_checkout(tmp_path): assert "netopsbench/platform/observability/assets/grafana/provisioning/datasources/default.yaml" in names assert "netopsbench/platform/scenario/specs/fault_campaign.yaml" in names assert "netopsbench/models/scale_profiles.yaml" in names + assert "netopsbench/platform/simulator/service.py" not in names + assert "netopsbench/sdk/simulator_service.py" not in names assert not any("rl_experiment" in name or "verl" in name for name in names) assert not any(name.startswith("netopsbench/resources/") for name in names) assert "netopsbench/platform/observability/assets/telegraf.conf" not in names @@ -46,12 +55,7 @@ def test_installed_wheel_generates_topology_without_source_checkout(tmp_path): capture_output=True, text=True, ) - subprocess.run( - [str(venv_dir / "bin" / "netopsbench-simulator"), "--help"], - check=True, - capture_output=True, - text=True, - ) + assert not (venv_dir / "bin" / "netopsbench-simulator").exists() assert not (venv_dir / "bin" / "netopsbench-rl").exists() outside = tmp_path / "outside" @@ -63,6 +67,7 @@ def test_installed_wheel_generates_topology_without_source_checkout(tmp_path): from netopsbench.platform.observability.lifecycle import observability_asset_root from netopsbench.platform.topology.generator import generate_topology from netopsbench.models.profiles import default_scale_registry +from netopsbench.sdk import NetOpsBench, SimulatorConfig source_root = Path({str(repo)!r}).resolve() package_file = Path(netopsbench.__file__).resolve() diff --git a/tests/test_worker_health.py b/tests/test_worker_health.py index 6167f4b..fccb30e 100644 --- a/tests/test_worker_health.py +++ b/tests/test_worker_health.py @@ -1,46 +1,44 @@ +import json import subprocess import time from pathlib import Path +from types import SimpleNamespace + +import pytest from netopsbench.models.runtime import RuntimeIdentity from netopsbench.platform.runtime import health from netopsbench.platform.topology.topology_utils import coerce_topology_manifest +def test_k18_expectations_distinguish_client_links_and_bgp_fabric(): + from netopsbench.platform.topology.config import config_for_scale + from netopsbench.platform.topology.fat_tree_builder import build_fat_tree_plan + + topo = build_fat_tree_plan(config_for_scale("fat-tree-k18")).manifest + counts = health.expected_network_counts(topo) + assert counts["core81"] == {"active_interfaces": 18, "bgp_neighbors": 18} + assert counts["agg162"] == {"active_interfaces": 18, "bgp_neighbors": 18} + assert counts["edge162"] == {"active_interfaces": 11, "bgp_neighbors": 9} + assert counts["client324"] == {"active_interfaces": 1, "bgp_neighbors": 0} + assert sum(row["bgp_neighbors"] for row in counts.values()) == 5832 + assert sum(row["active_interfaces"] for row in counts.values()) == 6480 + + def _canonical_topology_dict(*, scale: str, spines: int, leafs: int, clients: int) -> dict: - devices = [ - *[{"name": f"spine{i}", "role": "spine", "mgmt_ip": f"172.20.20.{10 + i}"} for i in range(1, spines + 1)], - *[{"name": f"leaf{i}", "role": "leaf", "mgmt_ip": f"172.20.20.{10 + spines + i}"} for i in range(1, leafs + 1)], - *[ - { - "name": f"client{i}", - "role": "client", - "attached_switch": f"leaf{((i - 1) % leafs) + 1}", - "data_ip": f"192.168.{100 + i}.2", - } - for i in range(1, clients + 1) - ], - ] - return { - "schema_version": "3", - "topology_id": scale, - "name": scale, - "scale": scale, - "family": "clos", - "management": {"network": f"clab-{scale}", "ipv4_subnet": "172.20.20.0/23"}, - "collector": {"ipv4": "172.20.20.200"}, - "defaults": {"link_mtu": 9232, "sonic_port_mtu": 9100}, - "facts": { - "num_spines": spines, - "num_leafs": leafs, - "clients_per_attached_switch": 1, - "total_clients": clients, - "total_switches": spines + leafs, - }, - "routing": {"ecmp_hash_policy_by_role": {"spine": 1, "leaf": 1}}, - "devices": devices, - "links": [], - } + from netopsbench.platform.topology.clos_builder import build_clos_plan + from netopsbench.platform.topology.config import TopologyConfig + + return build_clos_plan( + TopologyConfig( + name=scale, + scale_name=scale, + num_spines=spines, + num_leafs=leafs, + clients_per_leaf=clients // leafs, + mgmt_ipv4_subnet="172.20.20.0/23", + ) + ).manifest.model_dump(mode="json") def _runtime_identity(topology_dir: Path, name: str) -> RuntimeIdentity: @@ -57,17 +55,18 @@ def _runtime_identity(topology_dir: Path, name: str) -> RuntimeIdentity: def test_active_interface_parser_exposes_incomplete_xlarge_spine(): - topo = _canonical_topology_dict(scale="xlarge", spines=16, leafs=128, clients=128) + topo = coerce_topology_manifest(_canonical_topology_dict(scale="xlarge", spines=16, leafs=128, clients=256)) output = "\n".join(f"Ethernet{idx * 4} 1,2,3,4 100G 9100 N/A up up QSFP" for idx in range(32)) active = health._parse_active_interfaces(output) assert len(active) == 32 - assert health._expected_active_interface_count(topo, "spine1") == 128 - assert health._expected_active_interface_count(topo, "leaf128") == 17 + counts = health.expected_network_counts(topo) + assert counts["spine1"]["active_interfaces"] == 128 + assert counts["leaf128"]["active_interfaces"] == 18 def test_deployment_convergence_checks_every_routing_device(): - topo = coerce_topology_manifest(_canonical_topology_dict(scale="xlarge", spines=16, leafs=128, clients=128)) + topo = coerce_topology_manifest(_canonical_topology_dict(scale="xlarge", spines=16, leafs=128, clients=256)) assert len(health._convergence_targets(topo, all_routing_devices=True)) == 144 assert len(health._convergence_targets(topo, all_routing_devices=False)) == 3 @@ -83,27 +82,56 @@ def test_fat_tree_sparse_expected_active_interface_counts(): generate_topology("fat-tree-k12", raw_dir) topo = load_topology_manifest(raw_dir) - assert health._expected_active_interface_count(topo, "core1") == 12 - assert health._expected_active_interface_count(topo, "agg1") == 12 - assert health._expected_active_interface_count(topo, "edge72") == 8 + counts = health.expected_network_counts(topo) + assert counts["core1"]["active_interfaces"] == 12 + assert counts["agg1"]["active_interfaces"] == 12 + assert counts["edge72"]["active_interfaces"] == 8 -def test_worker_health_retries_observability_until_collector_is_ready(tmp_path, monkeypatch): +@pytest.mark.parametrize("budgeted", [False, True]) +@pytest.mark.parametrize("fib_delay", [False, True]) +def test_worker_health_retries_observability_until_collector_is_ready(tmp_path, monkeypatch, budgeted, fib_delay): from netopsbench.platform.observability import influxdb, validation from netopsbench.platform.topology.generator import generate_topology - generate_topology("xs", str(tmp_path), name="health-xs") + metadata = generate_topology("xs", str(tmp_path), name="health-xs")["metadata"] monkeypatch.setattr( health, "safe_run", lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 0, stdout="telegraf-health-xs\n", stderr=""), ) - monkeypatch.setattr(health, "_running_container_count", lambda _lab_name: 6) + monkeypatch.setattr(health, "_running_container_count", lambda _lab_name, **kw: 6) + + exec_calls = [] + fib_polls = {} def fake_docker_exec(_container, *command, **_kwargs): + exec_calls.append(command) joined = " ".join(command) - if "show ip bgp summary" in joined: + if command[:2] == ("python3", "-c"): + fib_polls[_container] = fib_polls.get(_container, 0) + 1 + hops = [{"gateway": "10.0.0.1"}] + if fib_polls[_container] > 1: + hops.append({"gateway": "10.0.0.2"}) + fib = [{"dst": "192.168.12.0/30", "protocol": "bgp", "nexthops": hops}] + output = json.dumps( + { + "version": 1, + "checks": { + "bgp": { + "returncode": 0, + "stdout": fake_docker_exec(_container, "vtysh", "-c", "show ip bgp summary").stdout, + }, + "interfaces": { + "returncode": 0, + "stdout": fake_docker_exec(_container, "bash", "-lc", "show interfaces status").stdout, + }, + "fib": {"returncode": 0, "stdout": json.dumps(fib)}, + }, + } + ) + elif "show ip bgp summary" in joined: output = "".join(f"10.0.0.{index} 4 65001 0 0 0 0 0 00:10:00 1\n" for index in range(1, 5)) elif "show interfaces status" in joined: output = "".join(f"Ethernet{index * 4} 1,2,3,4 100G 9100 N/A up up QSFP\n" for index in range(4)) @@ -121,25 +149,201 @@ def fake_docker_exec(_container, *command, **_kwargs): "status": { "ready": True, "heartbeat_unix_ns": time.time_ns(), + "plan_id": metadata["pingmesh_plan"]["settings"]["plan_id"], + "config_schema_version": 2, }, }, ) attempts = [] def fake_check_observability(*_args, **_kwargs): - attempts.append(1) - return ["collector has not written its first sample"] if len(attempts) == 1 else [] + check = next(iter(_kwargs["checks"])) + attempts.append(check) + if budgeted: + time.sleep(0.02) + return ["collector still unavailable"] + return ( + ["collector has not written its first sample"] if check == "syslog" and attempts.count(check) == 1 else [] + ) monkeypatch.setattr(validation, "check_observability", fake_check_observability) monkeypatch.setattr( influxdb, "query_flux", lambda *_args, **_kwargs: type("Result", (), {"status": "ok", "text": ""})() ) + started = time.monotonic() + expected_routes = { + "nodes": { + device["name"]: { + "fib": [ + { + "dst": "192.168.12.0/30", + "protocol": "bgp", + "nexthops": [{"gateway": "10.0.0.1"}, {"gateway": "10.0.0.2"}], + } + ] + } + for device in metadata["devices"] + if device["role"] != "client" + } + } errors = health.check_worker_health( _runtime_identity(tmp_path, "health-xs"), - health_retries=2, - health_delay=0, + health_retries=100 if budgeted else 2, + health_delay=0.01 if budgeted else 0, + deadline=started + 0.15 if budgeted else None, + route_snapshot={} if fib_delay else None, + expected_routes=expected_routes if fib_delay else None, ) + if budgeted: + assert errors == ["Worker health check deadline exceeded"] + assert time.monotonic() - started < 1 + assert attempts + return assert errors == [] - assert len(attempts) == 2 + if fib_delay: + assert all(polls >= 2 for polls in fib_polls.values()) + assert "logger -n" in " ".join(exec_calls[0]) + assert sum(c == ("bash", "-lc", "show interfaces status") for c in exec_calls) == (6 if fib_delay else 3) + assert sorted(attempts) == ["bgp", "interfaces", "pingmesh", "syslog", "syslog"] + + +def test_network_probe_preserves_commands_order_and_deadlines(): + from netopsbench.platform.observability._routing_probe import probe + + calls = [] + + def run(command, **kwargs): + calls.append((command, kwargs)) + return subprocess.CompletedProcess(command, 0, stdout="\n".join(command)) + + result = probe(run) + assert [c[0] for c in calls] == [ + ["vtysh", "-c", "show ip bgp summary"], + ["bash", "-lc", "show interfaces status"], + ["ip", "-j", "-4", "route", "show"], + ] + assert all(c[1]["timeout"] == 60 for c in calls) + assert result["checks"]["bgp"]["stdout"] == "vtysh\n-c\nshow ip bgp summary" + + +@pytest.mark.parametrize("failure", [subprocess.TimeoutExpired("vtysh", 60), OSError("missing")]) +def test_network_probe_preserves_independent_check_after_failure(failure): + from netopsbench.platform.observability._routing_probe import probe + + def run(command, **kwargs): + if command[0] == "vtysh": + raise failure + return subprocess.CompletedProcess(command, 0, stdout="Ethernet0 up up") + + result = probe(run) + assert result["checks"]["bgp"]["returncode"] == -1 + assert result["checks"]["interfaces"]["returncode"] == 0 + + +@pytest.mark.parametrize( + "payload", + ["not json", "null", "[]", '{"version": 2}', '{"version": 1, "checks": {}}'], +) +def test_routing_state_rejects_invalid_response(monkeypatch, payload): + monkeypatch.setattr(health, "_docker_exec", lambda *a, **kw: subprocess.CompletedProcess(a, 0, stdout=payload)) + assert health._routing_state("node") == ("", "") + + +@pytest.mark.parametrize("failed", [None, "bgp", "interfaces", "transport"]) +def test_routing_state_uses_one_exec_and_rejects_failed_command(monkeypatch, failed): + calls = [] + + def execute(*args, **kwargs): + calls.append((args, kwargs)) + payload = { + "version": 1, + "checks": { + name: {"returncode": 7 if name == failed else 0, "stdout": name} for name in ["bgp", "interfaces"] + }, + } + return subprocess.CompletedProcess(args, 1 if failed == "transport" else 0, stdout=json.dumps(payload)) + + monkeypatch.setattr(health, "_docker_exec", execute) + assert health._routing_state("node") == (("bgp", "interfaces") if failed is None else ("", "")) + assert len(calls) == 1 + assert calls[0][0][:3] == ("node", "python3", "-c") + assert calls[0][1]["timeout"] == 125 + + +def test_large_health_queue_stops_launching_probes_at_shared_deadline(): + import threading + + from netopsbench.platform.utils.control import OperationControl + + control = OperationControl(deadline=time.monotonic() + 0.04) + started = [] + lock = threading.Lock() + + def probe(device): + with lock: + started.append(device) + control.sleep(0.02) + return device + + before = time.monotonic() + with pytest.raises(TimeoutError): + health._parallel_check(probe, list(range(405)), 16, control) + assert len(started) < 405 + assert time.monotonic() - before < 1 + + +def test_health_external_deadline_includes_initial_probes(tmp_path, monkeypatch): + from netopsbench.platform.topology.generator import generate_topology + + generate_topology("xs", str(tmp_path), name="health-xs") + calls = [] + monkeypatch.setattr(health, "safe_run", lambda *a, **kw: calls.append(a) or pytest.fail("expired probe started")) + errors = health.check_worker_health(_runtime_identity(tmp_path, "health-xs"), deadline=time.monotonic() - 1) + assert errors == ["Worker health check deadline exceeded"] + assert calls == [] + + +def test_warm_records_fresh_complete_health_check(tmp_path, monkeypatch): + from types import SimpleNamespace + + from netopsbench.platform.runtime import lifecycle + + calls = [] + monkeypatch.setattr(lifecycle, "check_worker_health", lambda *a, **kw: calls.append(kw) or []) + runtime = SimpleNamespace(workers=[_runtime_identity(tmp_path, "warm-xs")], root_dir=tmp_path, size=1) + result = lifecycle.RuntimeLifecycle()._warm(runtime) + assert len(calls) == 1 and calls[0]["all_routing_devices"] is True + assert result["all_routing_devices"] is True and result["checked_at"] + + +def test_quarantine_accumulates_workers_without_duplicate_writes(tmp_path, monkeypatch): + from netopsbench.platform.runtime.manager import RuntimePool + + runtime = RuntimePool("id", "name", "xs", tmp_path, []) + writes = [] + monkeypatch.setattr(runtime, "_write_metadata", lambda: writes.append(dict(runtime.metadata))) + runtime.mark_quarantined("scenario_cleanup_failure", ["worker-1"]) + runtime.mark_quarantined("scenario_cleanup_failure", ["worker-1"]) + runtime.mark_quarantined("scenario_cleanup_failure", ["worker-2"]) + assert runtime.state == "quarantined" + assert runtime.metadata["quarantined_workers"] == ["worker-1", "worker-2"] + assert len(writes) == 2 + + +def test_routing_probe_subcommands_share_one_deadline(monkeypatch): + import netopsbench.platform.observability._routing_probe as probe_module + + clock = [0.0] + monkeypatch.setattr(probe_module.time, "monotonic", lambda: clock[0]) + timeouts = [] + + def run(command, **kwargs): + timeouts.append(kwargs["timeout"]) + clock[0] += 4 + return SimpleNamespace(returncode=0, stdout="[]") + + payload = probe_module.probe(run, budget_seconds=5) + assert timeouts == [5, 1] + assert payload["checks"]["fib"]["error"] == "deadline_exceeded"