assay-bittensor 0.4.0__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.
assay/__init__.py ADDED
@@ -0,0 +1,40 @@
1
+ """assay — adversarial test harness for Bittensor subnet incentive mechanisms.
2
+
3
+ Point it at your mechanism, get a table of which gaming strategies break it.
4
+
5
+ from assay import Mechanism, Batch, Response
6
+ """
7
+
8
+ from .types import (
9
+ Batch,
10
+ Miner,
11
+ Outcome,
12
+ Report as AssayReport,
13
+ Response,
14
+ Verdict,
15
+ )
16
+ from .mechanism import Evaluator, Mechanism, NoisyEvaluator, clamp_weights, load_mechanism
17
+ from .runner import run_all, run_scenario, sanity_check
18
+ from .scenarios import ALL_SCENARIOS, Scenario
19
+
20
+ __version__ = "0.4.0"
21
+
22
+ __all__ = [
23
+ "Batch",
24
+ "Miner",
25
+ "Outcome",
26
+ "Response",
27
+ "Verdict",
28
+ "AssayReport",
29
+ "Mechanism",
30
+ "Evaluator",
31
+ "NoisyEvaluator",
32
+ "clamp_weights",
33
+ "load_mechanism",
34
+ "run_all",
35
+ "run_scenario",
36
+ "sanity_check",
37
+ "Scenario",
38
+ "ALL_SCENARIOS",
39
+ "__version__",
40
+ ]
assay/cli.py ADDED
@@ -0,0 +1,543 @@
1
+ """assay command line.
2
+
3
+ Exit codes are the contract with CI:
4
+ 0 every scenario held
5
+ 1 at least one scenario broke the mechanism
6
+ 2 usage / loading error
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from . import __version__, conformance, report as report_mod, runner
16
+ from .mechanism import load_mechanism
17
+ from .scenarios import ALL_SCENARIOS
18
+
19
+ TEMPLATE = '''"""An assay adapter for a Bittensor subnet.
20
+
21
+ Wrap your subnet's actual reward logic in `score()`. The only contract is:
22
+
23
+ score(batch, evaluate) -> {uid: weight in [0, 1]}
24
+
25
+ `evaluate(response)` returns a noisy quality estimate — it stands in for
26
+ whatever expensive judgement your validator really does.
27
+
28
+ Run: assay run {filename}
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from assay import Batch, Mechanism, Response
34
+
35
+
36
+ class MyMechanism(Mechanism):
37
+ name = "my-subnet"
38
+
39
+ def score(self, batch: Batch, evaluate) -> dict[int, float]:
40
+ weights: dict[int, float] = {{}}
41
+ for resp in batch.responses:
42
+ # TODO: this is the naive version — it trusts one noisy sample and
43
+ # does not deduplicate. Run `assay` and watch it fail.
44
+ weights[resp.uid] = evaluate(resp)
45
+ return weights
46
+
47
+
48
+ MECHANISM = MyMechanism()
49
+ '''
50
+
51
+
52
+ def _build_parser() -> argparse.ArgumentParser:
53
+ p = argparse.ArgumentParser(
54
+ prog="assay",
55
+ description="Assay a Bittensor subnet's incentive mechanism against a library of adversaries.",
56
+ )
57
+ p.add_argument("--version", action="version", version=f"assay {__version__}")
58
+ sub = p.add_subparsers(dest="command", required=True)
59
+
60
+ run = sub.add_parser("run", help="run the attack library against a mechanism")
61
+ run.add_argument("mechanism", help="path to a .py file exposing a Mechanism")
62
+ run.add_argument("--scenario", "-s", action="append", help="run only these scenarios (repeatable)")
63
+ run.add_argument("--format", "-f", choices=["table", "json", "markdown"], default="table")
64
+ run.add_argument("--out", "-o", help="write the report to a file instead of stdout")
65
+ run.add_argument("--seed", type=int, default=0)
66
+ run.add_argument("--sigma", type=float, default=0.12, help="evaluator noise (default 0.12)")
67
+ run.add_argument("--no-color", action="store_true")
68
+ # live-chain replay
69
+ run.add_argument(
70
+ "--netuid", type=int, help="replay against this real subnet's miner distribution"
71
+ )
72
+ run.add_argument("--network", default="finney", help="finney (mainnet), test, or local")
73
+ run.add_argument(
74
+ "--honest-count", type=int, default=32, help="cap real miners included (default 32)"
75
+ )
76
+ run.add_argument("--no-adversaries", action="store_true", help="real miners only, no injected adversaries")
77
+ run.add_argument("--snapshot", help="use this saved metagraph snapshot instead of the network")
78
+ run.add_argument("--cached", action="store_true", help="use the cache, never hit the network")
79
+
80
+ cons = sub.add_parser(
81
+ "consensus",
82
+ help="run validator-side scenarios through stake-weighted consensus",
83
+ )
84
+ cons.add_argument("mechanism", help="path to a .py file exposing a Mechanism")
85
+ cons.add_argument("--scenario", "-s", action="append", help="run only these (repeatable)")
86
+ cons.add_argument("--format", "-f", choices=["table", "json", "markdown"], default="table")
87
+ cons.add_argument("--out", "-o", help="write the report to a file instead of stdout")
88
+ cons.add_argument("--seed", type=int, default=0)
89
+ cons.add_argument("--sigma", type=float, default=0.12)
90
+ cons.add_argument("--no-color", action="store_true")
91
+
92
+ sub.add_parser("list", help="list the adversaries in the library")
93
+
94
+ scan = sub.add_parser(
95
+ "scan", help="profile many subnets and rank by reward concentration"
96
+ )
97
+ scan.add_argument("--netuids", help="comma-separated netuids, e.g. 1,4,8,64")
98
+ scan.add_argument(
99
+ "--top",
100
+ type=int,
101
+ default=20,
102
+ help="when --netuids is omitted, scan the N largest subnets by neuron count (default 20)",
103
+ )
104
+ scan.add_argument("--network", default="finney")
105
+ scan.add_argument("--workers", type=int, default=4, help="parallel fetches (default 4)")
106
+ scan.add_argument("--min-neurons", type=int, default=8, help="skip smaller subnets")
107
+ scan.add_argument("--format", "-f", choices=["table", "json", "markdown"], default="table")
108
+ scan.add_argument("--out", "-o", help="write the report to a file")
109
+ scan.add_argument("--refresh", action="store_true", help="ignore the metagraph cache")
110
+ scan.add_argument("--no-color", action="store_true")
111
+
112
+ fid = sub.add_parser(
113
+ "fidelity",
114
+ help="verify the harness's weights-into-rewards model against the chain",
115
+ )
116
+ fid.add_argument("--netuid", type=int, help="subnet to check")
117
+ fid.add_argument("--network", default="finney")
118
+ fid.add_argument("--mechid", type=int, default=0, help="mechanism index (default 0)")
119
+ fid.add_argument("--snapshot", help="read a saved weight snapshot instead of the chain")
120
+ fid.add_argument("--save", help="write the weight snapshot to this path")
121
+ fid.add_argument("--refresh", action="store_true", help="ignore the cache")
122
+ fid.add_argument("--worst", type=int, default=10, help="how many rows to show (default 10)")
123
+ fid.add_argument("--format", "-f", choices=["table", "json"], default="table")
124
+ fid.add_argument("--no-color", action="store_true")
125
+
126
+ live = sub.add_parser("live", help="inspect a real subnet's miner distribution")
127
+ live.add_argument("--netuid", type=int, required=True)
128
+ live.add_argument("--network", default="finney", help="finney (mainnet), test, or local")
129
+ live.add_argument("--snapshot", help="read this saved snapshot instead of the network")
130
+ live.add_argument("--cached", action="store_true", help="use the cache, never hit the network")
131
+ live.add_argument("--save", help="write the snapshot to this path")
132
+ live.add_argument("--json", action="store_true", help="machine-readable output")
133
+ live.add_argument("--no-color", action="store_true")
134
+
135
+ conf = sub.add_parser("conformance", help="check btauth/1 against the published golden vectors")
136
+ conf.add_argument("--format", "-f", choices=["table", "json"], default="table")
137
+ conf.add_argument("--no-color", action="store_true")
138
+
139
+ rep = sub.add_parser(
140
+ "report", help="re-render a saved JSON report as a table or markdown"
141
+ )
142
+ rep.add_argument("path", help="path to a JSON report written by `assay run -f json`")
143
+ rep.add_argument("--format", "-f", choices=["table", "markdown", "json"], default="markdown")
144
+ rep.add_argument("--out", "-o", help="write to this file instead of stdout")
145
+ rep.add_argument("--no-color", action="store_true")
146
+
147
+ init = sub.add_parser("init", help="scaffold a mechanism adapter")
148
+ init.add_argument("path", help="where to write the adapter (e.g. assay_my_subnet.py)")
149
+
150
+ return p
151
+
152
+
153
+ def cmd_run(args: argparse.Namespace) -> int:
154
+ try:
155
+ load_mechanism(args.mechanism)
156
+ except Exception as exc:
157
+ print(f"assay: cannot load mechanism: {exc}", file=sys.stderr)
158
+ return 2
159
+
160
+ try:
161
+ scenarios = runner.ordered_scenarios(args.scenario, ALL_SCENARIOS)
162
+ except KeyError as exc:
163
+ print(f"assay: {exc}", file=sys.stderr)
164
+ return 2
165
+
166
+ # --- optional live-chain population --------------------------------------
167
+ population_builder = None
168
+ header = ""
169
+ if args.netuid is not None or args.snapshot:
170
+ from . import live as live_mod
171
+
172
+ try:
173
+ if args.snapshot:
174
+ snapshot = live_mod.load_snapshot(args.snapshot)
175
+ else:
176
+ snapshot = live_mod.fetch_metagraph(
177
+ args.netuid,
178
+ network=args.network,
179
+ use_cache=True,
180
+ max_age=(
181
+ float("inf") if args.cached else live_mod.CACHE_TTL_SECONDS
182
+ ),
183
+ )
184
+ except live_mod.ChainUnavailable as exc:
185
+ print(f"assay: {exc}", file=sys.stderr)
186
+ return 2
187
+
188
+ def population_builder(scenario_name: str, snap=snapshot):
189
+ # honest_baseline gets a clean population: injecting adversaries
190
+ # there would guarantee a failing baseline and make every other
191
+ # PASS in the report meaningless.
192
+ return live_mod.population_from_snapshot(
193
+ snap,
194
+ honest_count=args.honest_count,
195
+ adversaries=(scenario_name != "honest_baseline") and not args.no_adversaries,
196
+ seed=args.seed,
197
+ )
198
+
199
+ inc = snapshot.incentive_distribution()
200
+ header = (
201
+ f"replaying {snapshot.name or ('netuid ' + str(snapshot.netuid))} "
202
+ f"({snapshot.network}, block {snapshot.block}) — "
203
+ f"{int(inc.get('count', 0))} real miners, gini {inc.get('gini', 0):.3f}"
204
+ )
205
+ if args.format == "table":
206
+ print(f"\n {header}\n", file=sys.stderr)
207
+
208
+ def on_scenario(scenario, verdict):
209
+ if args.format == "table" and not args.no_color:
210
+ mark = {"PASS": "\033[32m·\033[0m", "FAIL": "\033[31mx\033[0m"}.get(verdict.status, "·")
211
+ print(f" {mark} {scenario.name}", file=sys.stderr, end="\r")
212
+
213
+ rep = runner.run_all(
214
+ scenarios,
215
+ lambda: load_mechanism(args.mechanism),
216
+ seed=args.seed,
217
+ eval_sigma=args.sigma,
218
+ on_scenario=on_scenario,
219
+ population_builder=population_builder,
220
+ )
221
+ rep.source = header
222
+ warnings = runner.sanity_check(rep)
223
+
224
+ if args.format == "json":
225
+ text = report_mod.render_json(rep, warnings)
226
+ elif args.format == "markdown":
227
+ text = report_mod.render_markdown(rep, warnings)
228
+ else:
229
+ text = report_mod.render_table(rep, color=not args.no_color)
230
+ if warnings:
231
+ text += "\n" + "\n".join(f" ⚠️ {w}" for w in warnings) + "\n"
232
+
233
+ if args.out:
234
+ Path(args.out).write_text(text, encoding="utf-8")
235
+ print(f"wrote {args.out}", file=sys.stderr)
236
+ else:
237
+ print(text)
238
+
239
+ return rep.exit_code()
240
+
241
+
242
+ def cmd_consensus(args: argparse.Namespace) -> int:
243
+ from .validator_scenarios import ALL_CONSENSUS_SCENARIOS
244
+
245
+ try:
246
+ load_mechanism(args.mechanism)
247
+ except Exception as exc:
248
+ print(f"assay: cannot load mechanism: {exc}", file=sys.stderr)
249
+ return 2
250
+
251
+ selected = list(ALL_CONSENSUS_SCENARIOS)
252
+ if args.scenario:
253
+ wanted = [s.strip() for s in args.scenario]
254
+ known = {c().name for c in ALL_CONSENSUS_SCENARIOS}
255
+ unknown = [w for w in wanted if w not in known]
256
+ if unknown:
257
+ print(
258
+ f"assay: unknown scenario {unknown[0]!r}; known: {', '.join(sorted(known))}",
259
+ file=sys.stderr,
260
+ )
261
+ return 2
262
+ selected = [c for c in ALL_CONSENSUS_SCENARIOS if c().name in wanted]
263
+
264
+ rep = runner.run_all_consensus(
265
+ selected,
266
+ lambda: load_mechanism(args.mechanism),
267
+ seed=args.seed,
268
+ eval_sigma=args.sigma,
269
+ )
270
+ rep.source = "validator-side: mechanism runs once per validator, combined by stake"
271
+
272
+ warnings: list[str] = []
273
+ informational = [v for v in rep.verdicts if v.status == "SKIP"]
274
+ if informational:
275
+ warnings.append(
276
+ f"{len(informational)} scenario(s) are informational: a hostile validator "
277
+ "overwrites the mechanism's output after it runs, so no scoring rule "
278
+ "prevents the damage. Those numbers measure stake concentration, not your code."
279
+ )
280
+
281
+ if args.format == "json":
282
+ text = report_mod.render_json(rep, warnings)
283
+ elif args.format == "markdown":
284
+ text = report_mod.render_markdown(rep, warnings)
285
+ else:
286
+ text = report_mod.render_table(rep, color=not args.no_color)
287
+ if warnings:
288
+ text += "\n" + "\n".join(f" ⚠️ {w}" for w in warnings) + "\n"
289
+
290
+ if args.out:
291
+ Path(args.out).write_text(text, encoding="utf-8")
292
+ print(f"wrote {args.out}", file=sys.stderr)
293
+ else:
294
+ print(text)
295
+ return rep.exit_code()
296
+
297
+
298
+ def cmd_list(_args: argparse.Namespace) -> int:
299
+ print(report_mod.render_list(cls() for cls in ALL_SCENARIOS))
300
+ return 0
301
+
302
+
303
+ def cmd_conformance(args: argparse.Namespace) -> int:
304
+ checks = conformance.run_conformance()
305
+ if args.format == "json":
306
+ import json
307
+
308
+ print(
309
+ json.dumps(
310
+ [{"check": c.name, "status": c.status, "detail": c.detail} for c in checks],
311
+ indent=2,
312
+ )
313
+ )
314
+ else:
315
+ print(conformance.render(checks, color=not args.no_color))
316
+ return 0 if all(c.status != "FAIL" for c in checks) else 1
317
+
318
+
319
+ def cmd_fidelity(args: argparse.Namespace) -> int:
320
+ from . import fidelity as fid_mod
321
+ from .live import ChainUnavailable
322
+
323
+ if not args.netuid and not args.snapshot:
324
+ print("assay: fidelity needs --netuid or --snapshot", file=sys.stderr)
325
+ return 2
326
+
327
+ try:
328
+ if args.snapshot:
329
+ snapshot = fid_mod.load_weight_snapshot(args.snapshot)
330
+ else:
331
+ snapshot = fid_mod.fetch_weights(
332
+ args.netuid,
333
+ network=args.network,
334
+ mechid=args.mechid,
335
+ use_cache=not args.refresh,
336
+ )
337
+ except ChainUnavailable as exc:
338
+ print(f"assay: {exc}", file=sys.stderr)
339
+ return 2
340
+ except FileNotFoundError as exc:
341
+ print(f"assay: {exc}", file=sys.stderr)
342
+ return 2
343
+
344
+ if args.save:
345
+ import json
346
+
347
+ Path(args.save).write_text(json.dumps(snapshot.to_dict()), encoding="utf-8")
348
+ print(f"wrote weight snapshot to {args.save}", file=sys.stderr)
349
+
350
+ if not snapshot.rows:
351
+ print(
352
+ "assay: no validator weight rows on this subnet — nothing to verify "
353
+ "(nobody has set weights this epoch)",
354
+ file=sys.stderr,
355
+ )
356
+ return 2
357
+
358
+ result = fid_mod.measure_fidelity(snapshot, worst_n=args.worst)
359
+
360
+ if args.format == "json":
361
+ print(fid_mod.render_fidelity_json(result))
362
+ else:
363
+ print(fid_mod.render_fidelity(result, color=not args.no_color))
364
+
365
+ # exit code reports whether the model held, so CI can gate on it
366
+ return 0 if result.tvd <= fid_mod.CLOSE else 1
367
+
368
+
369
+ def cmd_scan(args: argparse.Namespace) -> int:
370
+ from . import scan as scan_mod
371
+ from .live import ChainUnavailable
372
+
373
+ if args.netuids:
374
+ try:
375
+ netuids = [int(x.strip()) for x in args.netuids.split(",") if x.strip()]
376
+ except ValueError:
377
+ print("assay: --netuids must be a comma-separated list of integers", file=sys.stderr)
378
+ return 2
379
+ else:
380
+ try:
381
+ netuids = scan_mod.list_active_netuids(
382
+ network=args.network, min_neurons=args.min_neurons, limit=args.top
383
+ )
384
+ except ChainUnavailable as exc:
385
+ print(f"assay: {exc}", file=sys.stderr)
386
+ return 2
387
+ except Exception as exc:
388
+ print(f"assay: cannot list subnets: {exc}", file=sys.stderr)
389
+ return 2
390
+
391
+ if not netuids:
392
+ print("assay: no subnets to scan", file=sys.stderr)
393
+ return 2
394
+
395
+ def progress(done: int, total: int, netuid: int, profile) -> None:
396
+ if args.format == "table":
397
+ mark = "." if profile is not None else "\033[31mx\033[0m"
398
+ print(f" {done}/{total} netuid {netuid} {mark}", file=sys.stderr, end="\r")
399
+
400
+ profiles = scan_mod.scan(
401
+ netuids,
402
+ network=args.network,
403
+ workers=args.workers,
404
+ use_cache=not args.refresh,
405
+ on_progress=progress,
406
+ )
407
+ if args.format == "table":
408
+ print(" " * 48, file=sys.stderr, end="\r")
409
+
410
+ if not profiles:
411
+ print("assay: no subnets could be profiled", file=sys.stderr)
412
+ return 2
413
+
414
+ if args.format == "json":
415
+ text = scan_mod.render_scan_json(profiles)
416
+ elif args.format == "markdown":
417
+ text = scan_mod.render_scan_markdown(profiles)
418
+ else:
419
+ text = scan_mod.render_scan(profiles, color=not args.no_color)
420
+
421
+ if args.out:
422
+ Path(args.out).write_text(text, encoding="utf-8")
423
+ print(f"wrote {args.out}", file=sys.stderr)
424
+ else:
425
+ print(text)
426
+ return 0
427
+
428
+
429
+ def cmd_live(args: argparse.Namespace) -> int:
430
+ from . import live as live_mod
431
+
432
+ try:
433
+ if args.snapshot:
434
+ snapshot = live_mod.load_snapshot(args.snapshot)
435
+ else:
436
+ snapshot = live_mod.fetch_metagraph(
437
+ args.netuid,
438
+ network=args.network,
439
+ use_cache=True,
440
+ max_age=float("inf") if args.cached else live_mod.CACHE_TTL_SECONDS,
441
+ )
442
+ except live_mod.ChainUnavailable as exc:
443
+ print(f"assay: {exc}", file=sys.stderr)
444
+ return 2
445
+ except FileNotFoundError as exc:
446
+ print(f"assay: {exc}", file=sys.stderr)
447
+ return 2
448
+
449
+ if args.save:
450
+ import json
451
+
452
+ Path(args.save).write_text(json.dumps(snapshot.to_dict()), encoding="utf-8")
453
+ print(f"wrote snapshot to {args.save}", file=sys.stderr)
454
+
455
+ if args.json:
456
+ import json
457
+
458
+ payload = {
459
+ "netuid": snapshot.netuid,
460
+ "network": snapshot.network,
461
+ "block": snapshot.block,
462
+ "name": snapshot.name,
463
+ "symbol": snapshot.symbol,
464
+ "price": snapshot.price,
465
+ "miners": len(snapshot.miners),
466
+ "validators": len(snapshot.validators),
467
+ "incentive": snapshot.incentive_distribution(),
468
+ "emission": snapshot.emission_distribution(),
469
+ }
470
+ print(json.dumps(payload, indent=2))
471
+ else:
472
+ print(live_mod.render_snapshot(snapshot, color=not args.no_color))
473
+ return 0
474
+
475
+
476
+ def cmd_report(args: argparse.Namespace) -> int:
477
+ import json
478
+
479
+ from .types import Report as ProbeReport
480
+
481
+ path = Path(args.path)
482
+ try:
483
+ payload = json.loads(path.read_text(encoding="utf-8"))
484
+ except FileNotFoundError:
485
+ print(f"assay: no such report: {path}", file=sys.stderr)
486
+ return 2
487
+ except json.JSONDecodeError as exc:
488
+ print(f"assay: {path} is not valid JSON: {exc}", file=sys.stderr)
489
+ return 2
490
+
491
+ try:
492
+ rep = ProbeReport.from_dict(payload)
493
+ except Exception as exc:
494
+ print(f"assay: {path} does not look like an assay report: {exc}", file=sys.stderr)
495
+ return 2
496
+
497
+ warnings = payload.get("warnings") or []
498
+ if args.format == "json":
499
+ text = report_mod.render_json(rep, warnings)
500
+ elif args.format == "markdown":
501
+ text = report_mod.render_markdown(rep, warnings)
502
+ else:
503
+ text = report_mod.render_table(rep, color=not args.no_color)
504
+
505
+ if args.out:
506
+ Path(args.out).write_text(text, encoding="utf-8")
507
+ print(f"wrote {args.out}", file=sys.stderr)
508
+ else:
509
+ print(text)
510
+ return rep.exit_code()
511
+
512
+
513
+ def cmd_init(args: argparse.Namespace) -> int:
514
+ path = Path(args.path)
515
+ if path.exists():
516
+ print(f"assay: {path} already exists", file=sys.stderr)
517
+ return 2
518
+ path.parent.mkdir(parents=True, exist_ok=True)
519
+ path.write_text(TEMPLATE.format(filename=path.name), encoding="utf-8")
520
+ print(f"wrote {path}")
521
+ print(f"next: assay run {path}")
522
+ return 0
523
+
524
+
525
+ def main(argv: list[str] | None = None) -> int:
526
+ parser = _build_parser()
527
+ args = parser.parse_args(argv)
528
+ handlers = {
529
+ "run": cmd_run,
530
+ "consensus": cmd_consensus,
531
+ "list": cmd_list,
532
+ "live": cmd_live,
533
+ "scan": cmd_scan,
534
+ "fidelity": cmd_fidelity,
535
+ "conformance": cmd_conformance,
536
+ "report": cmd_report,
537
+ "init": cmd_init,
538
+ }
539
+ return handlers[args.command](args)
540
+
541
+
542
+ if __name__ == "__main__": # pragma: no cover
543
+ raise SystemExit(main())