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
@@ -0,0 +1,360 @@
1
+ """Elaboration (plan 8): make each branch's timing policy explicit program structure.
2
+
3
+ EQ inserts a barrier, a wait of `hi` and arm padding; SYNC adds a join where the personality has
4
+ none; EXP keeps the programmer's delays; loops are unrolled with fresh proposition names.
5
+ Elaboration is not verification: it inserts statements, it never decides safety. The output is
6
+ itself valid TQ and elaborating it again changes nothing (idempotence, plan 8.9): an elaborated
7
+ `If` carries `origin_nid` and is left alone.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, replace
13
+ from typing import Any
14
+
15
+ from qtiming.contract.compat import compat
16
+ from qtiming.contract.model import Contract
17
+ from qtiming.core.ast import (
18
+ Assign,
19
+ Barrier,
20
+ Box,
21
+ Call,
22
+ Delay,
23
+ For,
24
+ Gate,
25
+ If,
26
+ Measure,
27
+ Policy,
28
+ Reset,
29
+ Seq,
30
+ Stmt,
31
+ Switch,
32
+ While,
33
+ Within,
34
+ )
35
+ from qtiming.core.errors import QtError
36
+ from qtiming.core.ids import bit_prop
37
+ from qtiming.core.labels import Derived, EBin, EBit, EUn, Expr
38
+ from qtiming.frontend.payload import parse_within, to_dt
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class ElabProgram:
43
+ body: Stmt
44
+ derived: tuple[Derived, ...]
45
+ first_ops: dict[int, dict[int, tuple[int, ...]]] # within nid -> qubit -> first-op nids
46
+ within: dict[int, tuple[int, str]] # within nid -> (deadline dt, anchor proposition)
47
+ hard: frozenset[int] # within nids whose box carries timing.hard
48
+ missing: frozenset[str] # contract keys needed but unbounded (dependants are UNKNOWN)
49
+ policy_map: dict[int, Policy] # effective policy per branch nid
50
+ contract_sha256: str
51
+
52
+
53
+ def _children(s: Stmt) -> list[Stmt]:
54
+ out: list[Stmt] = []
55
+ for f in ("stmts", "body", "then_", "else_", "default", "exhaust"):
56
+ v = getattr(s, f, None)
57
+ if isinstance(v, tuple):
58
+ out += [x for x in v if isinstance(x, Stmt.__args__)] # type: ignore[attr-defined]
59
+ elif v is not None and isinstance(v, Stmt.__args__): # type: ignore[attr-defined]
60
+ out.append(v)
61
+ return out
62
+
63
+
64
+ def _max_nid(s: Stmt) -> int:
65
+ return max([s.nid, *(_max_nid(c) for c in _children(s))])
66
+
67
+
68
+ def _props(e: Expr) -> list[str]:
69
+ if isinstance(e, EBit):
70
+ return [e.prop]
71
+ if isinstance(e, EUn):
72
+ return _props(e.a)
73
+ if isinstance(e, EBin):
74
+ return _props(e.a) + _props(e.b)
75
+ return []
76
+
77
+
78
+ def _subst(e: Expr, m: dict[str, str]) -> Expr:
79
+ if isinstance(e, EBit):
80
+ return EBit(m.get(e.prop, e.prop))
81
+ if isinstance(e, EUn):
82
+ return EUn(e.op, _subst(e.a, m))
83
+ if isinstance(e, EBin):
84
+ return EBin(e.op, _subst(e.a, m), _subst(e.b, m))
85
+ return e
86
+
87
+
88
+ def qubits_of(s: Stmt | None) -> set[int]:
89
+ if s is None:
90
+ return set()
91
+ if isinstance(s, (Gate, Delay, Barrier)):
92
+ return set(s.qubits)
93
+ if isinstance(s, (Measure, Reset)):
94
+ return {s.qubit}
95
+ return set().union(*(qubits_of(c) for c in _children(s))) if _children(s) else set()
96
+
97
+
98
+ class Elaborator:
99
+ def __init__(self, contract: Contract, unroll_limit: int = 64) -> None:
100
+ self.c = contract
101
+ self.limit = unroll_limit
102
+ self.next = 0
103
+ self.meas: dict[str, Measure] = {}
104
+ self.missing: set[str] = set()
105
+ self.policy_map: dict[int, Policy] = {}
106
+ self.first_ops: dict[int, dict[int, tuple[int, ...]]] = {}
107
+ self.within: dict[int, tuple[int, str]] = {}
108
+ self.hard: set[int] = set()
109
+ self.last_write: dict[tuple[str, int], str] = {}
110
+
111
+ def fresh(self) -> int:
112
+ self.next += 1
113
+ return self.next
114
+
115
+ # -- cloning with fresh ids (loop unrolling) ----------------------------------------
116
+ def clone(self, s: Stmt, m: dict[str, str]) -> Stmt:
117
+ kw: dict[str, Any] = {"nid": self.fresh(), "origin_nid": s.origin_nid or s.nid}
118
+ if isinstance(s, Measure):
119
+ m[bit_prop(s.cbit.reg, s.cbit.idx, s.nid)] = bit_prop(s.cbit.reg, s.cbit.idx,
120
+ kw["nid"])
121
+ return replace(s, **kw)
122
+ if isinstance(s, Seq):
123
+ return replace(s, stmts=tuple(self.clone(x, m) for x in s.stmts), **kw)
124
+ if isinstance(s, (Box, Within, For)):
125
+ return replace(s, body=self.clone(s.body, m), **kw)
126
+ if isinstance(s, If):
127
+ kw["origin_nid"] = None # set only on ELABORATED Ifs: elab_if skips those
128
+ return replace(s, cond=_subst(s.cond, m), then_=self.clone(s.then_, m),
129
+ else_=self.clone(s.else_, m) if s.else_ else None, **kw)
130
+ if isinstance(s, While):
131
+ return replace(s, cond=_subst(s.cond, m), body=self.clone(s.body, m),
132
+ exhaust=self.clone(s.exhaust, m), **kw)
133
+ return replace(s, **kw)
134
+
135
+ # -- static durations of elaborated statements --------------------------------------
136
+ def dur(self, s: Stmt | None) -> dict[int, int]:
137
+ clock: dict[int, int] = {}
138
+
139
+ def go(x: Stmt) -> None:
140
+ if isinstance(x, Seq):
141
+ for y in x.stmts:
142
+ go(y)
143
+ elif isinstance(x, (Box, Within)):
144
+ go(x.body)
145
+ elif isinstance(x, (Gate, Delay)):
146
+ st = max(clock.get(q, 0) for q in x.qubits)
147
+ for q in x.qubits:
148
+ clock[q] = st + x.dur
149
+ elif isinstance(x, Measure):
150
+ d = self.c.duration("measure_2" if x.variant == "mid" else "measure")
151
+ clock[x.qubit] = clock.get(x.qubit, 0) + d
152
+ elif isinstance(x, Barrier):
153
+ j = max((clock.get(q, 0) for q in x.qubits), default=0)
154
+ for q in x.qubits:
155
+ clock[q] = j
156
+ elif isinstance(x, If) and x.origin_nid is not None:
157
+ a, b = self.dur(x.then_), self.dur(x.else_) # elaborated EQ block: equal arms
158
+ if a != b:
159
+ raise QtError("E-ELAB-EQ-VARIABLE-ARM", "nested block has unequal arms", x.loc)
160
+ st = max((clock.get(q, 0) for q in a), default=0)
161
+ for q, d in a.items():
162
+ clock[q] = st + d
163
+ else:
164
+ raise QtError("E-ELAB-EQ-VARIABLE-ARM",
165
+ f"EQ cannot equalise an arm containing {type(x).__name__}", x.loc)
166
+
167
+ if s is not None:
168
+ go(s)
169
+ return clock
170
+
171
+ # -- main ---------------------------------------------------------------------------
172
+ def elab(self, s: Stmt, m: dict[str, str]) -> Stmt:
173
+ if isinstance(s, Measure):
174
+ prop = bit_prop(s.cbit.reg, s.cbit.idx, s.nid)
175
+ self.meas[prop] = s
176
+ self.last_write[(s.cbit.reg, s.cbit.idx)] = prop
177
+ return s
178
+ if isinstance(s, (Gate, Delay, Barrier, Reset)):
179
+ return s
180
+ if isinstance(s, Seq):
181
+ return replace(s, stmts=tuple(self.elab(x, m) for x in s.stmts))
182
+ if isinstance(s, Box):
183
+ body = self.elab(s.body, m)
184
+ anns = dict(s.annotations)
185
+ if "within" in anns: # the front end validated it; here it becomes a deadline
186
+ dur, anchor = parse_within(anns["within"])
187
+ w = Within(nid=s.nid, loc=s.loc, deadline=to_dt(dur, self.c.dt_ns, "deadline"),
188
+ anchor=anchor, body=body)
189
+ self.record_within(w, body)
190
+ if "hard" in anns:
191
+ self.hard.add(w.nid)
192
+ return replace(s, body=body)
193
+ if isinstance(s, Within):
194
+ body = self.elab(s.body, m)
195
+ self.record_within(s, body)
196
+ return body
197
+ if isinstance(s, For):
198
+ if s.n > self.limit:
199
+ raise QtError("E-ELAB-LOOP-LIMIT",
200
+ f"for loop of {s.n} > unroll limit {self.limit}", s.loc,
201
+ hint="raise the unroll limit, or omit --no-window (IBM windowing)")
202
+ out = tuple(self.elab(self.clone(s.body, m), m) for _ in range(s.n))
203
+ return Seq(nid=self.fresh(), loc=s.loc, stmts=out, origin_nid=s.nid)
204
+ if isinstance(s, While):
205
+ return self.elab_while(s, m)
206
+ if isinstance(s, If):
207
+ return self.elab_if(s, m)
208
+ if isinstance(s, (Assign, Switch, Call)):
209
+ raise QtError("E-ELAB-UNSUPPORTED", f"{type(s).__name__} is not elaborated yet", s.loc)
210
+ raise QtError("E-ELAB-UNSUPPORTED", type(s).__name__) # pragma: no cover
211
+
212
+ def record_within(self, s: Within, body: Stmt) -> None:
213
+ anchor = self.last_write.get((s.anchor.reg, s.anchor.idx))
214
+ if anchor is None:
215
+ raise QtError("E-ELAB-WITHIN-ANCHOR",
216
+ f"within anchor {s.anchor.reg}[{s.anchor.idx}] is never written", s.loc)
217
+ self.within[s.nid] = (s.deadline, anchor)
218
+ firsts: dict[int, list[int]] = {}
219
+ self._firsts(body, firsts, set(), False)
220
+ self.first_ops[s.nid] = {q: tuple(v) for q, v in firsts.items()}
221
+
222
+ def _firsts(self, s: Stmt, out: dict[int, list[int]], seen: set[int], in_arm: bool) -> None:
223
+ """First USER operation per qubit; both arms of a branch are alternatives. Synthesised
224
+ prefix delays and barriers are skipped; padding inside an arm counts (plan A.3)."""
225
+ if isinstance(s, Seq):
226
+ for x in s.stmts:
227
+ self._firsts(x, out, seen, in_arm)
228
+ elif isinstance(s, (Gate, Delay, Measure)):
229
+ if isinstance(s, Delay) and s.origin_nid is not None and not in_arm:
230
+ return
231
+ for q in (s.qubits if not isinstance(s, Measure) else (s.qubit,)):
232
+ if q not in seen:
233
+ out.setdefault(q, []).append(s.nid)
234
+ seen.add(q)
235
+ elif isinstance(s, If):
236
+ merged = set(seen)
237
+ for arm in (s.then_, s.else_):
238
+ if arm is not None:
239
+ sa = set(seen)
240
+ self._firsts(arm, out, sa, True)
241
+ merged |= sa
242
+ seen |= merged
243
+
244
+ def elab_while(self, s: While, m: dict[str, str]) -> Stmt:
245
+ """Capped while as nested ifs: iteration j exists only if iterations < j all looped."""
246
+ if s.cap > self.limit:
247
+ raise QtError("E-ELAB-LOOP-LIMIT", f"while cap {s.cap} > unroll limit {self.limit}",
248
+ s.loc)
249
+ cur = dict(m)
250
+ # The condition names the bit's measurement BEFORE the loop. A body that re-measures the
251
+ # bit writes a new proposition each iteration, which `clone` only remaps under the body
252
+ # measurement's own id; so iteration j+1 must read the bit's latest write, or every
253
+ # unrolled iteration tests the stale pre-loop outcome (contradictory nested arms).
254
+ locs = {p: (self.meas[p].cbit.reg, self.meas[p].cbit.idx)
255
+ for p in _props(s.cond) if p in self.meas}
256
+
257
+ def rec(j: int) -> Stmt:
258
+ latest = {p: self.last_write[loc] for p, loc in locs.items()
259
+ if j > 0 and loc in self.last_write}
260
+ cond = _subst(s.cond, {**cur, **latest})
261
+ if j == s.cap:
262
+ then: Stmt = self.elab(self.clone(s.exhaust, cur), cur)
263
+ else:
264
+ body = self.elab(self.clone(s.body, cur), cur)
265
+ then = Seq(nid=self.fresh(), loc=s.loc, stmts=(body, rec(j + 1)), origin_nid=s.nid)
266
+ return self.elab_if(
267
+ If(nid=self.fresh(), loc=s.loc, cond=cond, then_=then, else_=None,
268
+ policy=s.policy), cur)
269
+
270
+ return rec(0)
271
+
272
+ def elab_if(self, s: If, m: dict[str, str]) -> Stmt:
273
+ if s.origin_nid is not None: # already elaborated: idempotence
274
+ return s
275
+ then_ = self.elab(s.then_, m)
276
+ else_ = self.elab(s.else_, m) if s.else_ else None
277
+ pol = s.policy or Policy(self.c.branch.default_policy) # type: ignore[arg-type]
278
+ cp = compat(pol.kind, self.c.branch.klass)
279
+ if not cp.accepted:
280
+ raise QtError("E-ELAB-POLICY-REJECTED",
281
+ f"policy {pol.kind!r} is not accepted on {self.c.branch.klass} "
282
+ f"backends: {cp.note}", s.loc)
283
+ self.policy_map[s.nid] = pol
284
+ node = replace(s, then_=then_, else_=else_, policy=pol, origin_nid=s.nid)
285
+ res = sorted(qubits_of(then_) | qubits_of(else_))
286
+ if pol.kind == "eq" and self.c.personality != "artiq":
287
+ return self.eq(node, res)
288
+ if pol.kind == "sync" and self.c.personality == "qua": # QUA joins only via align
289
+ return Seq(nid=self.fresh(), loc=s.loc, origin_nid=s.nid, stmts=(
290
+ node, Barrier(nid=self.fresh(), loc=s.loc, qubits=tuple(res), origin_nid=s.nid)))
291
+ return node # ibm: the block model joins; artiq/exp: the programmer's delays decide
292
+
293
+ def eq(self, node: If, res: list[int]) -> Stmt:
294
+ loc, org = node.loc, node.nid
295
+ w, meas_res = 0, set()
296
+ for p in dict.fromkeys(_props(node.cond)):
297
+ mm = self.meas.get(p)
298
+ if mm is None:
299
+ raise QtError("E-ELAB-UNBOUND", f"condition reads {p!r} before a measurement", loc)
300
+ cl = self.c.find_latency("measure", "branch", mm.tier)
301
+ meas_res.add(mm.qubit)
302
+ if cl.latency.iv.hi is None: # unbounded: wait lo, dependants become UNKNOWN
303
+ self.missing.add(cl.latency.key)
304
+ w = max(w, cl.latency.iv.lo if cl.latency.iv.hi is None else cl.latency.iv.hi)
305
+ if self.c.personality == "q1":
306
+ self.q1_equalisable(node)
307
+ then_, else_ = node.then_, node.else_
308
+ else:
309
+ da, db = self.dur(node.then_), self.dur(node.else_)
310
+ d = {r: max(da.get(r, 0), db.get(r, 0)) for r in res}
311
+
312
+ def pad(arm: Stmt | None, got: dict[int, int]) -> Stmt:
313
+ extra = tuple(
314
+ Delay(nid=self.fresh(), loc=loc, qubits=(r,), dur=d[r] - got.get(r, 0),
315
+ declared=True, origin_nid=org)
316
+ for r in res if d[r] > got.get(r, 0))
317
+ return Seq(nid=self.fresh(), loc=loc, origin_nid=org,
318
+ stmts=((arm,) if arm is not None else ()) + extra)
319
+
320
+ then_, else_ = pad(node.then_, da), pad(node.else_, db)
321
+ prefix: list[Stmt] = [Barrier(nid=self.fresh(), loc=loc,
322
+ qubits=tuple(sorted(set(res) | meas_res)), origin_nid=org)]
323
+ if w:
324
+ prefix += [Delay(nid=self.fresh(), loc=loc, qubits=(r,), dur=w, declared=True,
325
+ origin_nid=org) for r in res]
326
+ return Seq(nid=self.fresh(), loc=loc, origin_nid=org,
327
+ stmts=(*prefix, replace(node, then_=then_, else_=else_)))
328
+
329
+ def q1_equalisable(self, node: If) -> None:
330
+ """Q1 per-instruction timeline (plan 8.5): the two outcome totals must agree."""
331
+ def instrs(s: Stmt | None) -> list[int]:
332
+ if s is None:
333
+ return []
334
+ if isinstance(s, (Gate, Delay)):
335
+ return [s.dur]
336
+ if isinstance(s, Barrier):
337
+ return []
338
+ if isinstance(s, (Seq, Box)):
339
+ return [d for c in _children(s) for d in instrs(c)]
340
+ raise QtError("E-ELAB-Q1-NOT-EQUALISABLE",
341
+ f"Q1 arms may only hold RT instructions, found {type(s).__name__}",
342
+ s.loc)
343
+
344
+ e = int(self.c.param("q1", "else_time_dt", 1)) # type: ignore[call-overload]
345
+ a, b = instrs(node.then_), instrs(node.else_)
346
+ t_true, t_false = sum(a) + len(b) * e, len(a) * e + sum(b)
347
+ if t_true != t_false:
348
+ raise QtError(
349
+ "E-ELAB-Q1-NOT-EQUALISABLE",
350
+ f"arm totals differ: {t_true} dt when true, {t_false} dt when false", node.loc,
351
+ hint="match RT instruction counts and durations, or use policy sync/exp",
352
+ )
353
+
354
+
355
+ def elaborate(prog: Stmt, contract: Contract, *, unroll_limit: int = 64) -> ElabProgram:
356
+ el = Elaborator(contract, unroll_limit)
357
+ el.next = _max_nid(prog)
358
+ body = el.elab(prog, {})
359
+ return ElabProgram(body, (), el.first_ops, el.within, frozenset(el.hard),
360
+ frozenset(el.missing), el.policy_map, contract.sha256)
@@ -0,0 +1,15 @@
1
+ """Evidence ingestion (plan 7.7, 18.3): raw IBM `scheduler_timing` job files -> contract patch."""
2
+
3
+ from .ingest import (
4
+ EvidenceError,
5
+ Job,
6
+ apply_patch,
7
+ build_patch,
8
+ emit_toml,
9
+ ingest,
10
+ load_job,
11
+ report,
12
+ )
13
+
14
+ __all__ = ["EvidenceError", "Job", "apply_patch", "build_patch", "emit_toml", "ingest", "load_job",
15
+ "report"]
@@ -0,0 +1,235 @@
1
+ """Job schema `qtiming-evidence-job/1` (documented in experiments/ibm_dryrun/README.md).
2
+
3
+ Stdlib only. Output is byte-reproducible: sorted keys, no generation timestamp, the SHA-256 of
4
+ every input recorded. Values read from a schedule are provenance class `sched` (plan decision 15).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import hashlib
11
+ import json
12
+ from dataclasses import dataclass
13
+ from decimal import Decimal, InvalidOperation
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ JOB_SCHEMA = "qtiming-evidence-job/1"
18
+ PATCH_SCHEMA = "qtiming-evidence-patch/1"
19
+ _REQ = ("schema", "job_id", "backend", "runtime_version", "qiskit_version", "circuit_qpy_sha256",
20
+ "submitted_date", "dry_run", "family", "dt_ns", "scheduler_timing")
21
+ _INSTR = ("name", "qubits", "start_dt", "stop_dt", "block_id")
22
+
23
+
24
+ class EvidenceError(ValueError):
25
+ pass
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Job:
30
+ path: str
31
+ sha256: str
32
+ d: dict[str, Any]
33
+
34
+ @property
35
+ def synthetic(self) -> bool:
36
+ return self.d.get("synthetic") is True
37
+
38
+ @property
39
+ def dt(self) -> Decimal:
40
+ return Decimal(self.d["dt_ns"])
41
+
42
+ @property
43
+ def instrs(self) -> list[dict[str, Any]]:
44
+ return self.d["scheduler_timing"]["instructions"]
45
+
46
+
47
+ def load_job(path: str) -> Job:
48
+ data = Path(path).read_bytes()
49
+ try:
50
+ d = json.loads(data)
51
+ except ValueError as e:
52
+ raise EvidenceError(f"{path}: not JSON ({e})") from e
53
+ miss = [k for k in _REQ if k not in d] if isinstance(d, dict) else list(_REQ)
54
+ if miss:
55
+ raise EvidenceError(f"{path}: missing fields {miss}")
56
+ if d["schema"] != JOB_SCHEMA:
57
+ raise EvidenceError(f"{path}: schema {d['schema']!r}, expected {JOB_SCHEMA!r}")
58
+ if d["dry_run"] is not True:
59
+ raise EvidenceError(f"{path}: dry_run is not true; refusing non-dry-run evidence")
60
+ try:
61
+ if Decimal(d["dt_ns"]) <= 0:
62
+ raise InvalidOperation
63
+ except (InvalidOperation, TypeError) as e:
64
+ raise EvidenceError(f"{path}: dt_ns must be a positive decimal string") from e
65
+ st = d["scheduler_timing"]
66
+ ins = st.get("instructions") if isinstance(st, dict) else None
67
+ if not isinstance(ins, list) or any(
68
+ not isinstance(i, dict) or any(k not in i for k in _INSTR) for i in ins):
69
+ raise EvidenceError(f"{path}: scheduler_timing.instructions needs fields {list(_INSTR)}")
70
+ return Job(path, hashlib.sha256(data).hexdigest(), d)
71
+
72
+
73
+ def _ns(x: Decimal) -> str:
74
+ return format(x.normalize(), "f")
75
+
76
+
77
+ def _is_measure(i: dict[str, Any]) -> bool:
78
+ return str(i["name"]).startswith("measure")
79
+
80
+
81
+ def _blocks(job: Job) -> dict[Any, list[dict[str, Any]]]:
82
+ out: dict[Any, list[dict[str, Any]]] = {}
83
+ for i in job.instrs:
84
+ if i["block_id"] is not None:
85
+ out.setdefault(i["block_id"], []).append(i)
86
+ return out
87
+
88
+
89
+ def derive_ff(job: Job) -> list[Decimal]:
90
+ """Per conditional block: first block start minus end of the latest earlier measure (ns)."""
91
+ obs = []
92
+ for bid, ins in _blocks(job).items():
93
+ start = min(i["start_dt"] for i in ins)
94
+ ends = [i["stop_dt"] for i in job.instrs if _is_measure(i) and i["stop_dt"] <= start]
95
+ if not ends:
96
+ raise EvidenceError(f"{job.path}: block {bid} has no preceding measure")
97
+ obs.append((start - max(ends)) * job.dt)
98
+ return obs
99
+
100
+
101
+ def derive_join(job: Job) -> str | None:
102
+ """'pad' / 'restart' for an unequal-arm job; None if the job cannot tell them apart."""
103
+ arms = job.d.get("arms")
104
+ if not arms or arms["then_dt"] == arms["else_dt"]:
105
+ return None
106
+ longest, taken = max(arms["then_dt"], arms["else_dt"]), arms[f"{arms['taken']}_dt"]
107
+ if taken == longest:
108
+ return None # both models predict the same block length
109
+ (ins,) = _blocks(job).values()
110
+ extent = max(i["stop_dt"] for i in ins) - min(i["start_dt"] for i in ins)
111
+ return "pad" if extent == longest else "restart" if extent == taken else "other"
112
+
113
+
114
+ def build_patch(jobs: list[Job], *, allow_synthetic: bool = False) -> dict[str, Any]:
115
+ if not jobs:
116
+ raise EvidenceError("no job files given")
117
+ synth = [j.path for j in jobs if j.synthetic]
118
+ if synth and not allow_synthetic:
119
+ raise EvidenceError(f"synthetic job(s) {synth}: pass allow_synthetic to ingest test data")
120
+ ids = [j.d["job_id"] for j in jobs]
121
+ if len(set(ids)) != len(ids):
122
+ raise EvidenceError("duplicate job_id among inputs")
123
+ jobs = sorted(jobs, key=lambda j: (j.d["job_id"], j.sha256))
124
+ tag = "SYNTHETIC TEST DATA, not hardware; " if synth else ""
125
+ who = (f"backends={sorted({j.d['backend'] for j in jobs})} "
126
+ f"runtime={sorted({j.d['runtime_version'] for j in jobs})}")
127
+
128
+ groups: dict[tuple[str, str], list[tuple[Job, Decimal]]] = {}
129
+ for j in jobs:
130
+ tier = j.d.get("tier", "default")
131
+ key = j.d.get("latency_key") or f"ff.{tier}"
132
+ for o in derive_ff(j):
133
+ groups.setdefault((key, tier), []).append((j, o))
134
+ lats = []
135
+ for (key, tier), obs in sorted(groups.items()):
136
+ vals = [o for _, o in obs]
137
+ n = len({j.d["job_id"] for j, _ in obs})
138
+ lats.append({"key": key, "src": "measure", "dst": "branch", "tier": tier,
139
+ "lo_ns": _ns(min(vals)), "hi_ns": _ns(max(vals)), "data_dependent": False,
140
+ "prov": "sched", "n": n,
141
+ "source": f"{tag}scheduler_timing dry_run jobs, n={n}; min/max; {who}"})
142
+
143
+ votes = [v for v in (derive_join(j) for j in jobs) if v is not None]
144
+ ibm: dict[str, Any] = {}
145
+ if votes and len(set(votes)) == 1 and votes[0] in ("pad", "restart"):
146
+ ibm["join_behavior"] = "pad_to_longest_block" if votes[0] == "pad" else "restart_at_join"
147
+ ibm["join_behavior_prov"] = {
148
+ "prov": "sched",
149
+ "source": f"{tag}{len(votes)} unequal-arm job(s) all show {votes[0]}; {who}"}
150
+ elif votes: # conflicting or unrecognised: record the result, do not choose
151
+ ibm["join_behavior_prov"] = {
152
+ "prov": "vendor",
153
+ "source": f"{tag}inconclusive: unequal-arm jobs gave {sorted(votes)}; "
154
+ f"join_behavior left unchanged; {who}"}
155
+
156
+ patch: dict[str, Any] = {"patch": {"schema": PATCH_SCHEMA, "synthetic": bool(synth)}}
157
+ if lats:
158
+ patch["latency"] = lats
159
+ if ibm:
160
+ patch["personality_params"] = {"ibm": ibm}
161
+ patch["evidence"] = [
162
+ {"job_id": j.d["job_id"], "file": Path(j.path).name, "sha256": j.sha256,
163
+ "backend": j.d["backend"], "family": j.d["family"],
164
+ "runtime_version": j.d["runtime_version"], **({"synthetic": True} if j.synthetic else {})}
165
+ for j in jobs]
166
+ return patch
167
+
168
+
169
+ def _val(v: Any) -> str:
170
+ if isinstance(v, bool):
171
+ return "true" if v else "false"
172
+ if isinstance(v, int):
173
+ return str(v)
174
+ if isinstance(v, str):
175
+ return json.dumps(v)
176
+ raise EvidenceError(f"cannot emit {type(v).__name__} as TOML")
177
+
178
+
179
+ def emit_toml(d: dict[str, Any]) -> str:
180
+ """Minimal deterministic TOML: scalars, nested tables, arrays of tables; sorted keys."""
181
+ out: list[str] = []
182
+
183
+ def table(t: dict[str, Any], path: tuple[str, ...], aot: bool) -> None:
184
+ scal = [k for k in sorted(t) if not isinstance(t[k], (dict, list))]
185
+ if path and (scal or not any(isinstance(v, (dict, list)) for v in t.values())):
186
+ out.extend(["", f"[[{'.'.join(path)}]]" if aot else f"[{'.'.join(path)}]"])
187
+ out.extend(f"{k} = {_val(t[k])}" for k in scal)
188
+ for k in sorted(t):
189
+ if isinstance(t[k], dict):
190
+ table(t[k], (*path, k), False)
191
+ elif isinstance(t[k], list):
192
+ for item in t[k]:
193
+ table(item, (*path, k), True)
194
+
195
+ table(d, (), False)
196
+ return "\n".join(out).lstrip("\n") + "\n"
197
+
198
+
199
+ def ingest(files: list[str | Path], *, allow_synthetic: bool = False) -> str:
200
+ jobs = [load_job(str(f)) for f in files]
201
+ return emit_toml(build_patch(jobs, allow_synthetic=allow_synthetic))
202
+
203
+
204
+ def report(files: list[str | Path]) -> str:
205
+ jobs = [load_job(str(f)) for f in files]
206
+ lines = ["job_id family backend observed_ff_ns join"]
207
+ for j in sorted(jobs, key=lambda j: j.d["job_id"]):
208
+ ff = ",".join(_ns(o) for o in derive_ff(j))
209
+ lines.append(f"{j.d['job_id']} {j.d['family']} {j.d['backend']} {ff} "
210
+ f"{derive_join(j) or '-'}{' [SYNTHETIC]' if j.synthetic else ''}")
211
+ return "\n".join(lines) + "\n"
212
+
213
+
214
+ def apply_patch(contract: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
215
+ """New contract dict: latencies replaced by key (or appended), params merged, evidence added."""
216
+ out = copy.deepcopy(contract)
217
+ lats = out.setdefault("latency", [])
218
+ for new in copy.deepcopy(patch.get("latency", [])):
219
+ for i, old in enumerate(lats):
220
+ if old.get("key") == new["key"]:
221
+ lats[i] = new
222
+ break
223
+ else:
224
+ lats.append(new)
225
+
226
+ def merge(dst: dict[str, Any], src: dict[str, Any]) -> None:
227
+ for k, v in src.items():
228
+ if isinstance(v, dict) and isinstance(dst.get(k), dict):
229
+ merge(dst[k], v)
230
+ else:
231
+ dst[k] = copy.deepcopy(v)
232
+
233
+ merge(out.setdefault("personality_params", {}), patch.get("personality_params", {}))
234
+ out.setdefault("evidence", []).extend(copy.deepcopy(patch.get("evidence", [])))
235
+ return out
File without changes