Dataset Viewer
Auto-converted to Parquet
repo
stringclasses
5 values
instance_id
stringclasses
5 values
base_commit
stringclasses
5 values
patch
stringclasses
5 values
test_patch
stringclasses
1 value
problem_statement
stringclasses
5 values
hints_text
stringclasses
4 values
created_at
stringdate
2019-02-24 16:30:32
2023-08-02 16:35:14
version
stringclasses
1 value
FAIL_TO_PASS
stringclasses
1 value
PASS_TO_PASS
stringclasses
1 value
environment_setup_commit
stringclasses
1 value
PrefectHQ/prefect
PrefectHQ__prefect-856
5739feb6eaac6a62e090e5c4590873d4474823bb
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -17,6 +17,7 @@ "google-cloud-storage >= 1.13, < 2.0", ], "kubernetes": ["dask-kubernetes == 0.7.0", "kubernetes >= 8.0.1, < 9.0"], + "rss": ["feedparser >= 5.0.1, < 6.0"], "templates": ["jinja2 >= 2.0, < 3.0"], "viz": ["graphviz >= 0.8.3"], "twitter": ["tweepy >= 3.5, < 4.0"], diff --git a/src/prefect/tasks/rss/__init__.py b/src/prefect/tasks/rss/__init__.py new file mode 100644 --- /dev/null +++ b/src/prefect/tasks/rss/__init__.py @@ -0,0 +1,9 @@ +""" +Tasks for interacting with RSS feeds. +""" +try: + from prefect.tasks.rss.feed import ParseRSSFeed +except ImportError: + raise ImportError( + 'Using `prefect.tasks.rss` requires Prefect to be installed with the "rss" extra.' + ) diff --git a/src/prefect/tasks/rss/feed.py b/src/prefect/tasks/rss/feed.py new file mode 100644 --- /dev/null +++ b/src/prefect/tasks/rss/feed.py @@ -0,0 +1,42 @@ +from typing import Any + +import feedparser + +from prefect import Task +from prefect.utilities.tasks import defaults_from_attrs + + +class ParseRSSFeed(Task): + """ + Task for parsing RSS feeds. + + Args: + - feed_url (str): A remote URL pointing to an RSS feed + - **kwargs (dict, optional): additional keyword arguments to pass to the Task + constructor + """ + + def __init__(self, feed_url: str = None, **kwargs: Any): + self.feed_url = feed_url + + super().__init__(**kwargs) + + @defaults_from_attrs("feed_url") + def run(self, feed_url: str = None) -> "feedparser.FeedParserDict": + """ + Task run method. + + Args: + - feed_url (str): A remote URL pointing to an RSS feed + + Return: + - FeedParserDict: A dictionary representing the information from the + parsed feed. The object is accessable through indexing and attributes. + + Raises: + - ValueError: if `feed_url` is `None` + """ + if not feed_url: + raise ValueError("The feed_url must be provided.") + + return feedparser.parse(feed_url)
Create RSS Tasks for Task Library
2019-03-26T19:27:14Z
[]
[]
Qiskit/qiskit
Qiskit__qiskit-1856
240398505c6df0308992e697b4ad26c611faf248
diff --git a/examples/python/hello_quantum.py b/examples/python/hello_quantum.py --- a/examples/python/hello_quantum.py +++ b/examples/python/hello_quantum.py @@ -50,16 +50,17 @@ # Compile and run the Quantum Program on a real device backend try: least_busy_device = least_busy(IBMQ.backends(simulator=False)) - print("Running on current least busy device: ", least_busy_device) - - #running the job - job_exp = execute(qc, least_busy_device, shots=1024, max_credits=10) - result_exp = job_exp.result() - - # Show the results - print(result_exp.get_counts(qc)) except: print("All devices are currently unavailable.") + print("Running on current least busy device: ", least_busy_device) + + #running the job + job_exp = execute(qc, least_busy_device, shots=1024, max_credits=10) + result_exp = job_exp.result() + + # Show the results + print(result_exp.get_counts(qc)) + except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) diff --git a/examples/python/rippleadd.py b/examples/python/rippleadd.py --- a/examples/python/rippleadd.py +++ b/examples/python/rippleadd.py @@ -13,7 +13,8 @@ """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile, BasicAer +from qiskit import BasicAer +from qiskit import execute ############################################################### # Set the backend name and coupling map. @@ -76,14 +77,12 @@ def unmajority(p, a, b, c): ############################################################### # First version: not mapped -qobj = compile(qc, backend=backend, coupling_map=None, shots=1024) -job = backend.run(qobj) +job = execute(qc, backend=backend, coupling_map=None, shots=1024) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph -qobj = compile(qc, backend=backend, coupling_map=coupling_map, shots=1024) -job = backend.run(qobj) +job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024) result = job.result() print(result.get_counts(qc)) diff --git a/examples/python/teleport.py b/examples/python/teleport.py --- a/examples/python/teleport.py +++ b/examples/python/teleport.py @@ -13,7 +13,8 @@ """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit -from qiskit import compile, BasicAer +from qiskit import BasicAer +from qiskit import execute ############################################################### # Set the backend name and coupling map. @@ -58,20 +59,14 @@ ############################################################### # First version: not mapped -initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1), - ("q", 2): ("q", 2)} -qobj = compile(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) -job = backend.run(qobj) -qobj_exp = qobj.experiments[0] +initial_layout = [q[0], q[1], q[2]] +job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Second version: mapped to 2x8 array coupling graph -qobj = compile(qc, backend=backend, coupling_map=coupling_map, shots=1024,initial_layout=initial_layout) -qobj_exp = qobj.experiments[0] -qobj_exp.header.compiled_circuit_qasm = "" -job = backend.run(qobj) +job = execute(qc, backend=backend, coupling_map=coupling_map, shots=1024,initial_layout=initial_layout) result = job.result() print(result.get_counts(qc)) # Both versions should give the same distribution diff --git a/examples/python/using_qiskit_terra_level_0.py b/examples/python/using_qiskit_terra_level_0.py --- a/examples/python/using_qiskit_terra_level_0.py +++ b/examples/python/using_qiskit_terra_level_0.py @@ -68,18 +68,20 @@ try: # select least busy available device and execute. least_busy_device = least_busy(IBMQ.backends(simulator=False)) - print("Running on current least busy device: ", least_busy_device) + except: + print("All devices are currently unavailable.") - # running the job - job_exp = execute([qc1, qc2], backend=least_busy_device, shots=1024, max_credits=10) + print("Running on current least busy device: ", least_busy_device) - job_monitor(job_exp) - exp_result = job_exp.result() + # running the job + job_exp = execute([qc1, qc2], backend=least_busy_device, shots=1024, max_credits=10) + + job_monitor(job_exp) + exp_result = job_exp.result() + + # Show the results + print(exp_result.get_counts(qc1)) + print(exp_result.get_counts(qc2)) - # Show the results - print(exp_result.get_counts(qc1)) - print(exp_result.get_counts(qc2)) - except: - print("All devices are currently unavailable.") except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) diff --git a/examples/python/using_qiskit_terra_level_1.py b/examples/python/using_qiskit_terra_level_1.py --- a/examples/python/using_qiskit_terra_level_1.py +++ b/examples/python/using_qiskit_terra_level_1.py @@ -8,20 +8,28 @@ """ Example showing how to use Qiskit at level 1 (intermediate). -This example shows how an intermediate user interacts with Terra. It builds some circuits -and compiles them from compile parameters. It makes a qobj object which is just and container to be -run on a backend. The same qobj can run on many backends (as shown). It is the -user responsibility to make sure it can be run. This is useful when you want to compare the same -circuits on different backends or change the compile parameters. - -To control the passes and we have a pass manager for level 2 user. +This example shows how an intermediate user interacts with Terra. +It builds some circuits and transpiles them with transpile options. +It then makes a qobj object which is just a container to be run on a backend. +The same qobj can be submitted to many backends (as shown). +It is the user's responsibility to make sure it can be run (i.e. it conforms +to the restrictions of the backend, if any). +This is useful when you want to compare the same +circuit on different backends without recompiling the whole circuit, +or just want to change some runtime parameters. + +To control the passes that transform the circuit, we have a pass manager +for the level 2 user. """ import pprint, time # Import the Qiskit modules -from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError -from qiskit import compile, IBMQ, BasicAer +from qiskit import IBMQ, BasicAer +from qiskit import QiskitError +from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister +from qiskit.compiler import transpile, assemble_circuits +from qiskit.compiler import TranspileConfig, RunConfig from qiskit.providers.ibmq import least_busy from qiskit.tools.monitor import job_monitor @@ -33,7 +41,7 @@ For now, there's only access to local simulator backends...""") try: - # Create a Quantum and Classical Register and giving a name. + # Create a Quantum and Classical Register and give them names. qubit_reg = QuantumRegister(2, name='q') clbit_reg = ClassicalRegister(2, name='c') @@ -52,31 +60,48 @@ print("(Aer Backends)") for backend in BasicAer.backends(): print(backend.status()) - my_backend = BasicAer.get_backend('qasm_simulator') + qasm_simulator = BasicAer.get_backend('qasm_simulator') print("(QASM Simulator configuration) ") - pprint.pprint(my_backend.configuration()) + pprint.pprint(qasm_simulator.configuration()) print("(QASM Simulator properties) ") - pprint.pprint(my_backend.properties()) + pprint.pprint(qasm_simulator.properties()) - print("\n(IMQ Backends)") + # Compile and run the circuit on a real device backend + # See a list of available remote backends + print("\n(IBMQ Backends)") for backend in IBMQ.backends(): print(backend.status()) - # select least busy available device and execute. - least_busy_device = least_busy(IBMQ.backends(simulator=False)) + try: + # select least busy available device and execute. + least_busy_device = least_busy(IBMQ.backends(simulator=False)) + except: + print("All devices are currently unavailable.") + print("Running on current least busy device: ", least_busy_device) print("(with configuration) ") pprint.pprint(least_busy_device.configuration()) print("(with properties) ") pprint.pprint(least_busy_device.properties()) + # Transpile the circuits to make them compatible with the experimental backend + [qc1_new, qc2_new] = transpile(circuits=[qc1, qc2], + transpile_config=TranspileConfig(backend=least_busy_device)) + print("Bell circuit before transpile:") + print(qc1) + print("Bell circuit after transpile:") + print(qc1_new) + print("Superposition circuit before transpile:") + print(qc2) + print("Superposition circuit after transpile:") + print(qc2_new) - # Compiling the job for the experimental backend - qobj = compile([qc1, qc2], backend=least_busy_device, shots=1024, max_credits=10) + # Assemble the two circuits into a runnable qobj + qobj = assemble_circuits([qc1_new, qc2_new], run_config=RunConfig(shots=1000)) - # Running the job - sim_job = my_backend.run(qobj) + # Running qobj on the simulator + sim_job = qasm_simulator.run(qobj) # Getting the result sim_result=sim_job.result() @@ -85,20 +110,15 @@ print(sim_result.get_counts(qc1)) print(sim_result.get_counts(qc2)) - # Compile and run the Quantum Program on a real device backend - # See a list of available remote backends - try: - # Running the job. - exp_job = least_busy_device.run(qobj) + # Running the job. + exp_job = least_busy_device.run(qobj) - job_monitor(exp_job) - exp_result = exp_job.result() + job_monitor(exp_job) + exp_result = exp_job.result() - # Show the results - print(exp_result.get_counts(qc1)) - print(exp_result.get_counts(qc2)) - except: - print("All devices are currently unavailable.") + # Show the results + print(exp_result.get_counts(qc1)) + print(exp_result.get_counts(qc2)) except QiskitError as ex: print('There was an error in the circuit!. Error = {}'.format(ex)) diff --git a/qiskit/__init__.py b/qiskit/__init__.py --- a/qiskit/__init__.py +++ b/qiskit/__init__.py @@ -7,6 +7,7 @@ # pylint: disable=wrong-import-order + """Main Qiskit public functionality.""" import pkgutil @@ -21,7 +22,9 @@ from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit -from .tools.compiler import (compile, execute) +# pylint: disable=redefined-builtin +from qiskit.tools.compiler import compile # TODO remove after 0.8 +from qiskit.execute import (execute_circuits, execute) # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. @@ -38,12 +41,12 @@ # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer -# Try to import the Aer provider if the Aer element is installed. +# Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass -# Try to import the IBQM provider if the IBMQ element is installed. +# Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: diff --git a/qiskit/compiler/__init__.py b/qiskit/compiler/__init__.py new file mode 100644 --- /dev/null +++ b/qiskit/compiler/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Helper module for Qiskit compiler. + +""" + +from .run_config import RunConfig +from .transpile_config import TranspileConfig +from .assembler import assemble_circuits +from .transpiler import transpile diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py new file mode 100644 --- /dev/null +++ b/qiskit/compiler/assembler.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Assemble function for converting a list of circuits into a qobj""" +import uuid +import sympy +import numpy + +from qiskit.circuit.quantumcircuit import QuantumCircuit +from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction, QobjHeader +from qiskit.qobj import QobjExperimentConfig, QobjExperimentHeader, QobjConditional +from qiskit.compiler.run_config import RunConfig +from qiskit.qobj.utils import QobjType + + +def assemble_circuits(circuits, run_config=None, qobj_header=None, qobj_id=None): + """Assembles a list of circuits into a qobj which can be run on the backend. + + Args: + circuits (list[QuantumCircuits] or QuantumCircuit): circuits to assemble + run_config (RunConfig): RunConfig object + qobj_header (QobjHeader): header to pass to the results + qobj_id (int): identifier for the generated qobj + + Returns: + Qobj: the Qobj to be run on the backends + """ + qobj_header = qobj_header or QobjHeader() + run_config = run_config or RunConfig() + if isinstance(circuits, QuantumCircuit): + circuits = [circuits] + + userconfig = QobjConfig(**run_config.to_dict()) + experiments = [] + max_n_qubits = 0 + max_memory_slots = 0 + for circuit in circuits: + # header stuff + n_qubits = 0 + memory_slots = 0 + qubit_labels = [] + clbit_labels = [] + + qreg_sizes = [] + creg_sizes = [] + for qreg in circuit.qregs: + qreg_sizes.append([qreg.name, qreg.size]) + for j in range(qreg.size): + qubit_labels.append([qreg.name, j]) + n_qubits += qreg.size + for creg in circuit.cregs: + creg_sizes.append([creg.name, creg.size]) + for j in range(creg.size): + clbit_labels.append([creg.name, j]) + memory_slots += creg.size + + # TODO: why do we need creq_sizes and qreg_sizes in header + # TODO: we need to rethink memory_slots as they are tied to classical bit + experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels, + n_qubits=n_qubits, + qreg_sizes=qreg_sizes, + clbit_labels=clbit_labels, + memory_slots=memory_slots, + creg_sizes=creg_sizes, + name=circuit.name) + # TODO: why do we need n_qubits and memory_slots in both the header and the config + experimentconfig = QobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots) + + instructions = [] + for opt in circuit.data: + current_instruction = QobjInstruction(name=opt.name) + if opt.qargs: + qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]]) + for qubit in opt.qargs] + current_instruction.qubits = qubit_indices + if opt.cargs: + clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]]) + for clbit in opt.cargs] + current_instruction.memory = clbit_indices + + if opt.params: + params = list(map(lambda x: x.evalf(), opt.params)) + params = [sympy.matrix2numpy(x, dtype=complex) + if isinstance(x, sympy.Matrix) else x for x in params] + if len(params) == 1 and isinstance(params[0], numpy.ndarray): + # TODO: Aer expects list of rows for unitary instruction params; + # change to matrix in Aer. + params = params[0] + current_instruction.params = params + # TODO (jay): I really dont like this for snapshot. I also think we should change + # type to snap_type + if opt.name == "snapshot": + current_instruction.label = str(opt.params[0]) + current_instruction.type = str(opt.params[1]) + if opt.control: + mask = 0 + for clbit in clbit_labels: + if clbit[0] == opt.control[0].name: + mask |= (1 << clbit_labels.index(clbit)) + + current_instruction.conditional = QobjConditional(mask="0x%X" % mask, + type='equals', + val="0x%X" % opt.control[1]) + + instructions.append(current_instruction) + experiments.append(QobjExperiment(instructions=instructions, header=experimentheader, + config=experimentconfig)) + if n_qubits > max_n_qubits: + max_n_qubits = n_qubits + if memory_slots > max_memory_slots: + max_memory_slots = memory_slots + + userconfig.memory_slots = max_memory_slots + userconfig.n_qubits = max_n_qubits + + return Qobj(qobj_id=qobj_id or str(uuid.uuid4()), config=userconfig, + experiments=experiments, header=qobj_header, + type=QobjType.QASM.value) diff --git a/qiskit/compiler/compile.py b/qiskit/compiler/compile.py new file mode 100644 --- /dev/null +++ b/qiskit/compiler/compile.py @@ -0,0 +1,75 @@ +# -*- coding: utf-8 -*- + +# Copyright 2018, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Helper module for simplified Qiskit usage.""" +import warnings +import logging + +from qiskit import transpiler +from qiskit.converters import circuits_to_qobj +from qiskit.compiler import RunConfig +from qiskit.qobj import QobjHeader +from qiskit.mapper import Layout + + +logger = logging.getLogger(__name__) + + +# pylint: disable=redefined-builtin +def compile(circuits, backend, + config=None, basis_gates=None, coupling_map=None, initial_layout=None, + shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None, + pass_manager=None, memory=False): + """Compile a list of circuits into a qobj. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile + backend (BaseBackend): a backend to compile for + config (dict): dictionary of parameters (e.g. noise) used by runner + basis_gates (list[str]): list of basis gates names supported by the + target. Default: ['u1','u2','u3','cx','id'] + coupling_map (list): coupling map (perhaps custom) to target in mapping + initial_layout (list): initial layout of qubits in mapping + shots (int): number of repetitions of each circuit, for sampling + max_credits (int): maximum credits to use + seed (int): random seed for simulators + seed_mapper (int): random seed for swapper mapper + qobj_id (int): identifier for the generated qobj + pass_manager (PassManager): a pass manger for the transpiler pipeline + memory (bool): if True, per-shot measurement bitstrings are returned as well + + Returns: + Qobj: the qobj to be run on the backends + + Raises: + QiskitError: if the desired options are not supported by backend + """ + if config: + warnings.warn('The `config` argument is deprecated and ' + 'does not do anything', DeprecationWarning) + + if initial_layout is not None and not isinstance(initial_layout, Layout): + initial_layout = Layout(initial_layout) + + circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout, + seed_mapper, pass_manager) + + # step 4: Making a qobj + run_config = RunConfig() + + if seed: + run_config.seed = seed + if shots: + run_config.shots = shots + if max_credits: + run_config.max_credits = max_credits + if memory: + run_config.memory = memory + qobj = circuits_to_qobj(circuits, qobj_header=QobjHeader(), run_config=run_config, + qobj_id=qobj_id) + + return qobj diff --git a/qiskit/compiler/models.py b/qiskit/compiler/models.py new file mode 100644 --- /dev/null +++ b/qiskit/compiler/models.py @@ -0,0 +1,35 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Models for RunConfig and its related components.""" + +from marshmallow.validate import Range + +from qiskit.validation import BaseSchema +from qiskit.validation.fields import Boolean, Integer + + +class TranspileConfigSchema(BaseSchema): + """Schema for TranspileConfig.""" + + # Required properties. + # None + + # Optional properties. + + +class RunConfigSchema(BaseSchema): + """Schema for RunConfig.""" + + # Required properties. + # None + + # Optional properties. + shots = Integer(validate=Range(min=1)) + max_credits = Integer(validate=Range(min=3, max=10)) # TODO: can we check the range + seed = Integer() + memory = Boolean() # set default to be False diff --git a/qiskit/qobj/run_config.py b/qiskit/compiler/run_config.py similarity index 60% rename from qiskit/qobj/run_config.py rename to qiskit/compiler/run_config.py --- a/qiskit/qobj/run_config.py +++ b/qiskit/compiler/run_config.py @@ -7,23 +7,8 @@ """Models for RunConfig and its related components.""" -from marshmallow.validate import Range - -from qiskit.validation import BaseModel, BaseSchema, bind_schema -from qiskit.validation.fields import Boolean, Integer - - -class RunConfigSchema(BaseSchema): - """Schema for RunConfig.""" - - # Required properties. - # None - - # Optional properties. - shots = Integer(validate=Range(min=1)) - max_credits = Integer(validate=Range(min=3, max=10)) # TODO: can we check the range - seed = Integer() - memory = Boolean() # set default to be False +from qiskit.compiler.models import RunConfigSchema +from qiskit.validation import BaseModel, bind_schema @bind_schema(RunConfigSchema) diff --git a/qiskit/compiler/transpile_config.py b/qiskit/compiler/transpile_config.py new file mode 100644 --- /dev/null +++ b/qiskit/compiler/transpile_config.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Models for TranspileConfig and its related components.""" + +from qiskit.compiler.models import TranspileConfigSchema +from qiskit.validation import BaseModel, bind_schema + + +@bind_schema(TranspileConfigSchema) +class TranspileConfig(BaseModel): + """Model for TranspileConfig. + + Please note that this class only describes the required fields. For the + full description of the model, please check ``TranspileConfigSchema``. + + Attributes: + + """ diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py new file mode 100644 --- /dev/null +++ b/qiskit/compiler/transpiler.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +"""Circuit transpile function """ +import logging + +from qiskit import transpiler +from qiskit.mapper import Layout + + +logger = logging.getLogger(__name__) + + +def transpile(circuits, transpile_config=None): + """Compile a list of circuits into a list of optimized circuits. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile + transpile_config (TranspileConfig): configuration for the transpiler + + Returns: + circuits: the optimized circuits + """ + + # ------------ + # TODO: This is a hack while we are still using the old transpiler. + initial_layout = getattr(transpile_config, 'initial_layout', None) + basis_gates = getattr(transpile_config, 'basis_gates', None) + coupling_map = getattr(transpile_config, 'coupling_map', None) + seed_mapper = getattr(transpile_config, 'seed_mapper', None) + + if initial_layout is not None and not isinstance(initial_layout, Layout): + initial_layout = Layout(initial_layout) + + pass_manager = None + backend = transpile_config.backend + new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, + initial_layout, seed_mapper, pass_manager) + # --------- + + # THE IDEAL CODE HERE WILL BE. + # 1 set up the pass_manager using transpile_config options + # pass_manager = PassManager(TranspileConig) + # run the passes + # new_circuits = pass_manager.run(circuits) + return new_circuits diff --git a/qiskit/converters/circuits_to_qobj.py b/qiskit/converters/circuits_to_qobj.py --- a/qiskit/converters/circuits_to_qobj.py +++ b/qiskit/converters/circuits_to_qobj.py @@ -6,19 +6,14 @@ # the LICENSE.txt file in the root directory of this source tree. """Compile function for converting a list of circuits to the qobj""" -import uuid import warnings -import sympy -import numpy -from qiskit.circuit.quantumcircuit import QuantumCircuit -from qiskit.qobj import Qobj, QobjConfig, QobjExperiment, QobjInstruction, QobjHeader -from qiskit.qobj import QobjExperimentConfig, QobjExperimentHeader, QobjConditional -from qiskit.qobj.run_config import RunConfig -from qiskit.qobj.utils import QobjType +from qiskit.qobj import QobjHeader +from qiskit.compiler.run_config import RunConfig +from qiskit.compiler import assemble_circuits -def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, +def circuits_to_qobj(circuits, qobj_header=None, run_config=None, qobj_id=None, backend_name=None, config=None, shots=None, max_credits=None, basis_gates=None, @@ -27,10 +22,10 @@ def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, Args: circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile - user_qobj_header (QobjHeader): header to pass to the results + qobj_header (QobjHeader): header to pass to the results run_config (RunConfig): RunConfig object - qobj_id (int): identifier for the generated qobj + qobj_id (int): TODO: delete after qiskit-terra 0.8 backend_name (str): TODO: delete after qiskit-terra 0.8 config (dict): TODO: delete after qiskit-terra 0.8 shots (int): TODO: delete after qiskit-terra 0.8 @@ -43,14 +38,16 @@ def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, Returns: Qobj: the Qobj to be run on the backends """ - user_qobj_header = user_qobj_header or QobjHeader() + warnings.warn('circuits_to_qobj is deprecated and will be removed in Qiskit Terra 0.9. ' + 'Use qiskit.compiler.assemble_circuits() to serialize circuits into a qobj.', + DeprecationWarning) + + qobj_header = qobj_header or QobjHeader() run_config = run_config or RunConfig() - if isinstance(circuits, QuantumCircuit): - circuits = [circuits] if backend_name: warnings.warn('backend_name is not required anymore', DeprecationWarning) - user_qobj_header.backend_name = backend_name + qobj_header.backend_name = backend_name if config: warnings.warn('config is not used anymore. Set all configs in ' 'run_config.', DeprecationWarning) @@ -70,90 +67,9 @@ def circuits_to_qobj(circuits, user_qobj_header=None, run_config=None, if max_credits: warnings.warn('max_credits is not used anymore. Set it via run_config', DeprecationWarning) run_config.max_credits = max_credits + if qobj_id: + warnings.warn('qobj_id is not used anymore', DeprecationWarning) - userconfig = QobjConfig(**run_config.to_dict()) - experiments = [] - max_n_qubits = 0 - max_memory_slots = 0 - for circuit in circuits: - # header stuff - n_qubits = 0 - memory_slots = 0 - qubit_labels = [] - clbit_labels = [] - - qreg_sizes = [] - creg_sizes = [] - for qreg in circuit.qregs: - qreg_sizes.append([qreg.name, qreg.size]) - for j in range(qreg.size): - qubit_labels.append([qreg.name, j]) - n_qubits += qreg.size - for creg in circuit.cregs: - creg_sizes.append([creg.name, creg.size]) - for j in range(creg.size): - clbit_labels.append([creg.name, j]) - memory_slots += creg.size - - # TODO: why do we need creq_sizes and qreg_sizes in header - # TODO: we need to rethink memory_slots as they are tied to classical bit - experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels, - n_qubits=n_qubits, - qreg_sizes=qreg_sizes, - clbit_labels=clbit_labels, - memory_slots=memory_slots, - creg_sizes=creg_sizes, - name=circuit.name) - # TODO: why do we need n_qubits and memory_slots in both the header and the config - experimentconfig = QobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots) - - instructions = [] - for opt in circuit.data: - current_instruction = QobjInstruction(name=opt.name) - if opt.qargs: - qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]]) - for qubit in opt.qargs] - current_instruction.qubits = qubit_indices - if opt.cargs: - clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]]) - for clbit in opt.cargs] - current_instruction.memory = clbit_indices - - if opt.params: - params = list(map(lambda x: x.evalf(), opt.params)) - params = [sympy.matrix2numpy(x, dtype=complex) - if isinstance(x, sympy.Matrix) else x for x in params] - if len(params) == 1 and isinstance(params[0], numpy.ndarray): - # TODO: Aer expects list of rows for unitary instruction params; - # change to matrix in Aer. - params = params[0] - current_instruction.params = params - # TODO: I really dont like this for snapshot. I also think we should change - # type to snap_type - if opt.name == "snapshot": - current_instruction.label = str(opt.params[0]) - current_instruction.type = str(opt.params[1]) - if opt.control: - mask = 0 - for clbit in clbit_labels: - if clbit[0] == opt.control[0].name: - mask |= (1 << clbit_labels.index(clbit)) - - current_instruction.conditional = QobjConditional(mask="0x%X" % mask, - type='equals', - val="0x%X" % opt.control[1]) - - instructions.append(current_instruction) - experiments.append(QobjExperiment(instructions=instructions, header=experimentheader, - config=experimentconfig)) - if n_qubits > max_n_qubits: - max_n_qubits = n_qubits - if memory_slots > max_memory_slots: - max_memory_slots = memory_slots - - userconfig.memory_slots = max_memory_slots - userconfig.n_qubits = max_n_qubits + qobj = assemble_circuits(circuits, qobj_header, run_config) - return Qobj(qobj_id=qobj_id or str(uuid.uuid4()), config=userconfig, - experiments=experiments, header=user_qobj_header, - type=QobjType.QASM.value) + return qobj diff --git a/qiskit/execute.py b/qiskit/execute.py new file mode 100644 --- /dev/null +++ b/qiskit/execute.py @@ -0,0 +1,133 @@ +# -*- coding: utf-8 -*- + +# Copyright 2019, IBM. +# +# This source code is licensed under the Apache License, Version 2.0 found in +# the LICENSE.txt file in the root directory of this source tree. + +""" +Helper module for simplified Qiskit usage. + +This module includes + execute_circuits: compile and run a list of quantum circuits. + execute: simplified usage of either execute_circuits or execute_schedules + +In general we recommend using the SDK functions directly. However, to get something +running quickly we have provider this wrapper module. +""" + +import logging +import warnings + +from qiskit.compiler import assemble_circuits, transpile +from qiskit.compiler import RunConfig, TranspileConfig +from qiskit.qobj import QobjHeader + +logger = logging.getLogger(__name__) + + +def execute(circuits, backend, qobj_header=None, config=None, basis_gates=None, + coupling_map=None, initial_layout=None, shots=1024, max_credits=10, + seed=None, qobj_id=None, seed_mapper=None, pass_manager=None, + memory=False, **kwargs): + """Executes a set of circuits. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute + backend (BaseBackend): a backend to execute the circuits on + qobj_header (QobjHeader): user input to go into the header + config (dict): dictionary of parameters (e.g. noise) used by runner + basis_gates (list[str]): list of basis gate names supported by the + target. Default: ['u1','u2','u3','cx','id'] + coupling_map (list): coupling map (perhaps custom) to target in mapping + initial_layout (list): initial layout of qubits in mapping + shots (int): number of repetitions of each circuit, for sampling + max_credits (int): maximum credits to use + seed (int): random seed for simulators + seed_mapper (int): random seed for swapper mapper + qobj_id (int): identifier for the generated qobj + pass_manager (PassManager): a pass manger for the transpiler pipeline + memory (bool): if True, per-shot measurement bitstrings are returned as well. + kwargs: extra arguments used by AER for running configurable backends. + Refer to the backend documentation for details on these arguments + + Returns: + BaseJob: returns job instance derived from BaseJob + """ + + transpile_config = TranspileConfig() + run_config = RunConfig() + + if config: + warnings.warn('config is deprecated in terra 0.8', DeprecationWarning) + if qobj_id: + warnings.warn('qobj_id is deprecated in terra 0.8', DeprecationWarning) + if basis_gates: + transpile_config.basis_gate = basis_gates + if coupling_map: + transpile_config.coupling_map = coupling_map + if initial_layout: + transpile_config.initial_layout = initial_layout + if seed_mapper: + transpile_config.seed_mapper = seed_mapper + if shots: + run_config.shots = shots + if max_credits: + run_config.max_credits = max_credits + if seed: + run_config.seed = seed + if memory: + run_config.memory = memory + if pass_manager: + warnings.warn('pass_manager in the execute function is deprecated in terra 0.8.', + DeprecationWarning) + + job = execute_circuits(circuits, backend, qobj_header=qobj_header, + run_config=run_config, + transpile_config=transpile_config, **kwargs) + + return job + + +def execute_circuits(circuits, backend, qobj_header=None, + transpile_config=None, run_config=None, **kwargs): + """Executes a list of circuits. + + Args: + circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute + backend (BaseBackend): a backend to execute the circuits on + qobj_header (QobjHeader): User input to go in the header + transpile_config (TranspileConfig): Configurations for the transpiler + run_config (RunConfig): Run Configuration + kwargs: extra arguments used by AER for running configurable backends. + Refer to the backend documentation for details on these arguments + + Returns: + BaseJob: returns job instance derived from BaseJob + """ + + # TODO: a hack, remove when backend is not needed in transpile + # ------ + transpile_config = transpile_config or TranspileConfig() + transpile_config.backend = backend + # ------ + + # filling in the header with the backend name the qobj was run on + qobj_header = qobj_header or QobjHeader() + qobj_header.backend_name = backend.name() + + # default values + if not run_config: + # TODO remove max_credits from the default when it is not + # required by by the backend. + run_config = RunConfig(shots=1024, max_credits=10, memory=False) + + # transpiling the circuits using the transpiler_config + new_circuits = transpile(circuits, transpile_config=transpile_config) + + # assembling the circuits into a qobj to be run on the backend + qobj = assemble_circuits(new_circuits, qobj_header=qobj_header, + run_config=run_config) + + # executing the circuits on the backend and returning the job + return backend.run(qobj, **kwargs) diff --git a/qiskit/qobj/__init__.py b/qiskit/qobj/__init__.py --- a/qiskit/qobj/__init__.py +++ b/qiskit/qobj/__init__.py @@ -11,6 +11,5 @@ from .models import (QobjConfig, QobjExperiment, QobjInstruction, QobjHeader, QobjExperimentHeader, QobjConditional, QobjExperimentConfig) from .exceptions import QobjValidationError -from .run_config import RunConfig from ._validation import validate_qobj_against_schema diff --git a/qiskit/qobj/qobj.py b/qiskit/qobj/qobj.py --- a/qiskit/qobj/qobj.py +++ b/qiskit/qobj/qobj.py @@ -20,9 +20,9 @@ """Current version of the Qobj schema. Qobj schema versions: -* 1.1.0: Qiskit 0.8 -* 1.0.0: Qiskit 0.6 -* 0.0.1: Qiskit 0.5.x format (pre-schemas). +* 1.1.0: Qiskit Terra 0.8 +* 1.0.0: Qiskit Terra 0.6 +* 0.0.1: Qiskit Terra 0.5.x format (pre-schemas). """ diff --git a/qiskit/tools/__init__.py b/qiskit/tools/__init__.py --- a/qiskit/tools/__init__.py +++ b/qiskit/tools/__init__.py @@ -16,4 +16,4 @@ """ from .parallel import parallel_map -from .compiler import (compile, execute) +from .compiler import compile diff --git a/qiskit/tools/compiler.py b/qiskit/tools/compiler.py --- a/qiskit/tools/compiler.py +++ b/qiskit/tools/compiler.py @@ -5,17 +5,14 @@ # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. -"""Helper module for simplified Qiskit usage.""" +"""Helper module for simplified Qiskit usage. THIS WILL BE REMOVED IN AFTER 0.8.""" import warnings import logging +from qiskit.compiler import assemble_circuits, RunConfig from qiskit import transpiler -from qiskit.converters import circuits_to_qobj -from qiskit.qobj import RunConfig -from qiskit.qobj import QobjHeader from qiskit.mapper import Layout - logger = logging.getLogger(__name__) @@ -48,64 +45,32 @@ def compile(circuits, backend, Raises: QiskitError: if the desired options are not supported by backend """ - if config: - warnings.warn('The `config` argument is deprecated and ' - 'does not do anything', DeprecationWarning) - - if initial_layout is not None and not isinstance(initial_layout, Layout): - initial_layout = Layout(initial_layout) - - circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout, - seed_mapper, pass_manager) + warnings.warn('qiskit.compile() is deprecated and will be removed in Qiskit Terra 0.9. ' + 'Please use qiskit.transpile() to transform circuits ' + 'and qiskit.assemble_circuits() to produce qobj.', + DeprecationWarning) - # step 4: Making a qobj run_config = RunConfig() - if seed: - run_config.seed = seed + if config: + warnings.warn('config is not used anymore. Set all configs in ' + 'run_config.', DeprecationWarning) if shots: run_config.shots = shots if max_credits: run_config.max_credits = max_credits + if seed: + run_config.seed = seed if memory: run_config.memory = memory - qobj = circuits_to_qobj(circuits, user_qobj_header=QobjHeader(), run_config=run_config, - qobj_id=qobj_id) - - return qobj - -def execute(circuits, backend, config=None, basis_gates=None, coupling_map=None, - initial_layout=None, shots=1024, max_credits=10, seed=None, - qobj_id=None, seed_mapper=None, pass_manager=None, - memory=False, **kwargs): - """Executes a set of circuits. - - Args: - circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute - backend (BaseBackend): a backend to execute the circuits on - config (dict): dictionary of parameters (e.g. noise) used by runner - basis_gates (list[str]): list of basis gate names supported by the - target. Default: ['u1','u2','u3','cx','id'] - coupling_map (list): coupling map (perhaps custom) to target in mapping - initial_layout (list): initial layout of qubits in mapping - shots (int): number of repetitions of each circuit, for sampling - max_credits (int): maximum credits to use - seed (int): random seed for simulators - seed_mapper (int): random seed for swapper mapper - qobj_id (int): identifier for the generated qobj - pass_manager (PassManager): a pass manger for the transpiler pipeline - memory (bool): if True, per-shot measurement bitstrings are returned as well. - kwargs: extra arguments used by AER for running configurable backends. - Refer to the backend documentation for details on these arguments + if initial_layout is not None and not isinstance(initial_layout, Layout): + initial_layout = Layout(initial_layout) - Returns: - BaseJob: returns job instance derived from BaseJob - """ + new_circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, + initial_layout, seed_mapper, pass_manager) - qobj = compile(circuits, backend, - config, basis_gates, coupling_map, initial_layout, - shots, max_credits, seed, qobj_id, seed_mapper, - pass_manager, memory) + qobj = assemble_circuits(new_circuits, qobj_header=None, run_config=run_config, + qobj_id=qobj_id) - return backend.run(qobj, **kwargs) + return qobj
Allow for setting qobj header description in execute and propagate to job <!-- ⚠️ If you do not respect this template, your issue will be closed --> <!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. --> ### What is the expected enhancement? The Qobj accepts a description in the header that allows the user to label the qobj with whatever message they want, e.g. `'cool_exp_v1'`. However, this can not be set unless one first does `compile` and then manually sets the description. Because the user never sees the qobj (and perhaps never should since it is just a fancy box) when using `execute` it is impossible to save this info. In addition, if I try to grab a job by the description (see #1710), or some substring in description, to the best of my knowledge I need to load all the jobs, and then make another API call for each job to load the qobj and then search the header description. It would be nice if the qobj header description could be set in execute, and then this description gets added to the resulting job, e.g. `job.description` so that I can search jobs by this value without needing to load qobjs.
This is good but it has to be done after the update to the compile interfaces. I will try and do it with that.
2019-02-24T16:30:32Z
[]
[]
apache/airflow
apache__airflow-33043
d989e9dba5899e87780df9a8c5994ed1e3f8a776
diff --git a/airflow/auth/managers/fab/views/roles_list.py b/airflow/auth/managers/fab/views/roles_list.py new file mode 100644 --- /dev/null +++ b/airflow/auth/managers/fab/views/roles_list.py @@ -0,0 +1,42 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +from flask_appbuilder.security.views import RoleModelView + +from airflow.security import permissions + + +class CustomRoleModelView(RoleModelView): + """Customize permission names for FAB's builtin RoleModelView.""" + + class_permission_name = permissions.RESOURCE_ROLE + method_permission_name = { + "delete": "delete", + "download": "read", + "show": "read", + "list": "read", + "edit": "edit", + "add": "create", + "copy_role": "create", + } + base_permissions = [ + permissions.ACTION_CAN_CREATE, + permissions.ACTION_CAN_READ, + permissions.ACTION_CAN_EDIT, + permissions.ACTION_CAN_DELETE, + ] diff --git a/airflow/www/fab_security/manager.py b/airflow/www/fab_security/manager.py --- a/airflow/www/fab_security/manager.py +++ b/airflow/www/fab_security/manager.py @@ -258,7 +258,7 @@ def create_builtin_roles(self): """Returns FAB builtin roles.""" return self.appbuilder.get_app.config.get("FAB_ROLES", {}) - def get_roles_from_keys(self, role_keys: list[str]) -> set[RoleModelView]: + def get_roles_from_keys(self, role_keys: list[str]) -> set[Role]: """ Construct a list of FAB role objects, from a list of keys. @@ -267,7 +267,7 @@ def get_roles_from_keys(self, role_keys: list[str]) -> set[RoleModelView]: - we use AUTH_ROLES_MAPPING to map from keys, to FAB role names :param role_keys: the list of FAB role keys - :return: a list of RoleModelView + :return: a list of Role """ _roles = set() _role_keys = set(role_keys) diff --git a/airflow/www/fab_security/views.py b/airflow/www/fab_security/views.py --- a/airflow/www/fab_security/views.py +++ b/airflow/www/fab_security/views.py @@ -20,7 +20,6 @@ from flask_appbuilder.security.views import ( PermissionModelView, PermissionViewModelView, - RoleModelView, ViewMenuModelView, ) from flask_babel import lazy_gettext @@ -72,27 +71,6 @@ class PermissionPairModelView(PermissionViewModelView): list_columns = ["action", "resource"] -class CustomRoleModelView(RoleModelView): - """Customize permission names for FAB's builtin RoleModelView.""" - - class_permission_name = permissions.RESOURCE_ROLE - method_permission_name = { - "delete": "delete", - "download": "read", - "show": "read", - "list": "read", - "edit": "edit", - "add": "create", - "copy_role": "create", - } - base_permissions = [ - permissions.ACTION_CAN_CREATE, - permissions.ACTION_CAN_READ, - permissions.ACTION_CAN_EDIT, - permissions.ACTION_CAN_DELETE, - ] - - class ResourceModelView(ViewMenuModelView): """Customize permission names for FAB's builtin ViewMenuModelView.""" diff --git a/airflow/www/security.py b/airflow/www/security.py --- a/airflow/www/security.py +++ b/airflow/www/security.py @@ -25,6 +25,7 @@ from sqlalchemy.orm import Session, joinedload from airflow.auth.managers.fab.models import Permission, Resource, Role, User +from airflow.auth.managers.fab.views.roles_list import CustomRoleModelView from airflow.auth.managers.fab.views.user import ( CustomUserDBModelView, CustomUserLDAPModelView, @@ -47,7 +48,6 @@ from airflow.www.fab_security.sqla.manager import SecurityManager from airflow.www.fab_security.views import ( ActionModelView, - CustomRoleModelView, PermissionPairModelView, ResourceModelView, )
AIP-56 - FAB AM - Role views Move role related views to FAB Auth manager: - List roles - Edit role - Create role - View role
2023-08-02T16:35:14Z
[]
[]
celery/celery
celery__celery-6629
c7f2f141627de69645d1885b000b12def97152ec
diff --git a/celery/backends/base.py b/celery/backends/base.py --- a/celery/backends/base.py +++ b/celery/backends/base.py @@ -853,7 +853,11 @@ def _store_result(self, task_id, result, state, if current_meta['status'] == states.SUCCESS: return result - self._set_with_state(self.get_key_for_task(task_id), self.encode(meta), state) + try: + self._set_with_state(self.get_key_for_task(task_id), self.encode(meta), state) + except BackendStoreError as ex: + raise BackendStoreError(str(ex), state=state, task_id=task_id) from ex + return result def _save_group(self, group_id, result): diff --git a/celery/backends/redis.py b/celery/backends/redis.py --- a/celery/backends/redis.py +++ b/celery/backends/redis.py @@ -12,7 +12,7 @@ from celery import states from celery._state import task_join_will_block from celery.canvas import maybe_signature -from celery.exceptions import ChordError, ImproperlyConfigured +from celery.exceptions import BackendStoreError, ChordError, ImproperlyConfigured from celery.result import GroupResult, allow_join_result from celery.utils.functional import dictfilter from celery.utils.log import get_logger @@ -192,6 +192,10 @@ class RedisBackend(BaseKeyValueStoreBackend, AsyncBackendMixin): supports_autoexpire = True supports_native_join = True + #: Maximal length of string value in Redis. + #: 512 MB - https://redis.io/topics/data-types + _MAX_STR_VALUE_SIZE = 536870912 + def __init__(self, host=None, port=None, db=None, password=None, max_connections=None, url=None, connection_pool=None, **kwargs): @@ -364,6 +368,9 @@ def on_connection_error(self, max_retries, exc, intervals, retries): return tts def set(self, key, value, **retry_policy): + if len(value) > self._MAX_STR_VALUE_SIZE: + raise BackendStoreError('value too large for Redis backend') + return self.ensure(self._set, (key, value), **retry_policy) def _set(self, key, value): diff --git a/celery/exceptions.py b/celery/exceptions.py --- a/celery/exceptions.py +++ b/celery/exceptions.py @@ -288,7 +288,7 @@ def __repr__(self): class BackendStoreError(BackendError): - """An issue writing from the backend.""" + """An issue writing to the backend.""" def __init__(self, *args, **kwargs): self.state = kwargs.get('state', "")
Workers retry Redis connection when task result is larger than 512MB - retry is useless as it never fits to Redis <!-- Please fill this template entirely and do not erase parts of it. We reserve the right to close without a response bug reports which are incomplete. --> # Checklist <!-- To check an item on the list replace [ ] with [x]. --> - [x] I have verified that the issue exists against the `master` branch of Celery. - [ ] This has already been asked to the [discussion group](https://groups.google.com/forum/#!forum/celery-users) first. - [x] I have read the relevant section in the [contribution guide](http://docs.celeryproject.org/en/latest/contributing.html#other-bugs) on reporting bugs. - [x] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22) for similar or identical bug reports. - [x] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22) for existing proposed fixes. - [x] I have checked the [commit log](https://github.com/celery/celery/commits/master) to find out if the bug was already fixed in the master branch. - [x] I have included all related issues and possible duplicate issues in this issue (If there are none, check this box anyway). ## Mandatory Debugging Information - [x] I have included the output of ``celery -A proj report`` in the issue. (if you are not able to do this, then at least specify the Celery version affected). - [x] I have verified that the issue exists against the `master` branch of Celery. - [x] I have included the contents of ``pip freeze`` in the issue. - [x] I have included all the versions of all the external dependencies required to reproduce this bug. ## Optional Debugging Information <!-- Try some of the below if you think they are relevant. It will help us figure out the scope of the bug and how many users it affects. --> - [ ] I have tried reproducing the issue on more than one Python version and/or implementation. - [ ] I have tried reproducing the issue on more than one message broker and/or result backend. - [ ] I have tried reproducing the issue on more than one version of the message broker and/or result backend. - [ ] I have tried reproducing the issue on more than one operating system. - [ ] I have tried reproducing the issue on more than one workers pool. - [ ] I have tried reproducing the issue with autoscaling, retries, ETA/Countdown & rate limits disabled. - [ ] I have tried reproducing the issue after downgrading and/or upgrading Celery and its dependencies. ## Related Issues and Possible Duplicates <!-- Please make sure to search and mention any related issues or possible duplicates to this issue as requested by the checklist above. This may or may not include issues in other repositories that the Celery project maintains or other repositories that are dependencies of Celery. If you don't know how to mention issues, please refer to Github's documentation on the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests --> #### Related Issues - None #### Possible Duplicates - None ## Environment & Settings <!-- Include the contents of celery --version below --> **Celery version**: 5.0.4 (singularity) <!-- Include the output of celery -A proj report below --> <details> <summary><b><code>celery report</code> Output:</b></summary> <p> ``` software -> celery:5.0.4 (singularity) kombu:5.0.2 py:3.9.0 billiard:3.6.3.0 py-amqp:5.0.2 platform -> system:Linux arch:64bit, ELF kernel version:5.9.12-arch1-1 imp:CPython loader -> celery.loaders.app.AppLoader settings -> transport:amqp results:redis://:**@****:6379/10 broker_url: 'amqp://**:********@*****:5672/**' result_backend: 'redis://:********@*****:6379/10' deprecated_settings: None ``` </p> </details> # Steps to Reproduce ## Required Dependencies <!-- Please fill the required dependencies to reproduce this issue --> * **Minimal Python Version**: N/A or Unknown * **Minimal Celery Version**: N/A or Unknown * **Minimal Kombu Version**: N/A or Unknown * **Minimal Broker Version**: N/A or Unknown * **Minimal Result Backend Version**: N/A or Unknown * **Minimal OS and/or Kernel Version**: N/A or Unknown * **Minimal Broker Client Version**: N/A or Unknown * **Minimal Result Backend Client Version**: N/A or Unknown ### Python Packages <!-- Please fill the contents of pip freeze below --> <details> <summary><b><code>pip freeze</code> Output:</b></summary> <p> ``` amqp==5.0.2 billiard==3.6.3.0 celery @ git+https://github.com/celery/celery.git@420e3931a63538bd225ef57916deccf53cbcb57a // == master, tried also 5.0.4 click==7.1.2 click-didyoumean==0.0.3 click-plugins==1.1.1 click-repl==0.1.6 kombu==5.0.2 prompt-toolkit==3.0.8 pytz==2020.4 redis==3.5.3 six==1.15.0 vine==5.0.0 wcwidth==0.2.5 ``` </p> </details> ### Other Dependencies <!-- Please provide system dependencies, configuration files and other dependency information if applicable --> <details> <p> N/A </p> </details> ## Minimally Reproducible Test Case <!-- Please provide a reproducible test case. Refer to the Reporting Bugs section in our contribution guide. We prefer submitting test cases in the form of a PR to our integration test suite. If you can provide one, please mention the PR number below. If not, please attach the most minimal code example required to reproduce the issue below. If the test case is too large, please include a link to a gist or a repository below. --> <details> <p> ```python #!/usr/bin/env python3 from celery import Celery app = Celery( 'tasks', broker='amqp://user:***@**:5672/**', backend='redis://:**@**:6379/1', ) @app.task(ignore_result=False) def test(*args, **kwargs): return 'x' * 536870911 # 512MB ``` </p> </details> # Expected Behavior <!-- Describe in detail what you expect to happen --> I'd except an exception or error. There is no point in retrying storing result to Redis when it simply never fits there. String limit is 512 MB. I could check size of the data I'm returning in task. However, Celery adds additional metadata to my result so I do not know to what size should I limit my result. # Actual Behavior <!-- Describe in detail what actually happened. Please include a backtrace and surround it with triple backticks (```). In addition, include the Celery daemon logs, the broker logs, the result backend logs and system logs below if they will help us debug the issue. --> ``` [2020-12-09 08:38:52,786: ERROR/ForkPoolWorker-8] Connection to Redis lost: Retry (0/20) now. [2020-12-09 08:38:53,328: ERROR/ForkPoolWorker-8] Connection to Redis lost: Retry (1/20) in 1.00 second. [2020-12-09 08:38:54,940: ERROR/ForkPoolWorker-8] Connection to Redis lost: Retry (2/20) in 1.00 second. [2020-12-09 08:38:56,547: ERROR/ForkPoolWorker-8] Connection to Redis lost: Retry (3/20) in 1.00 second. .... and so on ``` Redis fails with the following error when you try to set string larger than 512 MB: ``` raise ConnectionError("Error %s while writing to socket. %s." % redis.exceptions.ConnectionError: Error 32 while writing to socket. Broken pipe. ``` Tried via another script with direct Redis connection. This says nothing about input size therefore I think value size should be checked before sending data to Redis.
Pull requests are welcome.
2021-02-07T09:06:11Z
[]
[]
pandas-dev/pandas
pandas-dev__pandas-39217
b31c069ded78a67e0a6f54fc776a7920fd09beca
"diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py\n--- a/pandas/io/json/_json.py\n+++ (...TRUNCATED)
"TST/REF: splitting pandas/io/parsers.py into multiple files\n`pandas/io/parsers.py` is close to 4k (...TRUNCATED)
sure seems reasonable
2021-01-17T00:38:48Z
[]
[]
README.md exists but content is empty.
Downloads last month
31