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
11 changes: 0 additions & 11 deletions .claude/launch.json

This file was deleted.

3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Optional. Enables the LLM rewrite in the explanation layer; without it the
# deterministic briefing is used and the fallback reason is recorded.
OPENAI_API_KEY=
16 changes: 16 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,19 @@ reports/

# Downloaded public datasets (fetched by the adapter on demand)
data/raw/external/

# Secrets and local environment
.env
.env.*
!.env.example

# Coverage / mutation testing
.coverage
coverage.xml
htmlcov/
mutants/

# IDE tooling
.vscode/
.idea/
.DS_Store
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ Reproduced by the committed test suite and evaluation scripts.
| **Data quality** | **8 errors** detected across 10 raw tables; cleaning imputes 3 fields, drops 2 exact duplicates, quarantines 1 impossible line; **zero errors** after |
| **Plan vs actual** | Attainment spans **87.4% to 125.6%** across 64 region/category/channel segments, evenly split 32 above plan and 32 below. KAM quota attainment runs **89.8% to 106.0%** across four managers, three ahead and one behind |
| **Reproducibility** | Identical results on **numpy 1.26 under Windows and numpy 2.5 under Linux** — same signal, same impact to the cent, same forecast improvement. The container resolves the top of the declared dependency range rather than a lockfile, which is how the numpy 2.x break was found |
| **Tests** | **308 automated tests**, passing on both dependency sets. One asserts that no output ever claims causation |
| **Tests** | **316 automated tests**, passing on both dependency sets. One asserts that no output ever claims causation |
| **Mutation testing** | `scripts/mutation_test.py` applies 37 operator and constant mutations to the KPI layer; the suite kills **34 (91.9%)**. The 3 survivors are equivalent mutants (`> 0` vs `>= 0` on a count that is never zero, or on a ratio where 0/0 is already NaN) |

**On that false-alarm figure.** The 12 counts every signal that matched nothing
planted, wherever it was raised: 9 on the two control windows and 3 alongside
Expand Down Expand Up @@ -140,6 +141,7 @@ python scripts/evaluate_forecasts.py # forecast accuracy, five models
python scripts/build_excel_reports.py # six operational workbooks
python scripts/run_sql_query.py # the seven analytical SQL queries
pytest # the full suite
python scripts/mutation_test.py # mutation score for the KPI layer
```

</details>
Expand Down
112 changes: 112 additions & 0 deletions scripts/mutation_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""Lightweight mutation testing for core logic.

mutmut does not run natively on Windows, so this does the same job on a small
scale: it applies one AST-level mutation at a time to a target module (swap a
comparison, flip an arithmetic operator, nudge an integer constant), runs the
module's test file, and counts how many mutants the tests kill.

python scripts/mutation_test.py
python scripts/mutation_test.py --target src/rootsignal/metrics/kpis.py \
--tests tests/test_kpis.py tests/test_kpis_edges.py

The target file is always restored, including on Ctrl+C.
"""

from __future__ import annotations

import argparse
import ast
import subprocess
import sys
from pathlib import Path

from rootsignal.console import use_utf8_output

ROOT = Path(__file__).resolve().parents[1]

SWAPS: dict[type, type] = {
ast.Lt: ast.LtE,
ast.LtE: ast.Lt,
ast.Gt: ast.GtE,
ast.GtE: ast.Gt,
ast.Eq: ast.NotEq,
ast.NotEq: ast.Eq,
ast.Add: ast.Sub,
ast.Sub: ast.Add,
ast.Mult: ast.Div,
ast.Div: ast.Mult,
ast.Mod: ast.FloorDiv,
}


def _sites(tree: ast.AST) -> list[tuple[int, str]]:
"""Every mutable node, identified by its walk position and a label."""
sites = []
for index, node in enumerate(ast.walk(tree)):
if isinstance(node, ast.Compare) and type(node.ops[0]) in SWAPS:
sites.append((index, f"line {node.lineno}: {type(node.ops[0]).__name__}"))
elif isinstance(node, ast.BinOp) and type(node.op) in SWAPS:
sites.append((index, f"line {node.lineno}: {type(node.op).__name__}"))
elif (
isinstance(node, ast.Constant)
and type(node.value) is int
and hasattr(node, "lineno")
):
sites.append((index, f"line {node.lineno}: int {node.value}"))
return sites


def _mutate(source: str, target_index: int) -> str:
tree = ast.parse(source)
for index, node in enumerate(ast.walk(tree)):
if index != target_index:
continue
if isinstance(node, ast.Compare):
node.ops[0] = SWAPS[type(node.ops[0])]()
elif isinstance(node, ast.BinOp):
node.op = SWAPS[type(node.op)]()
elif isinstance(node, ast.Constant):
node.value = node.value + 1
break
return ast.unparse(tree)


def main() -> int:
use_utf8_output()
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--target", default="src/rootsignal/metrics/kpis.py")
parser.add_argument("--tests", nargs="+", default=["tests/test_kpis.py", "tests/test_kpis_edges.py"])
args = parser.parse_args()

target = ROOT / args.target
if not target.is_file():
print(f"Target not found: {target}", file=sys.stderr)
return 2
original = target.read_text(encoding="utf-8")
sites = _sites(ast.parse(original))
killed, survivors = 0, []
try:
for index, label in sites:
target.write_text(_mutate(original, index), encoding="utf-8")
result = subprocess.run(
[sys.executable, "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider", *args.tests],
cwd=ROOT,
capture_output=True,
)
if result.returncode != 0:
killed += 1
else:
survivors.append(label)
finally:
target.write_text(original, encoding="utf-8")

total = len(sites)
score = 100.0 * killed / total if total else 0.0
print(f"{args.target}: {killed}/{total} mutants killed ({score:.1f}%)")
for label in survivors:
print(f" survived: {label}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
118 changes: 118 additions & 0 deletions tests/test_kpis_edges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""Boundary and precision cases for the KPI helpers.

These pin the zero-denominator guards, the unit-denominator case, and the
rounding precision of every derived ratio.
"""

from __future__ import annotations

import numpy as np
import pandas as pd

from rootsignal.metrics import (
add_growth,
calculate_fill_rate,
calculate_order_kpis,
calculate_primary_secondary_mix,
calculate_sales_kpis,
calculate_target_variance,
)

DAY_1, DAY_2 = pd.to_datetime(["2026-01-01", "2026-01-02"]).date


def test_sales_kpis_round_money_to_two_decimals_with_single_order() -> None:
sales = pd.DataFrame(
{
"order_id": ["O1"],
"date": [DAY_1],
"units": [3],
"unit_price": [11.1111],
"discount_pct": [0.0],
"net_sales": [3.337],
}
)
row = calculate_sales_kpis(sales).iloc[0]
assert row["order_count"] == 1
assert row["net_sales"] == 3.34
assert row["gross_sales"] == 33.33
assert row["discount_value"] == 30.0 # 29.9963 before rounding # 29.9963 before rounding
assert row["aov"] == 3.34


def test_order_kpis_zero_and_unit_demand() -> None:
orders = pd.DataFrame(
{
"order_id": ["O1", "O2"],
"date": [DAY_1, DAY_2],
"ordered_units": [0, 1],
"fulfilled_units": [0, 1],
"cancelled_units": [1, 1],
}
)
result = calculate_order_kpis(orders).set_index("date")
assert pd.isna(result.loc[DAY_1, "fill_rate"])
assert pd.isna(result.loc[DAY_1, "cancellation_rate"])
assert result.loc[DAY_2, "fill_rate"] == 1.0
assert result.loc[DAY_2, "cancellation_rate"] == 1.0


def test_fill_rate_unit_denominator_and_four_decimal_precision() -> None:
result = calculate_fill_rate(pd.Series([1, 1]), pd.Series([1, 3]))
assert result.iloc[0] == 1.0
assert result.iloc[1] == 0.3333


def test_mix_fills_missing_sales_type_with_zero_and_rounds() -> None:
sales = pd.DataFrame(
{
"date": [DAY_1, DAY_2, DAY_2],
"sales_type": ["PRIMARY", "PRIMARY", "SECONDARY"],
"net_sales": [1.0, 1.0, 2.0],
}
)
result = calculate_primary_secondary_mix(sales).set_index("date")
assert result.loc[DAY_1, "secondary_sales"] == 0
assert result.loc[DAY_1, "total_sales"] == 1.0
assert result.loc[DAY_1, "primary_mix"] == 1.0
assert result.loc[DAY_1, "secondary_mix"] == 0.0
assert result.loc[DAY_2, "primary_mix"] == 0.3333
assert result.loc[DAY_2, "secondary_mix"] == 0.6667


def test_mix_with_no_sales_is_undefined() -> None:
sales = pd.DataFrame(
{"date": [DAY_1], "sales_type": ["PRIMARY"], "net_sales": [0.0]}
)
row = calculate_primary_secondary_mix(sales).iloc[0]
assert pd.isna(row["primary_mix"])
assert pd.isna(row["secondary_mix"])


def test_growth_without_groups_handles_zero_and_unit_previous() -> None:
frame = pd.DataFrame(
{
"date": pd.to_datetime(["2026-01-01", "2026-01-02", "2026-01-03", "2026-01-04"]),
"net_sales": [0.0, 1.0, 4.0, 5.0],
}
)
result = add_growth(frame, "net_sales")
assert pd.isna(result.loc[0, "growth_pct"])
assert pd.isna(result.loc[1, "growth_pct"])
assert result.loc[2, "growth_pct"] == 3.0
assert result.loc[3, "growth_pct"] == 0.25
assert result["previous_value"].tolist()[1:] == [0.0, 1.0, 4.0]


def test_growth_rounds_to_four_decimals() -> None:
frame = pd.DataFrame({"date": [DAY_1, DAY_2], "net_sales": [3.0, 4.0]})
assert add_growth(frame, "net_sales").loc[1, "growth_pct"] == 0.3333


def test_target_variance_zero_and_unit_targets() -> None:
dims = ["date"]
actuals = pd.DataFrame({"date": [DAY_1, DAY_2], "net_sales": [5.0, 3.0]})
targets = pd.DataFrame({"date": [DAY_1, DAY_2], "sales_target": [0.0, 1.0]})
result = calculate_target_variance(actuals, targets, dims).set_index("date")
assert pd.isna(result.loc[DAY_1, "variance_pct"])
assert np.isclose(result.loc[DAY_2, "variance_pct"], 2.0)