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.
- qtiming/__init__.py +0 -0
- qtiming/bench/__init__.py +327 -0
- qtiming/bench/diff.py +230 -0
- qtiming/bench/report.py +161 -0
- qtiming/bench/truth.py +88 -0
- qtiming/cli/__init__.py +0 -0
- qtiming/cli/cmd_evidence.py +35 -0
- qtiming/cli/main.py +398 -0
- qtiming/contract/__init__.py +0 -0
- qtiming/contract/compat.py +49 -0
- qtiming/contract/instances/README.md +30 -0
- qtiming/contract/instances/artiq.toml +45 -0
- qtiming/contract/instances/ibm_heron.toml +62 -0
- qtiming/contract/instances/ibm_heron_snapshot.json +22 -0
- qtiming/contract/instances/q1.toml +88 -0
- qtiming/contract/instances/qua.toml +65 -0
- qtiming/contract/loader.py +355 -0
- qtiming/contract/model.py +123 -0
- qtiming/contract/schema.py +106 -0
- qtiming/contract/target_import.py +46 -0
- qtiming/core/__init__.py +0 -0
- qtiming/core/ast.py +140 -0
- qtiming/core/errors.py +36 -0
- qtiming/core/ids.py +34 -0
- qtiming/core/labels.py +121 -0
- qtiming/core/provenance.py +77 -0
- qtiming/core/time.py +96 -0
- qtiming/dispatch/__init__.py +22 -0
- qtiming/dispatch/artiq.py +70 -0
- qtiming/dispatch/ibm.py +83 -0
- qtiming/dispatch/q1.py +102 -0
- qtiming/dispatch/qua.py +88 -0
- qtiming/elab/__init__.py +360 -0
- qtiming/evidence/__init__.py +15 -0
- qtiming/evidence/ingest.py +235 -0
- qtiming/exec/__init__.py +0 -0
- qtiming/exec/artiq.py +100 -0
- qtiming/exec/engine.py +235 -0
- qtiming/exec/explore.py +43 -0
- qtiming/exec/ibm.py +117 -0
- qtiming/exec/oracle.py +88 -0
- qtiming/exec/q1.py +95 -0
- qtiming/exec/qua.py +95 -0
- qtiming/frontend/__init__.py +40 -0
- qtiming/frontend/_shared.py +149 -0
- qtiming/frontend/annotations.py +81 -0
- qtiming/frontend/lint.py +116 -0
- qtiming/frontend/payload.py +113 -0
- qtiming/frontend/program.py +51 -0
- qtiming/frontend/qasm3_fe.py +341 -0
- qtiming/frontend/qiskit_expr.py +89 -0
- qtiming/frontend/qiskit_fe.py +220 -0
- qtiming/frontend/serialise.py +63 -0
- qtiming/frontend/stretch.py +71 -0
- qtiming/graph/__init__.py +0 -0
- qtiming/graph/builder.py +245 -0
- qtiming/graph/export.py +25 -0
- qtiming/graph/invariants.py +67 -0
- qtiming/graph/lteg.py +153 -0
- qtiming/graph/window.py +120 -0
- qtiming/oblig/__init__.py +0 -0
- qtiming/oblig/generate.py +145 -0
- qtiming/oblig/model.py +76 -0
- qtiming/py.typed +0 -0
- qtiming/qiskit_pass/__init__.py +7 -0
- qtiming/qiskit_pass/_common.py +21 -0
- qtiming/qiskit_pass/equalize.py +171 -0
- qtiming/qiskit_pass/plugin.py +23 -0
- qtiming/qiskit_pass/strip.py +42 -0
- qtiming/qiskit_pass/timing_check.py +40 -0
- qtiming/repair/__init__.py +0 -0
- qtiming/repair/suggest.py +146 -0
- qtiming/solve/__init__.py +0 -0
- qtiming/solve/concrete.py +148 -0
- qtiming/solve/dispatcher.py +55 -0
- qtiming/solve/interval.py +185 -0
- qtiming/solve/smt.py +167 -0
- qtiming/solve/smt_o5.py +1 -0
- qtiming/solve/synth/__init__.py +0 -0
- qtiming/solve/synth/bruteforce_dc.py +156 -0
- qtiming/solve/synth/model.py +59 -0
- qtiming/solve/synth/relax.py +93 -0
- qtiming/solve/synth/rigid.py +33 -0
- qtiming/solve/synth/sc.py +55 -0
- qtiming/solve/synth/stn.py +74 -0
- qtiming/solve/synth/stnu_dc.py +93 -0
- qtiming/verdict/__init__.py +0 -0
- qtiming/verdict/minimise.py +45 -0
- qtiming/verdict/model.py +107 -0
- qtiming/verdict/render.py +72 -0
- qtiming/verdict/render_html.py +80 -0
- qtiming/verdict/render_json.py +12 -0
- qtiming/verdict/render_sarif.py +104 -0
- qtiming/verdict/replay.py +77 -0
- qtiming/verdict/run.py +174 -0
- qtiming/verdict/rus.py +53 -0
- qtiming-0.1.0.dist-info/METADATA +262 -0
- qtiming-0.1.0.dist-info/RECORD +102 -0
- qtiming-0.1.0.dist-info/WHEEL +4 -0
- qtiming-0.1.0.dist-info/entry_points.txt +6 -0
- qtiming-0.1.0.dist-info/licenses/LICENSE +177 -0
- qtiming-0.1.0.dist-info/licenses/NOTICE +8 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
[meta]
|
|
2
|
+
name = "qblox_q1"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
schema = "qtiming-contract/0.2"
|
|
5
|
+
personality = "q1"
|
|
6
|
+
|
|
7
|
+
[timebase]
|
|
8
|
+
dt_ns = "4" # RT instruction durations are multiples of 4 ns
|
|
9
|
+
grid = { rt = 1 }
|
|
10
|
+
|
|
11
|
+
[timeline]
|
|
12
|
+
commit_lead = { lo_ns = 0, prov = { prov = "cyc", source = "Q1 docs: RT queue is fed ahead of use; lead = classical issue cost, see [issue_cost]" } }
|
|
13
|
+
late_policy = "halt" # SEQUENCE_PROCESSOR_RT_EXEC_COMMAND_UNDERFLOW; sequencer halts
|
|
14
|
+
|
|
15
|
+
[issue_cost] # classical Q1 core, ns (cycle-counted design values)
|
|
16
|
+
set_mov = { ns = 4, prov = "cyc", source = "Q1 instruction table (v1 value; re-verify)" }
|
|
17
|
+
alu = { ns = 12, prov = "cyc", source = "Q1 instruction table (v1 value; re-verify)" }
|
|
18
|
+
nop = { ns = 4, prov = "cyc", source = "Q1 docs" }
|
|
19
|
+
jmp = { ns = 16, prov = "cyc", source = "Q1 docs" }
|
|
20
|
+
# Old jge/jlt/loop forms are deprecated; the current form is cmp or sub followed by a flag jump,
|
|
21
|
+
# i.e. ONE EXTRA INSTRUCTION. The elaborator inserts it (cost = alu).
|
|
22
|
+
cond_jump = { taken_ns = 24, not_taken_ns = 4, prov = "cyc", source = "Q1 docs: jge, jlt, loop" }
|
|
23
|
+
|
|
24
|
+
[capacity]
|
|
25
|
+
rt_queue_depth = 32 # underflow halts, overflow back-pressures the Q1 core
|
|
26
|
+
|
|
27
|
+
[[latency]]
|
|
28
|
+
key = "trigger.network" # thresholded result -> all trigger-network receivers
|
|
29
|
+
src = "measure"
|
|
30
|
+
dst = "branch"
|
|
31
|
+
tier = "all_receivers"
|
|
32
|
+
lo_ns = 212
|
|
33
|
+
hi_ns = 239 # 212 to 239 ns depending on the 28 ns timegrid
|
|
34
|
+
prov = "vendor"
|
|
35
|
+
source = "docs.qblox.com trigger_handling; documented figure, not cycle-certified [verify page path]"
|
|
36
|
+
|
|
37
|
+
[[latency]]
|
|
38
|
+
key = "trigger.network_busy" # network occupied; a SECOND trigger inside this window is lost or delayed
|
|
39
|
+
src = "network"
|
|
40
|
+
dst = "network"
|
|
41
|
+
tier = "all_receivers"
|
|
42
|
+
lo_ns = 252
|
|
43
|
+
hi_ns = 252
|
|
44
|
+
prov = "vendor"
|
|
45
|
+
source = "docs.qblox.com trigger_handling"
|
|
46
|
+
|
|
47
|
+
[[latency]]
|
|
48
|
+
key = "path.opip.base" # OP + IP base
|
|
49
|
+
src = "measure"
|
|
50
|
+
dst = "network"
|
|
51
|
+
tier = "base"
|
|
52
|
+
lo_ns = 149
|
|
53
|
+
hi_ns = 149
|
|
54
|
+
prov = "vendor"
|
|
55
|
+
source = "docs.qblox.com trigger_handling: output 40 ns (baseband) or 50 ns (RF) + input 109 ns"
|
|
56
|
+
|
|
57
|
+
[[latency]]
|
|
58
|
+
key = "path.rtp_output" # real-time-processing output adder
|
|
59
|
+
src = "rt"
|
|
60
|
+
dst = "output"
|
|
61
|
+
tier = "rtp"
|
|
62
|
+
lo_ns = 24
|
|
63
|
+
hi_ns = 24
|
|
64
|
+
prov = "vendor"
|
|
65
|
+
source = "docs.qblox.com trigger_handling"
|
|
66
|
+
|
|
67
|
+
# Consistency fixture (not a contract entry): the documented worked example totals 388 ns =
|
|
68
|
+
# 149 (OP+IP) + 239 (network, worst timegrid case). [verify the decomposition against the page]
|
|
69
|
+
|
|
70
|
+
[branch]
|
|
71
|
+
class = "predicated"
|
|
72
|
+
default_policy = "eq"
|
|
73
|
+
allow_nested = true
|
|
74
|
+
allow_measure_in_branch = true
|
|
75
|
+
allow_loops = true
|
|
76
|
+
max_cond_bits = 15 # trigger-network addresses [verify]
|
|
77
|
+
|
|
78
|
+
[personality_params.q1]
|
|
79
|
+
set_cond_else_time_per_instruction = true # else_time ns are waited PER skipped RT instruction (plan Section 8.5)
|
|
80
|
+
else_time_dt = 1 # RT wait per skipped conditional instruction, dt; vendor assumption (min else_duration), see Docs/personality-spec/q1.md
|
|
81
|
+
ttl_input_speedup_ns = 35 # TTL input path is 35 ns faster than the standard input path (documented)
|
|
82
|
+
|
|
83
|
+
[idle]
|
|
84
|
+
max_gap_variation_ns = { default = 0 }
|
|
85
|
+
dd_inserted_by_backend = "unknown"
|
|
86
|
+
|
|
87
|
+
[loop]
|
|
88
|
+
while_supported = true
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
[meta]
|
|
2
|
+
name = "qm_qua"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
schema = "qtiming-contract/0.2"
|
|
5
|
+
personality = "qua"
|
|
6
|
+
|
|
7
|
+
[timebase]
|
|
8
|
+
dt_ns = "4" # clock cycle
|
|
9
|
+
|
|
10
|
+
[timeline]
|
|
11
|
+
late_policy = "compile_error" # with strict_timing_ on; warnings otherwise
|
|
12
|
+
|
|
13
|
+
[[latency]]
|
|
14
|
+
key = "align.same_fem"
|
|
15
|
+
src = "align"
|
|
16
|
+
dst = "align"
|
|
17
|
+
tier = "same_fem"
|
|
18
|
+
lo_ns = 0
|
|
19
|
+
hi_ns = 12 # ILLUSTRATIVE PLACEHOLDER: "a few cycles" is the only published statement
|
|
20
|
+
prov = "vendor"
|
|
21
|
+
placeholder = true
|
|
22
|
+
source = "QM Timing in QUA: non-deterministic align leaves 'a few cycles'; no number published"
|
|
23
|
+
|
|
24
|
+
[[latency]]
|
|
25
|
+
key = "align.cross_fem"
|
|
26
|
+
src = "align"
|
|
27
|
+
dst = "align"
|
|
28
|
+
tier = "cross_fem"
|
|
29
|
+
lo_ns = 0
|
|
30
|
+
hi_ns = 24 # ILLUSTRATIVE PLACEHOLDER (ordering documented, value is not)
|
|
31
|
+
prov = "vendor"
|
|
32
|
+
placeholder = true
|
|
33
|
+
source = "QM Timing in QUA; topology dependent: same FEM < cross-FEM < cross-chassis"
|
|
34
|
+
|
|
35
|
+
[[latency]]
|
|
36
|
+
key = "align.cross_chassis"
|
|
37
|
+
src = "align"
|
|
38
|
+
dst = "align"
|
|
39
|
+
tier = "cross_chassis"
|
|
40
|
+
lo_ns = 0
|
|
41
|
+
hi_ns = 48 # ILLUSTRATIVE PLACEHOLDER
|
|
42
|
+
prov = "vendor"
|
|
43
|
+
placeholder = true
|
|
44
|
+
source = "QM Timing in QUA"
|
|
45
|
+
|
|
46
|
+
[[latency]]
|
|
47
|
+
key = "active_reset"
|
|
48
|
+
src = "measure"
|
|
49
|
+
dst = "branch"
|
|
50
|
+
tier = "default"
|
|
51
|
+
lo_ns = 0
|
|
52
|
+
hi_ns = 224
|
|
53
|
+
prov = "vendor"
|
|
54
|
+
source = "QM claim: 224 ns active reset (vendor)"
|
|
55
|
+
|
|
56
|
+
[branch]
|
|
57
|
+
class = "resync"
|
|
58
|
+
default_policy = "sync"
|
|
59
|
+
|
|
60
|
+
[personality_params.qua]
|
|
61
|
+
skip_implicit_align = false # compiler flag skip-add-implicit-align
|
|
62
|
+
strict_timing = true # strict_timing_ ; "not-strict-timing" turns gap errors into warnings
|
|
63
|
+
# Implicit aligns: at the start of for_/while_/if_/else_/switch_ for participating elements
|
|
64
|
+
# (removable with skip_implicit_align); ALSO non-suppressible implicit aligns for broadcast
|
|
65
|
+
# operations and for measure() results that are read by another core.
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""TOML/JSON -> validated, frozen Contract (Section 7.5).
|
|
2
|
+
|
|
3
|
+
Never fills a default that silently weakens an obligation: absent required numbers are
|
|
4
|
+
recorded in `Contract.missing` and dependants become UNKNOWN downstream.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from dataclasses import fields, is_dataclass, replace
|
|
14
|
+
from enum import Enum
|
|
15
|
+
from fractions import Fraction
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from pydantic import ValidationError
|
|
19
|
+
|
|
20
|
+
from qtiming.core.errors import QtError
|
|
21
|
+
from qtiming.core.provenance import Prov, ProvClass
|
|
22
|
+
from qtiming.core.time import Interval, Latency, ns_to_dt
|
|
23
|
+
|
|
24
|
+
from .model import BranchSpec, Contract, ContractLatency, IssueCost
|
|
25
|
+
from .schema import PROV, ContractIn, frac
|
|
26
|
+
from .target_import import snapshot_from_target
|
|
27
|
+
|
|
28
|
+
try: # Python 3.11+
|
|
29
|
+
import tomllib
|
|
30
|
+
except ModuleNotFoundError: # pragma: no cover (3.10 backport)
|
|
31
|
+
import tomli as tomllib # type: ignore[no-redef]
|
|
32
|
+
|
|
33
|
+
_REQUIRED_COMMIT_LEAD = {"artiq"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ContractLoadError(QtError):
|
|
37
|
+
"""All problems found in one contract, not just the first."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, errors: list[QtError]) -> None:
|
|
40
|
+
code = errors[0].code if len({e.code for e in errors}) == 1 else "E-CT-SCHEMA"
|
|
41
|
+
super().__init__(code, "; ".join(f"[{e.code}] {e.message}" for e in errors))
|
|
42
|
+
self.errors = errors
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load_contract(path: str, *, target: Any = None, assume: tuple[str, ...] = ()) -> Contract:
|
|
46
|
+
with open(path, "rb") as fh:
|
|
47
|
+
data = fh.read()
|
|
48
|
+
raw = json.loads(data) if path.endswith(".json") else tomllib.loads(data.decode("utf-8"))
|
|
49
|
+
return load_contract_dict(
|
|
50
|
+
raw, base_dir=os.path.dirname(os.path.abspath(path)), target=target, assume=assume
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _freeze(v: Any) -> Any:
|
|
55
|
+
if isinstance(v, dict):
|
|
56
|
+
return tuple(sorted((str(k), _freeze(x)) for k, x in v.items()))
|
|
57
|
+
if isinstance(v, list):
|
|
58
|
+
return tuple(_freeze(x) for x in v)
|
|
59
|
+
return v
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _canon(o: Any) -> Any:
|
|
63
|
+
if is_dataclass(o) and not isinstance(o, type):
|
|
64
|
+
return {f.name: _canon(getattr(o, f.name)) for f in fields(o)}
|
|
65
|
+
if isinstance(o, Fraction):
|
|
66
|
+
return str(o)
|
|
67
|
+
if isinstance(o, Enum):
|
|
68
|
+
return o.name
|
|
69
|
+
if isinstance(o, (tuple, list)):
|
|
70
|
+
return [_canon(x) for x in o]
|
|
71
|
+
if isinstance(o, dict):
|
|
72
|
+
return {str(k): _canon(v) for k, v in o.items()}
|
|
73
|
+
return o
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _apply_assume(raw: dict[str, Any], assume: tuple[str, ...], errs: list[QtError]) -> None:
|
|
77
|
+
for a in assume:
|
|
78
|
+
key, sep, val = a.partition("=")
|
|
79
|
+
if not sep or not key or not val:
|
|
80
|
+
errs.append(QtError("E-CT-ASSUME", f"--assume {a!r}: expected key=value"))
|
|
81
|
+
continue
|
|
82
|
+
if key == "timeline.commit_lead":
|
|
83
|
+
raw.setdefault("timeline", {})["commit_lead"] = val
|
|
84
|
+
continue
|
|
85
|
+
if key.startswith("durations."): # a fixed duration in ns the user vouches for
|
|
86
|
+
raw.setdefault("durations", {})[key.removeprefix("durations.")] = val
|
|
87
|
+
continue
|
|
88
|
+
parts = val.split(":")
|
|
89
|
+
cls = parts[2] if len(parts) > 2 else "vendor"
|
|
90
|
+
if cls != "vendor":
|
|
91
|
+
errs.append(QtError("E-CT-ASSUME", f"--assume {a!r}: only class 'vendor' is allowed"))
|
|
92
|
+
continue
|
|
93
|
+
new = {
|
|
94
|
+
"lo_ns": parts[0],
|
|
95
|
+
"hi_ns": parts[1] if len(parts) > 1 and parts[1] != "" else None,
|
|
96
|
+
"prov": "vendor",
|
|
97
|
+
"source": f"--assume {a}",
|
|
98
|
+
"placeholder": True,
|
|
99
|
+
}
|
|
100
|
+
lats = raw.setdefault("latency", [])
|
|
101
|
+
for i, old in enumerate(lats):
|
|
102
|
+
if old.get("key") == key:
|
|
103
|
+
keep = {k: v for k, v in old.items() if k not in ("n", "p", "load", "k_sigma")}
|
|
104
|
+
lats[i] = {**keep, **new}
|
|
105
|
+
break
|
|
106
|
+
else:
|
|
107
|
+
lats.append({"key": key, "src": "assume", "dst": "assume", **new})
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _read_snapshot(tgt: dict[str, Any], base_dir: str | None, target: Any) -> dict[str, Any] | None:
|
|
111
|
+
src = str(tgt.get("source", "none"))
|
|
112
|
+
if target is not None:
|
|
113
|
+
if isinstance(target, dict):
|
|
114
|
+
return target
|
|
115
|
+
return snapshot_from_target(target, str(tgt.get("backend", "unknown")))
|
|
116
|
+
if src.startswith("snapshot:"):
|
|
117
|
+
path = os.path.join(base_dir or os.getcwd(), src[len("snapshot:"):])
|
|
118
|
+
try:
|
|
119
|
+
with open(path, encoding="utf-8") as fh:
|
|
120
|
+
snap: dict[str, Any] = json.load(fh)
|
|
121
|
+
except OSError as e:
|
|
122
|
+
raise QtError("E-CT-TARGET", f"cannot read target snapshot {path!r}: {e}") from e
|
|
123
|
+
return snap
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def load_contract_dict(
|
|
128
|
+
raw: dict[str, Any],
|
|
129
|
+
*,
|
|
130
|
+
base_dir: str | None = None,
|
|
131
|
+
target: Any = None,
|
|
132
|
+
assume: tuple[str, ...] = (),
|
|
133
|
+
) -> Contract:
|
|
134
|
+
raw = copy.deepcopy(raw)
|
|
135
|
+
errs: list[QtError] = []
|
|
136
|
+
_apply_assume(raw, assume, errs)
|
|
137
|
+
try:
|
|
138
|
+
c = ContractIn.model_validate(raw)
|
|
139
|
+
except ValidationError as ve:
|
|
140
|
+
for e in ve.errors():
|
|
141
|
+
path = ".".join(str(p) for p in e["loc"])
|
|
142
|
+
errs.append(QtError("E-CT-SCHEMA", f"{path}: {e['msg']}"))
|
|
143
|
+
raise ContractLoadError(errs) from None
|
|
144
|
+
if errs:
|
|
145
|
+
raise ContractLoadError(errs)
|
|
146
|
+
|
|
147
|
+
warns: list[str] = []
|
|
148
|
+
personality = c.meta.personality
|
|
149
|
+
|
|
150
|
+
# -- target snapshot, dt ------------------------------------------------------------
|
|
151
|
+
snapshot: dict[str, Any] | None = None
|
|
152
|
+
if c.target is not None:
|
|
153
|
+
try:
|
|
154
|
+
snapshot = _read_snapshot(c.target, base_dir, target)
|
|
155
|
+
except QtError as e:
|
|
156
|
+
errs.append(e)
|
|
157
|
+
imports = set(c.target.get("import", ["dt", "alignments", "durations"])) if c.target else set()
|
|
158
|
+
|
|
159
|
+
dt: Fraction | None = None
|
|
160
|
+
raw_dt = c.timebase.dt_ns
|
|
161
|
+
if raw_dt == "from_target":
|
|
162
|
+
if snapshot is None:
|
|
163
|
+
errs.append(QtError("E-CT-TARGET", "dt_ns = 'from_target' but no Target was supplied",
|
|
164
|
+
hint="pass a Target, or set [target] source = 'snapshot:<file>'"))
|
|
165
|
+
else:
|
|
166
|
+
dt = Fraction(str(snapshot["dt_ns"]))
|
|
167
|
+
else:
|
|
168
|
+
try:
|
|
169
|
+
dt = frac(raw_dt)
|
|
170
|
+
except ValueError:
|
|
171
|
+
errs.append(QtError("E-CT-SCHEMA", f"timebase.dt_ns: {raw_dt!r} is not a decimal"))
|
|
172
|
+
if dt is not None and snapshot is not None and "dt" in imports:
|
|
173
|
+
if dt != Fraction(str(snapshot["dt_ns"])):
|
|
174
|
+
errs.append(QtError("E-CT-TARGET-CONFLICT",
|
|
175
|
+
f"timebase.dt_ns = {raw_dt} disagrees with Target "
|
|
176
|
+
f"dt = {snapshot['dt_ns']} ns"))
|
|
177
|
+
if dt is not None and dt <= 0:
|
|
178
|
+
errs.append(QtError("E-CT-SCHEMA", "timebase.dt_ns must be > 0"))
|
|
179
|
+
dt = None
|
|
180
|
+
if dt is None:
|
|
181
|
+
raise ContractLoadError(errs)
|
|
182
|
+
|
|
183
|
+
grid = dict(c.timebase.grid)
|
|
184
|
+
if snapshot is not None and "alignments" in imports:
|
|
185
|
+
for k, v in snapshot.get("alignments", {}).items():
|
|
186
|
+
if k in grid and grid[k] != v:
|
|
187
|
+
errs.append(QtError("E-CT-TARGET-CONFLICT",
|
|
188
|
+
f"grid.{k} = {grid[k]} disagrees with Target ({v})"))
|
|
189
|
+
grid[k] = int(v)
|
|
190
|
+
|
|
191
|
+
# -- durations (role: exact) --------------------------------------------------------
|
|
192
|
+
target_durs: dict[str, int] = {}
|
|
193
|
+
if snapshot is not None and "durations" in imports:
|
|
194
|
+
for name, ns in snapshot.get("durations_ns", {}).items():
|
|
195
|
+
try:
|
|
196
|
+
target_durs[name] = ns_to_dt(Fraction(str(ns)), dt, "exact",
|
|
197
|
+
what=f"Target duration {name}")
|
|
198
|
+
except QtError as e:
|
|
199
|
+
errs.append(e)
|
|
200
|
+
durs: dict[str, int] = dict(target_durs) if c.durations.get("import_from_target") else {}
|
|
201
|
+
overrides: list[str] = []
|
|
202
|
+
for name, v in c.durations.items():
|
|
203
|
+
if name == "import_from_target":
|
|
204
|
+
continue
|
|
205
|
+
override, reason = False, None
|
|
206
|
+
ns = v
|
|
207
|
+
if isinstance(v, dict):
|
|
208
|
+
ns, override, reason = v.get("ns"), bool(v.get("override", False)), v.get("reason")
|
|
209
|
+
if isinstance(ns, bool) or not isinstance(ns, (str, int)):
|
|
210
|
+
errs.append(QtError("E-CT-SCHEMA",
|
|
211
|
+
f"durations.{name}: must be a decimal string or int, got {ns!r}"))
|
|
212
|
+
continue
|
|
213
|
+
try:
|
|
214
|
+
d = ns_to_dt(Fraction(str(ns)), dt, "exact", what=f"durations.{name}")
|
|
215
|
+
except QtError as e:
|
|
216
|
+
errs.append(e)
|
|
217
|
+
continue
|
|
218
|
+
except ValueError:
|
|
219
|
+
errs.append(QtError("E-CT-SCHEMA", f"durations.{name}: {ns!r} is not a decimal"))
|
|
220
|
+
continue
|
|
221
|
+
if name in target_durs and d != target_durs[name]:
|
|
222
|
+
if not override:
|
|
223
|
+
errs.append(QtError("E-CT-TARGET-CONFLICT",
|
|
224
|
+
f"durations.{name} = {ns} ns conflicts with Target "
|
|
225
|
+
f"({target_durs[name]} dt)",
|
|
226
|
+
hint="set override = true with a reason to use it"))
|
|
227
|
+
continue
|
|
228
|
+
if not reason:
|
|
229
|
+
errs.append(QtError("E-CT-TARGET-CONFLICT",
|
|
230
|
+
f"durations.{name}: override requires a reason"))
|
|
231
|
+
continue
|
|
232
|
+
overrides.append(f"durations.{name}")
|
|
233
|
+
durs[name] = d
|
|
234
|
+
|
|
235
|
+
# -- latencies (outward rounding) ---------------------------------------------------
|
|
236
|
+
lats: list[ContractLatency] = []
|
|
237
|
+
missing: list[str] = []
|
|
238
|
+
seen: set[str] = set()
|
|
239
|
+
for i, li in enumerate(c.latency):
|
|
240
|
+
if li.key in seen:
|
|
241
|
+
errs.append(QtError("E-CT-SCHEMA", f"latency.{i}.key: duplicate key {li.key!r}"))
|
|
242
|
+
continue
|
|
243
|
+
seen.add(li.key)
|
|
244
|
+
lo_ns = frac(li.lo_ns)
|
|
245
|
+
hi_ns = None if li.hi_ns is None else frac(li.hi_ns)
|
|
246
|
+
lo = ns_to_dt(lo_ns, dt, "latency_lo")
|
|
247
|
+
hi = None if hi_ns is None else ns_to_dt(hi_ns, dt, "latency_hi")
|
|
248
|
+
if c.timebase.latency_resolution == "dt" and (
|
|
249
|
+
lo_ns % dt != 0 or (hi_ns is not None and hi_ns % dt != 0)
|
|
250
|
+
):
|
|
251
|
+
errs.append(QtError("E-CT-RESOLUTION",
|
|
252
|
+
f"latency {li.key}: endpoints must be whole dt "
|
|
253
|
+
"(latency_resolution = 'dt')"))
|
|
254
|
+
continue
|
|
255
|
+
if Fraction(lo) != lo_ns / dt or (hi is not None and hi_ns is not None
|
|
256
|
+
and Fraction(hi) != hi_ns / dt):
|
|
257
|
+
warns.append(f"W-CT-ROUND: latency {li.key} [{lo_ns}, {hi_ns}] ns -> "
|
|
258
|
+
f"[{lo}, {hi}] dt (rounded outward)")
|
|
259
|
+
meta = tuple(sorted(li.meta.items())) + ((("placeholder", "true"),)
|
|
260
|
+
if li.placeholder else ())
|
|
261
|
+
prov = Prov(
|
|
262
|
+
ProvClass[li.prov.upper()], li.source, n=li.n,
|
|
263
|
+
p=None if li.p is None else frac(li.p), load=li.load,
|
|
264
|
+
k_sigma=None if li.k_sigma is None else frac(li.k_sigma), meta=meta,
|
|
265
|
+
)
|
|
266
|
+
if hi is None:
|
|
267
|
+
missing.append(f"latency.{li.key}.hi")
|
|
268
|
+
lats.append(ContractLatency(
|
|
269
|
+
Latency(li.key, Interval(lo, hi), prov), li.src, li.dst, li.tier,
|
|
270
|
+
lo_ns, hi_ns, li.data_dependent, li.placeholder))
|
|
271
|
+
|
|
272
|
+
# -- timeline -----------------------------------------------------------------------
|
|
273
|
+
cl = c.timeline.commit_lead
|
|
274
|
+
cl_ns = cl.get("lo_ns") if isinstance(cl, dict) else cl
|
|
275
|
+
commit_lead: int | None = None
|
|
276
|
+
if cl_ns is None:
|
|
277
|
+
if personality in _REQUIRED_COMMIT_LEAD:
|
|
278
|
+
missing.append("timeline.commit_lead")
|
|
279
|
+
elif isinstance(cl_ns, bool) or not isinstance(cl_ns, (str, int)):
|
|
280
|
+
errs.append(QtError("E-CT-SCHEMA", f"timeline.commit_lead: bad number {cl_ns!r}"))
|
|
281
|
+
else:
|
|
282
|
+
try:
|
|
283
|
+
commit_lead = ns_to_dt(frac(cl_ns), dt, "commit_lead")
|
|
284
|
+
except ValueError:
|
|
285
|
+
errs.append(QtError("E-CT-SCHEMA", f"timeline.commit_lead: {cl_ns!r} not a decimal"))
|
|
286
|
+
|
|
287
|
+
# -- issue cost (upper bounds round up) ---------------------------------------------
|
|
288
|
+
issue: list[IssueCost] = []
|
|
289
|
+
for name, entry in sorted(c.issue_cost.items()):
|
|
290
|
+
if not isinstance(entry, dict):
|
|
291
|
+
errs.append(QtError("E-CT-SCHEMA", f"issue_cost.{name}: expected a table"))
|
|
292
|
+
continue
|
|
293
|
+
p = entry.get("prov")
|
|
294
|
+
pcls, src = (p.get("prov"), p.get("source", "")) if isinstance(p, dict) else (
|
|
295
|
+
p, entry.get("source", ""))
|
|
296
|
+
if pcls not in PROV.__args__:
|
|
297
|
+
errs.append(QtError("E-CT-SCHEMA", f"issue_cost.{name}: bad prov {pcls!r}"))
|
|
298
|
+
continue
|
|
299
|
+
flds = []
|
|
300
|
+
for k, v in sorted(entry.items()):
|
|
301
|
+
if k.endswith("ns"):
|
|
302
|
+
role = "latency_lo" if k == "lo_ns" else "latency_hi"
|
|
303
|
+
try:
|
|
304
|
+
flds.append((k, ns_to_dt(frac(v), dt, role)))
|
|
305
|
+
except (ValueError, TypeError):
|
|
306
|
+
errs.append(QtError("E-CT-SCHEMA", f"issue_cost.{name}.{k}: bad number {v!r}"))
|
|
307
|
+
issue.append(IssueCost(name, tuple(flds), str(pcls), str(src)))
|
|
308
|
+
|
|
309
|
+
# -- idle, loop, feedback tiers -----------------------------------------------------
|
|
310
|
+
gaps: list[tuple[str, int]] = []
|
|
311
|
+
for name, v in sorted(dict(c.idle.get("max_gap_variation_ns", {})).items()):
|
|
312
|
+
try:
|
|
313
|
+
gaps.append((name, ns_to_dt(frac(v), dt, "gap_bound")))
|
|
314
|
+
except (ValueError, TypeError):
|
|
315
|
+
errs.append(QtError("E-CT-SCHEMA", f"idle.max_gap_variation_ns.{name}: bad number"))
|
|
316
|
+
while_ok = bool(c.loop.get("while_supported", False))
|
|
317
|
+
if while_ok and not c.branch.allow_loops:
|
|
318
|
+
errs.append(QtError("E-CT-LOOP",
|
|
319
|
+
"loop.while_supported = true but branch.allow_loops = false"))
|
|
320
|
+
for i, row in enumerate(c.feedback_tier):
|
|
321
|
+
ref = row.get("latency")
|
|
322
|
+
if ref not in seen:
|
|
323
|
+
errs.append(
|
|
324
|
+
QtError("E-CT-SCHEMA", f"feedback_tier.{i}.latency: unknown latency {ref!r}"))
|
|
325
|
+
|
|
326
|
+
if errs:
|
|
327
|
+
raise ContractLoadError(errs)
|
|
328
|
+
|
|
329
|
+
b = c.branch
|
|
330
|
+
extras = tuple(sorted(
|
|
331
|
+
(k, _freeze(v)) for k, v in {
|
|
332
|
+
"topology": c.topology, "feedback_tier": c.feedback_tier, "dep": c.dep,
|
|
333
|
+
"domain_call": c.domain_call, "sync": c.sync, "evidence": c.evidence,
|
|
334
|
+
}.items() if v))
|
|
335
|
+
snap_id = None
|
|
336
|
+
if snapshot is not None:
|
|
337
|
+
h = hashlib.sha256(json.dumps(snapshot, sort_keys=True).encode()).hexdigest()[:12]
|
|
338
|
+
snap_id = f"{snapshot.get('backend', 'unknown')}:{h}"
|
|
339
|
+
contract = Contract(
|
|
340
|
+
name=c.meta.name, version=c.meta.version, personality=personality, dt_ns=dt,
|
|
341
|
+
grid=tuple(sorted(grid.items())), late_policy=c.timeline.late_policy,
|
|
342
|
+
commit_lead=commit_lead, durations=tuple(sorted(durs.items())), latencies=tuple(lats),
|
|
343
|
+
issue_cost=tuple(issue),
|
|
344
|
+
branch=BranchSpec(b.klass, b.default_policy, b.allow_nested, b.allow_measure_in_branch,
|
|
345
|
+
b.allow_loops, b.max_cond_bits),
|
|
346
|
+
capacity=_freeze(c.capacity), params=_freeze(c.personality_params),
|
|
347
|
+
idle_variation=tuple(gaps),
|
|
348
|
+
dd_inserted=str(c.idle.get("dd_inserted_by_backend", "unknown")),
|
|
349
|
+
while_supported=while_ok, extras=extras, overrides=tuple(overrides),
|
|
350
|
+
assumed=tuple(assume), missing=tuple(missing), warnings=tuple(warns),
|
|
351
|
+
target_snapshot=snap_id, sha256="",
|
|
352
|
+
)
|
|
353
|
+
body = {k: v for k, v in _canon(contract).items() if k not in ("sha256", "warnings")}
|
|
354
|
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":")).encode())
|
|
355
|
+
return replace(contract, sha256=digest.hexdigest())
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""The frozen, validated Contract the rest of the pipeline sees (all times integer dt)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from fractions import Fraction
|
|
7
|
+
|
|
8
|
+
from qtiming.core.errors import QtError
|
|
9
|
+
from qtiming.core.time import Latency
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class ContractLatency:
|
|
14
|
+
latency: Latency
|
|
15
|
+
src: str
|
|
16
|
+
dst: str
|
|
17
|
+
tier: str
|
|
18
|
+
lo_ns: Fraction # as declared, before outward rounding
|
|
19
|
+
hi_ns: Fraction | None
|
|
20
|
+
data_dependent: bool
|
|
21
|
+
placeholder: bool
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True, slots=True)
|
|
25
|
+
class IssueCost:
|
|
26
|
+
name: str
|
|
27
|
+
fields: tuple[tuple[str, int], ...] # (field, dt); upper bounds rounded up
|
|
28
|
+
prov_cls: str
|
|
29
|
+
source: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class BranchSpec:
|
|
34
|
+
klass: str
|
|
35
|
+
default_policy: str
|
|
36
|
+
allow_nested: bool
|
|
37
|
+
allow_measure_in_branch: bool
|
|
38
|
+
allow_loops: bool
|
|
39
|
+
max_cond_bits: int
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class Contract:
|
|
44
|
+
name: str
|
|
45
|
+
version: str
|
|
46
|
+
personality: str
|
|
47
|
+
dt_ns: Fraction
|
|
48
|
+
grid: tuple[tuple[str, int], ...]
|
|
49
|
+
late_policy: str
|
|
50
|
+
commit_lead: int | None
|
|
51
|
+
durations: tuple[tuple[str, int], ...]
|
|
52
|
+
latencies: tuple[ContractLatency, ...]
|
|
53
|
+
issue_cost: tuple[IssueCost, ...]
|
|
54
|
+
branch: BranchSpec
|
|
55
|
+
capacity: tuple[tuple[str, object], ...]
|
|
56
|
+
params: tuple[tuple[str, object], ...]
|
|
57
|
+
idle_variation: tuple[tuple[str, int], ...]
|
|
58
|
+
dd_inserted: str
|
|
59
|
+
while_supported: bool
|
|
60
|
+
extras: tuple[tuple[str, object], ...]
|
|
61
|
+
overrides: tuple[str, ...]
|
|
62
|
+
assumed: tuple[str, ...]
|
|
63
|
+
missing: tuple[str, ...]
|
|
64
|
+
warnings: tuple[str, ...]
|
|
65
|
+
target_snapshot: str | None
|
|
66
|
+
sha256: str
|
|
67
|
+
|
|
68
|
+
def latency(self, key: str) -> ContractLatency:
|
|
69
|
+
for cl in self.latencies:
|
|
70
|
+
if cl.latency.key == key:
|
|
71
|
+
return cl
|
|
72
|
+
raise QtError("E-CT-MISSING", f"contract {self.name!r} has no latency {key!r}")
|
|
73
|
+
|
|
74
|
+
def duration(self, name: str) -> int:
|
|
75
|
+
for n, d in self.durations:
|
|
76
|
+
if n == name:
|
|
77
|
+
return d
|
|
78
|
+
raise QtError(
|
|
79
|
+
"E-CT-MISSING",
|
|
80
|
+
f"contract {self.name!r} has no duration for {name!r}",
|
|
81
|
+
hint="add it to [durations] or import it from the backend Target",
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def find_latency(self, src: str, dst: str, tier: str = "default") -> ContractLatency:
|
|
85
|
+
"""The latency declared from `src` to `dst` for `tier` (falls back to tier 'default')."""
|
|
86
|
+
hit = None
|
|
87
|
+
for cl in self.latencies:
|
|
88
|
+
if cl.src == src and cl.dst == dst:
|
|
89
|
+
if cl.tier == tier:
|
|
90
|
+
return cl
|
|
91
|
+
if cl.tier == "default" and hit is None:
|
|
92
|
+
hit = cl
|
|
93
|
+
if hit is None: # a single declared src->dst latency serves every tier
|
|
94
|
+
cands = [cl for cl in self.latencies if cl.src == src and cl.dst == dst]
|
|
95
|
+
hit = cands[0] if len(cands) == 1 else None
|
|
96
|
+
if hit is None:
|
|
97
|
+
raise QtError("E-CT-MISSING", f"contract {self.name!r} has no latency {src}->{dst}")
|
|
98
|
+
return hit
|
|
99
|
+
|
|
100
|
+
def param(self, personality: str, name: str, default: object = None) -> object:
|
|
101
|
+
"""A personality parameter from `[personality_params.<personality>]`."""
|
|
102
|
+
for k, v in self.params:
|
|
103
|
+
if k == personality and isinstance(v, tuple):
|
|
104
|
+
for k2, v2 in v:
|
|
105
|
+
if k2 == name:
|
|
106
|
+
return v2
|
|
107
|
+
return default
|
|
108
|
+
|
|
109
|
+
def cap(self, name: str, default: object = None) -> object:
|
|
110
|
+
for k, v in self.capacity:
|
|
111
|
+
if k == name:
|
|
112
|
+
return v
|
|
113
|
+
return default
|
|
114
|
+
|
|
115
|
+
def cost(self, name: str, field: str | None = None) -> int:
|
|
116
|
+
"""Issue cost in dt: `field` if given, else the first of ns, hi_ns, lo_ns present."""
|
|
117
|
+
for ic in self.issue_cost:
|
|
118
|
+
if ic.name == name:
|
|
119
|
+
d = dict(ic.fields)
|
|
120
|
+
for f in ((field,) if field else ("ns", "hi_ns", "lo_ns")):
|
|
121
|
+
if f in d:
|
|
122
|
+
return d[f]
|
|
123
|
+
raise QtError("E-CT-MISSING", f"contract {self.name!r} has no issue_cost {name}")
|