qtiming 0.1.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.
Files changed (102) hide show
  1. qtiming/__init__.py +0 -0
  2. qtiming/bench/__init__.py +327 -0
  3. qtiming/bench/diff.py +230 -0
  4. qtiming/bench/report.py +161 -0
  5. qtiming/bench/truth.py +88 -0
  6. qtiming/cli/__init__.py +0 -0
  7. qtiming/cli/cmd_evidence.py +35 -0
  8. qtiming/cli/main.py +398 -0
  9. qtiming/contract/__init__.py +0 -0
  10. qtiming/contract/compat.py +49 -0
  11. qtiming/contract/instances/README.md +30 -0
  12. qtiming/contract/instances/artiq.toml +45 -0
  13. qtiming/contract/instances/ibm_heron.toml +62 -0
  14. qtiming/contract/instances/ibm_heron_snapshot.json +22 -0
  15. qtiming/contract/instances/q1.toml +88 -0
  16. qtiming/contract/instances/qua.toml +65 -0
  17. qtiming/contract/loader.py +355 -0
  18. qtiming/contract/model.py +123 -0
  19. qtiming/contract/schema.py +106 -0
  20. qtiming/contract/target_import.py +46 -0
  21. qtiming/core/__init__.py +0 -0
  22. qtiming/core/ast.py +140 -0
  23. qtiming/core/errors.py +36 -0
  24. qtiming/core/ids.py +34 -0
  25. qtiming/core/labels.py +121 -0
  26. qtiming/core/provenance.py +77 -0
  27. qtiming/core/time.py +96 -0
  28. qtiming/dispatch/__init__.py +22 -0
  29. qtiming/dispatch/artiq.py +70 -0
  30. qtiming/dispatch/ibm.py +83 -0
  31. qtiming/dispatch/q1.py +102 -0
  32. qtiming/dispatch/qua.py +88 -0
  33. qtiming/elab/__init__.py +360 -0
  34. qtiming/evidence/__init__.py +15 -0
  35. qtiming/evidence/ingest.py +235 -0
  36. qtiming/exec/__init__.py +0 -0
  37. qtiming/exec/artiq.py +100 -0
  38. qtiming/exec/engine.py +235 -0
  39. qtiming/exec/explore.py +43 -0
  40. qtiming/exec/ibm.py +117 -0
  41. qtiming/exec/oracle.py +88 -0
  42. qtiming/exec/q1.py +95 -0
  43. qtiming/exec/qua.py +95 -0
  44. qtiming/frontend/__init__.py +40 -0
  45. qtiming/frontend/_shared.py +149 -0
  46. qtiming/frontend/annotations.py +81 -0
  47. qtiming/frontend/lint.py +116 -0
  48. qtiming/frontend/payload.py +113 -0
  49. qtiming/frontend/program.py +51 -0
  50. qtiming/frontend/qasm3_fe.py +341 -0
  51. qtiming/frontend/qiskit_expr.py +89 -0
  52. qtiming/frontend/qiskit_fe.py +220 -0
  53. qtiming/frontend/serialise.py +63 -0
  54. qtiming/frontend/stretch.py +71 -0
  55. qtiming/graph/__init__.py +0 -0
  56. qtiming/graph/builder.py +245 -0
  57. qtiming/graph/export.py +25 -0
  58. qtiming/graph/invariants.py +67 -0
  59. qtiming/graph/lteg.py +153 -0
  60. qtiming/graph/window.py +120 -0
  61. qtiming/oblig/__init__.py +0 -0
  62. qtiming/oblig/generate.py +145 -0
  63. qtiming/oblig/model.py +76 -0
  64. qtiming/py.typed +0 -0
  65. qtiming/qiskit_pass/__init__.py +7 -0
  66. qtiming/qiskit_pass/_common.py +21 -0
  67. qtiming/qiskit_pass/equalize.py +171 -0
  68. qtiming/qiskit_pass/plugin.py +23 -0
  69. qtiming/qiskit_pass/strip.py +42 -0
  70. qtiming/qiskit_pass/timing_check.py +40 -0
  71. qtiming/repair/__init__.py +0 -0
  72. qtiming/repair/suggest.py +146 -0
  73. qtiming/solve/__init__.py +0 -0
  74. qtiming/solve/concrete.py +148 -0
  75. qtiming/solve/dispatcher.py +55 -0
  76. qtiming/solve/interval.py +185 -0
  77. qtiming/solve/smt.py +167 -0
  78. qtiming/solve/smt_o5.py +1 -0
  79. qtiming/solve/synth/__init__.py +0 -0
  80. qtiming/solve/synth/bruteforce_dc.py +156 -0
  81. qtiming/solve/synth/model.py +59 -0
  82. qtiming/solve/synth/relax.py +93 -0
  83. qtiming/solve/synth/rigid.py +33 -0
  84. qtiming/solve/synth/sc.py +55 -0
  85. qtiming/solve/synth/stn.py +74 -0
  86. qtiming/solve/synth/stnu_dc.py +93 -0
  87. qtiming/verdict/__init__.py +0 -0
  88. qtiming/verdict/minimise.py +45 -0
  89. qtiming/verdict/model.py +107 -0
  90. qtiming/verdict/render.py +72 -0
  91. qtiming/verdict/render_html.py +80 -0
  92. qtiming/verdict/render_json.py +12 -0
  93. qtiming/verdict/render_sarif.py +104 -0
  94. qtiming/verdict/replay.py +77 -0
  95. qtiming/verdict/run.py +174 -0
  96. qtiming/verdict/rus.py +53 -0
  97. qtiming-0.1.0.dist-info/METADATA +262 -0
  98. qtiming-0.1.0.dist-info/RECORD +102 -0
  99. qtiming-0.1.0.dist-info/WHEEL +4 -0
  100. qtiming-0.1.0.dist-info/entry_points.txt +6 -0
  101. qtiming-0.1.0.dist-info/licenses/LICENSE +177 -0
  102. qtiming-0.1.0.dist-info/licenses/NOTICE +8 -0
qtiming/cli/main.py ADDED
@@ -0,0 +1,398 @@
1
+ """`qtiming` command line: `contract validate` (P2) and `check` (P7).
2
+
3
+ Exit codes (plan 19.6): 0 PROVED or PROVED-UNDER (1 with --strict-proved for PROVED-UNDER),
4
+ 1 REFUTED, 2 usage or lint error, 3 UNKNOWN, 4 internal error.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+ from collections.abc import Sequence
13
+ from dataclasses import replace
14
+ from pathlib import Path
15
+
16
+ from qtiming.contract.loader import ContractLoadError, load_contract
17
+ from qtiming.core.errors import QtError
18
+
19
+ INSTANCES = Path(__file__).resolve().parents[1] / "contract" / "instances"
20
+
21
+
22
+ def _validate(files: Sequence[str], assume: Sequence[str]) -> int:
23
+ bad = 0
24
+ for path in files:
25
+ try:
26
+ c = load_contract(path, assume=tuple(assume))
27
+ except ContractLoadError as e:
28
+ bad += 1
29
+ print(f"FAIL {path}", file=sys.stderr)
30
+ for err in e.errors:
31
+ print(f" {err}", file=sys.stderr)
32
+ except (OSError, QtError, ValueError) as e:
33
+ bad += 1
34
+ print(f"FAIL {path}: {e}", file=sys.stderr)
35
+ else:
36
+ n_ph = sum(cl.placeholder for cl in c.latencies)
37
+ print(f"OK {c.name} sha256={c.sha256[:12]} placeholders={n_ph} "
38
+ f"missing={len(c.missing)} warnings={len(c.warnings)}")
39
+ for m in c.missing:
40
+ print(f" missing: {m}")
41
+ return 1 if bad else 0
42
+
43
+
44
+ def resolve_contract(name: str) -> str:
45
+ """A path, or the name of a shipped instance (`ibm_heron`, `q1`, `artiq`, `qua`)."""
46
+ if Path(name).is_file():
47
+ return name
48
+ for cand in (INSTANCES / name, INSTANCES / f"{name}.toml", INSTANCES / f"{name}_heron.toml"):
49
+ if cand.is_file():
50
+ return str(cand)
51
+ names = ", ".join(sorted(p.stem for p in INSTANCES.glob("*.toml")))
52
+ raise QtError("E-CLI-CONTRACT", f"no contract file or shipped instance named {name!r}",
53
+ hint=f"shipped instances: {names}")
54
+
55
+
56
+ def resolve_program(name: str) -> Path:
57
+ p = Path(name)
58
+ for cand in (p, Path(f"{name}.qasm"), p / "program.qasm"):
59
+ if cand.is_file():
60
+ return cand
61
+ raise QtError("E-CLI-PROGRAM", f"no program found for {name!r}",
62
+ hint="pass an OpenQASM 3 file (.qasm); QPY files use .qpy")
63
+
64
+
65
+ def _load(args: argparse.Namespace): # type: ignore[no-untyped-def]
66
+ from qtiming.frontend import from_qasm3, from_qpy
67
+
68
+ contract = load_contract(resolve_contract(args.contract), assume=tuple(args.assume))
69
+ path = resolve_program(args.program)
70
+ if path.suffix == ".qpy":
71
+ prog = from_qpy(str(path), contract=contract)
72
+ else:
73
+ prog = from_qasm3(path.read_text(encoding="utf-8"), filename=str(path), contract=contract)
74
+ return contract, prog
75
+
76
+
77
+ def _guard(fn): # type: ignore[no-untyped-def]
78
+ """Map load/usage errors to exit code 2 and internal (I-*) errors to 4."""
79
+
80
+ def run(args: argparse.Namespace) -> int:
81
+ try:
82
+ return int(fn(args))
83
+ except ContractLoadError as e:
84
+ for err in e.errors:
85
+ print(f"error: {err}", file=sys.stderr)
86
+ return 2
87
+ except QtError as e:
88
+ print(f"error: {e}" + (f"\n hint: {e.hint}" if e.hint else ""), file=sys.stderr)
89
+ return 4 if e.code.startswith("I-") else 2 # I-* are internal errors
90
+
91
+ return run
92
+
93
+
94
+ def _emit(text: str, out: str | None) -> None:
95
+ if out:
96
+ Path(out).write_text(text + "\n", encoding="utf-8")
97
+ else:
98
+ print(text)
99
+
100
+
101
+ @_guard
102
+ def _check(args: argparse.Namespace) -> int:
103
+ from qtiming.frontend.lint import lint
104
+ from qtiming.solve.dispatcher import SolveCfg
105
+ from qtiming.verdict.model import PROVED_UNDER
106
+ from qtiming.verdict.render import render_text
107
+ from qtiming.verdict.render_html import render_html
108
+ from qtiming.verdict.render_json import render_json
109
+ from qtiming.verdict.render_sarif import render_sarif
110
+ from qtiming.verdict.run import check_program, max_safe
111
+
112
+ contract, prog = _load(args)
113
+ cfg = SolveCfg(use_tier1=not args.no_tier1, use_tier2=not args.no_tier2,
114
+ timeout_ms=int(args.timeout * 1000))
115
+ verdict = check_program(prog.body, contract, policy=args.policy, cfg=cfg,
116
+ first_failure=args.first_failure, window=not args.no_window)
117
+ if args.max_safe:
118
+ h = max_safe(prog.body, contract, args.max_safe, policy=args.policy)
119
+ found = ("not safe at the current bound" if h is None
120
+ else f"{h} dt = {float(h * contract.dt_ns):g} ns")
121
+ verdict = replace(verdict, max_safe={f"{args.max_safe}.hi": found})
122
+ dt = contract.dt_ns
123
+ if args.format == "json":
124
+ text = render_json(verdict, dt)
125
+ elif args.format == "sarif":
126
+ text = render_sarif(verdict, dt, lint(prog.body, contract.personality))
127
+ elif args.format == "html":
128
+ text = render_html(verdict, dt)
129
+ else:
130
+ text = render_text(verdict, dt)
131
+ _emit(text, args.out)
132
+ if args.strict_proved and verdict.verdict == PROVED_UNDER:
133
+ return 1
134
+ return verdict.exit_code
135
+
136
+
137
+ def dump_stmt(s, indent: int = 0) -> list[str]: # type: ignore[no-untyped-def]
138
+ """Readable dump of an elaborated TQ program (`explain --elaborated`)."""
139
+ pad = " " * indent
140
+ name = type(s).__name__
141
+ fields = []
142
+ for f in ("name", "qubits", "qubit", "dur", "cbit", "policy", "declared"):
143
+ if hasattr(s, f) and getattr(s, f) not in (None, False):
144
+ fields.append(f"{f}={getattr(s, f)!r}")
145
+ if getattr(s, "origin_nid", None) is not None:
146
+ fields.append(f"synth(from n{s.origin_nid})")
147
+ lines = [f"{pad}{name} n{s.nid} {' '.join(fields)}".rstrip()]
148
+ for f in ("stmts",):
149
+ for c in getattr(s, f, ()):
150
+ lines += dump_stmt(c, indent + 1)
151
+ for f, label in (("body", ""), ("then_", "then:"), ("else_", "else:")):
152
+ c = getattr(s, f, None)
153
+ if c is not None and hasattr(c, "nid"):
154
+ if label:
155
+ lines.append(f"{pad} {label}")
156
+ lines += dump_stmt(c, indent + (2 if label else 1))
157
+ return lines
158
+
159
+
160
+ @_guard
161
+ def _explain(args: argparse.Namespace) -> int:
162
+ from qtiming.core.ast import Policy
163
+ from qtiming.dispatch import build_graph
164
+ from qtiming.elab import elaborate
165
+ from qtiming.graph.export import to_dot
166
+ from qtiming.oblig.generate import generate
167
+ from qtiming.verdict.run import with_policy
168
+
169
+ contract, prog = _load(args)
170
+ body = with_policy(prog.body, Policy(args.policy)) if args.policy else prog.body
171
+ el = elaborate(body, contract)
172
+ g = build_graph(el.body, contract)
173
+ obs = generate(g, el, contract)
174
+ out: list[str] = []
175
+ if args.elaborated:
176
+ out += dump_stmt(el.body)
177
+ if args.graph == "dot":
178
+ out.append(to_dot(g))
179
+ if args.obligations:
180
+ for o in obs:
181
+ out.append(f"{o.code} n{o.nid}: {o.check} deps={sorted(o.deps)} {o.message}")
182
+ if not (args.elaborated or args.obligations or args.graph):
183
+ out.append(f"{contract.name} ({contract.personality}): {len(g.nodes)} nodes, "
184
+ f"{len(g.edges)} edges, {len(g.lats)} latency variables, "
185
+ f"{len(obs)} obligations")
186
+ for k, v in sorted(g.facts.items()):
187
+ out.append(f" facts[{k}]: {len(v)}")
188
+ _emit("\n".join(out), args.out)
189
+ return 0
190
+
191
+
192
+ @_guard
193
+ def _lint(args: argparse.Namespace) -> int:
194
+ from qtiming.frontend.lint import lint
195
+ from qtiming.verdict.model import Verdict
196
+
197
+ contract, prog = _load(args)
198
+ found = list(prog.notes) + lint(prog.body, contract.personality)
199
+ if args.format == "sarif":
200
+ from qtiming.verdict.render_sarif import render_sarif
201
+
202
+ empty = Verdict("PROVED", contract.name, contract.sha256, contract.branch.default_policy,
203
+ (), None, (), (), ())
204
+ _emit(render_sarif(empty, contract.dt_ns, found), args.out)
205
+ else:
206
+ for e in found:
207
+ where = f"{e.loc.file}:{e.loc.line}: " if e.loc and e.loc.line else ""
208
+ print(f"{where}{e.severity}: {e.code}: {e.message}")
209
+ if not found:
210
+ print("no lint findings")
211
+ return 2 if any(e.severity == "error" for e in found) else 0
212
+
213
+
214
+ @_guard
215
+ def _replay(args: argparse.Namespace) -> int:
216
+ from fractions import Fraction
217
+
218
+ from qtiming.core.ast import Policy
219
+ from qtiming.dispatch import build_graph
220
+ from qtiming.elab import elaborate
221
+ from qtiming.oblig.generate import generate
222
+ from qtiming.solve.concrete import Result
223
+ from qtiming.verdict.render import ascii_timeline
224
+ from qtiming.verdict.replay import replay
225
+ from qtiming.verdict.run import with_policy
226
+
227
+ contract, prog = _load(args)
228
+ doc = json.loads(Path(args.cex).read_text(encoding="utf-8"))
229
+ cexs = doc["counterexamples"] if "counterexamples" in doc else [doc]
230
+ cex = cexs[args.index]
231
+ body = with_policy(prog.body, Policy(args.policy)) if args.policy else prog.body
232
+ el = elaborate(body, contract)
233
+ g = build_graph(el.body, contract)
234
+ code, nid = cex["obligation"]["code"], cex["obligation"]["nid"]
235
+ obl = next((o for o in generate(g, el, contract) if o.code == code and o.nid == nid), None)
236
+ if obl is None:
237
+ print(f"error: no obligation {code} at node {nid} in this program", file=sys.stderr)
238
+ return 2
239
+ sec = cex.get("second")
240
+ res = Result("refuted", cex.get("tier"), omega={k: int(v) for k, v in cex["omega"].items()},
241
+ theta={k: Fraction(v) for k, v in cex["theta"].items()},
242
+ second=None if sec is None else {k: int(v) for k, v in sec["omega"].items()},
243
+ second_theta=None if sec is None else
244
+ {k: Fraction(v) for k, v in sec["theta"].items()})
245
+ ok = replay(g, obl, res, el.body, contract)
246
+ print(f"{'REPRODUCED' if ok else 'NOT REPRODUCED'}: {code} at node {nid}")
247
+ if args.trace:
248
+ from qtiming.exec.engine import execute
249
+ from qtiming.exec.oracle import Fixed
250
+
251
+ run = execute(el.body, contract, Fixed(res.omega, res.theta))
252
+ for ln in ascii_timeline(run, contract.dt_ns):
253
+ print(ln)
254
+ return 0 if ok else 1
255
+
256
+
257
+ def _contract_cmd(args: argparse.Namespace) -> int:
258
+ try:
259
+ a = load_contract(resolve_contract(args.files[0]), assume=tuple(args.assume))
260
+ b = (load_contract(resolve_contract(args.files[1]), assume=tuple(args.assume))
261
+ if args.sub == "diff" else None)
262
+ except (ContractLoadError, QtError) as e:
263
+ print(f"error: {e}", file=sys.stderr)
264
+ return 2
265
+
266
+ def view(c): # type: ignore[no-untyped-def]
267
+ return {"name": c.name, "personality": c.personality, "dt_ns": str(c.dt_ns),
268
+ "commit_lead_dt": c.commit_lead, "missing": list(c.missing),
269
+ "durations": dict(c.durations),
270
+ "latencies": {x.latency.key: [x.latency.iv.lo, x.latency.iv.hi,
271
+ x.latency.prov.cls.name.lower()]
272
+ for x in c.latencies}}
273
+
274
+ if b is None:
275
+ print(json.dumps(view(a), indent=2))
276
+ return 0
277
+ va, vb = view(a), view(b)
278
+ diffs = [f"{k}: {va[k]!r} -> {vb[k]!r}" for k in va if va[k] != vb[k]]
279
+ print("\n".join(diffs) if diffs else "contracts are equivalent")
280
+ return 1 if diffs else 0
281
+
282
+
283
+ @_guard
284
+ def _repair(args: argparse.Namespace) -> int:
285
+ from qtiming.repair.suggest import _find, repair
286
+ from qtiming.verdict.render import render_text
287
+
288
+ contract, prog = _load(args)
289
+ r = repair(prog.body, contract, policy=args.policy)
290
+ dt = contract.dt_ns
291
+ lines = [f"repair: {r.status}: {r.message}", f"before: {r.before.verdict} "
292
+ f"after: {r.after.verdict}"]
293
+ for h in r.hunks:
294
+ node = _find(r.program, h.nid)
295
+ where = f"line {node.loc.line}" if node is not None and node.loc.line else f"node {h.nid}"
296
+ qs = ", ".join(f"${q}" for q in getattr(node, "qubits", ()))
297
+ lines.append(f" {h.code}: insert before {where}: delay[{float(h.dur * dt):g}ns] {qs};"
298
+ f" ({h.dur} dt)")
299
+ if r.hunks:
300
+ lines.append(f"added idle time: {float(r.idle_dt * dt):g} ns; the patched program was "
301
+ "re-verified by the full pipeline")
302
+ _emit("\n".join(lines), args.out)
303
+ if args.verbose:
304
+ _emit(render_text(r.after, dt), None)
305
+ return {"ok": 0, "fixed": 0, "unknown": 3}.get(r.status, 1)
306
+
307
+
308
+ def _common(p: argparse.ArgumentParser) -> None:
309
+ p.add_argument("program", help="OpenQASM 3 file (.qasm) or QPY file (.qpy)")
310
+ p.add_argument("--contract", required=True, help="contract file or shipped instance name")
311
+ p.add_argument("--assume", action="append", default=[], metavar="KEY=VALUE",
312
+ help="e.g. durations.x=32, timeline.commit_lead=100, ff.default=0:600")
313
+
314
+
315
+ def main(argv: Sequence[str] | None = None) -> int:
316
+ ap = argparse.ArgumentParser(prog="qtiming")
317
+ sub = ap.add_subparsers(dest="cmd", required=True)
318
+ ct = sub.add_parser("contract", help="contract tools").add_subparsers(dest="sub", required=True)
319
+ v = ct.add_parser("validate", help="load and validate contract files")
320
+ v.add_argument("files", nargs="+")
321
+ v.add_argument("--assume", action="append", default=[], metavar="KEY=VALUE")
322
+ for name in ("show", "diff"):
323
+ x = ct.add_parser(name, help=f"{name} contract(s)")
324
+ x.add_argument("files", nargs="+")
325
+ x.add_argument("--assume", action="append", default=[], metavar="KEY=VALUE")
326
+
327
+ c = sub.add_parser("check", help="verify a program against a timing contract")
328
+ _common(c)
329
+ c.add_argument("--policy", choices=["eq", "sync", "exp"],
330
+ help="policy for branches that carry no annotation")
331
+ c.add_argument("--format", choices=["text", "json", "sarif", "html"], default="text")
332
+ c.add_argument("--out", metavar="FILE")
333
+ c.add_argument("--max-safe", metavar="KEY", help="bisect the largest safe hi of a latency")
334
+ c.add_argument("--no-tier1", action="store_true")
335
+ c.add_argument("--no-tier2", action="store_true", help="skip exact SMT (no z3 needed)")
336
+ c.add_argument("--timeout", type=float, default=10.0, help="seconds per SMT query")
337
+ c.add_argument("--first-failure", action="store_true", help="stop at the first REFUTED")
338
+ c.add_argument("--no-window", action="store_true",
339
+ help="never summarise long loops by a window; unroll or fail")
340
+ c.add_argument("--strict-proved", action="store_true",
341
+ help="treat PROVED-UNDER as failure (exit 1)")
342
+
343
+ e = sub.add_parser("explain", help="show the elaborated program, graph and obligations")
344
+ _common(e)
345
+ e.add_argument("--policy", choices=["eq", "sync", "exp"])
346
+ e.add_argument("--elaborated", action="store_true")
347
+ e.add_argument("--obligations", action="store_true")
348
+ e.add_argument("--graph", choices=["dot"])
349
+ e.add_argument("--out", metavar="FILE")
350
+
351
+ li = sub.add_parser("lint", help="front-end and static lint only")
352
+ _common(li)
353
+ li.add_argument("--format", choices=["text", "sarif"], default="text")
354
+ li.add_argument("--out", metavar="FILE")
355
+
356
+ r = sub.add_parser("replay", help="replay a counterexample in the reference executor")
357
+ r.add_argument("cex", help="JSON from `check --format json` (or one counterexample)")
358
+ _common(r)
359
+ r.add_argument("--policy", choices=["eq", "sync", "exp"])
360
+ r.add_argument("--index", type=int, default=0, help="which counterexample of the report")
361
+ r.add_argument("--trace", action="store_true")
362
+
363
+ rp = sub.add_parser("repair", help="suggest delays that fix a REFUTED program (re-verified)")
364
+ _common(rp)
365
+ rp.add_argument("--policy", choices=["eq", "sync", "exp"])
366
+ rp.add_argument("--out", metavar="FILE")
367
+ rp.add_argument("--verbose", action="store_true", help="also print the patched verdict")
368
+
369
+ from qtiming.cli import cmd_evidence
370
+
371
+ cmd_evidence.add_parser(sub)
372
+
373
+ args = ap.parse_args(argv)
374
+ try:
375
+ if args.cmd == "evidence":
376
+ return cmd_evidence.run(args)
377
+ if args.cmd == "repair":
378
+ return _repair(args)
379
+ if args.cmd == "check":
380
+ return _check(args)
381
+ if args.cmd == "explain":
382
+ return _explain(args)
383
+ if args.cmd == "lint":
384
+ return _lint(args)
385
+ if args.cmd == "replay":
386
+ return _replay(args)
387
+ if args.sub in ("show", "diff"):
388
+ return _contract_cmd(args)
389
+ return _validate(args.files, args.assume)
390
+ except KeyboardInterrupt: # pragma: no cover
391
+ return 130
392
+ except Exception as ex: # noqa: BLE001 (exit 4 = internal error, per the CLI reference)
393
+ print(f"internal error: {type(ex).__name__}: {ex}", file=sys.stderr)
394
+ return 4
395
+
396
+
397
+ if __name__ == "__main__":
398
+ raise SystemExit(main())
File without changes
@@ -0,0 +1,49 @@
1
+ """Policy-compatibility relation (Section 7.6): program policy x backend branch class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ POLICIES = ("eq", "sync", "exp")
8
+ CLASSES = ("predicated", "equalized", "resync", "exposed", "restricted")
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Compat:
13
+ kind: str # native | native_if_matched | pad | delays | reject
14
+ note: str
15
+
16
+ @property
17
+ def accepted(self) -> bool:
18
+ return self.kind != "reject"
19
+
20
+
21
+ _T: dict[tuple[str, str], Compat] = {
22
+ ("eq", "predicated"): Compat(
23
+ "native_if_matched",
24
+ "native only when arms match per RT instruction (set_cond waits else_time per skipped "
25
+ "instruction); otherwise EqualizeBranches rewrites arms to equal count and durations"),
26
+ ("eq", "equalized"): Compat("native", "backend equalises arms natively"),
27
+ ("eq", "resync"): Compat(
28
+ "pad", "via padding pass: delay before the branch up to hi, arms padded"),
29
+ ("eq", "exposed"): Compat("delays", "via explicit delays written by the programmer"),
30
+ ("eq", "restricted"): Compat(
31
+ "pad", "via padding pass; only for a single, non-nested if/else"),
32
+ ("sync", "predicated"): Compat(
33
+ "reject", "cannot express a join gap bound; the RT core never resynchronises"),
34
+ ("sync", "equalized"): Compat("reject", "cannot express a join gap bound"),
35
+ ("sync", "resync"): Compat("native", "backend resynchronises at the join"),
36
+ ("sync", "exposed"): Compat("delays", "via explicit resync delay"),
37
+ ("sync", "restricted"): Compat(
38
+ "native", "native for a single if_test; join behaviour is a calibrated parameter"),
39
+ ("exp", "predicated"): Compat("reject", "no exposed timeline on a predicated backend"),
40
+ ("exp", "equalized"): Compat("reject", "no exposed timeline on an equalized backend"),
41
+ ("exp", "resync"): Compat(
42
+ "reject", "implicit aligns remove the exposed cursor"),
43
+ ("exp", "exposed"): Compat("native", "the programmer owns the cursor"),
44
+ ("exp", "restricted"): Compat("reject", "restricted backend has no exposed timeline"),
45
+ }
46
+
47
+
48
+ def compat(policy: str, klass: str) -> Compat:
49
+ return _T[(policy, klass)]
@@ -0,0 +1,30 @@
1
+ # Shipped contract instances
2
+
3
+ Written only from public documentation. Every number carries its source string. Where a number is
4
+ not published it is absent (unbounded, listed in `Contract.missing`) or a flagged placeholder, so a
5
+ verdict depending on it is UNKNOWN or carries the placeholder in its assumption list.
6
+
7
+ ## ibm_heron.toml
8
+ - `dt`, alignments and gate/measure durations come from a Target. The shipped
9
+ `ibm_heron_snapshot.json` is an **unofficial** offline fixture (dt 4 ns; measure 2180 ns,
10
+ measure_2 1380 ns, kingston values from the plan); pass a live Target to replace it.
11
+ - `ff.default`: hi = 600 ns is a **vendor claim**; `lo = 0` is a conservative widening, not a
12
+ measurement. To be replaced by `sched` evidence (plan Section 18).
13
+ - `join_behavior` is a named parameter (vendor class) until calibrated.
14
+ - `dd_inserted_by_backend = "unknown"` (not documented in the sources reviewed).
15
+
16
+ ## q1.toml
17
+ - Trigger-network figures (212-239 ns, 252 ns busy, 149 ns OP+IP) are documented vendor figures
18
+ [verify page path]. 149 + 239 = 388 ns reproduces the documented worked example in ns; after
19
+ outward rounding to dt the same path is 392 ns, and the loader says so (`W-CT-ROUND`).
20
+ - Issue costs are cycle-counted design values (re-verify against the current instruction table).
21
+
22
+ ## artiq.toml
23
+ - `commit_lead` is required but **unpublished**: left absent (`timeline.commit_lead` in
24
+ `Contract.missing`). Supply with `--assume timeline.commit_lead=<ns>`.
25
+ - `in2cpu` has no published upper bound: `hi` absent.
26
+ - `lane_fifo_depth` unknown [verify].
27
+
28
+ ## qua.toml
29
+ - All three `align.*` entries are **placeholders** (illustrative: the docs say only "a few
30
+ cycles"). `active_reset` 224 ns is a vendor claim.
@@ -0,0 +1,45 @@
1
+ [meta]
2
+ name = "artiq_rtio"
3
+ version = "0.2.0"
4
+ schema = "qtiming-contract/0.2"
5
+ personality = "artiq"
6
+
7
+ [timebase]
8
+ dt_ns = "1" # machine unit mu = 1 ns (typical)
9
+ grid = { coarse = 8 } # coarse clock typically 125 MHz = 8 mu
10
+
11
+ [timeline]
12
+ # commit_lead is a REQUIRED but UNPUBLISHED number (minimum slack for an RTIO write to be accepted).
13
+ # Left absent: obligations depending on it are UNKNOWN until the user supplies
14
+ # --assume timeline.commit_lead=...
15
+ late_policy = "mixed" # underflow/overflow: raise; sequence/collision/busy: drop_log
16
+
17
+ [capacity]
18
+ lanes = 8 # SED lanes, gateware parameter sed_lanes (default 8)
19
+ coarse_mu = 8
20
+ sed_spread_enable = false # if true, lane assignment is not deterministic from reset
21
+ lane_fifo_depth = "unknown" # "nearly full" rule needs this; gateware dependent [verify]
22
+
23
+ [[latency]]
24
+ key = "in2cpu" # input event timestamp -> value usable by the kernel CPU
25
+ src = "input"
26
+ dst = "cpu"
27
+ tier = "default"
28
+ lo_ns = 0
29
+ # hi_ns absent: no number published ("low and predictable")
30
+ prov = "vendor"
31
+ source = "ARTIQ manual (no numeric bound)"
32
+
33
+ [issue_cost]
34
+ cpu_issue = { lo_ns = 0, prov = { prov = "vendor", source = "none published; kernel-compiler dependent" } }
35
+
36
+ [branch]
37
+ class = "exposed"
38
+ default_policy = "exp"
39
+
40
+ [idle]
41
+ max_gap_variation_ns = { default = 0 }
42
+ dd_inserted_by_backend = "unknown"
43
+
44
+ [loop]
45
+ while_supported = true
@@ -0,0 +1,62 @@
1
+ [meta]
2
+ name = "ibm_heron"
3
+ version = "0.2.0"
4
+ schema = "qtiming-contract/0.2"
5
+ personality = "ibm"
6
+
7
+ [target]
8
+ # Offline snapshot so CI needs no network. Pass a live Target to load_contract() to override.
9
+ # The snapshot is UNOFFICIAL (fixture only); see README.md in this directory.
10
+ source = "snapshot:ibm_heron_snapshot.json"
11
+ backend = "ibm_kingston"
12
+ import = ["dt", "alignments", "durations"]
13
+
14
+ [timebase]
15
+ dt_ns = "from_target"
16
+ latency_resolution = "continuous"
17
+
18
+ [timeline]
19
+ late_policy = "compile_error"
20
+ # commit_lead: IBM does not expose a commit model; not required for this personality
21
+
22
+ [durations]
23
+ # gate, measure and measure_2 durations come from the Target; they differ per backend.
24
+ import_from_target = true
25
+
26
+ [[latency]]
27
+ key = "ff.default"
28
+ src = "measure"
29
+ dst = "branch"
30
+ tier = "default"
31
+ lo_ns = 0 # conservative placeholder: no lower bound is published
32
+ hi_ns = 600
33
+ data_dependent = false
34
+ prov = "vendor"
35
+ source = "IBM blog, 2025-11-19 (feedforward about 600 ns); vendor claim, not a certified bound"
36
+
37
+ [branch]
38
+ class = "restricted"
39
+ default_policy = "sync"
40
+ allow_nested = false
41
+ allow_measure_in_branch = false
42
+ allow_loops = false
43
+ max_cond_bits = 32
44
+
45
+ [capacity]
46
+ instr_per_qubit = 26_800_000
47
+ broadcast_budget = { wide_60bit = 300, narrow_1bit = 2400 } # approximate job limits, verify at release
48
+
49
+ [personality_params.ibm]
50
+ # Join behaviour for unequal if/else arms.
51
+ # "pad_to_longest_block": both arms padded to the longest block (documented for the OLD
52
+ # fast-path stack, qiskit-ibm-runtime <= 0.39 only)
53
+ # "restart_at_join": each arm ends when it ends; the next block restarts at the join
54
+ join_behavior = "pad_to_longest_block"
55
+ join_behavior_prov = { prov = "vendor", source = "old fast-path stack docs; to be calibrated from scheduler_timing evidence (plan Section 18)" }
56
+
57
+ [idle]
58
+ max_gap_variation_ns = { default = 0 }
59
+ dd_inserted_by_backend = "unknown"
60
+
61
+ [loop]
62
+ while_supported = false
@@ -0,0 +1,22 @@
1
+ {
2
+ "backend": "ibm_kingston",
3
+ "unofficial": true,
4
+ "note": "UNOFFICIAL snapshot: values copied from the plan's Heron r2 notes; fixture only, not vendor-certified. Gate durations x, sx, h, z, cx, cz are ILLUSTRATIVE (plan Appendix A.1), not read from a Target.",
5
+ "dt_ns": "4",
6
+ "alignments": {
7
+ "acquire": 1,
8
+ "pulse": 1,
9
+ "granularity": 1
10
+ },
11
+ "durations_ns": {
12
+ "measure": "2180",
13
+ "measure_2": "1380",
14
+ "x": "32",
15
+ "sx": "32",
16
+ "h": "32",
17
+ "z": "32",
18
+ "cx": "80",
19
+ "cz": "68",
20
+ "reset": "1000"
21
+ }
22
+ }