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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
* text=auto
*.json text eol=lf
*.csv text eol=lf
20 changes: 19 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ name: ci
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
python-version: ["3.11", "3.12"]
steps:
- uses: actions/checkout@v4
Expand All @@ -14,3 +16,19 @@ jobs:
- run: pip install -e ".[dev]"
- run: pytest -q
- run: python -m node_verdict demo

web:
runs-on: ubuntu-latest
defaults:
run:
working-directory: web
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: web/package-lock.json
- run: npm ci
- run: npm run lint
- run: npm run build
50 changes: 50 additions & 0 deletions .github/workflows/pages.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: pages
on:
push:
branches: [main]
workflow_dispatch:

permissions:
contents: read
pages: write
id-token: write

concurrency:
group: pages
cancel-in-progress: true

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
# The site renders exported JSON. Fail the deploy if it drifted from the engine.
- run: pip install -e ".[dev]"
- run: pytest -q tests/test_export.py
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: web/package-lock.json
- run: npm ci
working-directory: web
- run: npm run build
working-directory: web
env:
PAGES_BASE_PATH: /node-verdict
- uses: actions/upload-pages-artifact@v3
with:
path: web/out

deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- id: deployment
uses: actions/deploy-pages@v4
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ walkthrough_audio.*
.env
.DS_Store
HANDOFF.md
node_modules/
3 changes: 3 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ python -m node_verdict demo
python -m node_verdict verdicts # add --json, or --no-history
python -m node_verdict simulate --sensitivity
python -m node_verdict robustness # threshold sweep
python scripts/export_json.py # regenerate web/src/data after any engine change
cd web && npm ci && npm run dev # the web demo (Next.js, static export)

# Rebuild data/derived/ from ByteDance's artifact (needs pyarrow)
git clone https://github.com/ByteDance-Seed/StragglerAnalysis <somewhere>
Expand All @@ -36,6 +38,7 @@ Evidence goes in, a verdict comes out, policy turns the verdict into an action.
- `scenario.py`: the 32-node demo. Real timing, synthetic node history.
- `robustness.py`: sweeps each threshold and reports where verdicts change.
- `simulator.py`: compares naive, naive+checkpoint, peer-aware, and attributed repair.
- `export.py`: writes everything the web demo shows to one JSON file. `web/` renders it and decides nothing. `tests/test_export.py` fails if the committed JSON drifts.

Things that are easy to get wrong:

Expand Down
23 changes: 23 additions & 0 deletions scripts/export_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Write web/src/data/node-verdict-data.json from the real engine and simulator.

Run from the repo root after any change to the engine, policy, simulator or data:

python scripts/export_json.py
"""
from __future__ import annotations

import argparse
from pathlib import Path

from node_verdict.export import DEFAULT_OUT, write


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
path = write(parser.parse_args().out)
print(f"wrote {path}")


if __name__ == "__main__":
main()
205 changes: 205 additions & 0 deletions src/node_verdict/export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
"""Export everything the web demo shows as one JSON document.

The web app renders this file and decides nothing. Every verdict, action,
policy result and robustness band comes from the same Python that the tests
cover. `tests/test_export.py` fails if the committed JSON drifts from a fresh
export, so the demo cannot quietly disagree with the engine.
"""
from __future__ import annotations

import json
from dataclasses import asdict
from pathlib import Path

from . import __version__
from .attribution import AttributionConfig
from .conditions import API_VERSION, ATTRIBUTED_TO, REASON_CODES_V1, ReasonCode
from .engine import run_engine
from .policy import DEFAULT_ACTIONS, PolicyConfig, plan
from .robustness import all_bands, healthy_nodes_ever_changed
from .scenario import BAD_NODE, DECOY_NODE, SDC_NODE, Scenario, build_scenario
from .simulator import SimParams, compare, owner_by_job, sensitivity

DEFAULT_OUT = Path(__file__).resolve().parents[2] / "web" / "src" / "data" / "node-verdict-data.json"

TRACE_LABELS = {
"AR": "One worker artificially slowed, a stand-in for a bad node",
"ST": "Uneven pipeline stage partitioning",
"SE": "Uneven sequence lengths",
}

REASON_TEXT = {
"NodeLemon": "Slow against stage peers in most steps, and the node was the outlier in other jobs too.",
"NodeSuspect": "Slow against stage peers in most steps, but only this job is on record.",
"SDCSuspect": "Training anomalies in two or more jobs while idle checks pass and timing is normal.",
"WorkloadImbalance": "The whole pipeline stage is slow and this rank matches its stage peers.",
}


def _r(x: float, n: int = 4) -> float:
return round(float(x), n)


def _job(job) -> dict:
sig = job.signals
table = job.table.sort_values(["rank", "step"])
steps = sorted(int(s) for s in table["step"].unique())
meta = job.whatif.get("job_meta", {})
ranks = []
for rank in sorted(sig.ranks):
s = sig.ranks[rank]
rows = table[table["rank"] == rank]
ranks.append({
"rank": rank,
"node": job.node_of_rank[rank],
"stage": s.stage,
"dp": s.dp_rank,
"meanComputeS": _r(s.mean_compute_s),
"vsJobMedian": _r(s.mean_compute_s / sig.job_median_compute_s, 3),
"peerRatio": _r(s.rel_median, 3),
"persistence": _r(s.persistence, 3),
"computeS": [_r(x) for x in rows["compute_s"]],
})
return {
"id": job.id,
"trace": job.trace,
"traceLabel": TRACE_LABELS[job.trace],
"cause": job.cause,
"nodes": job.nodes,
"steps": steps,
"stages": sorted({r["stage"] for r in ranks}),
"dps": sorted({r["dp"] for r in ranks}),
"stageRatio": {str(k): _r(v, 3) for k, v in sorted(sig.stage_ratio.items())},
"fbCorr": _r(sig.fb_corr, 3),
"stepCv": _r(sig.step_cv, 3),
"jobMedianComputeS": _r(sig.job_median_compute_s),
"slowdown": _r(job.whatif["blocking_slowdown"], 3),
"fullJob": {k: meta.get(k) for k in ("dp_size", "pp_size", "tp_size", "world_size")},
"ranks": ranks,
}


def _verdicts(scenario: Scenario, history=None) -> list[dict]:
conditions = run_engine(scenario, AttributionConfig(), history)
sizes = {j.id: len(j.nodes) for j in scenario.jobs}
actions = plan(conditions, len(scenario.pool), scenario.spares, sizes, PolicyConfig())
out = []
for c, a in zip(conditions, actions):
d = c.to_dict()
d["action"] = {"kind": a.kind, "status": a.status, "detail": a.detail, "changesNode": a.changes_node}
out.append(d)
return out


def _history(scenario: Scenario) -> dict:
current = scenario.job_ids()
out = {}
for name in scenario.history.names():
h = scenario.history.get(name)
rate = h.active_check_pass_rate()
out[name] = {
"elevatedJobs": h.elevated_jobs(),
"anomalyJobs": h.anomaly_jobs(),
"lemonScore": _r(h.lemon_score(), 2),
"activeCheckPassRate": None if rate is None else _r(rate, 2),
"observations": [
{
"job": o.job_id,
"current": o.job_id in current,
"persistentOutlier": o.persistent_outlier,
"peerRatio": o.peer_ratio,
"anomalyEvents": o.anomaly_events,
"excludedByJob": o.excluded_by_job,
"repairTickets": o.repair_tickets,
"multiNodeFailure": o.multi_node_failure,
"activeCheckPassed": o.active_check_passed,
}
for o in h.observations
],
}
return out


def _policy(r) -> dict:
return {
"name": r.name,
"replaced": r.replaced,
"quarantined": r.quarantined,
"healthyReplaced": r.healthy_replaced,
"sparesUsed": r.spares_used,
"flaggedUnserved": r.flagged_unserved,
"badNodeFixed": r.bad_node_fixed,
"sdcPulled": r.sdc_pulled,
"ownerByJob": r.owner_by_job,
"jobsRightOwner": r.jobs_right_owner,
"goodput": _r(r.goodput),
"goodputByJob": {k: _r(v) for k, v in r.goodput_by_job.items()},
}


def build_export() -> dict:
scenario = build_scenario()
params = SimParams()
cfg = AttributionConfig()
no_history = scenario.history.only_jobs(scenario.job_ids())
bands = all_bands()
changed = healthy_nodes_ever_changed()
return {
"meta": {
"version": __version__,
"apiVersion": API_VERSION,
"asOf": scenario.as_of,
"poolSize": len(scenario.pool),
"spares": scenario.spares,
"real": [
"Per-rank compute time per step for three jobs (ByteDance sample traces, Apache-2.0)",
"Per-job slowdown from ByteDance's published what-if analysis",
"What actually caused each job's slowdown (the trace labels)",
],
"synthetic": [
"Which node each trace rank runs on",
"Each node's history across earlier jobs",
"Training anomaly events that stand in for silent data corruption",
],
"planted": {"badNode": BAD_NODE, "sdcNode": SDC_NODE, "decoyNode": DECOY_NODE},
},
"config": {k: v for k, v in asdict(cfg).items() if k != "weights"} | {"lemonWeights": asdict(cfg.weights)},
"simParams": asdict(params),
"reasonCodes": [
{
"code": code,
"attributedTo": ATTRIBUTED_TO[ReasonCode(code)],
"defaultAction": DEFAULT_ACTIONS[ReasonCode(code)],
"when": REASON_TEXT[code],
}
for code in ("NodeLemon", "SDCSuspect", "NodeSuspect", "WorkloadImbalance")
if code in REASON_CODES_V1
],
"pool": scenario.pool,
"jobs": [_job(j) for j in scenario.jobs],
"verdicts": {"withHistory": _verdicts(scenario), "noHistory": _verdicts(scenario, no_history)},
"ownerByJob": {
"withHistory": owner_by_job(run_engine(scenario, cfg)),
"noHistory": owner_by_job(run_engine(scenario, cfg, no_history)),
},
"history": _history(scenario),
"policies": [_policy(r) for r in compare(scenario, params)],
"sensitivity": [
{"ckptSteps": c, "vsNaive": _r(a, 2), "vsNaiveCheckpoint": _r(b, 2), "vsPeerAware": _r(p, 2)}
for c, a, b, p in sensitivity(scenario, restart_steps=params.restart_steps)
],
"robustness": {
"bands": [asdict(b) | {"basis": b.basis} for b in bands],
"healthyNodesEverChanged": sum(len(v) for v in changed.values()),
},
}


def dumps(data: dict) -> str:
return json.dumps(data, indent=1, sort_keys=False) + "\n"


def write(out: Path = DEFAULT_OUT) -> Path:
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(dumps(build_export()), encoding="utf-8", newline="\n")
return out
20 changes: 15 additions & 5 deletions src/node_verdict/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,20 @@ def simulate_peer_aware(
return _finish(result, scenario, params, changed, at_ckpt=True)


def owner_by_job(conditions) -> dict[str, str]:
"""Who the verdicts say owns each job's slowdown. A timing claim against a node wins over a stage verdict.

SDCSuspect is not a timing claim, so it does not name an owner for the slowdown.
"""
out: dict[str, str] = {}
for c in conditions:
if c.reason in (ReasonCode.NODE_LEMON, ReasonCode.NODE_SUSPECT):
out[c.job] = "node"
elif c.reason == ReasonCode.WORKLOAD_IMBALANCE:
out.setdefault(c.job, "job")
return out


def simulate_attributed(
scenario: Scenario,
params: SimParams = SimParams(),
Expand All @@ -169,11 +183,7 @@ def simulate_attributed(
conditions = run_engine(scenario, cfg)
sizes = {j.id: len(j.nodes) for j in scenario.jobs}
actions = plan(conditions, len(scenario.pool), scenario.spares, sizes, policy_cfg)
for c in conditions:
if c.reason in (ReasonCode.NODE_LEMON, ReasonCode.NODE_SUSPECT):
result.owner_by_job[c.job] = "node" # a timing claim against a node
elif c.reason == ReasonCode.WORKLOAD_IMBALANCE:
result.owner_by_job.setdefault(c.job, "job")
result.owner_by_job = owner_by_job(conditions)
changed: dict[str, list[str]] = {}
for a in actions:
if a.kind in NODE_CHANGING and a.status == "planned":
Expand Down
23 changes: 23 additions & 0 deletions tests/test_export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import json

from node_verdict.export import DEFAULT_OUT, build_export, dumps


def test_web_data_matches_a_fresh_export():
# The web demo renders this file and decides nothing. If this fails, run
# `python scripts/export_json.py` and commit the result.
assert DEFAULT_OUT.exists(), "run python scripts/export_json.py"
committed = DEFAULT_OUT.read_text(encoding="utf-8").replace("\r\n", "\n")
assert committed == dumps(build_export())


def test_export_has_what_the_demo_needs():
data = json.loads(DEFAULT_OUT.read_text(encoding="utf-8"))
assert len(data["pool"]) == 32
assert [j["id"] for j in data["jobs"]] == ["job-a", "job-b", "job-c"]
assert [p["name"] for p in data["policies"]] == ["naive", "naive+checkpoint", "peer-aware", "attributed"]
reasons = {v["node"]: v["condition"]["reason"] for v in data["verdicts"]["withHistory"]}
assert reasons["N00"] == "NodeLemon" and reasons["N27"] == "SDCSuspect"
assert "N27" not in {v["node"] for v in data["verdicts"]["noHistory"]}
assert data["robustness"]["healthyNodesEverChanged"] == 0
assert {r["code"] for r in data["reasonCodes"]} == {"NodeLemon", "NodeSuspect", "SDCSuspect", "WorkloadImbalance"}
Loading
Loading