2 """Validation: canonical workflow contract. 4 Builds a machine-readable contract artifact for the canonical Phase 2 noisy 5 workflow. This is intentionally a thin contract layer: 6 - it freezes one stable workflow ID and contract version, 7 - it defines explicit input and output contract sections, 8 - it records supported / optional / deferred / unsupported workflow boundaries, 9 - and it links those contract sections back to the delivered validation-evidence 10 inventory without re-running the full validation stack. 13 python benchmarks/density_matrix/workflow_evidence/workflow_contract_validation.py 16 from __future__
import annotations
19 import importlib.metadata
23 from pathlib
import Path
27 REPO_ROOT = Path(__file__).resolve().parents[3]
28 if str(REPO_ROOT)
not in sys.path:
29 sys.path.insert(0, str(REPO_ROOT))
31 from benchmarks.density_matrix.noise_support.support_tiers
import SUPPORT_TIER_VOCABULARY
33 PRIMARY_BACKEND =
"density_matrix" 34 REFERENCE_BACKEND =
"qiskit_aer_density_matrix" 35 DEFAULT_ANSATZ =
"HEA" 37 DEFAULT_INNER_BLOCKS = 1
38 FIXED_PARAMETER_QUBITS = (4, 6)
39 EXACT_REGIME_WORKFLOW_QUBITS = (4, 6, 8, 10)
40 EXACT_REGIME_PARAMETER_SET_COUNT = 10
41 WORKFLOW_ERROR_TOL = 1e-8
44 OBSERVABLE_IMAG_TOL = 1e-10
45 REQUIRED_PASS_RATE = 1.0
47 SUITE_NAME =
"workflow_contract_validation" 48 ARTIFACT_FILENAME =
"workflow_contract_bundle.json" 49 DEFAULT_OUTPUT_DIR = (
50 REPO_ROOT /
"benchmarks" /
"density_matrix" /
"artifacts" /
"workflow_evidence" 52 VALIDATION_EVIDENCE_REFERENCE_BUNDLE_PATH = (
57 /
"validation_evidence" 58 /
"validation_evidence_publication_bundle.json" 60 WORKFLOW_ID =
"phase2_xxz_hea_density_matrix_anchor_workflow" 61 CONTRACT_VERSION =
"v1" 62 STATUS_VOCABULARY = (
"pass",
"fail",
"incomplete",
"completed",
"unsupported")
63 BOUNDARY_CLASS_NAMES = (
"supported",
"optional",
"deferred",
"unsupported")
64 ARTIFACT_CORE_FIELDS = (
75 "boundary_classification",
76 "reference_artifacts",
81 THRESHOLD_CORE_FIELDS = (
82 "absolute_energy_error",
85 "observable_imag_abs",
87 "required_end_to_end_qubits",
88 "required_workflow_qubits",
89 "fixed_parameter_sets_per_size",
90 "documented_anchor_qubit",
97 "channel":
"local_depolarizing",
99 "after_gate_index": 0,
103 "channel":
"amplitude_damping",
105 "after_gate_index": 2,
109 "channel":
"phase_damping",
111 "after_gate_index": 4,
118 return [(idx, idx + 1)
for idx
in range(qbit_num - 1)]
123 "max_inner_iterations": 4,
125 "convergence_length": 2,
140 return importlib.metadata.version(name)
141 except importlib.metadata.PackageNotFoundError:
147 "python": sys.version.split()[0],
148 "numpy": np.__version__,
156 result = subprocess.run(
157 [
"git",
"rev-parse",
"HEAD"],
163 return result.stdout.strip()
169 reference_path: Path = VALIDATION_EVIDENCE_REFERENCE_BUNDLE_PATH,
171 payload = json.loads(reference_path.read_text(encoding=
"utf-8"))
172 required_fields = (
"suite_name",
"status",
"artifacts",
"software",
"provenance")
173 missing_fields = [field
for field
in required_fields
if field
not in payload]
176 "Validation-evidence reference bundle is missing required fields: {}".format(
177 ", ".join(missing_fields)
184 mandatory_reference_artifact_ids = [
185 artifact[
"artifact_id"]
186 for artifact
in reference_bundle[
"artifacts"]
187 if artifact.get(
"mandatory",
False)
190 "workflow_id": WORKFLOW_ID,
191 "contract_version": CONTRACT_VERSION,
192 "support_tier_vocabulary": list(SUPPORT_TIER_VOCABULARY),
193 "status_vocabulary": list(STATUS_VOCABULARY),
194 "end_to_end_qubits": list(FIXED_PARAMETER_QUBITS),
195 "fixed_parameter_matrix_qubits": list(EXACT_REGIME_WORKFLOW_QUBITS),
196 "documented_anchor_qubit": 10,
197 "fixed_parameter_sets_per_size": EXACT_REGIME_PARAMETER_SET_COUNT,
198 "required_input_fields": [
201 "hamiltonian_family",
202 "hamiltonian_parameters",
206 "noise_schedule_policy",
210 "required_output_fields": [
211 "real_energy_semantics",
212 "case_status_vocabulary",
213 "bundle_status_vocabulary",
214 "aggregate_status_semantics",
215 "required_case_fields",
216 "required_trace_fields",
217 "required_unsupported_case_fields",
218 "required_bundle_fields",
221 "required_threshold_fields": list(THRESHOLD_CORE_FIELDS),
222 "required_boundary_classes": list(BOUNDARY_CLASS_NAMES),
223 "required_reference_artifact_ids": mandatory_reference_artifact_ids,
224 "required_reference_bundle_sources": [
225 "validation_evidence_publication",
232 "absolute_energy_error": WORKFLOW_ERROR_TOL,
233 "rho_is_valid_tol": VALIDITY_TOL,
234 "trace_deviation": TRACE_TOL,
235 "observable_imag_abs": OBSERVABLE_IMAG_TOL,
236 "required_pass_rate": REQUIRED_PASS_RATE,
237 "required_end_to_end_qubits": list(FIXED_PARAMETER_QUBITS),
238 "required_workflow_qubits": list(EXACT_REGIME_WORKFLOW_QUBITS),
239 "fixed_parameter_sets_per_size": EXACT_REGIME_PARAMETER_SET_COUNT,
240 "documented_anchor_qubit": 10,
246 "workflow_id": WORKFLOW_ID,
247 "contract_version": CONTRACT_VERSION,
248 "workflow_family":
"noisy_vqe_ground_state_estimation",
249 "hamiltonian_family":
"1d_xxz_with_local_z_field",
252 "end_to_end_qubits": list(FIXED_PARAMETER_QUBITS),
253 "fixed_parameter_matrix_qubits": list(EXACT_REGIME_WORKFLOW_QUBITS),
254 "documented_anchor_qubit": 10,
255 "topology_family":
"open_chain",
259 "family": DEFAULT_ANSATZ,
260 "layers": DEFAULT_LAYERS,
261 "inner_blocks": DEFAULT_INNER_BLOCKS,
262 "source_type":
"generated_hea_circuit",
264 "backend_selection": {
265 "selected_backend": PRIMARY_BACKEND,
266 "selection_mode":
"explicit",
267 "reference_backend": REFERENCE_BACKEND,
268 "silent_fallback_allowed":
False,
270 "noise_schedule_policy": {
271 "insertion_policy":
"explicit_ordered_after_gate_index",
272 "required_local_noise_models": [
273 "local_depolarizing",
280 "fixed_parameter_matrix": {
282 "parameter_sets_per_size": EXACT_REGIME_PARAMETER_SET_COUNT,
284 "bounded_optimization_trace": {
286 "canonical_trace_case_name":
"optimization_trace_4q",
287 "optimizer_name":
"COSINE",
292 "fixed_parameter_matrix": {
293 "source":
"deterministic_parameter_set_schedule",
294 "generator":
"build_exact_regime_parameter_sets",
295 "random_seed_required":
False,
297 "bounded_optimization_trace": {
298 "initial_parameter_source":
"deterministic_linspace_schedule",
299 "generator":
"build_initial_parameters",
300 "random_seed_required":
False,
308 "real_energy_semantics":
"Return exact Hermitian energy through Re Tr(H*rho).",
309 "case_status_vocabulary": list(STATUS_VOCABULARY),
310 "bundle_status_vocabulary": [
"pass",
"fail"],
311 "aggregate_status_semantics": {
312 "pass":
"All required contract sections, thresholds, boundary classes, and reference artifacts are present.",
313 "fail":
"At least one required contract section, threshold, boundary class, or reference artifact is missing or inconsistent.",
315 "required_case_fields": [
323 "counts_toward_mandatory_baseline",
324 "workflow_completed",
325 "absolute_energy_error",
327 "density_valid_pass",
330 "bridge_supported_pass",
331 "total_case_runtime_ms",
332 "process_peak_rss_kb",
334 "required_trace_fields": [
337 "workflow_completed",
338 "bridge_supported_pass",
343 "energy_improvement",
344 "total_trace_runtime_ms",
345 "process_peak_rss_kb",
347 "required_unsupported_case_fields": [
353 "counts_toward_mandatory_baseline",
354 "unsupported_category",
355 "unsupported_reason",
356 "first_unsupported_condition",
357 "noise_boundary_class",
362 "required_bundle_fields": list(ARTIFACT_CORE_FIELDS),
363 "stability_metrics": [
364 "workflow_completed",
365 "total_case_runtime_ms",
366 "total_trace_runtime_ms",
367 "process_peak_rss_kb",
375 "backend_modes": [PRIMARY_BACKEND],
376 "workflow_anchor":
"xxz_plus_hea_plus_density_matrix",
377 "bridge_source_type":
"generated_hea_circuit",
378 "required_gate_families": [
"U3",
"CNOT"],
379 "required_local_noise_models": [
380 "local_depolarizing",
385 "fixed_parameter_matrix",
386 "bounded_optimization_trace",
390 "secondary_reference_baselines": [
391 "one_additional_simulator_if_justified",
393 "regression_or_stress_only": [
394 "whole_register_depolarizing",
396 "supplemental_workflow_evidence": [
397 "extra_fixed_parameter_cases_not_counting_toward_mandatory_closure",
402 "correlated_multi_qubit_noise",
404 "calibration_aware_noise",
405 "non_markovian_noise",
407 "workflow_extensions": [
408 "broader_noisy_algorithm_families",
409 "broader_hamiltonian_classes",
410 "phase3_acceleration_claims",
411 "phase4_optimizer_studies",
415 "backend_behaviors": [
416 "implicit_auto_backend_selection",
417 "silent_density_to_state_vector_fallback",
419 "workflow_conditions": [
420 "unsupported_bridge_input",
421 "unsupported_gate_or_noise_schedule",
422 "unsupported_observable_request",
423 "backend_incompatible_request",
431 for artifact
in reference_bundle[
"artifacts"]:
434 "artifact_id": artifact[
"artifact_id"],
435 "artifact_class": artifact[
"artifact_class"],
436 "mandatory": artifact[
"mandatory"],
437 "path": artifact[
"path"],
438 "status": artifact[
"status"],
439 "expected_statuses": list(artifact[
"expected_statuses"]),
440 "purpose": artifact[
"purpose"],
441 "generation_command": artifact[
"generation_command"],
448 required_input_fields = artifact[
"requirements"][
"required_input_fields"]
449 required_output_fields = artifact[
"requirements"][
"required_output_fields"]
450 required_bundle_fields = artifact[
"output_contract"][
"required_bundle_fields"]
451 required_threshold_fields = artifact[
"requirements"][
"required_threshold_fields"]
452 required_boundary_classes = set(artifact[
"requirements"][
"required_boundary_classes"])
454 artifact[
"workflow_id"]
455 and artifact[
"contract_version"]
456 and all(field
in artifact[
"input_contract"]
for field
in required_input_fields)
457 and all(field
in artifact[
"output_contract"]
for field
in required_output_fields)
458 and all(field
in artifact
for field
in required_bundle_fields)
459 and all(field
in artifact[
"thresholds"]
for field
in required_threshold_fields)
460 and required_boundary_classes == set(artifact[
"boundary_classification"].
keys())
461 and artifact[
"reference_artifacts"]
467 "suite_name": SUITE_NAME,
469 "workflow_id": WORKFLOW_ID,
470 "contract_version": CONTRACT_VERSION,
471 "backend": PRIMARY_BACKEND,
472 "reference_backend": REFERENCE_BACKEND,
481 "generation_command": (
482 "python benchmarks/density_matrix/" 483 "workflow_evidence/workflow_contract_validation.py" 485 "working_directory": str(REPO_ROOT),
487 "reference_validation_bundle_path": str(
488 VALIDATION_EVIDENCE_REFERENCE_BUNDLE_PATH
493 artifact[
"summary"] = {
494 "required_input_field_count": len(
495 artifact[
"requirements"][
"required_input_fields"]
497 "required_output_field_count": len(
498 artifact[
"requirements"][
"required_output_fields"]
500 "required_threshold_field_count": len(
501 artifact[
"requirements"][
"required_threshold_fields"]
503 "required_bundle_field_count": len(
504 artifact[
"output_contract"][
"required_bundle_fields"]
506 "boundary_class_count": len(artifact[
"boundary_classification"]),
507 "mandatory_reference_artifact_count": sum(
508 entry[
"mandatory"]
for entry
in artifact[
"reference_artifacts"]
510 "reference_artifact_count": len(artifact[
"reference_artifacts"]),
513 artifact[
"status"] =
"pass" if artifact[
"summary"][
"contract_sections_complete"]
else "fail" 519 missing_fields = [field
for field
in ARTIFACT_CORE_FIELDS
if field
not in artifact]
522 "Workflow contract artifact is missing required fields: {}".format(
523 ", ".join(missing_fields)
527 if not artifact[
"workflow_id"]:
528 raise ValueError(
"Workflow contract workflow_id must be non-empty")
529 if not artifact[
"contract_version"]:
530 raise ValueError(
"Workflow contract contract_version must be non-empty")
532 if artifact[
"status"]
not in {
"pass",
"fail"}:
534 "Workflow contract artifact has unsupported status '{}'".format(
539 required_boundary_classes = set(artifact[
"requirements"][
"required_boundary_classes"])
540 observed_boundary_classes = set(artifact[
"boundary_classification"].
keys())
541 if required_boundary_classes != observed_boundary_classes:
543 "Workflow contract boundary classes mismatch: expected {}, observed {}".format(
544 sorted(required_boundary_classes), sorted(observed_boundary_classes)
548 for field
in artifact[
"requirements"][
"required_input_fields"]:
549 if field
not in artifact[
"input_contract"]:
551 "Workflow contract input_contract is missing required field '{}'".format(
556 for field
in artifact[
"requirements"][
"required_output_fields"]:
557 if field
not in artifact[
"output_contract"]:
559 "Workflow contract output_contract is missing required field '{}'".format(
564 for field
in artifact[
"output_contract"][
"required_bundle_fields"]:
565 if field
not in artifact:
567 "Workflow contract artifact is missing required bundle field '{}'".format(
572 for field
in artifact[
"requirements"][
"required_threshold_fields"]:
573 if field
not in artifact[
"thresholds"]:
575 "Workflow contract thresholds are missing required field '{}'".format(
580 aggregate_status_semantics = artifact[
"output_contract"][
"aggregate_status_semantics"]
581 if set(aggregate_status_semantics.keys()) != {
"pass",
"fail"}:
583 "Workflow contract aggregate_status_semantics must define exactly 'pass' and 'fail'" 586 if not artifact[
"reference_artifacts"]:
587 raise ValueError(
"Workflow contract requires at least one reference artifact")
589 required_reference_fields = (
597 "generation_command",
599 for entry
in artifact[
"reference_artifacts"]:
600 missing_reference_fields = [
601 field
for field
in required_reference_fields
if field
not in entry
603 if missing_reference_fields:
605 "Workflow contract reference artifact is missing fields: {}".format(
606 ", ".join(missing_reference_fields)
611 if artifact[
"summary"][
"contract_sections_complete"] != contract_sections_complete:
613 "Workflow contract contract_sections_complete summary is inconsistent" 619 output_path.parent.mkdir(parents=
True, exist_ok=
True)
620 output_path.write_text(
621 json.dumps(artifact, indent=2, sort_keys=
True) +
"\n", encoding=
"utf-8" 628 reference_bundle_path: Path = VALIDATION_EVIDENCE_REFERENCE_BUNDLE_PATH,
634 "{} [{}] workflow_id={} reference_artifacts={}".format(
635 artifact[
"suite_name"],
637 artifact[
"workflow_id"],
638 artifact[
"summary"][
"reference_artifact_count"],
641 return reference_bundle, artifact
645 parser = argparse.ArgumentParser(description=__doc__)
649 default=DEFAULT_OUTPUT_DIR,
650 help=
"Directory for the workflow-contract JSON artifact bundle.",
653 "--reference-bundle-path",
655 default=VALIDATION_EVIDENCE_REFERENCE_BUNDLE_PATH,
656 help=
"Path to the validation-evidence bundle used as the reference inventory.",
661 help=
"Suppress summary output.",
663 return parser.parse_args()
669 verbose=
not args.quiet,
670 reference_bundle_path=args.reference_bundle_path,
672 output_path = args.output_dir / ARTIFACT_FILENAME
675 "Wrote {} with status {} ({})".format(
678 artifact[
"workflow_id"],
681 if artifact[
"status"] !=
"pass":
685 if __name__ ==
"__main__":
def build_artifact_bundle(reference_bundle)
def build_requirement_metadata(reference_bundle)
def write_artifact_bundle
def _load_reference_validation_bundle
def _contract_sections_complete(artifact)
def build_reference_noise()
def build_boundary_classification()
def validate_artifact_bundle(artifact)
def build_hamiltonian_metadata()
def build_reference_artifacts(reference_bundle)
def build_open_chain_topology
def build_input_contract()
def build_output_contract()
def build_threshold_metadata()
def build_optimizer_config()
def build_software_metadata()