ablift 0.5.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ablift/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .engine import analyze, parse_payload
4
+ from .reporting import build_markdown_report
5
+
6
+ try:
7
+ __version__ = version("ablift")
8
+ except PackageNotFoundError: # pragma: no cover - running from an uninstalled checkout
9
+ __version__ = "0.0.0"
10
+
11
+ __all__ = ["analyze", "parse_payload", "build_markdown_report", "__version__"]
ablift/cli.py ADDED
@@ -0,0 +1,536 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.metadata
4
+ import json
5
+ import sys
6
+ import tomllib
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import click
11
+
12
+ from .connectors import build_duration_request_from_rows, build_payload_from_rows, read_table
13
+ from .engine import analyze as run_analysis
14
+ from .engine import parse_payload
15
+ from .models import SCHEMA_VERSION
16
+ from .planning import (
17
+ bayesian_duration_conversion,
18
+ fixed_horizon_duration_conversion,
19
+ sequential_duration_conversion,
20
+ )
21
+ from .reporting import build_markdown_report
22
+
23
+ ANALYZE_EPILOG = """\b
24
+ Examples:
25
+ ablift analyze --input experiment.json
26
+ ablift analyze --input experiment.csv
27
+ ablift analyze --input experiment.xlsx --sheet Results
28
+ ablift analyze --input experiment.csv --enable-recommendation --prob-threshold 0.9 --max-expected-loss 0.005
29
+ ablift analyze --input experiment.json --report report.md
30
+ """
31
+
32
+
33
+ def _write_text(path: str, content: str) -> None:
34
+ out = Path(path)
35
+ out.parent.mkdir(parents=True, exist_ok=True)
36
+ out.write_text(content, encoding="utf-8")
37
+
38
+
39
+ def _emit_analysis(result, output_path: str | None, report_path: str | None) -> None:
40
+ result_json = json.dumps(result.to_dict(), indent=2)
41
+ if output_path:
42
+ _write_text(output_path, result_json + "\n")
43
+ else:
44
+ click.echo(result_json)
45
+ if report_path:
46
+ _write_text(report_path, build_markdown_report(result))
47
+
48
+
49
+ def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
50
+ merged = dict(base)
51
+ for key, value in override.items():
52
+ if isinstance(value, dict) and isinstance(merged.get(key), dict):
53
+ merged[key] = _deep_merge(merged[key], value)
54
+ elif value is not None:
55
+ merged[key] = value
56
+ return merged
57
+
58
+
59
+ def _load_project_config() -> dict[str, Any]:
60
+ pyproject_path = Path.cwd() / "pyproject.toml"
61
+ if not pyproject_path.exists():
62
+ return {}
63
+ data = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))
64
+ return data.get("tool", {}).get("ablift", {})
65
+
66
+
67
+ def _load_analysis_payload(
68
+ *,
69
+ input_path: str,
70
+ sheet: str | None,
71
+ defaults: dict[str, Any],
72
+ ) -> dict[str, Any]:
73
+ config_payload = _load_project_config()
74
+ suffix = Path(input_path).suffix.lower()
75
+ if suffix == ".json":
76
+ input_payload = json.loads(Path(input_path).read_text(encoding="utf-8"))
77
+ if not isinstance(input_payload, dict):
78
+ raise ValueError("JSON input must be an object with a 'variants' list.")
79
+ payload = _deep_merge(config_payload, _deep_merge(input_payload, defaults))
80
+ payload.setdefault("input_interpretation", {"source_type": "json"})
81
+ return payload
82
+
83
+ if suffix not in {".csv", ".xlsx", ".xlsm"}:
84
+ raise click.ClickException("Unsupported analysis input. Use .json, .csv, .xlsx, or .xlsm.")
85
+
86
+ rows = read_table(input_path, sheet=sheet)
87
+ table_defaults = _deep_merge(config_payload, defaults)
88
+ return build_payload_from_rows(rows, defaults=table_defaults)
89
+
90
+
91
+ def example_payload() -> dict:
92
+ return {
93
+ "experiment_name": "checkout_button_color",
94
+ "method": "bayesian",
95
+ "primary_metric": "conversion_rate",
96
+ "alpha": 0.05,
97
+ "variants": [
98
+ {
99
+ "name": "control",
100
+ "visitors": 100000,
101
+ "conversions": 4000,
102
+ "is_control": True,
103
+ },
104
+ {
105
+ "name": "treatment_a",
106
+ "visitors": 100000,
107
+ "conversions": 4200,
108
+ "is_control": False,
109
+ },
110
+ ],
111
+ "guardrails": [
112
+ {
113
+ "name": "bounce_rate",
114
+ "control": 0.36,
115
+ "treatment": 0.365,
116
+ "direction": "decrease",
117
+ "max_relative_change": 0.03,
118
+ },
119
+ {
120
+ "name": "p95_latency_ms",
121
+ "control": 420.0,
122
+ "treatment": 430.0,
123
+ "direction": "decrease",
124
+ "max_relative_change": 0.05,
125
+ },
126
+ ],
127
+ "decision_policy": {
128
+ "enabled": True,
129
+ "bayes_prob_beats_control": 0.95,
130
+ "max_expected_loss": 0.001,
131
+ },
132
+ "samples": 50000,
133
+ "random_seed": 7,
134
+ }
135
+
136
+
137
+ def run_doctor() -> dict:
138
+ checks = []
139
+
140
+ py_ok = sys.version_info >= (3, 11)
141
+ checks.append(
142
+ {
143
+ "name": "python_version",
144
+ "passed": py_ok,
145
+ "detail": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
146
+ "required": ">=3.11",
147
+ }
148
+ )
149
+
150
+ for dep, required in [("numpy", ">=1.22"), ("openpyxl", ">=3.1.0")]:
151
+ try:
152
+ version = importlib.metadata.version(dep)
153
+ checks.append(
154
+ {
155
+ "name": f"dependency_{dep}",
156
+ "passed": True,
157
+ "detail": version,
158
+ "required": required,
159
+ }
160
+ )
161
+ except importlib.metadata.PackageNotFoundError:
162
+ checks.append(
163
+ {
164
+ "name": f"dependency_{dep}",
165
+ "passed": False,
166
+ "detail": "not installed",
167
+ "required": required,
168
+ }
169
+ )
170
+
171
+ all_passed = all(c["passed"] for c in checks)
172
+ return {"ok": all_passed, "checks": checks}
173
+
174
+
175
+ @click.group()
176
+ @click.version_option(package_name="ablift", prog_name="ablift")
177
+ def cli() -> None:
178
+ """Agent-friendly CLI for Bayesian and sequential (mSPRT) A/B/n experiment decisions."""
179
+
180
+
181
+ @cli.command(epilog=ANALYZE_EPILOG)
182
+ @click.option(
183
+ "--input",
184
+ "input_path",
185
+ required=True,
186
+ type=click.Path(exists=True),
187
+ help="Path to input .json, .csv, .xlsx, or .xlsm.",
188
+ )
189
+ @click.option(
190
+ "--sheet", required=False, default=None, help="Excel sheet name for .xlsx/.xlsm input."
191
+ )
192
+ @click.option(
193
+ "--experiment-name",
194
+ required=False,
195
+ default=None,
196
+ help="Optional experiment name override for CSV/XLSX input.",
197
+ )
198
+ @click.option(
199
+ "--method",
200
+ type=click.Choice(["bayesian", "sequential"]),
201
+ default=None,
202
+ help="Optional method override for CSV/XLSX input.",
203
+ )
204
+ @click.option(
205
+ "--primary-metric",
206
+ type=click.Choice(["conversion_rate", "arpu"]),
207
+ default=None,
208
+ help="Optional metric override for CSV/XLSX input.",
209
+ )
210
+ @click.option(
211
+ "--enable-recommendation/--no-recommendation",
212
+ default=None,
213
+ help="Enable or disable automated recommendation output.",
214
+ )
215
+ @click.option(
216
+ "--prob-threshold",
217
+ type=float,
218
+ default=None,
219
+ help="Bayesian probability-to-win threshold for recommendations.",
220
+ )
221
+ @click.option(
222
+ "--max-expected-loss",
223
+ type=float,
224
+ default=None,
225
+ help="Bayesian expected-loss threshold for recommendations.",
226
+ )
227
+ @click.option("--alpha", type=float, default=None, help="Optional alpha override.")
228
+ @click.option(
229
+ "--sequential-tau",
230
+ type=float,
231
+ default=None,
232
+ help="mSPRT mixing parameter (prior std on effect size). Defaults to 10% of control baseline.",
233
+ )
234
+ @click.option(
235
+ "--samples", type=int, default=None, help="Optional Bayesian posterior sample count override."
236
+ )
237
+ @click.option(
238
+ "--random-seed", type=int, default=None, help="Optional Bayesian random seed override."
239
+ )
240
+ @click.option(
241
+ "--output",
242
+ "output_path",
243
+ required=False,
244
+ type=click.Path(),
245
+ help="Path to output JSON. If omitted, writes to stdout.",
246
+ )
247
+ @click.option(
248
+ "--report",
249
+ "report_path",
250
+ required=False,
251
+ type=click.Path(),
252
+ help="Optional path to markdown report output.",
253
+ )
254
+ def analyze(
255
+ input_path: str,
256
+ sheet: str | None,
257
+ experiment_name: str | None,
258
+ method: str | None,
259
+ primary_metric: str | None,
260
+ enable_recommendation: bool | None,
261
+ prob_threshold: float | None,
262
+ max_expected_loss: float | None,
263
+ alpha: float | None,
264
+ sequential_tau: float | None,
265
+ samples: int | None,
266
+ random_seed: int | None,
267
+ output_path: str | None,
268
+ report_path: str | None,
269
+ ) -> None:
270
+ """Analyze JSON, CSV, or XLSX experiment input."""
271
+ decision_policy = None
272
+ if (
273
+ enable_recommendation is not None
274
+ or prob_threshold is not None
275
+ or max_expected_loss is not None
276
+ ):
277
+ decision_policy = {
278
+ "enabled": True if enable_recommendation is None else enable_recommendation,
279
+ "bayes_prob_beats_control": prob_threshold,
280
+ "max_expected_loss": max_expected_loss,
281
+ }
282
+
283
+ defaults = {
284
+ "experiment_name": experiment_name,
285
+ "method": method,
286
+ "primary_metric": primary_metric,
287
+ "decision_policy": decision_policy,
288
+ "alpha": alpha,
289
+ "sequential_tau": sequential_tau,
290
+ "samples": samples,
291
+ "random_seed": random_seed,
292
+ }
293
+ try:
294
+ input_payload = _load_analysis_payload(
295
+ input_path=input_path,
296
+ sheet=sheet,
297
+ defaults=defaults,
298
+ )
299
+ except (ValueError, KeyError, json.JSONDecodeError) as exc:
300
+ raise click.ClickException(f"Could not read {input_path}: {exc}") from exc
301
+ if Path(input_path).suffix.lower() in {".csv", ".xlsx", ".xlsm"} and input_payload.get(
302
+ "experiment_name"
303
+ ) in {None, "", "table_input_experiment"}:
304
+ input_payload["experiment_name"] = Path(input_path).stem
305
+ try:
306
+ _emit_analysis(run_analysis(parse_payload(input_payload)), output_path, report_path)
307
+ except ValueError as exc:
308
+ raise click.ClickException(str(exc)) from exc
309
+
310
+
311
+ DURATION_EPILOG = """\b
312
+ Examples:
313
+ ablift duration --method sequential --baseline-rate 0.04 --relative-mde 0.05 --daily-traffic 50000
314
+ ablift duration --method fixed --baseline-rate 0.04 --relative-mde 0.05 --daily-traffic 50000 --n-variants 3
315
+ ablift duration --method bayesian --baseline-rate 0.04 --relative-mde 0.08 --daily-traffic 60000
316
+ ablift duration --input assumptions.csv
317
+ """
318
+
319
+
320
+ _BAYESIAN_ONLY = ("prob_threshold", "max_expected_loss", "assurance_target", "max_days")
321
+
322
+
323
+ @cli.command(epilog=DURATION_EPILOG)
324
+ @click.option(
325
+ "--method",
326
+ type=click.Choice(["sequential", "fixed", "bayesian"]),
327
+ default=None,
328
+ help="Planning model. 'sequential' matches 'analyze --method sequential' (mSPRT). "
329
+ "[default: sequential]",
330
+ )
331
+ @click.option(
332
+ "--baseline-rate",
333
+ type=float,
334
+ default=None,
335
+ help="Baseline conversion rate, decimal (e.g. 0.04).",
336
+ )
337
+ @click.option(
338
+ "--relative-mde", type=float, default=None, help="Relative MDE, decimal (e.g. 0.05 for +5%)."
339
+ )
340
+ @click.option(
341
+ "--daily-traffic", type=int, default=None, help="Total daily traffic across all variants."
342
+ )
343
+ @click.option(
344
+ "--n-variants", type=int, default=None, help="Variants including control. [default: 2]"
345
+ )
346
+ @click.option("--alpha", type=float, default=None, help="Family-wise alpha. [default: 0.05]")
347
+ @click.option("--power", type=float, default=None, help="Target power. [default: 0.8]")
348
+ @click.option(
349
+ "--sequential-tau",
350
+ type=float,
351
+ default=None,
352
+ help="mSPRT mixing parameter. Defaults to 10% of the baseline rate.",
353
+ )
354
+ @click.option(
355
+ "--prob-threshold", type=float, default=None, help="Bayesian P(win) threshold. [default: 0.95]"
356
+ )
357
+ @click.option(
358
+ "--max-expected-loss",
359
+ type=float,
360
+ default=None,
361
+ help="Bayesian expected-loss threshold. [default: 0.001]",
362
+ )
363
+ @click.option(
364
+ "--assurance-target",
365
+ type=float,
366
+ default=None,
367
+ help="Bayesian probability of reaching a decision. [default: 0.8]",
368
+ )
369
+ @click.option(
370
+ "--max-days", type=int, default=None, help="Bayesian search horizon in days. [default: 60]"
371
+ )
372
+ @click.option("--output", "output_path", required=False, type=click.Path())
373
+ @click.option(
374
+ "--input",
375
+ "input_path",
376
+ required=False,
377
+ type=click.Path(exists=True),
378
+ help="CSV/XLSX with named columns (baseline_rate, relative_mde, daily_traffic, ...). "
379
+ "CLI flags override file values.",
380
+ )
381
+ @click.option("--sheet", required=False, default=None, help="Excel sheet name for duration input.")
382
+ def duration(
383
+ method: str | None,
384
+ baseline_rate: float | None,
385
+ relative_mde: float | None,
386
+ daily_traffic: int | None,
387
+ n_variants: int | None,
388
+ alpha: float | None,
389
+ power: float | None,
390
+ sequential_tau: float | None,
391
+ prob_threshold: float | None,
392
+ max_expected_loss: float | None,
393
+ assurance_target: float | None,
394
+ max_days: int | None,
395
+ output_path: str | None,
396
+ input_path: str | None,
397
+ sheet: str | None,
398
+ ) -> None:
399
+ """Estimate how long a conversion-rate test needs to run."""
400
+ flags = {
401
+ "method": method,
402
+ "baseline_rate": baseline_rate,
403
+ "relative_mde": relative_mde,
404
+ "daily_traffic": daily_traffic,
405
+ "n_variants": n_variants,
406
+ "alpha": alpha,
407
+ "power": power,
408
+ "sequential_tau": sequential_tau,
409
+ "prob_threshold": prob_threshold,
410
+ "max_expected_loss": max_expected_loss,
411
+ "assurance_target": assurance_target,
412
+ "max_days": max_days,
413
+ }
414
+ req: dict[str, Any] = {
415
+ "method": "sequential",
416
+ "n_variants": 2,
417
+ "alpha": 0.05,
418
+ "power": 0.8,
419
+ "prob_threshold": 0.95,
420
+ "max_expected_loss": 0.001,
421
+ "assurance_target": 0.8,
422
+ "max_days": 60,
423
+ }
424
+ try:
425
+ file_keys: set[str] = set()
426
+ if input_path:
427
+ file_req = build_duration_request_from_rows(read_table(input_path, sheet=sheet))
428
+ # When --method overrides the file's method, the file's other settings were written
429
+ # for a different planner, so they are not counted as explicitly requested.
430
+ overridden = method is not None and file_req.get("method", method) != method
431
+ file_keys = set() if overridden else set(file_req)
432
+ req.update(file_req)
433
+ req.update({k: v for k, v in flags.items() if v is not None})
434
+
435
+ missing = [
436
+ f"--{k.replace('_', '-')}"
437
+ for k in ("baseline_rate", "relative_mde", "daily_traffic")
438
+ if req.get(k) is None
439
+ ]
440
+ if missing:
441
+ raise click.UsageError(f"Missing required assumptions: {', '.join(missing)}.")
442
+
443
+ # Reject settings the chosen planner would silently ignore.
444
+ explicit = {k for k, v in flags.items() if v is not None} | file_keys
445
+ not_applicable = {
446
+ "bayesian": ("alpha", "power", "sequential_tau"),
447
+ "fixed": ("sequential_tau", *_BAYESIAN_ONLY),
448
+ "sequential": _BAYESIAN_ONLY,
449
+ }.get(req["method"], ())
450
+ ignored = [f"--{k.replace('_', '-')}" for k in not_applicable if k in explicit]
451
+ if ignored:
452
+ raise click.UsageError(
453
+ f"Not used by --method {req['method']}: {', '.join(ignored)} "
454
+ "(set as a flag or input-file column). Remove them or choose a method that "
455
+ "uses them."
456
+ )
457
+
458
+ common = {
459
+ "baseline_rate": req["baseline_rate"],
460
+ "relative_mde": req["relative_mde"],
461
+ "daily_total_traffic": req["daily_traffic"],
462
+ "n_variants": req["n_variants"],
463
+ }
464
+ if req["method"] == "sequential":
465
+ plan = sequential_duration_conversion(
466
+ **common,
467
+ alpha=req["alpha"],
468
+ power=req["power"],
469
+ sequential_tau=req.get("sequential_tau"),
470
+ )
471
+ elif req["method"] == "fixed":
472
+ plan = fixed_horizon_duration_conversion(
473
+ **common, alpha=req["alpha"], power=req["power"]
474
+ )
475
+ elif req["method"] == "bayesian":
476
+ plan = bayesian_duration_conversion(
477
+ **common,
478
+ prob_threshold=req["prob_threshold"],
479
+ max_expected_loss=req["max_expected_loss"],
480
+ assurance_target=req["assurance_target"],
481
+ max_days=req["max_days"],
482
+ )
483
+ else:
484
+ raise click.UsageError(
485
+ f"Unknown method '{req['method']}'. Use sequential, fixed, or bayesian."
486
+ )
487
+ except ValueError as exc:
488
+ raise click.ClickException(str(exc)) from exc
489
+
490
+ plan_json = json.dumps(
491
+ {
492
+ "schema_version": SCHEMA_VERSION,
493
+ "method": plan.method,
494
+ "estimated_days": plan.estimated_days,
495
+ "n_per_variant": plan.n_per_variant,
496
+ "assumptions": plan.assumptions,
497
+ "diagnostics": plan.diagnostics,
498
+ },
499
+ indent=2,
500
+ )
501
+ if output_path:
502
+ _write_text(output_path, plan_json + "\n")
503
+ else:
504
+ click.echo(plan_json)
505
+
506
+
507
+ @cli.command()
508
+ @click.option("--strict", is_flag=True, help="Exit non-zero if any check fails.")
509
+ @click.option(
510
+ "--json-output", "json_output", is_flag=True, help="Print machine-readable JSON output."
511
+ )
512
+ def doctor(strict: bool, json_output: bool) -> None:
513
+ """Run environment and dependency checks for agents/CI."""
514
+ result = run_doctor()
515
+ if json_output:
516
+ click.echo(json.dumps(result, indent=2))
517
+ else:
518
+ status = "OK" if result["ok"] else "FAIL"
519
+ click.echo(f"Doctor status: {status}")
520
+ for check in result["checks"]:
521
+ icon = "PASS" if check["passed"] else "FAIL"
522
+ click.echo(
523
+ f"- {icon} {check['name']}: {check['detail']} (required {check['required']})"
524
+ )
525
+ if strict and not result["ok"]:
526
+ raise SystemExit(1)
527
+
528
+
529
+ @cli.command("example-input")
530
+ def example_input() -> None:
531
+ """Print an example input JSON to stdout."""
532
+ click.echo(json.dumps(example_payload(), indent=2))
533
+
534
+
535
+ if __name__ == "__main__":
536
+ cli()