quapp-braket 0.0.12.dev2__tar.gz → 0.0.12.dev4__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 (44) hide show
  1. {quapp_braket-0.0.12.dev2/quapp_braket.egg-info → quapp_braket-0.0.12.dev4}/PKG-INFO +2 -2
  2. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/pyproject.toml +2 -2
  3. quapp_braket-0.0.12.dev4/quapp_braket/__init__.py +5 -0
  4. quapp_braket-0.0.12.dev4/quapp_braket/error_rules.py +164 -0
  5. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4/quapp_braket.egg-info}/PKG-INFO +2 -2
  6. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket.egg-info/SOURCES.txt +3 -1
  7. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket.egg-info/requires.txt +1 -1
  8. quapp_braket-0.0.12.dev4/tests/test_error_logging.py +304 -0
  9. quapp_braket-0.0.12.dev2/quapp_braket/__init__.py +0 -1
  10. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/LICENSE +0 -0
  11. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/README.md +0 -0
  12. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/async_tasks/__init__.py +0 -0
  13. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/async_tasks/braket_circuit_export_task.py +0 -0
  14. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/component/__init__.py +0 -0
  15. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/component/backend/__init__.py +0 -0
  16. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/component/backend/braket_invocation.py +0 -0
  17. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/component/backend/braket_job_fetching.py +0 -0
  18. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/constant/__init__.py +0 -0
  19. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/constant/authentication_const.py +0 -0
  20. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/constant/job_result_const.py +0 -0
  21. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/constant/job_status_const.py +0 -0
  22. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/factory/__init__.py +0 -0
  23. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/factory/braket_device_factory.py +0 -0
  24. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/factory/braket_handler_factory.py +0 -0
  25. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/factory/braket_provider_factory.py +0 -0
  26. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/handler/__init__.py +0 -0
  27. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/handler/invocation_handler.py +0 -0
  28. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/handler/job_fetching_handler.py +0 -0
  29. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/__init__.py +0 -0
  30. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/device/__init__.py +0 -0
  31. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/device/aws_braket_device.py +0 -0
  32. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/device/oqc_cloud_device.py +0 -0
  33. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/device/qapp_braket_device.py +0 -0
  34. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/provider/__init__.py +0 -0
  35. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/provider/aws_braket_provider.py +0 -0
  36. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/provider/oqc_cloud_provider.py +0 -0
  37. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/model/provider/qapp_braket_provider.py +0 -0
  38. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/util/__init__.py +0 -0
  39. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/util/braket_utils.py +0 -0
  40. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/util/circuit_convert_utils.py +0 -0
  41. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket/util/provider_job_utils.py +0 -0
  42. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket.egg-info/dependency_links.txt +0 -0
  43. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/quapp_braket.egg-info/top_level.txt +0 -0
  44. {quapp_braket-0.0.12.dev2 → quapp_braket-0.0.12.dev4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quapp-braket
3
- Version: 0.0.12.dev2
3
+ Version: 0.0.12.dev4
4
4
  Summary: Quapp braket library supporting Quapp Platform for Quantum Computing
5
5
  Author-email: "CITYNOW Co. Ltd. " <corp@citynow.vn>
6
6
  License: The MIT License (MIT)
@@ -19,7 +19,7 @@ Classifier: Programming Language :: Python :: 3
19
19
  Requires-Python: >=3.7
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
- Requires-Dist: quapp-common==0.0.13.dev5
22
+ Requires-Dist: quapp-common==0.0.14.dev10
23
23
  Requires-Dist: amazon-braket-sdk==1.83.0
24
24
  Requires-Dist: oqc-qcaas-client==3.20.0
25
25
  Requires-Dist: qiskit==1.4.3
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "quapp-braket"
7
- version = "0.0.12.dev2"
7
+ version = "0.0.12.dev4"
8
8
  description = "Quapp braket library supporting Quapp Platform for Quantum Computing"
9
9
  readme = "README.md"
10
10
  authors = [{ name = "CITYNOW Co. Ltd. ", email = "corp@citynow.vn" }]
@@ -16,7 +16,7 @@ classifiers = [
16
16
  ]
17
17
  keywords = ["quapp", "quapp-braket", "braket", "quantum"]
18
18
  dependencies = [
19
- "quapp-common==0.0.13.dev5",
19
+ "quapp-common==0.0.14.dev10",
20
20
  "amazon-braket-sdk==1.83.0",
21
21
  "oqc-qcaas-client==3.20.0",
22
22
  "qiskit==1.4.3",
@@ -0,0 +1,5 @@
1
+ from .factory.braket_handler_factory import BraketHandlerFactory
2
+
3
+ # Imported for the side effect: register_rules() has to run before the
4
+ # first job fails, so this import cannot be made lazy.
5
+ from . import error_rules as _error_rules # noqa: E402,F401
@@ -0,0 +1,164 @@
1
+ # Quapp Platform Project
2
+ # error_rules.py
3
+ # Copyright © CITYNOW Co. Ltd. All rights reserved.
4
+
5
+ """Amazon Braket / OQC-specific error classification rules.
6
+
7
+ Registered into ``quapp_common.util.error_classifier`` when ``quapp_braket`` is
8
+ imported, so ``quapp-common`` never has to depend on Braket.
9
+
10
+ Matching is done on the message text or on the class **NAME as a string**, never
11
+ ``isinstance``, and nothing from ``braket`` / ``boto3`` / ``qcaas_client`` is
12
+ imported: the classifier has to work even when the SDK is absent.
13
+
14
+ The first six rules key off messages **this lib itself** raises -- checked against
15
+ the code, not guessed:
16
+
17
+ quapp_braket/util/braket_utils.py:97
18
+ ValueError('Missing required AWS credentials')
19
+ quapp_braket/model/provider/qapp_braket_provider.py:29
20
+ ValueError('Unsupported device')
21
+ quapp_braket/factory/braket_provider_factory.py:39
22
+ ValueError('Unsupported provider!')
23
+ quapp_braket/factory/braket_device_factory.py:68
24
+ ValueError(f'Unsupported device for provider_type=..., sdk=...')
25
+ quapp_braket/component/backend/braket_invocation.py:126
26
+ ValueError(f'Invalid circuit type: {type(circuit)}')
27
+ quapp_braket/async_tasks/braket_circuit_export_task.py:43,50
28
+ ValueError('Circuit must not be None')
29
+ ValueError(f'Expected Braket Circuit, got {type(circuit)}')
30
+ quapp_braket/component/backend/braket_job_fetching.py:88
31
+ ValueError(f'Invalid {job_type} ARN: {job_id}')
32
+
33
+ The last two rules match exception names from boto3/botocore and qcaas_client. If
34
+ upstream renames them the rule becomes inert rather than broken -- the classifier
35
+ just falls back on the phase.
36
+
37
+ One distinction matters here: "the circuit is not a Braket Circuit" is USER_CODE
38
+ (fixing the processing function is enough), while "this device is not supported"
39
+ is PROVIDER_DEVICE (the platform or the function configuration). Both used to be a
40
+ bare ``ValueError``, so both came out under the same label.
41
+ """
42
+
43
+ from quapp_common.enum.error_category import ErrorCategory
44
+ from quapp_common.util.error_classifier import Rule, register_rules
45
+
46
+ DOC_AUTH = 'errors/braket-auth'
47
+ DOC_DEVICE = 'errors/braket-device'
48
+ DOC_CIRCUIT = 'errors/braket-circuit'
49
+
50
+
51
+ def _message(exception) -> str:
52
+ return str(exception).lower()
53
+
54
+
55
+ def _name(exception) -> str:
56
+ return type(exception).__name__
57
+
58
+
59
+ register_rules(
60
+ # ----------------- raised by quapp-braket itself (checked against code)
61
+ # braket_utils.py:97 -- AWS credentials missing, the user can fix it
62
+ Rule(match=lambda e: 'missing required aws credentials' in _message(e),
63
+ category=ErrorCategory.AUTHENTICATION,
64
+ code='BRAKET_AWS_CREDENTIALS_MISSING',
65
+ resolution='AWS credentials are missing, so Braket cannot be '
66
+ 'called.',
67
+ steps=('Check the AWS access key / secret in your workspace',
68
+ 'The credential needs braket:* plus s3 access to the result '
69
+ 'bucket'),
70
+ doc_slug=DOC_AUTH,
71
+ retryable=False),
72
+
73
+ # braket_invocation.py:126 and braket_circuit_export_task.py:43,50
74
+ # USER_CODE: fixing the processing function is enough.
75
+ Rule(match=lambda e: 'invalid circuit type' in _message(e)
76
+ or 'expected braket circuit' in _message(e)
77
+ or 'circuit must not be none' in _message(e),
78
+ category=ErrorCategory.USER_CODE,
79
+ code='BRAKET_INVALID_CIRCUIT_TYPE',
80
+ resolution='The circuit preparation function did not return a '
81
+ 'Braket Circuit.',
82
+ steps=('Check what your processing function returns',
83
+ 'The circuit must be a braket.circuits.Circuit',
84
+ 'Returning None is caught here as well'),
85
+ doc_slug=DOC_CIRCUIT),
86
+
87
+ # qapp_braket_provider.py:29, braket_device_factory.py:68,
88
+ # braket_provider_factory.py:39
89
+ Rule(match=lambda e: 'unsupported device' in _message(e)
90
+ or 'unsupported provider' in _message(e),
91
+ category=ErrorCategory.PROVIDER_DEVICE,
92
+ code='BRAKET_DEVICE_UNSUPPORTED',
93
+ resolution="This device or provider is not supported by Quapp's "
94
+ 'Braket lib yet.',
95
+ steps=('Check the device selected for the job',
96
+ 'quapp-braket serves AWS_BRAKET and OQC_CLOUD'),
97
+ doc_slug=DOC_DEVICE),
98
+
99
+ # braket_job_fetching.py:88 -- malformed ARN
100
+ Rule(match=lambda e: 'arn:' in _message(e) or 'invalid quantum task arn'
101
+ in _message(e) or ' arn: ' in _message(e),
102
+ category=ErrorCategory.INVALID_INPUT,
103
+ code='BRAKET_ARN_INVALID',
104
+ resolution='The quantum task or device ARN is malformed.',
105
+ steps=('Check the providerJobId sent with the request',
106
+ 'A Braket ARN looks like '
107
+ 'arn:aws:braket:<region>:<account>:...'),
108
+ doc_slug=DOC_DEVICE),
109
+
110
+ # ------------------------------------- boto3 / botocore exceptions
111
+ # AWS quota: kept separate from network errors, because the user has to
112
+ # request a higher limit rather than just wait and retry.
113
+ Rule(match=lambda e: _name(e) == 'ClientError'
114
+ and ('throttl' in _message(e)
115
+ or 'toomanyrequests' in _message(e)
116
+ or 'limitexceeded' in _message(e)),
117
+ category=ErrorCategory.QUOTA_EXCEEDED,
118
+ code='BRAKET_QUOTA_EXCEEDED',
119
+ resolution='AWS rejected the request: quota exceeded or throttled.',
120
+ steps=('Wait a few minutes and try again',
121
+ 'Request a higher Braket service quota if you run many '
122
+ 'jobs'),
123
+ retryable=True,
124
+ retry_after=300),
125
+
126
+ Rule(match=lambda e: _name(e) in {'NoCredentialsError',
127
+ 'PartialCredentialsError',
128
+ 'NoRegionError',
129
+ 'UnauthorizedOperation'},
130
+ category=ErrorCategory.AUTHENTICATION,
131
+ code='BRAKET_AWS_AUTH_FAILED',
132
+ resolution='AWS refused to authenticate the Braket request.',
133
+ steps=('Check that the AWS credential is still valid',
134
+ 'Check that the configured region actually serves Braket'),
135
+ doc_slug=DOC_AUTH,
136
+ retryable=False),
137
+
138
+ Rule(match=lambda e: _name(e) in {'EndpointConnectionError',
139
+ 'ConnectTimeoutError',
140
+ 'ReadTimeoutError',
141
+ 'ServiceUnavailable'},
142
+ category=ErrorCategory.PROVIDER_UNAVAILABLE,
143
+ code='BRAKET_API_UNAVAILABLE',
144
+ resolution='The AWS Braket API could not be reached.',
145
+ steps=('Try again in a few minutes',
146
+ 'Check the Braket service status in the region you use'),
147
+ retryable=True,
148
+ retry_after=120),
149
+
150
+ # Placed last: matching is by NAME, so only these exact names land here.
151
+ Rule(match=lambda e: _name(e) in {'AwsQuantumTaskFailure',
152
+ 'DeviceOfflineError',
153
+ 'DeviceRetiredError'},
154
+ category=ErrorCategory.PROVIDER_DEVICE,
155
+ code='BRAKET_TASK_FAILED',
156
+ resolution='Braket reports that the quantum task failed, or that '
157
+ 'the device is unavailable.',
158
+ steps=('Read the rootCause to see what Braket refused',
159
+ 'QPU devices have availability windows -- check the '
160
+ 'device availability'),
161
+ doc_slug=DOC_DEVICE,
162
+ retryable=True,
163
+ retry_after=180),
164
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quapp-braket
3
- Version: 0.0.12.dev2
3
+ Version: 0.0.12.dev4
4
4
  Summary: Quapp braket library supporting Quapp Platform for Quantum Computing
5
5
  Author-email: "CITYNOW Co. Ltd. " <corp@citynow.vn>
6
6
  License: The MIT License (MIT)
@@ -19,7 +19,7 @@ Classifier: Programming Language :: Python :: 3
19
19
  Requires-Python: >=3.7
20
20
  Description-Content-Type: text/markdown
21
21
  License-File: LICENSE
22
- Requires-Dist: quapp-common==0.0.13.dev5
22
+ Requires-Dist: quapp-common==0.0.14.dev10
23
23
  Requires-Dist: amazon-braket-sdk==1.83.0
24
24
  Requires-Dist: oqc-qcaas-client==3.20.0
25
25
  Requires-Dist: qiskit==1.4.3
@@ -2,6 +2,7 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  quapp_braket/__init__.py
5
+ quapp_braket/error_rules.py
5
6
  quapp_braket.egg-info/PKG-INFO
6
7
  quapp_braket.egg-info/SOURCES.txt
7
8
  quapp_braket.egg-info/dependency_links.txt
@@ -36,4 +37,5 @@ quapp_braket/model/provider/qapp_braket_provider.py
36
37
  quapp_braket/util/__init__.py
37
38
  quapp_braket/util/braket_utils.py
38
39
  quapp_braket/util/circuit_convert_utils.py
39
- quapp_braket/util/provider_job_utils.py
40
+ quapp_braket/util/provider_job_utils.py
41
+ tests/test_error_logging.py
@@ -1,4 +1,4 @@
1
- quapp-common==0.0.13.dev5
1
+ quapp-common==0.0.14.dev10
2
2
  amazon-braket-sdk==1.83.0
3
3
  oqc-qcaas-client==3.20.0
4
4
  qiskit==1.4.3
@@ -0,0 +1,304 @@
1
+ # Quapp Platform Project
2
+ # test_error_logging.py
3
+ # Copyright © CITYNOW Co. Ltd. All rights reserved.
4
+
5
+ """Locks four classes of error-logging bug, all found in real provider-lib code.
6
+
7
+ 1. **A copied hook lost its phase.** Some devices copied ``run_circuit`` /
8
+ ``_on_execution`` / ``_on_analysis`` wholesale from ``Device`` but dropped the
9
+ ``with phase(...)`` blocks, so that lib's log had no ``phase`` field at any
10
+ stage. Same class of bug as ``CustomDevice._on_analysis`` in quapp-common.
11
+
12
+ 2. **The error was flattened into a string.** ``job_response.job_result =
13
+ {"error": str(exception)}`` leaves the Job Log with a bare string: no
14
+ category, no phase, no rootCause -- exactly what the ticket complained about.
15
+
16
+ 3. **The error was logged twice.** ``logger.exception()`` immediately before
17
+ ``build_error_job_response`` emits a second ERROR line for the same failure,
18
+ skewing every metric that counts job_failed.
19
+
20
+ 4. **A fake job_id.** ``job_logger('SomeClass')`` -- the first argument of
21
+ ``job_logger()`` is the **job_id**. Passing a class name there sets a fake
22
+ job_id and it BEATS the real one (``_inject_job_context`` only fills keys that
23
+ are still None), so filtering by jobId in Grafana loses every line that
24
+ component logged.
25
+
26
+ The tests discover files inside the package, so this file works for any lib
27
+ without hardcoding names.
28
+ """
29
+
30
+ import ast
31
+ import io
32
+ import pathlib
33
+ import re
34
+ import tokenize
35
+
36
+ import pytest
37
+
38
+ REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
39
+
40
+ # The first release carrying a phase for analysis/post-processing and one traceId
41
+ # per job.
42
+ MINIMUM_COMMON = '0.0.14.dev6'
43
+
44
+ # Hooks already instrumented in quapp-common: copying one means copying its
45
+ # phases too. _on_execution creates the job and then talks to the provider, which
46
+ # is why it needs both -- a failed transpile and a rejected job are different
47
+ # errors.
48
+ INSTRUMENTED = {'_on_execution': {'COMPILATION', 'EXECUTION'},
49
+ '_on_analysis' : {'ANALYSIS'}}
50
+
51
+
52
+ def package_root() -> pathlib.Path:
53
+ """The provider lib's package directory, inferred from the tree.
54
+
55
+ A few repos hold more than one package -- quapp-hpc also has
56
+ ``quapp_slurm_hpc``, which only contains ``runner.py`` for the Slurm node and
57
+ is not the provider lib. Pick by structural evidence (it has ``model/`` or
58
+ ``factory/``) rather than by name.
59
+ """
60
+ candidates = [d for d in REPO_ROOT.iterdir()
61
+ if d.is_dir() and re.fullmatch(r'qu?app_\w+', d.name)
62
+ and (d / '__init__.py').is_file()]
63
+ assert candidates, 'found no package at all'
64
+
65
+ if len(candidates) > 1:
66
+ providers = [d for d in candidates
67
+ if (d / 'model').is_dir() or (d / 'factory').is_dir()]
68
+ assert len(providers) == 1, (
69
+ f'could not identify the provider package: '
70
+ f'{providers or candidates}')
71
+ return providers[0]
72
+
73
+ return candidates[0]
74
+
75
+
76
+ PACKAGE = package_root()
77
+
78
+
79
+ def code_only(path) -> str:
80
+ """Source with comments stripped out.
81
+
82
+ Needed because the explanatory comments *quote* the very code being banned
83
+ (``{"error": str(exception)}``, ``logger.exception(``). A raw scan would
84
+ report a false positive on the explanation itself.
85
+ """
86
+ source = path.read_text(encoding='utf-8')
87
+ kept = [token for token in
88
+ tokenize.generate_tokens(io.StringIO(source).readline)
89
+ if token.type != tokenize.COMMENT]
90
+ return tokenize.untokenize(kept)
91
+
92
+
93
+ def phases_opened_in(source: str) -> set:
94
+ """The RuntimePhases opened with ``with phase(...)`` in a piece of code."""
95
+ tree = ast.parse(source.lstrip())
96
+ return {
97
+ argument.attr
98
+ for node in ast.walk(tree) if isinstance(node, ast.With)
99
+ for item in node.items if isinstance(item.context_expr, ast.Call)
100
+ if (getattr(item.context_expr.func, 'id', None)
101
+ or getattr(item.context_expr.func, 'attr', None)) == 'phase'
102
+ for argument in item.context_expr.args
103
+ if isinstance(argument, ast.Attribute)
104
+ }
105
+
106
+
107
+ def python_files():
108
+ return sorted(PACKAGE.rglob('*.py'))
109
+
110
+
111
+ # ------------------------------------------- (1) a copied hook keeps its phases
112
+
113
+ def test_copied_hooks_keep_their_phases():
114
+ """Overriding an instrumented hook means copying its `with phase(...)` too."""
115
+ offenders = []
116
+ for path in python_files():
117
+ source = path.read_text(encoding='utf-8')
118
+ tree = ast.parse(source, filename=str(path))
119
+ for node in ast.walk(tree):
120
+ if not isinstance(node, ast.FunctionDef) \
121
+ or node.name not in INSTRUMENTED:
122
+ continue
123
+ opened = phases_opened_in(ast.get_source_segment(source, node))
124
+ missing = INSTRUMENTED[node.name] - opened
125
+ if missing:
126
+ offenders.append(
127
+ f'{path.name}::{node.name} is missing {sorted(missing)}')
128
+
129
+ assert not offenders, (
130
+ f'overridden hooks lost their phase: {offenders}. The original in '
131
+ f'quapp-common has `with phase(...)`; copying it without that leaves the '
132
+ f'log with no phase field.')
133
+
134
+
135
+ def test_at_least_one_phase_is_opened_somewhere():
136
+ """A lib that overrides no hook needs none; one that does needs a phase."""
137
+ overrides = any(
138
+ isinstance(node, ast.FunctionDef) and node.name in INSTRUMENTED
139
+ for path in python_files()
140
+ for node in ast.walk(ast.parse(path.read_text(encoding='utf-8')))
141
+ )
142
+ if not overrides:
143
+ pytest.skip('lib overrides no hook; phases come from quapp-common')
144
+
145
+ opened = set()
146
+ for path in python_files():
147
+ opened |= phases_opened_in(path.read_text(encoding='utf-8'))
148
+ assert opened, 'hooks are overridden but no phase is opened'
149
+
150
+
151
+ # --------------------------------- (2) no hand-rolled error string
152
+
153
+ @pytest.mark.parametrize('path', python_files(), ids=lambda p: p.name)
154
+ def test_no_hand_rolled_error_dict(path):
155
+ """`{"error": str(exception)}` bypasses the entire error envelope."""
156
+ assert '{"error": str(exception)}' not in code_only(path), (
157
+ f'{path.name}: flattens the error into a string, losing '
158
+ f'category/phase/rootCause. Use '
159
+ f'build_error_job_response(..., phase=..., context=...)')
160
+
161
+
162
+ def test_error_envelope_carries_phase_and_context():
163
+ """Every build_error_job_response in the device needs phase= and context=."""
164
+ for path in python_files():
165
+ source = code_only(path)
166
+ calls = source.count('build_error_job_response(')
167
+ if not calls:
168
+ continue
169
+ assert source.count('phase=RuntimePhase.') >= calls, (
170
+ f'{path.name}: has {calls} error envelopes but is missing phase=, '
171
+ f'so the ErrorReport would come out with phase=None')
172
+ assert source.count('context=self._error_context()') >= calls, (
173
+ f'{path.name}: error envelope is missing context=, leaving support '
174
+ f'without the device/provider')
175
+
176
+
177
+ # ------------------------------------------ (3) one error is logged once
178
+
179
+ def test_no_duplicate_error_log_before_envelope():
180
+ """logger.exception()/logger.error() right before the envelope = 2 ERRORs."""
181
+ offenders = []
182
+ for path in python_files():
183
+ source = code_only(path)
184
+ for match in re.finditer(r'logger\.(exception|error)\(', source):
185
+ if 'build_error_job_response(' in source[match.end():match.end() + 400]:
186
+ line = source[:match.start()].count('\n') + 1
187
+ offenders.append(f'{path.name}:{line}')
188
+
189
+ assert not offenders, (
190
+ f'duplicate ERROR log before build_error_job_response at {offenders}; '
191
+ f'the envelope already logs once')
192
+
193
+
194
+ # ------------------------------------------------- (4) no fake job_id
195
+
196
+ @pytest.mark.parametrize('path', python_files(), ids=lambda p: p.name)
197
+ def test_no_fake_job_logger_argument(path):
198
+ """`job_logger()` takes a real job_id; a component name belongs in `context`.
199
+
200
+ Two shapes of fake id are caught: a string literal (`job_logger('Provider')`)
201
+ and `__name__`, which quietly makes the job_id the dotted module path and
202
+ blows up jobId cardinality in Grafana as well as losing the real job.
203
+ """
204
+ tree = ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
205
+
206
+ offenders = []
207
+ for node in ast.walk(tree):
208
+ if not isinstance(node, ast.Call) or not node.args:
209
+ continue
210
+ if (getattr(node.func, 'id', None)
211
+ or getattr(node.func, 'attr', None)) != 'job_logger':
212
+ continue
213
+ first = node.args[0]
214
+ if isinstance(first, ast.Constant) and isinstance(first.value, str):
215
+ offenders.append(repr(first.value))
216
+ elif isinstance(first, ast.Name) and first.id == '__name__':
217
+ offenders.append('__name__')
218
+
219
+ assert not offenders, (
220
+ f'{path.name}: job_logger() got {offenders} -- those are fake job_ids. '
221
+ f"Use logger.bind(context='...') for the component name")
222
+
223
+
224
+ def test_providers_bind_their_name_to_context():
225
+ """A provider that logs must bind its own name, so lines say where they came
226
+ from."""
227
+ providers = sorted((PACKAGE / 'model' / 'provider').glob('*.py'))
228
+ if not providers:
229
+ pytest.skip('lib has no model/provider directory')
230
+
231
+ offenders = []
232
+ for path in providers:
233
+ if path.name == '__init__.py':
234
+ continue
235
+ # code_only: several providers keep their old logging commented out, and
236
+ # a raw scan would flag those as if they still logged.
237
+ source = code_only(path)
238
+ if 'logger' not in source:
239
+ continue
240
+ if not re.search(r"logger\.bind\(context='[A-Za-z]+'\)", source):
241
+ offenders.append(path.name)
242
+
243
+ assert not offenders, (
244
+ f'providers that log without binding context: {offenders}. The component '
245
+ f'name must be a field, not text inside the message, or Grafana cannot '
246
+ f'filter on it')
247
+
248
+
249
+ # ------------------------------------------ rules + the quapp-common pin
250
+
251
+ def test_error_rules_module_exists():
252
+ assert (PACKAGE / 'error_rules.py').is_file(), \
253
+ "no error_rules.py, so this SDK's errors never get classified"
254
+
255
+
256
+ def test_error_rules_are_registered_on_import():
257
+ init = (PACKAGE / '__init__.py').read_text(encoding='utf-8')
258
+ assert 'error_rules' in init, \
259
+ '__init__.py does not import error_rules, so the rules never register'
260
+
261
+
262
+ def test_error_rules_imports_no_vendor_sdk():
263
+ """The classifier has to run even with the SDK absent, hence name matching."""
264
+ tree = ast.parse((PACKAGE / 'error_rules.py').read_text(encoding='utf-8'))
265
+
266
+ roots = set()
267
+ for node in ast.walk(tree):
268
+ if isinstance(node, ast.Import):
269
+ roots.update(alias.name.split('.')[0] for alias in node.names)
270
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
271
+ roots.add(node.module.split('.')[0])
272
+
273
+ assert roots <= {'quapp_common'}, \
274
+ f'error_rules.py may only import quapp_common, but imports: {sorted(roots)}'
275
+
276
+
277
+ def test_common_pin_is_exact_and_current():
278
+ version = pytest.importorskip('packaging.version')
279
+
280
+ text = (REPO_ROOT / 'pyproject.toml').read_text(encoding='utf-8')
281
+ assert not re.findall(r'"quapp-common\s*(>=|>|~=)', text), (
282
+ 'quapp-common must be pinned with `==`: `>=` lets pip pick a higher '
283
+ 'stable release that is missing the feature (which already happened '
284
+ 'with quapp-qiskit 1.0.14)')
285
+
286
+ match = re.search(r'"quapp-common\s*==\s*([^"]+)"', text)
287
+ assert match, 'no quapp-common pin found'
288
+ assert version.Version(match.group(1)) >= version.Version(MINIMUM_COMMON), (
289
+ f'pin {match.group(1)} < {MINIMUM_COMMON}: that release has no phase for '
290
+ f'analysis/post-processing and still splits one job into two traceIds')
291
+
292
+
293
+ def test_registered_rules_are_reachable():
294
+ """Runs for real: import the lib and read the registry. Skips without the SDK."""
295
+ package_name = PACKAGE.name
296
+ pytest.importorskip(package_name)
297
+ __import__(package_name)
298
+ from quapp_common.util.error_classifier import registered_rules
299
+
300
+ codes = {rule.code for rule in registered_rules()}
301
+ own = {code for code in codes if not code.startswith(
302
+ ('INPUT_', 'DEPENDENCY_', 'PROVIDER_', 'HANDLER_', 'PLATFORM_',
303
+ 'COMPILATION_', 'EXECUTION_', 'ANALYSIS_', 'POST_'))}
304
+ assert own, f'no lib-specific rule registered, only generic ones: {sorted(codes)}'
@@ -1 +0,0 @@
1
- from .factory.braket_handler_factory import BraketHandlerFactory