localqpu 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. localqpu-0.1.0/.dockerignore +7 -0
  2. localqpu-0.1.0/.gitignore +11 -0
  3. localqpu-0.1.0/.python-version +1 -0
  4. localqpu-0.1.0/Dockerfile +9 -0
  5. localqpu-0.1.0/LICENSE +202 -0
  6. localqpu-0.1.0/PKG-INFO +117 -0
  7. localqpu-0.1.0/README.md +94 -0
  8. localqpu-0.1.0/pyproject.toml +80 -0
  9. localqpu-0.1.0/src/localqpu/__init__.py +10 -0
  10. localqpu-0.1.0/src/localqpu/_compat.py +53 -0
  11. localqpu-0.1.0/src/localqpu/app.py +52 -0
  12. localqpu-0.1.0/src/localqpu/cli.py +158 -0
  13. localqpu-0.1.0/src/localqpu/client.py +57 -0
  14. localqpu-0.1.0/src/localqpu/constants.py +39 -0
  15. localqpu-0.1.0/src/localqpu/context.py +34 -0
  16. localqpu-0.1.0/src/localqpu/control.py +84 -0
  17. localqpu-0.1.0/src/localqpu/control_client.py +58 -0
  18. localqpu-0.1.0/src/localqpu/http_util.py +39 -0
  19. localqpu-0.1.0/src/localqpu/ibm/__init__.py +1 -0
  20. localqpu-0.1.0/src/localqpu/ibm/backends.py +100 -0
  21. localqpu-0.1.0/src/localqpu/ibm/routes.py +274 -0
  22. localqpu-0.1.0/src/localqpu/jobs.py +272 -0
  23. localqpu-0.1.0/src/localqpu/programs/__init__.py +31 -0
  24. localqpu-0.1.0/src/localqpu/programs/base.py +47 -0
  25. localqpu-0.1.0/src/localqpu/programs/executor.py +95 -0
  26. localqpu-0.1.0/src/localqpu/programs/sampler.py +63 -0
  27. localqpu-0.1.0/src/localqpu/pytest_plugin.py +44 -0
  28. localqpu-0.1.0/src/localqpu/scenario.py +351 -0
  29. localqpu-0.1.0/src/localqpu/server.py +290 -0
  30. localqpu-0.1.0/src/localqpu/simulation.py +139 -0
  31. localqpu-0.1.0/tests/__init__.py +0 -0
  32. localqpu-0.1.0/tests/contract/__init__.py +0 -0
  33. localqpu-0.1.0/tests/contract/helpers.py +13 -0
  34. localqpu-0.1.0/tests/contract/test_fault_contract.py +153 -0
  35. localqpu-0.1.0/tests/contract/test_happy_path_contract.py +63 -0
  36. localqpu-0.1.0/tests/test_backends.py +44 -0
  37. localqpu-0.1.0/tests/test_cli.py +88 -0
  38. localqpu-0.1.0/tests/test_control.py +93 -0
  39. localqpu-0.1.0/tests/test_ibm_routes.py +219 -0
  40. localqpu-0.1.0/tests/test_jobs.py +294 -0
  41. localqpu-0.1.0/tests/test_package.py +10 -0
  42. localqpu-0.1.0/tests/test_programs.py +99 -0
  43. localqpu-0.1.0/tests/test_scenario.py +170 -0
  44. localqpu-0.1.0/tests/test_server.py +166 -0
  45. localqpu-0.1.0/tests/test_simulation.py +137 -0
  46. localqpu-0.1.0/uv.lock +2117 -0
@@ -0,0 +1,7 @@
1
+ .venv
2
+ .git
3
+ **/__pycache__
4
+ .pytest_cache
5
+ .mypy_cache
6
+ .ruff_cache
7
+ dist
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ .env
9
+ .env.*
10
+ # 로컬 코드 분석 도구(serena) 캐시
11
+ .serena/
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,9 @@
1
+ # localqpu 컨테이너. 컨테이너 안에서는 외부에서 접속할 수 있도록 0.0.0.0에 바인딩한다.
2
+ # 호스트에서는 루프백에만 노출하는 것을 권장한다: docker run -p 127.0.0.1:8787:8787 localqpu
3
+ FROM python:3.12-slim
4
+ WORKDIR /app
5
+ COPY pyproject.toml README.md LICENSE ./
6
+ COPY src ./src
7
+ RUN pip install --no-cache-dir .
8
+ EXPOSE 8787
9
+ CMD ["localqpu", "start", "--host", "0.0.0.0", "--port", "8787"]
localqpu-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.5
2
+ Name: localqpu
3
+ Version: 0.1.0
4
+ Summary: A local emulator of the IBM Quantum Platform API, built for testing
5
+ Project-URL: Repository, https://github.com/ictechgy/localqpu
6
+ Project-URL: Issues, https://github.com/ictechgy/localqpu/issues
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: emulator,ibm-quantum,mock,qiskit,quantum,testing
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Pytest
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Physics
17
+ Classifier: Topic :: Software Development :: Testing :: Mocking
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: pyjwt>=2.8
20
+ Requires-Dist: qiskit-aer>=0.17
21
+ Requires-Dist: qiskit-ibm-runtime>=0.50
22
+ Description-Content-Type: text/markdown
23
+
24
+ # localqpu
25
+
26
+ A local emulator of the IBM Quantum Platform API, built for testing.
27
+ Like a payment provider's "test mode", it lets you test code that calls a quantum cloud **without queues, without cost, and with any failure you want to simulate**.
28
+
29
+ > localqpu does not verify that quantum results are *correct*. It verifies **the code around the quantum API call**: submission, waiting, retries, result parsing, and error handling.
30
+
31
+ ## Install and run
32
+
33
+ ```bash
34
+ pip install localqpu # https://pypi.org/project/localqpu/
35
+ localqpu start # http://127.0.0.1:8787
36
+ # or
37
+ docker build -t localqpu . && docker run -p 127.0.0.1:8787:8787 localqpu
38
+ ```
39
+
40
+ ## Connect existing Qiskit code
41
+
42
+ ```python
43
+ import localqpu
44
+
45
+ service = localqpu.connect(port=8787) # use this instead of QiskitRuntimeService(...)
46
+ backend = service.least_busy()
47
+ ```
48
+
49
+ > ⚠️ **Always use `localqpu.connect()`.** In qiskit-ibm-runtime the runtime authentication endpoint is hard-coded to `iam.cloud.ibm.com` and can only be changed through the `IAM_URL` environment variable. If you configure the client by hand and miss it, the client **sends your key to the real IBM Cloud**. `connect()` sets `IAM_URL` and routes both HTTP and HTTPS through localqpu, so any leaking HTTPS request is blocked. Blocked attempts are counted in `blocked_connect_requests` on `GET /_localqpu/health`.
50
+ >
51
+ > Note that `connect()` changes process-wide environment variables: it sets `IAM_URL` and appends `localqpu.test` to `NO_PROXY`/`no_proxy` (so that `HTTP_PROXY` settings cannot redirect localqpu traffic to a corporate proxy). Run tests that talk to the real IBM Cloud in a separate process.
52
+
53
+ ## Use with pytest
54
+
55
+ The fixtures are registered automatically once the package is installed.
56
+
57
+ ```python
58
+ def test_retry_on_failure(localqpu_service, localqpu_control):
59
+ localqpu_control.set_scenario({"next_jobs": [{"outcome": "failed", "reason": "calibrating"}]})
60
+ ...
61
+ ```
62
+
63
+ | Fixture | Description |
64
+ |---|---|
65
+ | `localqpu_server` | A server on a free port for the whole test session |
66
+ | `localqpu_control` | Change scenarios, inspect jobs, reset state. Reset before and after each test |
67
+ | `localqpu_service` | A connected `QiskitRuntimeService` |
68
+
69
+ ## Failure scenarios
70
+
71
+ Use `localqpu start --scenario scenario.json` or `localqpu_control.set_scenario({...})`.
72
+
73
+ ```json
74
+ {
75
+ "seed": 42,
76
+ "queue": { "delay_seconds": 0, "polls_before_running": 1 },
77
+ "failures": { "rate": 0.0, "reason": "Simulated failure", "reason_code": 9999 },
78
+ "next_jobs": [
79
+ { "outcome": "failed", "reason": "QPU calibration in progress", "reason_code": 1517 },
80
+ { "outcome": "cancelled" }
81
+ ],
82
+ "backends": { "ibm_brisbane": { "status": "offline", "queue_length": 120 } },
83
+ "usage": { "limit_seconds": 600, "consumed_seconds": 600 },
84
+ "auth": { "reject_tokens": false }
85
+ }
86
+ ```
87
+
88
+ | Scenario | What the client sees |
89
+ |---|---|
90
+ | `next_jobs` failure | `RuntimeJobFailureError` (with the reason) |
91
+ | `next_jobs` cancellation | `RuntimeInvalidStateError` |
92
+ | Failure **or cancellation** with `reason_code: 1305` | `RuntimeJobMaxTimeoutError` (the client treats 1305 as a max-time error and turns a cancelled job with this code into an error) |
93
+ | `job.cancel()` from your code | `CANCELLED`; localqpu records `reason_code: 9001` |
94
+ | Backend `offline` | Excluded from `least_busy()`; submitted jobs stay `QUEUED` until it is back online |
95
+ | Backend `paused` | A "currently has a status of paused" warning, then normal processing |
96
+ | Usage limit reached | A warning, then submission fails with `IBMRuntimeError` (403) |
97
+ | `auth.reject_tokens` | `InvalidAccountError` when creating the service |
98
+
99
+ > `QiskitRuntimeService` caches the backend list after the first `least_busy()`/`backends()` call, exactly as it does against IBM. After changing backend status in a scenario, create a new service (the `localqpu_service` fixture gives you a fresh one per test).
100
+
101
+ ## Control API
102
+
103
+ | Method and path | Purpose |
104
+ |---|---|
105
+ | `GET /_localqpu/health` | Status, backends, blocked CONNECT count |
106
+ | `GET`/`PUT /_localqpu/scenario` | Read or replace the scenario |
107
+ | `POST /_localqpu/reset` | Reset jobs, scenario, and stats |
108
+ | `GET /_localqpu/jobs` | Summary of submitted jobs |
109
+
110
+ ## Limitations (v0.1)
111
+
112
+ - IBM Quantum Platform only. Supported programs: the legacy `SamplerV2` (`sampler`) and the new executor-based Sampler (`executor`, schema v2.0).
113
+ - Noiseless simulation. If the number of active qubits exceeds `--max-sim-qubits` (default 24), the sampler returns a shape-correct stub result (`metadata["localqpu_stub"]`) and the executor fails with guidance.
114
+ - Estimator, Session/Batch, and Qiskit Functions are not supported yet.
115
+ - Jobs are kept in memory only and are lost when the server restarts.
116
+ - A running simulation cannot be interrupted. `POST /_localqpu/reset` (used by the pytest fixtures between tests) discards its result and starts a fresh worker pool, so later jobs are not blocked, but the old computation keeps using CPU until it finishes.
117
+ - Failure reasons use localqpu codes: `9000` for localqpu-side failures (invalid input, simulation limits) and `9001` for user cancellation.
@@ -0,0 +1,94 @@
1
+ # localqpu
2
+
3
+ A local emulator of the IBM Quantum Platform API, built for testing.
4
+ Like a payment provider's "test mode", it lets you test code that calls a quantum cloud **without queues, without cost, and with any failure you want to simulate**.
5
+
6
+ > localqpu does not verify that quantum results are *correct*. It verifies **the code around the quantum API call**: submission, waiting, retries, result parsing, and error handling.
7
+
8
+ ## Install and run
9
+
10
+ ```bash
11
+ pip install localqpu # https://pypi.org/project/localqpu/
12
+ localqpu start # http://127.0.0.1:8787
13
+ # or
14
+ docker build -t localqpu . && docker run -p 127.0.0.1:8787:8787 localqpu
15
+ ```
16
+
17
+ ## Connect existing Qiskit code
18
+
19
+ ```python
20
+ import localqpu
21
+
22
+ service = localqpu.connect(port=8787) # use this instead of QiskitRuntimeService(...)
23
+ backend = service.least_busy()
24
+ ```
25
+
26
+ > ⚠️ **Always use `localqpu.connect()`.** In qiskit-ibm-runtime the runtime authentication endpoint is hard-coded to `iam.cloud.ibm.com` and can only be changed through the `IAM_URL` environment variable. If you configure the client by hand and miss it, the client **sends your key to the real IBM Cloud**. `connect()` sets `IAM_URL` and routes both HTTP and HTTPS through localqpu, so any leaking HTTPS request is blocked. Blocked attempts are counted in `blocked_connect_requests` on `GET /_localqpu/health`.
27
+ >
28
+ > Note that `connect()` changes process-wide environment variables: it sets `IAM_URL` and appends `localqpu.test` to `NO_PROXY`/`no_proxy` (so that `HTTP_PROXY` settings cannot redirect localqpu traffic to a corporate proxy). Run tests that talk to the real IBM Cloud in a separate process.
29
+
30
+ ## Use with pytest
31
+
32
+ The fixtures are registered automatically once the package is installed.
33
+
34
+ ```python
35
+ def test_retry_on_failure(localqpu_service, localqpu_control):
36
+ localqpu_control.set_scenario({"next_jobs": [{"outcome": "failed", "reason": "calibrating"}]})
37
+ ...
38
+ ```
39
+
40
+ | Fixture | Description |
41
+ |---|---|
42
+ | `localqpu_server` | A server on a free port for the whole test session |
43
+ | `localqpu_control` | Change scenarios, inspect jobs, reset state. Reset before and after each test |
44
+ | `localqpu_service` | A connected `QiskitRuntimeService` |
45
+
46
+ ## Failure scenarios
47
+
48
+ Use `localqpu start --scenario scenario.json` or `localqpu_control.set_scenario({...})`.
49
+
50
+ ```json
51
+ {
52
+ "seed": 42,
53
+ "queue": { "delay_seconds": 0, "polls_before_running": 1 },
54
+ "failures": { "rate": 0.0, "reason": "Simulated failure", "reason_code": 9999 },
55
+ "next_jobs": [
56
+ { "outcome": "failed", "reason": "QPU calibration in progress", "reason_code": 1517 },
57
+ { "outcome": "cancelled" }
58
+ ],
59
+ "backends": { "ibm_brisbane": { "status": "offline", "queue_length": 120 } },
60
+ "usage": { "limit_seconds": 600, "consumed_seconds": 600 },
61
+ "auth": { "reject_tokens": false }
62
+ }
63
+ ```
64
+
65
+ | Scenario | What the client sees |
66
+ |---|---|
67
+ | `next_jobs` failure | `RuntimeJobFailureError` (with the reason) |
68
+ | `next_jobs` cancellation | `RuntimeInvalidStateError` |
69
+ | Failure **or cancellation** with `reason_code: 1305` | `RuntimeJobMaxTimeoutError` (the client treats 1305 as a max-time error and turns a cancelled job with this code into an error) |
70
+ | `job.cancel()` from your code | `CANCELLED`; localqpu records `reason_code: 9001` |
71
+ | Backend `offline` | Excluded from `least_busy()`; submitted jobs stay `QUEUED` until it is back online |
72
+ | Backend `paused` | A "currently has a status of paused" warning, then normal processing |
73
+ | Usage limit reached | A warning, then submission fails with `IBMRuntimeError` (403) |
74
+ | `auth.reject_tokens` | `InvalidAccountError` when creating the service |
75
+
76
+ > `QiskitRuntimeService` caches the backend list after the first `least_busy()`/`backends()` call, exactly as it does against IBM. After changing backend status in a scenario, create a new service (the `localqpu_service` fixture gives you a fresh one per test).
77
+
78
+ ## Control API
79
+
80
+ | Method and path | Purpose |
81
+ |---|---|
82
+ | `GET /_localqpu/health` | Status, backends, blocked CONNECT count |
83
+ | `GET`/`PUT /_localqpu/scenario` | Read or replace the scenario |
84
+ | `POST /_localqpu/reset` | Reset jobs, scenario, and stats |
85
+ | `GET /_localqpu/jobs` | Summary of submitted jobs |
86
+
87
+ ## Limitations (v0.1)
88
+
89
+ - IBM Quantum Platform only. Supported programs: the legacy `SamplerV2` (`sampler`) and the new executor-based Sampler (`executor`, schema v2.0).
90
+ - Noiseless simulation. If the number of active qubits exceeds `--max-sim-qubits` (default 24), the sampler returns a shape-correct stub result (`metadata["localqpu_stub"]`) and the executor fails with guidance.
91
+ - Estimator, Session/Batch, and Qiskit Functions are not supported yet.
92
+ - Jobs are kept in memory only and are lost when the server restarts.
93
+ - A running simulation cannot be interrupted. `POST /_localqpu/reset` (used by the pytest fixtures between tests) discards its result and starts a fresh worker pool, so later jobs are not blocked, but the old computation keeps using CPU until it finishes.
94
+ - Failure reasons use localqpu codes: `9000` for localqpu-side failures (invalid input, simulation limits) and `9001` for user cancellation.
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "localqpu"
3
+ version = "0.1.0"
4
+ description = "A local emulator of the IBM Quantum Platform API, built for testing"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "Apache-2.0"
8
+ keywords = ["qiskit", "quantum", "emulator", "testing", "mock", "ibm-quantum"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Framework :: Pytest",
12
+ "Intended Audience :: Developers",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.10",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Topic :: Scientific/Engineering :: Physics",
17
+ "Topic :: Software Development :: Testing :: Mocking",
18
+ ]
19
+ dependencies = [
20
+ "qiskit-ibm-runtime>=0.50",
21
+ "qiskit-aer>=0.17",
22
+ "PyJWT>=2.8",
23
+ ]
24
+
25
+ [project.urls]
26
+ Repository = "https://github.com/ictechgy/localqpu"
27
+ Issues = "https://github.com/ictechgy/localqpu/issues"
28
+
29
+ [project.scripts]
30
+ localqpu = "localqpu.cli:main"
31
+
32
+ [project.entry-points.pytest11]
33
+ localqpu = "localqpu.pytest_plugin"
34
+
35
+ [dependency-groups]
36
+ dev = ["pytest>=8", "ruff>=0.14", "mypy>=1.13"]
37
+
38
+ [build-system]
39
+ requires = ["hatchling>=1.26"]
40
+ build-backend = "hatchling.build"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/localqpu"]
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ # 로컬 도구 폴더와 배포에 필요 없는 CI·설계 문서는 소스 배포본에서 뺀다.
47
+ exclude = [".superpowers", ".serena", ".github", "docs"]
48
+
49
+ [tool.ruff]
50
+ line-length = 100
51
+ target-version = "py310"
52
+ # 계획서·설계서 마크다운 안의 코드 블록은 검사 대상이 아니다.
53
+ extend-exclude = ["docs"]
54
+
55
+ [tool.ruff.lint]
56
+ select = ["E", "F", "I", "UP", "B", "SIM"]
57
+ # 한국어 문자열은 폭이 2로 계산돼 E501이 과도하게 걸린다. 줄 길이는 formatter에 맡긴다.
58
+ ignore = ["E501"]
59
+
60
+ [tool.mypy]
61
+ files = ["src"]
62
+ # numpy 타입 스텁이 3.12 문법을 쓰므로 개발·CI 파이썬과 같은 3.12로 검사한다. 3.10 호환 문법은 ruff(target py310)가 본다.
63
+ python_version = "3.12"
64
+ disallow_untyped_defs = true
65
+ check_untyped_defs = true
66
+ no_implicit_optional = true
67
+ warn_unused_ignores = true
68
+
69
+ [[tool.mypy.overrides]]
70
+ module = ["qiskit.*", "qiskit_ibm_runtime.*", "qiskit_aer.*", "ibm_quantum_schemas.*", "samplomatic.*"]
71
+ ignore_missing_imports = true
72
+
73
+ [tool.pytest.ini_options]
74
+ testpaths = ["tests"]
75
+ markers = ["contract: 실제 qiskit-ibm-runtime 클라이언트를 localqpu에 붙여 도는 계약 테스트"]
76
+ filterwarnings = [
77
+ "ignore::DeprecationWarning:qiskit_ibm_runtime.*",
78
+ # 계약 테스트는 폐기 예정인 기존 SamplerV2 호환을 일부러 검증한다.
79
+ "ignore:The SamplerV2 class is deprecated:DeprecationWarning",
80
+ ]
@@ -0,0 +1,10 @@
1
+ """localqpu: IBM Quantum Platform API를 로컬에서 흉내 내는 테스트용 에뮬레이터."""
2
+
3
+ #: 패키지 버전. pyproject.toml의 version과 같아야 한다.
4
+ __version__ = "0.1.0"
5
+
6
+ from localqpu.app import start_server # noqa: E402
7
+ from localqpu.client import connect # noqa: E402
8
+ from localqpu.context import ServerConfig # noqa: E402
9
+
10
+ __all__ = ["ServerConfig", "__version__", "connect", "start_server"]
@@ -0,0 +1,53 @@
1
+ """qiskit-ibm-runtime 내부 모듈 의존을 한곳에 모은다.
2
+
3
+ localqpu는 클라이언트와 똑같이 인코딩·디코딩하려고 공개 API가 아닌 내부 모듈을 쓴다.
4
+ SDK가 바뀌면 이 파일만 고치면 되도록, 다른 모듈은 이 심볼들을 여기서만 가져온다(설계서 9절).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import qiskit_ibm_runtime.fake_provider as _fake_provider_package
13
+ from ibm_quantum_schemas.common.tensor import CompressedTensorModel
14
+ from ibm_quantum_schemas.executor.version_2_0.models import (
15
+ ItemMetadataModel,
16
+ MetadataModel,
17
+ QuantumProgramResultItemModel,
18
+ QuantumProgramResultModel,
19
+ )
20
+ from ibm_quantum_schemas.executor.version_2_0.models import ParamsModel as ExecutorParamsModel
21
+ from qiskit_ibm_runtime.fake_provider.executor.run_quantum_program import run_quantum_program
22
+ from qiskit_ibm_runtime.json import RuntimeDecoder, RuntimeEncoder
23
+ from qiskit_ibm_runtime.options_models.simulator import SimulatorOptions
24
+ from qiskit_ibm_runtime.quantum_program.converters.converters_2_0 import (
25
+ passthrough_data_to_2_0,
26
+ quantum_program_from_2_0,
27
+ )
28
+
29
+ #: qiskit-ibm-runtime가 함께 배포하는 실제 칩 스냅샷(conf_*.json, props_*.json) 폴더.
30
+ FAKE_PROVIDER_BACKENDS_DIR: Path = Path(_fake_provider_package.__file__).parent / "backends"
31
+
32
+
33
+ def semantic_role_of(program: Any) -> str | None:
34
+ """QuantumProgram의 semantic_role. 클라이언트가 비공개 속성에 두므로 여기서만 읽는다."""
35
+ return getattr(program, "_semantic_role", None)
36
+
37
+
38
+ __all__ = [
39
+ "FAKE_PROVIDER_BACKENDS_DIR",
40
+ "CompressedTensorModel",
41
+ "ExecutorParamsModel",
42
+ "ItemMetadataModel",
43
+ "MetadataModel",
44
+ "QuantumProgramResultItemModel",
45
+ "QuantumProgramResultModel",
46
+ "RuntimeDecoder",
47
+ "RuntimeEncoder",
48
+ "SimulatorOptions",
49
+ "passthrough_data_to_2_0",
50
+ "quantum_program_from_2_0",
51
+ "run_quantum_program",
52
+ "semantic_role_of",
53
+ ]
@@ -0,0 +1,52 @@
1
+ """구성 요소를 조립해 서버를 띄운다."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from localqpu.context import AppContext, ServerConfig
6
+ from localqpu.control import register_control_routes
7
+ from localqpu.ibm.backends import BackendCatalog
8
+ from localqpu.ibm.routes import register_ibm_routes
9
+ from localqpu.jobs import JobManager
10
+ from localqpu.scenario import ScenarioState, ensure_known_backends
11
+ from localqpu.server import Router, RunningServer, ServerStats, serve
12
+
13
+
14
+ def build_context(config: ServerConfig) -> AppContext:
15
+ """설정으로 카탈로그·시나리오·작업 관리자·통계를 만든다.
16
+
17
+ Raises:
18
+ BackendCatalogError: 없는 칩을 지정했을 때.
19
+ ScenarioError: 시나리오가 카탈로그에 없는 백엔드를 가리킬 때.
20
+ """
21
+ catalog = BackendCatalog(config.backends)
22
+ ensure_known_backends(config.scenario, catalog.names)
23
+ scenario_state = ScenarioState(config.scenario)
24
+ return AppContext(
25
+ config=config,
26
+ catalog=catalog,
27
+ scenario_state=scenario_state,
28
+ jobs=JobManager(scenario_state, config.max_sim_qubits),
29
+ stats=ServerStats(),
30
+ )
31
+
32
+
33
+ def build_router(context: AppContext) -> Router:
34
+ """모든 라우트를 등록한 라우터."""
35
+ router = Router()
36
+ register_ibm_routes(router, context)
37
+ register_control_routes(router, context)
38
+ return router
39
+
40
+
41
+ def start_server(config: ServerConfig | None = None) -> RunningServer:
42
+ """localqpu 서버를 백그라운드로 띄운다. 멈출 때 작업 스레드 풀도 정리한다."""
43
+ context = build_context(config or ServerConfig())
44
+ server = serve(
45
+ build_router(context),
46
+ context.stats,
47
+ context.config.host,
48
+ context.config.port,
49
+ context.config.is_verbose,
50
+ )
51
+ server.on_stop = context.jobs.shutdown
52
+ return server