Buckets:

download
raw
20 kB
# Copyright (c) 2025-2026 Yutaro Maeda. All rights reserved.
# Licensed under the Apache License 2.0. See LICENSE file for details.
"""CLI commands for P2 engines: predict, markov, bayesian, gameday."""
from __future__ import annotations
import json as json_lib
from pathlib import Path
import typer
from faultray.cli.main import (
app,
console,
)
@app.command()
def predict(
yaml_file: Path = typer.Argument(..., help="Infrastructure YAML file"),
horizon: int = typer.Option(90, "--horizon", help="Prediction horizon in days"),
json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
) -> None:
"""Predict future failures from degradation trends and MTBF data.
Examples:
# Default 90-day prediction
faultray predict infra.yaml
# Predict over 180 days
faultray predict infra.yaml --horizon 180
# JSON output
faultray predict infra.yaml --json
"""
from faultray.model.loader import load_yaml
from faultray.simulator.predictive_engine import PredictiveEngine
if not yaml_file.exists():
console.print(f"[red]File not found: {yaml_file}[/]")
raise typer.Exit(1)
try:
graph = load_yaml(yaml_file)
except (FileNotFoundError, ValueError) as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
engine = PredictiveEngine(graph)
report = engine.predict(horizon_days=horizon)
if json_output:
import dataclasses
data = dataclasses.asdict(report)
console.print_json(json_lib.dumps(data, indent=2, default=str))
return
# Rich output
from rich.panel import Panel
from rich.table import Table
console.print()
console.print(Panel(
report.summary,
title=f"[bold]Predictive Analysis (horizon={horizon}d)[/]",
border_style="cyan",
))
if report.exhaustion_predictions:
table = Table(title="Resource Exhaustion Predictions", show_header=True)
table.add_column("Component", style="cyan", width=16)
table.add_column("Resource", width=12)
table.add_column("Current %", justify="right", width=10)
table.add_column("Rate/hr", justify="right", width=10)
table.add_column("Days Left", justify="right", width=10)
table.add_column("Action", width=40)
for p in report.exhaustion_predictions:
days_color = "red" if p.days_to_exhaustion <= 7 else (
"yellow" if p.days_to_exhaustion <= 30 else "green"
)
table.add_row(
p.component_id,
p.resource,
f"{p.current_usage_percent:.1f}%",
f"{p.growth_rate_per_hour:.4f}%",
f"[{days_color}]{p.days_to_exhaustion:.1f}[/]",
p.recommended_action[:40],
)
console.print(table)
if report.failure_forecasts:
table = Table(title="Failure Probability Forecast", show_header=True)
table.add_column("Component", style="cyan", width=16)
table.add_column("MTBF (h)", justify="right", width=10)
table.add_column("P(7d)", justify="right", width=10)
table.add_column("P(30d)", justify="right", width=10)
table.add_column("P(90d)", justify="right", width=10)
for f in report.failure_forecasts:
table.add_row(
f.component_id,
f"{f.mtbf_hours:.0f}",
f"{f.probability_7d:.4f}",
f"{f.probability_30d:.4f}",
f"{f.probability_90d:.4f}",
)
console.print()
console.print(table)
console.print(f"\n[dim]{report.recommended_maintenance_window}[/]")
@app.command()
def markov(
yaml_file: Path = typer.Argument(..., help="Infrastructure YAML file"),
json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
) -> None:
"""Compute Markov chain steady-state availability for each component.
Examples:
# Run Markov analysis
faultray markov infra.yaml
# JSON output
faultray markov infra.yaml --json
"""
from faultray.model.loader import load_yaml
from faultray.simulator.markov_model import compute_system_markov
if not yaml_file.exists():
console.print(f"[red]File not found: {yaml_file}[/]")
raise typer.Exit(1)
try:
graph = load_yaml(yaml_file)
except (FileNotFoundError, ValueError) as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
results = compute_system_markov(graph)
if json_output:
import dataclasses
data = {
comp_id: dataclasses.asdict(result)
for comp_id, result in results.items()
}
console.print_json(json_lib.dumps(data, indent=2, default=str))
return
from rich.table import Table
table = Table(title="Markov Chain Availability Analysis", show_header=True)
table.add_column("Component", style="cyan", width=16)
table.add_column("P(HEALTHY)", justify="right", width=12)
table.add_column("P(DEGRADED)", justify="right", width=12)
table.add_column("P(DOWN)", justify="right", width=12)
table.add_column("Availability", justify="right", width=12)
table.add_column("Nines", justify="right", width=8)
for comp_id, result in results.items():
avail_color = "green" if result.nines >= 3 else (
"yellow" if result.nines >= 2 else "red"
)
table.add_row(
comp_id,
f"{result.steady_state.get('HEALTHY', 0):.6f}",
f"{result.steady_state.get('DEGRADED', 0):.6f}",
f"{result.steady_state.get('DOWN', 0):.6f}",
f"[{avail_color}]{result.availability:.6f}[/]",
f"[{avail_color}]{result.nines:.2f}[/]",
)
console.print()
console.print(table)
@app.command()
def bayesian(
yaml_file: Path = typer.Argument(..., help="Infrastructure YAML file"),
json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
) -> None:
"""Compute Bayesian conditional failure probabilities.
Examples:
# Run Bayesian analysis
faultray bayesian infra.yaml
# JSON output
faultray bayesian infra.yaml --json
"""
from faultray.model.loader import load_yaml
from faultray.simulator.bayesian_model import BayesianEngine
if not yaml_file.exists():
console.print(f"[red]File not found: {yaml_file}[/]")
raise typer.Exit(1)
try:
graph = load_yaml(yaml_file)
except (FileNotFoundError, ValueError) as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
engine = BayesianEngine(graph)
results = engine.analyze()
if json_output:
import dataclasses
data = [dataclasses.asdict(r) for r in results]
console.print_json(json_lib.dumps(data, indent=2, default=str))
return
from rich.table import Table
table = Table(title="Bayesian Failure Probability Analysis", show_header=True)
table.add_column("Component", style="cyan", width=16)
table.add_column("P(fail) prior", justify="right", width=14)
table.add_column("P(fail|deps)", justify="right", width=14)
table.add_column("Critical Dep", width=16)
table.add_column("Impact", width=30)
for r in results:
impact_str = ", ".join(
f"{k}={v:.4f}" for k, v in list(r.conditional_impacts.items())[:3]
) if r.conditional_impacts else "-"
# Use scientific notation for very small probabilities
def _fmt_prob(p: float) -> str:
if p == 0:
return "0"
if p < 0.0001:
return f"{p:.2e}"
return f"{p:.6f}"
table.add_row(
r.component_id,
_fmt_prob(r.prior_failure_prob),
_fmt_prob(r.posterior_given_deps),
r.most_critical_dependency or "-",
impact_str,
)
console.print()
console.print(table)
@app.command()
def gameday(
yaml_file: Path = typer.Argument(..., help="Infrastructure YAML file"),
plan: Path = typer.Option(
None, "--plan", "-p",
help="Game Day plan YAML file. Omit to auto-generate scenarios.",
),
scenarios: int = typer.Option(
5, "--scenarios", "-n",
help="Number of scenarios to generate (auto-generate mode).",
),
difficulty: str = typer.Option(
"medium", "--difficulty", "-d",
help="Scenario difficulty: easy, medium, or hard.",
),
output: Path = typer.Option(
None, "--output", "-o",
help="Write HTML GameDay plan to this file.",
),
json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
) -> None:
"""Execute a Game Day exercise or auto-generate GameDay scenarios.
Without --plan: generates ranked failure scenarios from the topology.
With --plan: executes a structured Game Day exercise.
Examples:
# Auto-generate top 5 scenarios
faultray gameday infra.yaml
# Generate 10 hard scenarios
faultray gameday infra.yaml --scenarios 10 --difficulty hard
# Export HTML GameDay plan
faultray gameday infra.yaml --output gameday-plan.html
# JSON output
faultray gameday infra.yaml --json
# Run a pre-written exercise plan
faultray gameday infra.yaml --plan gameday-plan.yaml
"""
from faultray.model.loader import load_yaml
if not yaml_file.exists():
console.print(f"[red]Infrastructure file not found: {yaml_file}[/]")
raise typer.Exit(1)
try:
graph = load_yaml(yaml_file)
except (FileNotFoundError, ValueError) as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1)
# -----------------------------------------------------------------------
# Mode A: execute a pre-written plan (--plan provided)
# -----------------------------------------------------------------------
if plan is not None:
import yaml
from faultray.simulator.gameday_engine import (
GameDayEngine,
GameDayPlan,
GameDayStep,
)
from faultray.simulator.scenarios import Fault, FaultType
if not plan.exists():
console.print(f"[red]Game Day plan not found: {plan}[/]")
raise typer.Exit(1)
raw = yaml.safe_load(plan.read_text(encoding="utf-8")) or {}
if not isinstance(raw, dict):
console.print("[red]Game Day plan must be a YAML mapping.[/]")
raise typer.Exit(1)
raw_steps = raw.get("steps", [])
if not isinstance(raw_steps, list):
console.print("[red]Game Day plan 'steps' must be a list.[/]")
raise typer.Exit(1)
steps: list[GameDayStep] = []
try:
for raw_step in raw_steps:
if not isinstance(raw_step, dict):
raise ValueError("each step must be a mapping")
fault = None
if raw_step.get("fault"):
fault_data = raw_step["fault"]
if not isinstance(fault_data, dict):
raise ValueError("step 'fault' must be a mapping")
fault = Fault(
target_component_id=fault_data["target_component_id"],
fault_type=FaultType(fault_data["fault_type"]),
severity=fault_data.get("severity", 1.0),
duration_seconds=fault_data.get("duration_seconds", 300),
)
steps.append(GameDayStep(
time_offset_seconds=raw_step.get("time_offset_seconds", 0),
action=raw_step.get("action", "manual_check"),
fault=fault,
expected_outcome=raw_step.get("expected_outcome", ""),
runbook_step=raw_step.get("runbook_step", ""),
))
except (KeyError, ValueError) as exc:
console.print(f"[red]Invalid Game Day plan: {exc}[/]")
raise typer.Exit(1)
gameday_plan = GameDayPlan(
name=raw.get("name", "Unnamed Game Day"),
description=raw.get("description", ""),
steps=steps,
success_criteria=raw.get("success_criteria", []),
rollback_plan=raw.get("rollback_plan", ""),
)
engine = GameDayEngine(graph)
report = engine.execute(gameday_plan)
if json_output:
import dataclasses
data = dataclasses.asdict(report)
console.print_json(json_lib.dumps(data, indent=2, default=str))
return
from rich.panel import Panel
from rich.table import Table
overall_color = "green" if report.overall == "PASS" else "red"
console.print()
console.print(Panel(
f"[bold]Plan:[/] {report.plan_name}\n"
f"[bold]Steps:[/] {len(report.steps)} total, "
f"[green]{report.passed} passed[/], "
f"[red]{report.failed} failed[/]\n"
f"[bold]Overall:[/] [{overall_color}]{report.overall}[/]",
title="[bold]Game Day Report[/]",
border_style=overall_color,
))
table = Table(title="Step Results", show_header=True)
table.add_column("Step", width=6, justify="right")
table.add_column("Time", width=8, justify="right")
table.add_column("Action", width=16)
table.add_column("Outcome", width=8, justify="center")
table.add_column("Details", width=50)
for r in report.steps:
outcome_color = (
"green" if r.outcome == "PASS" else
"red" if r.outcome == "FAIL" else "yellow"
)
table.add_row(
str(r.step_index),
f"T+{r.time_seconds}s",
r.action,
f"[{outcome_color}]{r.outcome}[/]",
r.details[:50],
)
console.print(table)
if report.timeline_summary:
console.print(f"\n[dim]{report.timeline_summary}[/]")
return
# -----------------------------------------------------------------------
# Mode B: auto-generate scenarios from topology
# -----------------------------------------------------------------------
from faultray.simulator.gameday import GameDayGenerator
gen = GameDayGenerator(graph)
generated = gen.generate_scenarios(count=scenarios, difficulty=difficulty)
if not generated:
console.print("[yellow]No scenarios could be generated for this infrastructure.[/]")
raise typer.Exit(0)
# --- JSON output ---
if json_output:
import dataclasses
data = [dataclasses.asdict(s) for s in generated]
console.print_json(json_lib.dumps(data, indent=2, default=str))
return
# --- HTML output ---
if output is not None:
_write_gameday_html(generated, output, yaml_file.stem, difficulty)
console.print(f"[green]GameDay HTML plan written to:[/] {output}")
return
# --- Rich terminal output ---
_print_gameday_scenarios(generated, difficulty)
# ---------------------------------------------------------------------------
# GameDay generator helpers
# ---------------------------------------------------------------------------
def _write_gameday_html(
scenarios: list,
output_path: "Path",
infra_name: str,
difficulty: str,
) -> None:
"""Render the gameday HTML template and write to output_path."""
from datetime import datetime, timezone
from pathlib import Path as _Path
from jinja2 import Environment, FileSystemLoader
_TEMPLATE_DIR = _Path(__file__).resolve().parent.parent / "reporter" / "templates"
env = Environment(loader=FileSystemLoader(str(_TEMPLATE_DIR)), autoescape=True)
tmpl = env.get_template("gameday_report.html")
avg_impact = (
sum(s.estimated_impact_score for s in scenarios) / len(scenarios)
if scenarios else 0.0
)
avg_mttr = (
sum(s.estimated_mttr_minutes for s in scenarios) / len(scenarios)
if scenarios else 0.0
)
# Collect unique component IDs across all scenarios
all_comp_ids: set[str] = set()
for s in scenarios:
all_comp_ids.update(s.trigger_components)
all_comp_ids.update(s.affected_components)
total_components = len(all_comp_ids)
html = tmpl.render(
scenarios=scenarios,
generated_date=datetime.now(timezone.utc).strftime("%Y-%m-%d"),
infra_name=infra_name,
difficulty=difficulty,
total_components=total_components,
avg_impact=f"{avg_impact:.0f}/100",
avg_mttr=f"{avg_mttr:.0f}",
)
output_path.write_text(html, encoding="utf-8")
def _print_gameday_scenarios(scenarios: list, difficulty: str) -> None:
"""Print GameDay scenarios to the terminal using Rich."""
from rich.panel import Panel
diff_color = {"easy": "green", "medium": "yellow", "hard": "red"}.get(
difficulty.lower(), "cyan"
)
console.print()
console.print(Panel(
f"[bold]GameDay Scenario Generator[/]\n\n"
f"Difficulty: [{diff_color}]{difficulty.upper()}[/{diff_color}] | "
f"Scenarios: [bold]{len(scenarios)}[/]\n\n"
"[dim]Scenarios ranked by estimated impact. "
"Use --output to export an HTML plan.[/dim]",
title="[bold cyan]GameDay Plan[/]",
border_style="cyan",
))
for sc in scenarios:
impact = sc.estimated_impact_score
if impact >= 70:
impact_color = "red"
elif impact >= 40:
impact_color = "yellow"
else:
impact_color = "green"
diff_badge = {
"easy": "[green]EASY[/]",
"medium": "[yellow]MEDIUM[/]",
"hard": "[red]HARD[/]",
}.get(sc.difficulty, sc.difficulty.upper())
header = (
f"[bold cyan]{sc.scenario_id}[/] — [bold]{sc.title}[/] "
f"{diff_badge} [{impact_color}]Impact: {impact:.0f}/100[/{impact_color}]"
)
body_lines = [
f"[dim]{sc.description}[/dim]",
f"\n[dim]Category:[/dim] {sc.category} "
f"[dim]Mode:[/dim] {sc.failure_mode} "
f"[dim]Cascade depth:[/dim] {sc.cascade_depth} "
f"[dim]MTTR:[/dim] ~{sc.estimated_mttr_minutes:.0f}m "
f"[dim]Users affected:[/dim] {sc.affected_users_pct:.0f}%",
]
if sc.trigger_components:
body_lines.append(
f"[dim]Trigger:[/dim] {', '.join(sc.trigger_components)}"
)
if sc.affected_components:
shown = sc.affected_components[:5]
extra = len(sc.affected_components) - len(shown)
aff_str = ", ".join(shown)
if extra > 0:
aff_str += f" (+{extra} more)"
body_lines.append(f"[dim]Affected:[/dim] {aff_str}")
body_lines.append(f"\n[bold]SLO Impact:[/bold] {sc.slo_impact}")
# Execution steps preview
if sc.execution_steps:
steps_preview = "\n".join(
f" {i+1}. {s}" for i, s in enumerate(sc.execution_steps[:4])
)
if len(sc.execution_steps) > 4:
steps_preview += f"\n ... ({len(sc.execution_steps) - 4} more steps)"
body_lines.append(f"\n[bold]Execution Steps:[/bold]\n{steps_preview}")
if sc.success_criteria:
crit = "\n".join(f" [green]+ {c}[/]" for c in sc.success_criteria[:3])
body_lines.append(f"\n[bold]Go Criteria:[/bold]\n{crit}")
body_lines.append(f"\n[dim]Rollback:[/dim] {sc.rollback_plan[:120]}...")
console.print(Panel(
header + "\n\n" + "\n".join(body_lines),
border_style=impact_color,
))
console.print()

Xet Storage Details

Size:
20 kB
·
Xet hash:
e04c7d1d974374a1109bd2355e7110fd22c3c7a494ab6efa93cac296bdfde48e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.