From 5fc8e357b418cc14a631cc5b56e798c45ec35c32 Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 13:34:12 +0200 Subject: [PATCH 1/8] add a deprecation test that runs the notebooks with the classiq API mocked Co-Authored-By: Claude Opus 5.5 --- .github/workflows/Test-CI-deprecations.yml | 6 +- tests/config_deprecations.ini | 17 + tests/config_quick_tests.ini | 1 + tests/deprecations/mock_classiq_api.py | 428 +++++++++++++++++++++ tests/deprecations/test_deprecations.py | 71 ++++ 5 files changed, 522 insertions(+), 1 deletion(-) create mode 100644 tests/config_deprecations.ini create mode 100644 tests/deprecations/mock_classiq_api.py create mode 100644 tests/deprecations/test_deprecations.py diff --git a/.github/workflows/Test-CI-deprecations.yml b/.github/workflows/Test-CI-deprecations.yml index 7e319ab61..3402c468e 100644 --- a/.github/workflows/Test-CI-deprecations.yml +++ b/.github/workflows/Test-CI-deprecations.yml @@ -187,8 +187,12 @@ jobs: # Run Tests # - name: Run Notebooks (mocked API, deprecation warnings) - run: echo "TODO - the mocked deprecation test" + run: python -m pytest -c tests/config_deprecations.ini --rootdir=. env: SHOULD_TEST_ALL_FILES: ${{ github.event_name != 'pull_request' }} LIST_OF_IPYNB_CHANGED: "${{ steps.code-changed.outputs.list }}" LIST_OF_IPYNB_TESTS_CHANGED: "${{ steps.changed-files.outputs.tests_all_changed_files }}" + CLASSIQ_TELEMETRY_MODE: disabled + CLASSIQ_HOST: http://127.0.0.1:9 # the API is mocked: nothing may reach the platform + JUPYTER_PLATFORM_DIRS: "1" + PYTHONDONTWRITEBYTECODE: "1" diff --git a/tests/config_deprecations.ini b/tests/config_deprecations.ini new file mode 100644 index 000000000..dd5929a71 --- /dev/null +++ b/tests/config_deprecations.ini @@ -0,0 +1,17 @@ +[pytest] +testpaths = + tests/deprecations + +addopts = + --color=yes + --log-cli-level=INFO + --durations=0 + --durations-min=1 + +# +# Common settings +# +python_files = test_*.py + +filterwarnings = + error diff --git a/tests/config_quick_tests.ini b/tests/config_quick_tests.ini index f573578d7..64d9f9356 100644 --- a/tests/config_quick_tests.ini +++ b/tests/config_quick_tests.ini @@ -6,6 +6,7 @@ testpaths = norecursedirs = tests/notebooks tests/readme + tests/deprecations addopts = --color=yes diff --git a/tests/deprecations/mock_classiq_api.py b/tests/deprecations/mock_classiq_api.py new file mode 100644 index 000000000..f4c8e0e07 --- /dev/null +++ b/tests/deprecations/mock_classiq_api.py @@ -0,0 +1,428 @@ +"""Mock the classiq API inside a notebook's kernel, and record deprecation warnings. + +`test_deprecations.py` injects a cell that imports this module and calls `install()`. +- Every classiq API call returns a fake but valid result (a quantum program, samples, + a state vector, expectation values, ...), so the notebook runs to its end and reaches + all of its API calls. Nothing is sent to the Classiq platform: an API call without + a fake raises `MockedClassiqApiCall`. +- Every deprecation warning is recorded. `report()` returns them. +""" + +import datetime +import math +import random +import warnings + +from IPython import get_ipython + +DEPRECATIONS = ( + DeprecationWarning, + PendingDeprecationWarning, + FutureWarning, + SyntaxWarning, +) + +# A fake sample returns every possible bitstring of the outputs, up to this many +MAX_STATES = 1024 +# The size of an output whose size the notebook doesn't set (e.g. `Output[QNum]`) +UNKNOWN_SIZE = 4 +DEFAULT_NUM_SHOTS = 2048 + + +class MockedClassiqApiCall(Exception): + """The deprecation test has no fake result for this classiq API call.""" + + +def install() -> None: + global _first_cell + _first_cell = get_ipython().execution_count + warnings.showwarning = _record_warning + warnings.simplefilter("always") + _mock_client() + _install_fakes() + + +def report() -> list[dict]: + return list(_warnings.values()) + + +# +# Recording warnings +# + +_first_cell = 0 # the execution count of the cell that installs the mock +_warnings: dict[tuple, dict] = {} +_showwarning = warnings.showwarning + + +def _record_warning(message, category, filename, lineno, file=None, line=None): + # IPython compiles each cell twice. The first compile, named "<>", warns before the cell starts. + if issubclass(category, DEPRECATIONS) and filename != "<>": + location = f"{filename.split('site-packages/')[-1]}:{lineno}" + _warnings.setdefault( + (category, str(message), location), + { + # The notebook's code cell: 1, 2, ... (the mock is installed right before them) + "cell": get_ipython().execution_count - _first_cell, + "category": category.__name__, + "message": str(message), + "location": location, + }, + ) + _showwarning(message, category, filename, lineno, file, line) + + +# +# The client: no authentication, and no request leaves the kernel +# + + +def _mock_client() -> None: + from classiq._internals import client + from classiq._internals.authentication import password_manager, token_manager + + async def request(self, http_client, method, url, *args, **kwargs): + raise MockedClassiqApiCall(f"{method.upper()} {url}") + + def sync_call_api(self, http_method, url, *args, **kwargs): + raise MockedClassiqApiCall(f"{http_method.upper()} {url}") + + async def authenticate(self, overwrite): + pass + + token_manager.TokenManager._make_password_manager = classmethod( + lambda cls, config: password_manager.DummyPasswordManager() + ) + client.Client.check_host = lambda self: None + client.Client.authenticate = authenticate + client.Client.request = request + client.Client.sync_call_api = sync_call_api + + +# +# Fake results +# + + +def _install_fakes() -> None: + from classiq._internals.api_wrapper import ApiWrapper + + fakes = { + "call_generation_task": _synthesize, + "call_transpilation_task": _same_program, + "call_assign_parameters_task": _same_program, + "call_export_task": _export, + "call_circuit_metrics_task": _circuit_metrics, + "call_transpiled_circuit_metrics_task": _transpiled_circuit_metrics, + "call_convert_quantum_program": _convert, + "call_execute_execution_input": _execute, + "call_create_execution_session": _create_session, + "call_create_openqasm_execution_session": _create_openqasm_session, + "call_close_execution_session": _nothing, + "call_create_session_job": _create_session_job, + "call_get_execution_job_details": _job_details, + "call_get_execution_job_result": _job_result, + "call_cancel_execution_job": _nothing, + } + for name, fake in fakes.items(): + setattr(ApiWrapper, name, classmethod(_api_call(fake))) + + +def _api_call(fake): + async def api_call(cls, *args, **kwargs): + return fake(*args, **kwargs) + + return api_call + + +_random = random.Random(0) +_programs: dict = {} # program id -> quantum program +_sessions: dict = {} # session id -> quantum program +_jobs: dict = {} # job id -> (quantum program, primitives input) + + +def _nothing(*_, **__) -> None: + pass + + +def _synthesize(model, *_, **__): + from classiq.interface.compression_utils import compress_pydantic + from classiq.interface.generator.generated_circuit_data import ( + GeneratedCircuitData, + ) + from classiq.interface.generator.hardware.hardware_data import ( + SynthesisHardwareData, + ) + from classiq.interface.generator.model.model import ExecutionModel + from classiq.interface.generator.quantum_program import QuantumProgram + from classiq.interface.model.classical_parameter_declaration import ( + ClassicalParameterDeclaration, + ) + + output_types = _output_types(model) + parameters = [ + parameter + for parameter in model.main_func.positional_arg_declarations + if isinstance(parameter, ClassicalParameterDeclaration) + ] + program = QuantumProgram( + outputs={}, + hardware_data=SynthesisHardwareData(), + data=GeneratedCircuitData( + width=max(1, sum(output.size for output in output_types.values())) + ), + model=ExecutionModel( + circuit_output_types=output_types, + circuit_execution_params={p.name: p for p in parameters}, + execution_preferences=model.execution_preferences, + classical_execution_code=model.classical_execution_code, + ), + compressed_compiled_qmod=compress_pydantic(model), + ) + _programs[program.program_id] = program + return program + + +def _output_types(model) -> dict: + """The types of main's outputs, with each struct's fields and a size for each.""" + from classiq.interface.generator.functions.port_declaration import ( + PortDeclarationDirection, + ) + from classiq.interface.model.quantum_type import ( + quantum_type_to_register_quantum_type, + ) + + structs = {struct.name: struct for struct in model.qstructs} + output_types = {} + for port in model.main_func.port_declarations: + if port.direction == PortDeclarationDirection.Input: + continue + quantum_type = _with_fields(port.quantum_type, structs) + size = ( + quantum_type.size_in_bits if quantum_type.has_size_in_bits else UNKNOWN_SIZE + ) + output_types[port.name] = quantum_type_to_register_quantum_type( + quantum_type, size + ) + return output_types + + +def _with_fields(quantum_type, structs: dict): + from classiq.interface.generator.functions.type_name import TypeName + from classiq.interface.model.quantum_type import QuantumBitvector + + if isinstance(quantum_type, QuantumBitvector): + _with_fields(quantum_type.element_type, structs) + elif isinstance(quantum_type, TypeName) and quantum_type.name in structs: + fields = structs[quantum_type.name].fields + quantum_type.set_fields( + {name: _with_fields(field, structs) for name, field in fields.items()} + ) + return quantum_type + + +def _same_program(params, *_, **__): + return params.quantum_program + + +def _export(params, *_, **__): + from classiq.interface.executor.quantum_program_params import TargetCode + + width = params.quantum_program.data.width + if "3" in str(params.target_language): + code = f'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[{width}] q;\n' + else: + code = f'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[{width}];\n' + return TargetCode(code=code) + + +def _circuit_metrics(program, *_, **__): + from classiq.interface.ide.visual_model import CircuitMetrics + + width = program.data.width + return CircuitMetrics(width=width, depth=width, count_ops={"cx": width, "u": width}) + + +def _transpiled_circuit_metrics(program, *_, **__): + from classiq.interface.generator.hardware.hardware_data import ( + SynthesisHardwareData, + ) + from classiq.interface.ide.visual_model import ProgramData + + return ProgramData( + hardware_data=SynthesisHardwareData(), + circuit_metrics=_circuit_metrics(program), + ) + + +def _convert(program, *_, **__) -> dict: + _programs[program.program_id] = program + return {"program_id": program.program_id} + + +def _execute(execution_input: dict, *_, **__): + program = _programs[execution_input["program_id"]] + return _new_job(program, program.execution_primitives_input) + + +def _create_session(program, *_, **__) -> str: + session_id = f"session-{len(_sessions)}" + _sessions[session_id] = program + return session_id + + +def _create_openqasm_session(qasm, execution_preferences, *_, **__) -> str: + from classiq.interface.generator.generated_circuit_data import ( + GeneratedCircuitData, + ) + from classiq.interface.generator.hardware.hardware_data import ( + SynthesisHardwareData, + ) + from classiq.interface.generator.model.model import ExecutionModel + from classiq.interface.generator.quantum_program import QuantumProgram + + program = QuantumProgram( + outputs={}, + hardware_data=SynthesisHardwareData(), + data=GeneratedCircuitData(width=1), + model=ExecutionModel(execution_preferences=execution_preferences), + ) + return _create_session(program) + + +def _create_session_job(session_id: str, primitives_input, *_, **__): + return _new_job(_sessions[session_id], primitives_input) + + +def _new_job(program, primitives_input): + job_id = f"job-{len(_jobs)}" + _jobs[job_id] = (program, primitives_input) + return _job_details(job_id) + + +def _job_details(job_id, *_, **__): + from classiq.interface.executor.execution_request import ExecutionJobDetails + + job_id = getattr(job_id, "job_id", job_id) + program, primitives_input = _jobs[job_id] + return ExecutionJobDetails( + id=job_id, + start_time=datetime.datetime.now(datetime.timezone.utc), + end_time=datetime.datetime.now(datetime.timezone.utc), + status="COMPLETED", + program_id=program.program_id, + ) + + +def _job_result(job_id, *_, **__): + from classiq.interface.executor.execution_result import ( + ExecuteGeneratedCircuitResults, + ) + + program, primitives_input = _jobs[job_id.job_id] + return ExecuteGeneratedCircuitResults(results=[_result(program, primitives_input)]) + + +def _result(program, primitives_input): + from classiq.interface.executor.execution_result import ( + TaggedEstimationResults, + TaggedExecutionDetails, + TaggedMinimizeResult, + TaggedMultipleExecutionDetails, + ) + from classiq.interface.executor.result import ( + EstimationResult, + EstimationResults, + MultipleExecutionDetails, + ) + + preferences = program.model.execution_preferences + num_shots = ( + getattr(primitives_input, "num_shots", None) + or preferences.num_shots + or DEFAULT_NUM_SHOTS + ) + if primitives_input is not None and primitives_input.estimate is not None: + estimate = primitives_input.estimate + observables = estimate.observables + count = (len(observables) if isinstance(observables, list) else 1) * max( + 1, len(estimate.parameters) + ) + results = [ + EstimationResult(value=_random.uniform(0.25, 0.75), metadata={}) + for _ in range(count) + ] + return TaggedEstimationResults( + value_type="EstimationResults", + name="result", + value=EstimationResults(results=results), + ) + if primitives_input is not None and primitives_input.minimize is not None: + minimize = primitives_input.minimize + parameters = list(minimize.initial_params.values()) + iterations = [ + {"expectation_value": 1 / iteration, "parameters": parameters} + for iteration in range(1, max(1, minimize.max_iteration) + 1) + ] + return TaggedMinimizeResult( + value_type="MinimizeResult", name="result", value=iterations + ) + samples = getattr(primitives_input, "sample", None) or [{}] + if len(samples) == 1: + return TaggedExecutionDetails( + value_type="ExecutionDetails", + name="result", + value=_sample(program, num_shots), + ) + return TaggedMultipleExecutionDetails( + value_type="MultipleExecutionDetails", + name="result", + value=MultipleExecutionDetails( + details=[_sample(program, num_shots) for _ in samples] + ), + ) + + +def _sample(program, num_shots: int): + """Every possible value of the outputs (up to MAX_STATES), with similar counts.""" + from classiq.interface.executor.result import ExecutionDetails + from classiq.interface.executor.result_parsing import parse_states + + output_types = program.model.circuit_output_types + qubits, width = {}, 0 + for name, output_type in output_types.items(): + qubits[name] = tuple(range(width, width + output_type.size)) + width += output_type.size + bitstrings = _bitstrings(max(width, 1)) + parsed_states = parse_states(bitstrings, qubits, output_types) + + backend = str(program.model.execution_preferences.backend_preferences.backend_name) + if "statevector" in backend: + amplitude = complex(1 / math.sqrt(len(bitstrings))) + return ExecutionDetails( + vendor_format_result={}, + state_vector={bitstring: amplitude for bitstring in bitstrings}, + parsed_state_vector_states=parsed_states, + physical_qubits_map=qubits, + output_qubits_map=qubits, + output_type_map=output_types, + ) + counts = {bitstring: 1 for bitstring in bitstrings} + for _ in range(max(0, num_shots - len(bitstrings))): + counts[_random.choice(bitstrings)] += 1 + return ExecutionDetails( + vendor_format_result={}, + counts=counts, + parsed_states=parsed_states, + output_qubits_map=qubits, + output_type_map=output_types, + num_shots=sum(counts.values()), + ) + + +def _bitstrings(width: int) -> list[str]: + if 2**width <= MAX_STATES: + values = range(2**width) + else: + values = sorted({0, *(_random.getrandbits(width) for _ in range(MAX_STATES))}) + return [format(value, f"0{width}b") for value in values] diff --git a/tests/deprecations/test_deprecations.py b/tests/deprecations/test_deprecations.py new file mode 100644 index 000000000..8aa032936 --- /dev/null +++ b/tests/deprecations/test_deprecations.py @@ -0,0 +1,71 @@ +import re +from pathlib import Path + +import nbformat +import pytest +from nbclient.exceptions import CellExecutionError +from testbook import testbook # type: ignore[import] +from tests.utils_for_tests import ROOT_DIRECTORY, iterate_notebooks +from tests.utils_for_testbook import ( + DEFAULT_CODE_INJECTIONS, + NotebookEdit, + _build_cd_decorator, +) + +TIMEOUT: int = 60 * 15 # 15 minutes + +PYTHON_CODE_PATTERN = r"(?s)```python\s*\n(.*?)```" + +INSTALL_MOCK = ( + f"import sys; sys.path.insert(0, {str(Path(__file__).parent)!r})\n" + "import mock_classiq_api; sys.path.pop(0); mock_classiq_api.install()" +) +# NotebookEdit inserts each cell at the top, so the mock is installed right before the notebook's first cell +INJECTED_CELLS = [INSTALL_MOCK] + DEFAULT_CODE_INJECTIONS +REPORT = "__import__('mock_classiq_api').report()" + + +def _should_test_notebook(notebook_path: str) -> bool: + return True + + +@pytest.mark.parametrize( + "notebook_path", list(filter(_should_test_notebook, iterate_notebooks())) +) +def test_notebook(notebook_path: str) -> None: + _test_notebook(notebook_path) + + +def test_readme(tmp_path: Path) -> None: + readme = (ROOT_DIRECTORY / "README.md").read_text() + cells = [ + nbformat.v4.new_code_cell(code) + for code in re.findall(PYTHON_CODE_PATTERN, readme) + ] + notebook_path = str(tmp_path / "README.ipynb") + nbformat.write(nbformat.v4.new_notebook(cells=cells), notebook_path) + _test_notebook(notebook_path) + + +def _test_notebook(notebook_path: str) -> None: + test = _run_without_deprecations + with NotebookEdit(notebook_path, code_injection_at_start=INJECTED_CELLS): + test = testbook(notebook_path, timeout=TIMEOUT)(test) + test = _build_cd_decorator(notebook_path)(test) + test() + + +def _run_without_deprecations(tb) -> None: + error = None + try: + tb.execute() + except CellExecutionError as exc: + error = exc + + problems = [ + f"cell {warning['cell']}: {warning['category']}: {warning['message']} ({warning['location']})" + for warning in tb.value(REPORT) + ] + if error is not None: + problems.append(str(error)) + assert not problems, "\n".join(problems) From f5263155b48806823395be13c30503c8e65eb29a Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 13:34:17 +0200 Subject: [PATCH 2/8] temporarily run the deprecation test on workflow_dispatch Co-Authored-By: Claude Opus 5.5 --- .github/workflows/Test-CI-deprecations.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Test-CI-deprecations.yml b/.github/workflows/Test-CI-deprecations.yml index 3402c468e..83741874c 100644 --- a/.github/workflows/Test-CI-deprecations.yml +++ b/.github/workflows/Test-CI-deprecations.yml @@ -21,7 +21,7 @@ defaults: jobs: test: - if: false # TODO: remove once the test exists + if: github.event_name == 'workflow_dispatch' # TEMPORARY: for a full dispatch run; back to `if: false` before review permissions: contents: read From 34885d33b21f82099acd06b594c0780c85a10295 Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 14:21:18 +0200 Subject: [PATCH 3/8] make the fake results realistic enough to run more notebooks to the end Co-Authored-By: Claude Opus 5.5 --- tests/deprecations/mock_classiq_api.py | 116 +++++++++++++++++++++---- 1 file changed, 101 insertions(+), 15 deletions(-) diff --git a/tests/deprecations/mock_classiq_api.py b/tests/deprecations/mock_classiq_api.py index f4c8e0e07..2cca18940 100644 --- a/tests/deprecations/mock_classiq_api.py +++ b/tests/deprecations/mock_classiq_api.py @@ -12,6 +12,7 @@ import math import random import warnings +from collections import Counter from IPython import get_ipython @@ -22,7 +23,7 @@ SyntaxWarning, ) -# A fake sample returns every possible bitstring of the outputs, up to this many +# A fake sample returns every combination of the outputs' values, up to this many MAX_STATES = 1024 # The size of an output whose size the notebook doesn't set (e.g. `Output[QNum]`) UNKNOWN_SIZE = 4 @@ -123,6 +124,8 @@ def _install_fakes() -> None: "call_get_execution_job_details": _job_details, "call_get_execution_job_result": _job_result, "call_cancel_execution_job": _nothing, + "call_get_all_hardware_devices": lambda *_, **__: [], + "call_rb_analysis_task": _rb_analysis, } for name, fake in fakes.items(): setattr(ApiWrapper, name, classmethod(_api_call(fake))) @@ -172,6 +175,7 @@ def _synthesize(model, *_, **__): width=max(1, sum(output.size for output in output_types.values())) ), model=ExecutionModel( + circuit_outputs=model.main_func.outputs_dict, circuit_output_types=output_types, circuit_execution_params={p.name: p for p in parameters}, execution_preferences=model.execution_preferences, @@ -226,13 +230,16 @@ def _same_program(params, *_, **__): def _export(params, *_, **__): - from classiq.interface.executor.quantum_program_params import TargetCode + from classiq.interface.executor.quantum_program_params import ( + TargetCode, + TargetLanguage, + ) width = params.quantum_program.data.width - if "3" in str(params.target_language): - code = f'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[{width}] q;\n' - else: + if params.target_language == TargetLanguage.QASM2: code = f'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[{width}];\n' + else: + code = f'OPENQASM 3.0;\ninclude "stdgates.inc";\nqubit[{width}] q;\n' return TargetCode(code=code) @@ -240,7 +247,11 @@ def _circuit_metrics(program, *_, **__): from classiq.interface.ide.visual_model import CircuitMetrics width = program.data.width - return CircuitMetrics(width=width, depth=width, count_ops={"cx": width, "u": width}) + model = program.compiled_qmod + gates = model.preferences.custom_hardware_settings.basis_gates if model else [] + return CircuitMetrics( + width=width, depth=width, count_ops={str(gate): width for gate in gates} + ) def _transpiled_circuit_metrics(program, *_, **__): @@ -255,6 +266,19 @@ def _transpiled_circuit_metrics(program, *_, **__): ) +def _rb_analysis(params, *_, **__): + from classiq.interface.analyzer.result import RbResults + + return RbResults( + mean_fidelity=0.99, + average_error=0.01, + A=0.5, + B=0.5, + success_probability=[0.9] * len(params.num_clifford), + parameters_error=(0.01, 0.01, 0.01), + ) + + def _convert(program, *_, **__) -> dict: _programs[program.program_id] = program return {"program_id": program.program_id} @@ -320,9 +344,61 @@ def _job_result(job_id, *_, **__): ) program, primitives_input = _jobs[job_id.job_id] + if "vqe(" in program.model.classical_execution_code: + return ExecuteGeneratedCircuitResults(results=_vqe_results(program)) return ExecuteGeneratedCircuitResults(results=[_result(program, primitives_input)]) +def _vqe_results(program) -> list: + """The legacy flow: the program's classical code runs VQE, and saves its result and the hamiltonian.""" + import base64 + import io + + from classiq.interface.executor.execution_result import ( + TaggedUnstructured, + TaggedVQESolverResult, + ) + from classiq.interface.executor.vqe_result import ( + VQEIntermediateData, + VQESolverResult, + ) + from PIL import Image + + sample = _sample(program, DEFAULT_NUM_SHOTS) + probabilities = { + bitstring: count / sample.num_shots + for bitstring, count in sample.counts.items() + } + convergence_graph = io.BytesIO() + Image.new("RGB", (1, 1)).save(convergence_graph, format="PNG") + vqe_result = VQESolverResult( + energy=0.5, + time=1.0, + eigenstate={bitstring: math.sqrt(p) for bitstring, p in probabilities.items()}, + reduced_probabilities=probabilities, + optimized_circuit_sample_results=sample, + intermediate_results=[ + VQEIntermediateData( + utc_time=datetime.datetime.now(datetime.timezone.utc), + iteration_number=1, + parameters=[0.0], + mean_all_solutions=0.5, + solutions=[], + standard_deviation=0.1, + ) + ], + optimal_parameters={"param_0": 0.0}, + convergence_graph_str=base64.b64encode(convergence_graph.getvalue()).decode(), + num_shots=sample.num_shots, + ) + return [ + TaggedVQESolverResult( + value_type="VQESolverResult", name="vqe_result", value=vqe_result + ), + TaggedUnstructured(value_type="Unstructured", name="hamiltonian", value=[]), + ] + + def _result(program, primitives_input): from classiq.interface.executor.execution_result import ( TaggedEstimationResults, @@ -384,7 +460,7 @@ def _result(program, primitives_input): def _sample(program, num_shots: int): - """Every possible value of the outputs (up to MAX_STATES), with similar counts.""" + """Every possible value of the outputs, with similar counts.""" from classiq.interface.executor.result import ExecutionDetails from classiq.interface.executor.result_parsing import parse_states @@ -393,7 +469,7 @@ def _sample(program, num_shots: int): for name, output_type in output_types.items(): qubits[name] = tuple(range(width, width + output_type.size)) width += output_type.size - bitstrings = _bitstrings(max(width, 1)) + bitstrings = _bitstrings(qubits, max(width, 1)) parsed_states = parse_states(bitstrings, qubits, output_types) backend = str(program.model.execution_preferences.backend_preferences.backend_name) @@ -407,22 +483,32 @@ def _sample(program, num_shots: int): output_qubits_map=qubits, output_type_map=output_types, ) - counts = {bitstring: 1 for bitstring in bitstrings} - for _ in range(max(0, num_shots - len(bitstrings))): - counts[_random.choice(bitstrings)] += 1 + # Each value once (as far as the shots go), and the other shots at random + counts = Counter(bitstrings[:num_shots]) + counts.update(_random.choices(bitstrings, k=num_shots - counts.total())) return ExecutionDetails( vendor_format_result={}, - counts=counts, + counts=dict(counts), parsed_states=parsed_states, output_qubits_map=qubits, output_type_map=output_types, - num_shots=sum(counts.values()), + num_shots=num_shots, ) -def _bitstrings(width: int) -> list[str]: +def _bitstrings(qubits: dict, width: int) -> list[str]: + """Every combination of the outputs' values. + If there are too many, every value of each output (up to MAX_STATES), while the others are 0. + """ if 2**width <= MAX_STATES: values = range(2**width) else: - values = sorted({0, *(_random.getrandbits(width) for _ in range(MAX_STATES))}) + values = sorted( + { + value << indices[0] + for indices in qubits.values() + if indices + for value in range(min(2 ** len(indices), MAX_STATES)) + } + ) return [format(value, f"0{width}b") for value in values] From 98585e0e464fe12686a0f74d118d2b50bc6287ae Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 14:21:25 +0200 Subject: [PATCH 4/8] skip the notebooks' asserts, since the fakes can't reproduce real results Co-Authored-By: Claude Opus 5.5 --- tests/deprecations/mock_classiq_api.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/deprecations/mock_classiq_api.py b/tests/deprecations/mock_classiq_api.py index 2cca18940..80a882b5d 100644 --- a/tests/deprecations/mock_classiq_api.py +++ b/tests/deprecations/mock_classiq_api.py @@ -5,9 +5,12 @@ a state vector, expectation values, ...), so the notebook runs to its end and reaches all of its API calls. Nothing is sent to the Classiq platform: an API call without a fake raises `MockedClassiqApiCall`. +- The fakes can't reproduce real results, so the notebook's `assert` statements are + skipped, like with `python -O`. - Every deprecation warning is recorded. `report()` returns them. """ +import ast import datetime import math import random @@ -37,6 +40,7 @@ class MockedClassiqApiCall(Exception): def install() -> None: global _first_cell _first_cell = get_ipython().execution_count + get_ipython().ast_transformers.append(_SkipAsserts()) warnings.showwarning = _record_warning warnings.simplefilter("always") _mock_client() @@ -47,6 +51,11 @@ def report() -> list[dict]: return list(_warnings.values()) +class _SkipAsserts(ast.NodeTransformer): + def visit_Assert(self, node: ast.Assert) -> ast.Pass: + return ast.copy_location(ast.Pass(), node) + + # # Recording warnings # From 561373f4522e7aa061b04ae4142294884a0650b5 Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 15:24:38 +0200 Subject: [PATCH 5/8] sample every combination of up to 14 qubits, add counts to state vectors, and skip the notebooks the fakes can't run Co-Authored-By: Claude Opus 5.5 --- tests/deprecations/mock_classiq_api.py | 26 +++++++++++-------------- tests/deprecations/test_deprecations.py | 17 +++++++++++++++- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/tests/deprecations/mock_classiq_api.py b/tests/deprecations/mock_classiq_api.py index 80a882b5d..f1bb5717c 100644 --- a/tests/deprecations/mock_classiq_api.py +++ b/tests/deprecations/mock_classiq_api.py @@ -27,7 +27,7 @@ ) # A fake sample returns every combination of the outputs' values, up to this many -MAX_STATES = 1024 +MAX_STATES = 2**14 # The size of an output whose size the notebook doesn't set (e.g. `Output[QNum]`) UNKNOWN_SIZE = 4 DEFAULT_NUM_SHOTS = 2048 @@ -481,21 +481,10 @@ def _sample(program, num_shots: int): bitstrings = _bitstrings(qubits, max(width, 1)) parsed_states = parse_states(bitstrings, qubits, output_types) - backend = str(program.model.execution_preferences.backend_preferences.backend_name) - if "statevector" in backend: - amplitude = complex(1 / math.sqrt(len(bitstrings))) - return ExecutionDetails( - vendor_format_result={}, - state_vector={bitstring: amplitude for bitstring in bitstrings}, - parsed_state_vector_states=parsed_states, - physical_qubits_map=qubits, - output_qubits_map=qubits, - output_type_map=output_types, - ) - # Each value once (as far as the shots go), and the other shots at random - counts = Counter(bitstrings[:num_shots]) + # Each value once (or a random part of them, if there are fewer shots), and the other shots at random + counts = Counter(_random.sample(bitstrings, min(num_shots, len(bitstrings)))) counts.update(_random.choices(bitstrings, k=num_shots - counts.total())) - return ExecutionDetails( + details = ExecutionDetails( vendor_format_result={}, counts=dict(counts), parsed_states=parsed_states, @@ -503,6 +492,13 @@ def _sample(program, num_shots: int): output_type_map=output_types, num_shots=num_shots, ) + backend = str(program.model.execution_preferences.backend_preferences.backend_name) + if "statevector" in backend: + amplitude = complex(1 / math.sqrt(len(bitstrings))) + details.state_vector = {bitstring: amplitude for bitstring in bitstrings} + details.parsed_state_vector_states = parsed_states + details.physical_qubits_map = qubits + return details def _bitstrings(qubits: dict, width: int) -> list[str]: diff --git a/tests/deprecations/test_deprecations.py b/tests/deprecations/test_deprecations.py index 8aa032936..885569795 100644 --- a/tests/deprecations/test_deprecations.py +++ b/tests/deprecations/test_deprecations.py @@ -1,3 +1,4 @@ +import os import re from pathlib import Path @@ -25,8 +26,22 @@ REPORT = "__import__('mock_classiq_api').report()" +# Notebooks that the fakes can't run to their end +SKIPPED_NOTEBOOKS = { + "fault_tolerance_engine_end_to_end.ipynb": "uses the logical-noise API, which has no fake", + "projected_based_embedding_tutorial.ipynb": "runs chemistry DFT jobs, which have no fake", + "adapt_vqe.ipynb": "builds its next model from the measured gradients", + "bpde.ipynb": "fits a Gaussian to its samples", + "discrete_log.ipynb": "needs an invertible measured value", + "fermi_hubbard_1D.ipynb": "expects one-hot states in its state vector", + "hhl.ipynb": "raises when its result is far from the classical solution", + "hidden_shift.ipynb": "solves a linear system built from its samples", + "vehicle_routing_problem.ipynb": "colors a graph by the sampled solution", +} + + def _should_test_notebook(notebook_path: str) -> bool: - return True + return os.path.basename(notebook_path) not in SKIPPED_NOTEBOOKS @pytest.mark.parametrize( From f0ac36a9f9ff5a5e7d32f86c541eaee992443868 Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 16:08:08 +0200 Subject: [PATCH 6/8] apply the state filters, sample with replacement when there are fewer shots than states, and skip adapt_qaoa Co-Authored-By: Claude Opus 5.5 --- tests/deprecations/mock_classiq_api.py | 11 ++++++++--- tests/deprecations/test_deprecations.py | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/deprecations/mock_classiq_api.py b/tests/deprecations/mock_classiq_api.py index f1bb5717c..5407f57c3 100644 --- a/tests/deprecations/mock_classiq_api.py +++ b/tests/deprecations/mock_classiq_api.py @@ -478,11 +478,16 @@ def _sample(program, num_shots: int): for name, output_type in output_types.items(): qubits[name] = tuple(range(width, width + output_type.size)) width += output_type.size - bitstrings = _bitstrings(qubits, max(width, 1)) + width = max(width, 1) + bitstrings = _bitstrings(qubits, width) + # Keep the states that pass the filters, e.g. of `calculate_state_vector(filters=...)` + for name, legal_values in program.model.register_filter_bitstrings.items(): + start, end = width - qubits[name][-1] - 1, width - qubits[name][0] + bitstrings = [b for b in bitstrings if b[start:end] in legal_values] parsed_states = parse_states(bitstrings, qubits, output_types) - # Each value once (or a random part of them, if there are fewer shots), and the other shots at random - counts = Counter(_random.sample(bitstrings, min(num_shots, len(bitstrings)))) + # Each value once (if the shots suffice), and the other shots at random + counts = Counter(bitstrings if num_shots >= len(bitstrings) else []) counts.update(_random.choices(bitstrings, k=num_shots - counts.total())) details = ExecutionDetails( vendor_format_result={}, diff --git a/tests/deprecations/test_deprecations.py b/tests/deprecations/test_deprecations.py index 885569795..abef59182 100644 --- a/tests/deprecations/test_deprecations.py +++ b/tests/deprecations/test_deprecations.py @@ -30,6 +30,7 @@ SKIPPED_NOTEBOOKS = { "fault_tolerance_engine_end_to_end.ipynb": "uses the logical-noise API, which has no fake", "projected_based_embedding_tutorial.ipynb": "runs chemistry DFT jobs, which have no fake", + "adapt_qaoa.ipynb": "loops until the measured gradients are small", "adapt_vqe.ipynb": "builds its next model from the measured gradients", "bpde.ipynb": "fits a Gaussian to its samples", "discrete_log.ipynb": "needs an invertible measured value", From f8cf1dcad0c8554f1c2a7a3092c08f7db13f0861 Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 16:50:19 +0200 Subject: [PATCH 7/8] keep the deprecation test off until the notebooks are free of deprecations Co-Authored-By: Claude Opus 5.5 --- .github/workflows/Test-CI-deprecations.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Test-CI-deprecations.yml b/.github/workflows/Test-CI-deprecations.yml index 83741874c..89cc0e8db 100644 --- a/.github/workflows/Test-CI-deprecations.yml +++ b/.github/workflows/Test-CI-deprecations.yml @@ -2,7 +2,7 @@ name: "Test Library CI (deprecations)" # Will run the notebooks with the classiq API mocked, and fail on deprecation warnings: # PRs: the notebooks whose code changed. Weekly: all notebooks. -# A placeholder for now: the job is off (`if: false`) until the test exists. +# The job is off (`if: false`) until the notebooks are free of deprecations. on: # PRs (including forks) @@ -21,7 +21,7 @@ defaults: jobs: test: - if: github.event_name == 'workflow_dispatch' # TEMPORARY: for a full dispatch run; back to `if: false` before review + if: false # TODO: remove once the notebooks are free of deprecations permissions: contents: read From 867ea02244271d05bbfb59c6545b5fe32b0c4d1e Mon Sep 17 00:00:00 2001 From: Dor Harpaz Date: Thu, 19 Nov 2026 16:52:59 +0200 Subject: [PATCH 8/8] import the sdk at the top of the mock, and share the fake program's fields Co-Authored-By: Claude Opus 5.5 --- tests/deprecations/mock_classiq_api.py | 186 ++++++++++--------------- 1 file changed, 72 insertions(+), 114 deletions(-) diff --git a/tests/deprecations/mock_classiq_api.py b/tests/deprecations/mock_classiq_api.py index 5407f57c3..b9ed75114 100644 --- a/tests/deprecations/mock_classiq_api.py +++ b/tests/deprecations/mock_classiq_api.py @@ -11,13 +11,56 @@ """ import ast +import base64 import datetime +import io import math import random import warnings from collections import Counter +from classiq._internals import client +from classiq._internals.api_wrapper import ApiWrapper +from classiq._internals.authentication import password_manager, token_manager +from classiq.interface.analyzer.result import RbResults +from classiq.interface.compression_utils import compress_pydantic +from classiq.interface.executor.execution_request import ExecutionJobDetails +from classiq.interface.executor.execution_result import ( + ExecuteGeneratedCircuitResults, + TaggedEstimationResults, + TaggedExecutionDetails, + TaggedMinimizeResult, + TaggedMultipleExecutionDetails, + TaggedUnstructured, + TaggedVQESolverResult, +) +from classiq.interface.executor.quantum_program_params import TargetCode, TargetLanguage +from classiq.interface.executor.result import ( + EstimationResult, + EstimationResults, + ExecutionDetails, + MultipleExecutionDetails, +) +from classiq.interface.executor.result_parsing import parse_states +from classiq.interface.executor.vqe_result import VQEIntermediateData, VQESolverResult +from classiq.interface.generator.functions.port_declaration import ( + PortDeclarationDirection, +) +from classiq.interface.generator.functions.type_name import TypeName +from classiq.interface.generator.generated_circuit_data import GeneratedCircuitData +from classiq.interface.generator.hardware.hardware_data import SynthesisHardwareData +from classiq.interface.generator.model.model import ExecutionModel +from classiq.interface.generator.quantum_program import QuantumProgram +from classiq.interface.ide.visual_model import CircuitMetrics, ProgramData +from classiq.interface.model.classical_parameter_declaration import ( + ClassicalParameterDeclaration, +) +from classiq.interface.model.quantum_type import ( + QuantumBitvector, + quantum_type_to_register_quantum_type, +) from IPython import get_ipython +from PIL import Image DEPRECATIONS = ( DeprecationWarning, @@ -88,9 +131,6 @@ def _record_warning(message, category, filename, lineno, file=None, line=None): def _mock_client() -> None: - from classiq._internals import client - from classiq._internals.authentication import password_manager, token_manager - async def request(self, http_client, method, url, *args, **kwargs): raise MockedClassiqApiCall(f"{method.upper()} {url}") @@ -115,8 +155,6 @@ async def authenticate(self, overwrite): def _install_fakes() -> None: - from classiq._internals.api_wrapper import ApiWrapper - fakes = { "call_generation_task": _synthesize, "call_transpilation_task": _same_program, @@ -157,35 +195,27 @@ def _nothing(*_, **__) -> None: pass -def _synthesize(model, *_, **__): - from classiq.interface.compression_utils import compress_pydantic - from classiq.interface.generator.generated_circuit_data import ( - GeneratedCircuitData, - ) - from classiq.interface.generator.hardware.hardware_data import ( - SynthesisHardwareData, - ) - from classiq.interface.generator.model.model import ExecutionModel - from classiq.interface.generator.quantum_program import QuantumProgram - from classiq.interface.model.classical_parameter_declaration import ( - ClassicalParameterDeclaration, +def _program(model: ExecutionModel, **fields) -> QuantumProgram: + width = sum(output.size for output in model.circuit_output_types.values()) + return QuantumProgram( + outputs={}, + hardware_data=SynthesisHardwareData(), + data=GeneratedCircuitData(width=max(1, width)), + model=model, + **fields, ) - output_types = _output_types(model) + +def _synthesize(model, *_, **__) -> QuantumProgram: parameters = [ parameter for parameter in model.main_func.positional_arg_declarations if isinstance(parameter, ClassicalParameterDeclaration) ] - program = QuantumProgram( - outputs={}, - hardware_data=SynthesisHardwareData(), - data=GeneratedCircuitData( - width=max(1, sum(output.size for output in output_types.values())) - ), - model=ExecutionModel( + program = _program( + ExecutionModel( + circuit_output_types=_output_types(model), circuit_outputs=model.main_func.outputs_dict, - circuit_output_types=output_types, circuit_execution_params={p.name: p for p in parameters}, execution_preferences=model.execution_preferences, classical_execution_code=model.classical_execution_code, @@ -198,13 +228,6 @@ def _synthesize(model, *_, **__): def _output_types(model) -> dict: """The types of main's outputs, with each struct's fields and a size for each.""" - from classiq.interface.generator.functions.port_declaration import ( - PortDeclarationDirection, - ) - from classiq.interface.model.quantum_type import ( - quantum_type_to_register_quantum_type, - ) - structs = {struct.name: struct for struct in model.qstructs} output_types = {} for port in model.main_func.port_declarations: @@ -221,9 +244,6 @@ def _output_types(model) -> dict: def _with_fields(quantum_type, structs: dict): - from classiq.interface.generator.functions.type_name import TypeName - from classiq.interface.model.quantum_type import QuantumBitvector - if isinstance(quantum_type, QuantumBitvector): _with_fields(quantum_type.element_type, structs) elif isinstance(quantum_type, TypeName) and quantum_type.name in structs: @@ -234,16 +254,11 @@ def _with_fields(quantum_type, structs: dict): return quantum_type -def _same_program(params, *_, **__): +def _same_program(params, *_, **__) -> QuantumProgram: return params.quantum_program -def _export(params, *_, **__): - from classiq.interface.executor.quantum_program_params import ( - TargetCode, - TargetLanguage, - ) - +def _export(params, *_, **__) -> TargetCode: width = params.quantum_program.data.width if params.target_language == TargetLanguage.QASM2: code = f'OPENQASM 2.0;\ninclude "qelib1.inc";\nqreg q[{width}];\n' @@ -252,9 +267,7 @@ def _export(params, *_, **__): return TargetCode(code=code) -def _circuit_metrics(program, *_, **__): - from classiq.interface.ide.visual_model import CircuitMetrics - +def _circuit_metrics(program, *_, **__) -> CircuitMetrics: width = program.data.width model = program.compiled_qmod gates = model.preferences.custom_hardware_settings.basis_gates if model else [] @@ -263,21 +276,14 @@ def _circuit_metrics(program, *_, **__): ) -def _transpiled_circuit_metrics(program, *_, **__): - from classiq.interface.generator.hardware.hardware_data import ( - SynthesisHardwareData, - ) - from classiq.interface.ide.visual_model import ProgramData - +def _transpiled_circuit_metrics(program, *_, **__) -> ProgramData: return ProgramData( hardware_data=SynthesisHardwareData(), circuit_metrics=_circuit_metrics(program), ) -def _rb_analysis(params, *_, **__): - from classiq.interface.analyzer.result import RbResults - +def _rb_analysis(params, *_, **__) -> RbResults: return RbResults( mean_fidelity=0.99, average_error=0.01, @@ -293,7 +299,7 @@ def _convert(program, *_, **__) -> dict: return {"program_id": program.program_id} -def _execute(execution_input: dict, *_, **__): +def _execute(execution_input: dict, *_, **__) -> ExecutionJobDetails: program = _programs[execution_input["program_id"]] return _new_job(program, program.execution_primitives_input) @@ -305,53 +311,34 @@ def _create_session(program, *_, **__) -> str: def _create_openqasm_session(qasm, execution_preferences, *_, **__) -> str: - from classiq.interface.generator.generated_circuit_data import ( - GeneratedCircuitData, - ) - from classiq.interface.generator.hardware.hardware_data import ( - SynthesisHardwareData, - ) - from classiq.interface.generator.model.model import ExecutionModel - from classiq.interface.generator.quantum_program import QuantumProgram - - program = QuantumProgram( - outputs={}, - hardware_data=SynthesisHardwareData(), - data=GeneratedCircuitData(width=1), - model=ExecutionModel(execution_preferences=execution_preferences), - ) + program = _program(ExecutionModel(execution_preferences=execution_preferences)) return _create_session(program) -def _create_session_job(session_id: str, primitives_input, *_, **__): +def _create_session_job(session_id, primitives_input, *_, **__) -> ExecutionJobDetails: return _new_job(_sessions[session_id], primitives_input) -def _new_job(program, primitives_input): +def _new_job(program, primitives_input) -> ExecutionJobDetails: job_id = f"job-{len(_jobs)}" _jobs[job_id] = (program, primitives_input) return _job_details(job_id) -def _job_details(job_id, *_, **__): - from classiq.interface.executor.execution_request import ExecutionJobDetails - +def _job_details(job_id, *_, **__) -> ExecutionJobDetails: job_id = getattr(job_id, "job_id", job_id) program, primitives_input = _jobs[job_id] + now = datetime.datetime.now(datetime.timezone.utc) return ExecutionJobDetails( id=job_id, - start_time=datetime.datetime.now(datetime.timezone.utc), - end_time=datetime.datetime.now(datetime.timezone.utc), + start_time=now, + end_time=now, status="COMPLETED", program_id=program.program_id, ) -def _job_result(job_id, *_, **__): - from classiq.interface.executor.execution_result import ( - ExecuteGeneratedCircuitResults, - ) - +def _job_result(job_id, *_, **__) -> ExecuteGeneratedCircuitResults: program, primitives_input = _jobs[job_id.job_id] if "vqe(" in program.model.classical_execution_code: return ExecuteGeneratedCircuitResults(results=_vqe_results(program)) @@ -360,19 +347,6 @@ def _job_result(job_id, *_, **__): def _vqe_results(program) -> list: """The legacy flow: the program's classical code runs VQE, and saves its result and the hamiltonian.""" - import base64 - import io - - from classiq.interface.executor.execution_result import ( - TaggedUnstructured, - TaggedVQESolverResult, - ) - from classiq.interface.executor.vqe_result import ( - VQEIntermediateData, - VQESolverResult, - ) - from PIL import Image - sample = _sample(program, DEFAULT_NUM_SHOTS) probabilities = { bitstring: count / sample.num_shots @@ -409,22 +383,9 @@ def _vqe_results(program) -> list: def _result(program, primitives_input): - from classiq.interface.executor.execution_result import ( - TaggedEstimationResults, - TaggedExecutionDetails, - TaggedMinimizeResult, - TaggedMultipleExecutionDetails, - ) - from classiq.interface.executor.result import ( - EstimationResult, - EstimationResults, - MultipleExecutionDetails, - ) - - preferences = program.model.execution_preferences num_shots = ( getattr(primitives_input, "num_shots", None) - or preferences.num_shots + or program.model.execution_preferences.num_shots or DEFAULT_NUM_SHOTS ) if primitives_input is not None and primitives_input.estimate is not None: @@ -468,11 +429,8 @@ def _result(program, primitives_input): ) -def _sample(program, num_shots: int): +def _sample(program, num_shots: int) -> ExecutionDetails: """Every possible value of the outputs, with similar counts.""" - from classiq.interface.executor.result import ExecutionDetails - from classiq.interface.executor.result_parsing import parse_states - output_types = program.model.circuit_output_types qubits, width = {}, 0 for name, output_type in output_types.items():